diff --git a/backend/app/api/dashboards.py b/backend/app/api/dashboards.py index 07fd70c9..88389002 100644 --- a/backend/app/api/dashboards.py +++ b/backend/app/api/dashboards.py @@ -15,12 +15,13 @@ would be a broken dashboard the user cannot fix without an API call. """ import logging -from flask import Blueprint, jsonify +from flask import Blueprint, jsonify, request from flask_jwt_extended import jwt_required, get_jwt_identity from app.services import dashboard_service -from app.services.dashboard_service import GRID_COLS, MAX_WIDGETS_PER_BOARD +from app.services.dashboard_service import ENTITY_SCOPES, GRID_COLS, MAX_WIDGETS_PER_BOARD from app.api._request import json_object +from app.exceptions import ValidationError logger = logging.getLogger(__name__) @@ -126,8 +127,17 @@ def _validate_icon(value): @dashboards_bp.route('/', methods=['GET']) @jwt_required() def list_boards(): - """This user's boards, seeding the shipped defaults on the first call.""" + """This user's dashboard tabs, seeding the shipped defaults on the first + call. With ``?scope=entity:`` it returns instead the overview layout + the user saved for that kind of detail page: a list of one, or empty while + they are still on the shipped layout.""" user_id = get_jwt_identity() + scope = request.args.get('scope') + if scope is not None: + if scope not in ENTITY_SCOPES: + raise ValidationError('Unknown board scope') + board = dashboard_service.get_entity_board(user_id, scope) + return jsonify({'boards': [board.to_dict()] if board else []}) boards = dashboard_service.get_boards_for_user(user_id) return jsonify({'boards': [b.to_dict() for b in boards]}) @@ -137,10 +147,18 @@ def list_boards(): @jwt_required() def create_board(): """Add a board for this user. ``widgets`` is optional — a new tab usually - starts empty and gets filled from the widget library.""" + starts empty and gets filled from the widget library. + + With ``scope: 'entity:'`` the board is the user's overview layout for + that kind of detail page rather than a dashboard tab. A user has one per + kind, so posting again replaces it (200 instead of 201).""" user_id = get_jwt_identity() body = json_object(optional=True) + scope = body.get('scope') + if scope is not None and scope not in ENTITY_SCOPES: + raise ValidationError('Unknown board scope') + name, err = _validate_name(body.get('name')) if err: return jsonify({'error': err}), 400 @@ -157,6 +175,10 @@ def create_board(): if err: return jsonify({'error': err}), 400 + if scope is not None: + board, created = dashboard_service.save_entity_board(user_id, scope, name, widgets) + return jsonify(board.to_dict()), 201 if created else 200 + board = dashboard_service.create_board(user_id, name, icon=icon, widgets=widgets) return jsonify(board.to_dict()), 201 diff --git a/backend/app/services/dashboard_service.py b/backend/app/services/dashboard_service.py index 0844ed12..e319a0b8 100644 --- a/backend/app/services/dashboard_service.py +++ b/backend/app/services/dashboard_service.py @@ -49,6 +49,14 @@ GRID_COLS = 12 # JSON per board. MAX_WIDGETS_PER_BOARD = 100 +# A board can also hold the Overview layout a user saved for one kind of +# detail page (every server page shares the user's server layout, the page's +# own server being the board's variable). It is an ordinary board row whose +# slug names the kind, so it reuses the same storage, validation and +# ownership rules; it is just never listed among the dashboard tabs. +ENTITY_SCOPE_PREFIX = 'entity:' +ENTITY_SCOPES = ('entity:server', 'entity:service') + DEFAULT_BOARDS = [ { @@ -257,14 +265,21 @@ def _repair_board(board): return True +def _dashboard_tabs(user_id): + """This user's dashboard tabs: every board except saved overview layouts.""" + return (DashboardBoard.query + .filter_by(user_id=user_id) + .filter(db.or_(DashboardBoard.slug.is_(None), + ~DashboardBoard.slug.like(f'{ENTITY_SCOPE_PREFIX}%'))) + .order_by(DashboardBoard.position, DashboardBoard.id) + .all()) + + def get_boards_for_user(user_id): - """Every board owned by this user, seeding the shipped defaults on the - first read for a user who has none, and repairing configs that predate the - current renderer contract.""" - boards = (DashboardBoard.query - .filter_by(user_id=user_id) - .order_by(DashboardBoard.position, DashboardBoard.id) - .all()) + """Every dashboard tab owned by this user, seeding the shipped defaults on + the first read for a user who has none, and repairing configs that predate + the current renderer contract.""" + boards = _dashboard_tabs(user_id) if boards: # Not `any(...)`: it short-circuits, so only the first repairable board # would ever be fixed. @@ -272,10 +287,28 @@ def get_boards_for_user(user_id): db.session.commit() return boards seed_defaults(user_id) - return (DashboardBoard.query - .filter_by(user_id=user_id) - .order_by(DashboardBoard.position, DashboardBoard.id) - .all()) + return _dashboard_tabs(user_id) + + +def get_entity_board(user_id, scope): + """The overview layout this user saved for one kind of detail page, or + None when they are still on the shipped layout.""" + return DashboardBoard.query.filter_by(user_id=user_id, slug=scope).first() + + +def save_entity_board(user_id, scope, name, widgets): + """Store a user's overview layout for one kind of detail page. There is at + most one per user and kind, so a second save replaces the first. Returns + ``(board, created)``.""" + board = get_entity_board(user_id, scope) + created = board is None + if created: + board = DashboardBoard(user_id=user_id, slug=scope, icon='grid', position=0) + db.session.add(board) + board.name = name + board.widgets = list(widgets or []) + db.session.commit() + return board, created def get_board_for_user(user_id, board_id): diff --git a/backend/tests/test_dashboards.py b/backend/tests/test_dashboards.py index 564eceeb..e0c15366 100644 --- a/backend/tests/test_dashboards.py +++ b/backend/tests/test_dashboards.py @@ -464,3 +464,71 @@ def test_repair_leaves_a_current_board_untouched(app, client, auth_headers): boards = client.get('/api/v1/dashboards', headers=auth_headers).get_json()['boards'] current = next(b for b in boards if b['name'] == 'Current') assert current['widgets'][0]['cfg'] == cfg + + +# --- saved overview layouts (entity-scoped boards) --------------------------- + +def test_overview_layout_is_stored_but_is_not_a_dashboard_tab(client, auth_headers): + saved = client.post('/api/v1/dashboards', headers=auth_headers, json={ + 'name': 'Server overview', 'scope': 'entity:server', 'widgets': [_widget()], + }) + assert saved.status_code == 201 + assert saved.get_json()['slug'] == 'entity:server' + + tabs = client.get('/api/v1/dashboards', headers=auth_headers).get_json()['boards'] + assert 'entity:server' not in [board['slug'] for board in tabs] + # Saving an overview first must not stop the shipped tabs from seeding. + assert [board['slug'] for board in tabs] == ['overview', 'infra', 'apps'] + + scoped = client.get('/api/v1/dashboards?scope=entity:server', headers=auth_headers).get_json()['boards'] + assert [board['id'] for board in scoped] == [saved.get_json()['id']] + assert scoped[0]['widgets'] == [_widget()] + + +def test_overview_layout_is_empty_until_saved(client, auth_headers): + resp = client.get('/api/v1/dashboards?scope=entity:service', headers=auth_headers) + assert resp.status_code == 200 + assert resp.get_json()['boards'] == [] + + +def test_saving_an_overview_layout_again_replaces_it(client, auth_headers): + first = client.post('/api/v1/dashboards', headers=auth_headers, json={ + 'name': 'Server overview', 'scope': 'entity:server', 'widgets': [_widget()], + }) + second = client.post('/api/v1/dashboards', headers=auth_headers, json={ + 'name': 'Server overview', 'scope': 'entity:server', + 'widgets': [_widget(i='w1'), _widget(i='w2', x=3)], + }) + assert second.status_code == 200 + assert second.get_json()['id'] == first.get_json()['id'] + + scoped = client.get('/api/v1/dashboards?scope=entity:server', headers=auth_headers).get_json()['boards'] + assert len(scoped) == 1 + assert [widget['i'] for widget in scoped[0]['widgets']] == ['w1', 'w2'] + + +def test_deleting_an_overview_layout_returns_to_the_shipped_one(client, auth_headers): + saved = client.post('/api/v1/dashboards', headers=auth_headers, json={ + 'name': 'Service overview', 'scope': 'entity:service', 'widgets': [_widget()], + }).get_json() + assert client.delete(f"/api/v1/dashboards/{saved['id']}", headers=auth_headers).status_code == 200 + scoped = client.get('/api/v1/dashboards?scope=entity:service', headers=auth_headers).get_json()['boards'] + assert scoped == [] + + +def test_overview_layouts_are_scoped_per_user(client, auth_headers, other_headers): + client.post('/api/v1/dashboards', headers=auth_headers, json={ + 'name': 'Server overview', 'scope': 'entity:server', 'widgets': [_widget()], + }) + theirs = client.get('/api/v1/dashboards?scope=entity:server', headers=other_headers).get_json()['boards'] + assert theirs == [] + + +@pytest.mark.parametrize('scope', ['entity:database', 'overview', '', 7]) +def test_unknown_board_scope_is_rejected(client, auth_headers, scope): + resp = client.post('/api/v1/dashboards', headers=auth_headers, json={ + 'name': 'Nope', 'scope': scope, 'widgets': [], + }) + assert resp.status_code == 400 + assert client.get('/api/v1/dashboards?scope=entity:database', headers=auth_headers).status_code == 400 +