From 625d9090965d29b963c159cd57901574dd1219d4 Mon Sep 17 00:00:00 2001 From: Andrea Leardini Date: Fri, 20 Nov 2026 16:36:09 +0100 Subject: [PATCH 01/17] feat(systems): let users star favorite systems Users who follow many systems need a quick way back to the few they work on. Each user can now star systems: the star sits next to the name in the list and on the system page, and the row menu adds or removes it too. A filter lists only favorites and a sort brings them to the top. Favorites are personal, kept in a new system_favorites table (migration 062) and removed with the user. They are read-only while impersonating. The authz suite covers the new endpoints. Assisted-by: Claude Code:claude-sonnet-5-5 --- backend/authz/routes.yml | 13 ++ backend/authz/special.yml | 11 ++ .../migrations/062_system_favorites.sql | 17 ++ .../062_system_favorites_rollback.sql | 3 + backend/database/schema.sql | 19 ++ backend/entities/local_system_favorites.go | 61 ++++++ .../entities/local_system_favorites_test.go | 177 ++++++++++++++++++ backend/entities/local_systems.go | 29 ++- backend/entities/local_users.go | 47 ++--- backend/main.go | 14 ++ backend/methods/system_favorites.go | 104 ++++++++++ backend/methods/system_favorites_unit_test.go | 69 +++++++ backend/methods/systems.go | 11 ++ backend/methods/systems_export.go | 29 +-- backend/models/systems.go | 9 + backend/openapi.yaml | 126 ++++++++++++- docs/docs/systems/management.md | 26 ++- .../current/systems/management.md | 27 ++- frontend/src/assets/main.css | 17 ++ .../systems/SystemFavoriteToggle.test.ts | 116 ++++++++++++ .../systems/SystemFavoriteToggle.vue | 131 +++++++++++++ .../src/components/systems/SystemsTable.vue | 58 +++++- frontend/src/i18n/en/translation.json | 11 +- frontend/src/i18n/it/translation.json | 11 +- frontend/src/lib/systems/systems.test.ts | 34 ++++ frontend/src/lib/systems/systems.ts | 29 ++- .../src/queries/systems/favoriteSystems.ts | 24 +++ frontend/src/queries/systems/systems.ts | 22 +++ frontend/src/views/SystemDetailView.vue | 15 +- frontend/src/views/SystemsView.vue | 2 + 30 files changed, 1209 insertions(+), 53 deletions(-) create mode 100644 backend/database/migrations/062_system_favorites.sql create mode 100644 backend/database/migrations/062_system_favorites_rollback.sql create mode 100644 backend/entities/local_system_favorites.go create mode 100644 backend/entities/local_system_favorites_test.go create mode 100644 backend/methods/system_favorites.go create mode 100644 backend/methods/system_favorites_unit_test.go create mode 100644 frontend/src/components/systems/SystemFavoriteToggle.test.ts create mode 100644 frontend/src/components/systems/SystemFavoriteToggle.vue create mode 100644 frontend/src/queries/systems/favoriteSystems.ts diff --git a/backend/authz/routes.yml b/backend/authz/routes.yml index 84ac15cae..73bf71c33 100644 --- a/backend/authz/routes.yml +++ b/backend/authz/routes.yml @@ -242,6 +242,19 @@ routes: - method: PATCH path: /api/systems/:id/reactivate intent: manage:systems + - method: PUT + path: /api/systems/:id/favorite + intent: read:systems + note: | + Starring is a personal bookmark that changes nothing on the system, so it + needs only read access to it — a Reader may star what it can see. The + system must still be in the caller's scope. + - method: DELETE + path: /api/systems/:id/favorite + intent: read:systems + note: | + Removes only the caller's own star, so it may target a system that has + since left the caller's scope. - method: GET path: /api/systems/totals intent: read:systems diff --git a/backend/authz/special.yml b/backend/authz/special.yml index d4136a8b1..0e2774535 100644 --- a/backend/authz/special.yml +++ b/backend/authz/special.yml @@ -196,6 +196,17 @@ cases: expect: denied note: the owner of this key holds impersonate:users, so only RejectAPIKey can stop it + - name: key cannot star a system + kind: api_key + as: d1r1-admin + mode: write + method: PUT + path: /api/systems/{system:s-d1r1c1}/favorite + expect: denied + note: | + The owner of this key can read the system, so only RejectAPIKey can stop + it: favorites are a personal bookmark of an interactive session. + - name: key cannot change the owner's password kind: api_key as: d1r1-admin diff --git a/backend/database/migrations/062_system_favorites.sql b/backend/database/migrations/062_system_favorites.sql new file mode 100644 index 000000000..088b91ee4 --- /dev/null +++ b/backend/database/migrations/062_system_favorites.sql @@ -0,0 +1,17 @@ +-- Migration 062: favorite systems +-- +-- One row per system a user starred. Keyed on the Logto user ID rather than +-- users(id): the Owner account has no local users row. A destroyed system +-- takes its rows with it; a destroyed user is cleaned up by the backend. + +CREATE TABLE IF NOT EXISTS system_favorites ( + user_logto_id VARCHAR(255) NOT NULL, + system_id VARCHAR(255) NOT NULL REFERENCES systems(id) ON DELETE CASCADE, + created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(), + PRIMARY KEY (user_logto_id, system_id) +); + +CREATE INDEX IF NOT EXISTS idx_system_favorites_system_id ON system_favorites(system_id); + +COMMENT ON TABLE system_favorites IS 'Systems a user starred as favorites; personal, never shared with other users'; +COMMENT ON COLUMN system_favorites.user_logto_id IS 'Logto user ID of the user who starred the system (no FK: the Owner has no users row)'; diff --git a/backend/database/migrations/062_system_favorites_rollback.sql b/backend/database/migrations/062_system_favorites_rollback.sql new file mode 100644 index 000000000..d8fed7800 --- /dev/null +++ b/backend/database/migrations/062_system_favorites_rollback.sql @@ -0,0 +1,3 @@ +-- Rollback 062: drop favorite systems + +DROP TABLE IF EXISTS system_favorites; diff --git a/backend/database/schema.sql b/backend/database/schema.sql index 8ee06c0de..c4b02463a 100644 --- a/backend/database/schema.sql +++ b/backend/database/schema.sql @@ -1460,3 +1460,22 @@ COMMENT ON COLUMN entitlement_seats.released_reason IS 'manual (freed by a user) COMMENT ON COLUMN entitlement_seats.released_by IS 'Actor snapshot of the user that freed the seat; NULL when collect freed it'; COMMENT ON COLUMN system_entitlements.renewal_stopped_at IS 'The shop must not renew this grant any more: it stays valid until valid_until. Cleared by an activation from a buyer that manages the system'; COMMENT ON COLUMN system_entitlements.renewal_stopped_reason IS 'Why the renewal stopped: customer_transferred, reseller_transferred or system_transferred (the buyer organization no longer manages what moved). NULL when renewing normally'; + +-- ============================================================================= +-- SYSTEM FAVORITES +-- ============================================================================= +-- Systems a user starred. Keyed on the Logto user ID rather than users(id): +-- the Owner account has no local users row. A destroyed system takes its rows +-- with it; a destroyed user is cleaned up by the backend. See migration 062. + +CREATE TABLE IF NOT EXISTS system_favorites ( + user_logto_id VARCHAR(255) NOT NULL, + system_id VARCHAR(255) NOT NULL REFERENCES systems(id) ON DELETE CASCADE, + created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(), + PRIMARY KEY (user_logto_id, system_id) +); + +CREATE INDEX IF NOT EXISTS idx_system_favorites_system_id ON system_favorites(system_id); + +COMMENT ON TABLE system_favorites IS 'Systems a user starred as favorites; personal, never shared with other users'; +COMMENT ON COLUMN system_favorites.user_logto_id IS 'Logto user ID of the user who starred the system (no FK: the Owner has no users row)'; diff --git a/backend/entities/local_system_favorites.go b/backend/entities/local_system_favorites.go new file mode 100644 index 000000000..ad9ae1c80 --- /dev/null +++ b/backend/entities/local_system_favorites.go @@ -0,0 +1,61 @@ +/* +Copyright (C) 2026 Nethesis S.r.l. +SPDX-License-Identifier: AGPL-3.0-or-later +*/ + +package entities + +import ( + "database/sql" + "fmt" + + "github.com/nethesis/my/backend/database" +) + +// LocalSystemFavoriteRepository reads / writes system_favorites: the systems +// each user starred. Rows are keyed on the user's Logto ID. +type LocalSystemFavoriteRepository struct { + db *sql.DB +} + +func NewLocalSystemFavoriteRepository() *LocalSystemFavoriteRepository { + return &LocalSystemFavoriteRepository{db: database.DB} +} + +// Add stars the system for the user. Starring it again is a no-op. +func (r *LocalSystemFavoriteRepository) Add(userLogtoID, systemID string) error { + _, err := r.db.Exec( + `INSERT INTO system_favorites (user_logto_id, system_id) VALUES ($1, $2) + ON CONFLICT (user_logto_id, system_id) DO NOTHING`, + userLogtoID, systemID, + ) + if err != nil { + return fmt.Errorf("failed to add system favorite: %w", err) + } + return nil +} + +// Remove unstars the system for the user. Removing a missing row is a no-op. +func (r *LocalSystemFavoriteRepository) Remove(userLogtoID, systemID string) error { + _, err := r.db.Exec( + `DELETE FROM system_favorites WHERE user_logto_id = $1 AND system_id = $2`, + userLogtoID, systemID, + ) + if err != nil { + return fmt.Errorf("failed to remove system favorite: %w", err) + } + return nil +} + +// IsFavorite reports whether the user starred the system. +func (r *LocalSystemFavoriteRepository) IsFavorite(userLogtoID, systemID string) (bool, error) { + var exists bool + err := r.db.QueryRow( + `SELECT EXISTS (SELECT 1 FROM system_favorites WHERE user_logto_id = $1 AND system_id = $2)`, + userLogtoID, systemID, + ).Scan(&exists) + if err != nil { + return false, fmt.Errorf("failed to check system favorite: %w", err) + } + return exists, nil +} diff --git a/backend/entities/local_system_favorites_test.go b/backend/entities/local_system_favorites_test.go new file mode 100644 index 000000000..1f95cbc7d --- /dev/null +++ b/backend/entities/local_system_favorites_test.go @@ -0,0 +1,177 @@ +/* +Copyright (C) 2026 Nethesis S.r.l. +SPDX-License-Identifier: AGPL-3.0-or-later +*/ + +package entities + +import ( + "context" + "database/sql/driver" + "errors" + "testing" + + "github.com/DATA-DOG/go-sqlmock" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/nethesis/my/backend/database" + "github.com/nethesis/my/backend/models" +) + +func setupSystemFavoritesMock(t *testing.T) (sqlmock.Sqlmock, func()) { + originalDB := database.DB + mockDB, mock, err := sqlmock.New() + require.NoError(t, err) + database.DB = mockDB + return mock, func() { + database.DB = originalDB + _ = mockDB.Close() + } +} + +func TestSystemFavoriteAdd_IsIdempotent(t *testing.T) { + mock, cleanup := setupSystemFavoritesMock(t) + defer cleanup() + + mock.ExpectExec(`INSERT INTO system_favorites \(user_logto_id, system_id\) VALUES \(\$1, \$2\)\s+ON CONFLICT \(user_logto_id, system_id\) DO NOTHING`). + WithArgs("user-1", "sys-1"). + WillReturnResult(sqlmock.NewResult(0, 0)) + + require.NoError(t, NewLocalSystemFavoriteRepository().Add("user-1", "sys-1")) + assert.NoError(t, mock.ExpectationsWereMet()) +} + +func TestSystemFavoriteRemove_DeletesOnlyTheCallersRow(t *testing.T) { + mock, cleanup := setupSystemFavoritesMock(t) + defer cleanup() + + mock.ExpectExec(`DELETE FROM system_favorites WHERE user_logto_id = \$1 AND system_id = \$2`). + WithArgs("user-1", "sys-1"). + WillReturnResult(sqlmock.NewResult(0, 1)) + + require.NoError(t, NewLocalSystemFavoriteRepository().Remove("user-1", "sys-1")) + assert.NoError(t, mock.ExpectationsWereMet()) +} + +func TestSystemFavoriteIsFavorite(t *testing.T) { + mock, cleanup := setupSystemFavoritesMock(t) + defer cleanup() + + mock.ExpectQuery(`SELECT EXISTS \(SELECT 1 FROM system_favorites WHERE user_logto_id = \$1 AND system_id = \$2\)`). + WithArgs("user-1", "sys-1"). + WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true)) + + got, err := NewLocalSystemFavoriteRepository().IsFavorite("user-1", "sys-1") + require.NoError(t, err) + assert.True(t, got) + assert.NoError(t, mock.ExpectationsWereMet()) +} + +func TestSystemFavoriteAdd_WrapsError(t *testing.T) { + mock, cleanup := setupSystemFavoritesMock(t) + defer cleanup() + + mock.ExpectExec(`INSERT INTO system_favorites`).WillReturnError(errors.New("fk violation")) + + err := NewLocalSystemFavoriteRepository().Add("user-1", "sys-1") + assert.ErrorContains(t, err, "failed to add system favorite") +} + +// captureSystemsListQuery runs the systems list as the Owner (no RBAC filter, +// so the only bound arguments are the favorites ones and paging), checks the +// arguments it bound and returns the SQL it sent. +func captureSystemsListQuery(t *testing.T, sortBy, sortDirection string, f models.SystemListFilters, wantArgs ...driver.Value) string { + t.Helper() + var gotSQL string + matcher := sqlmock.QueryMatcherFunc(func(_ string, actual string) error { + gotSQL = actual + return nil + }) + mockDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(matcher)) + require.NoError(t, err) + defer func() { _ = mockDB.Close() }() + + mock.ExpectQuery("").WithArgs(wantArgs...).WillReturnError(errors.New("stop")) + + repo := &LocalSystemRepository{db: mockDB} + _, _, err = repo.ListByCreatedByOrganizations(context.Background(), nil, 1, 50, "", sortBy, sortDirection, f) + require.ErrorContains(t, err, "stop") + return gotSQL +} + +func TestListSystems_FavoritesJoinIsScopedToTheCaller(t *testing.T) { + sql := captureSystemsListQuery(t, "", "asc", models.SystemListFilters{FavoritesOf: "user-1"}, "user-1", 50, 0) + + assert.Contains(t, sql, "LEFT JOIN system_favorites sf ON sf.system_id = s.id AND sf.user_logto_id = $1") + assert.Contains(t, sql, "(sf.system_id IS NOT NULL) as is_favorite") + assert.NotContains(t, sql, "AND (sf.system_id IS NOT NULL)") +} + +func TestListSystems_WithoutCallerNothingIsStarred(t *testing.T) { + sql := captureSystemsListQuery(t, "", "asc", models.SystemListFilters{}, 50, 0) + + assert.NotContains(t, sql, "system_favorites") + assert.Contains(t, sql, "FALSE as is_favorite") +} + +func TestListSystems_FavoritesOnlyFilter(t *testing.T) { + sql := captureSystemsListQuery(t, "", "asc", models.SystemListFilters{FavoritesOf: "user-1", FavoritesOnly: true}, "user-1", 50, 0) + + assert.Contains(t, sql, "s.deleted_at IS NULL AND (sf.system_id IS NOT NULL)") +} + +func TestListSystems_FavoritesOnlyWithoutCallerMatchesNothing(t *testing.T) { + sql := captureSystemsListQuery(t, "", "asc", models.SystemListFilters{FavoritesOnly: true}, 50, 0) + + assert.Contains(t, sql, "s.deleted_at IS NULL AND FALSE") +} + +func TestListSystems_SortByFavoriteAscendingListsFavoritesFirst(t *testing.T) { + sql := captureSystemsListQuery(t, "favorite", "asc", models.SystemListFilters{FavoritesOf: "user-1"}, "user-1", 50, 0) + + assert.Contains(t, sql, "ORDER BY (sf.system_id IS NULL) ASC, LOWER(s.name), s.id") +} + +func TestListSystems_SortByFavoriteDescendingListsFavoritesLast(t *testing.T) { + sql := captureSystemsListQuery(t, "favorite", "desc", models.SystemListFilters{FavoritesOf: "user-1"}, "user-1", 50, 0) + + assert.Contains(t, sql, "ORDER BY (sf.system_id IS NULL) DESC, LOWER(s.name), s.id") +} + +func TestUserHardDelete_RemovesTheUsersFavorites(t *testing.T) { + mock, cleanup := setupSystemFavoritesMock(t) + defer cleanup() + + mock.ExpectQuery(`WITH deleted AS \(\s+DELETE FROM users WHERE logto_id = \$1 RETURNING logto_id\s+\), favorites AS \(\s+DELETE FROM system_favorites WHERE user_logto_id IN \(SELECT logto_id FROM deleted\)\s+\)\s+SELECT COUNT\(\*\) FROM deleted`). + WithArgs("user-1"). + WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(1)) + + require.NoError(t, NewLocalUserRepository().HardDelete("user-1")) + assert.NoError(t, mock.ExpectationsWereMet()) +} + +func TestUserHardDelete_UnknownUser(t *testing.T) { + mock, cleanup := setupSystemFavoritesMock(t) + defer cleanup() + + mock.ExpectQuery(`WITH deleted AS`). + WithArgs("missing"). + WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(0)) + + assert.EqualError(t, NewLocalUserRepository().HardDelete("missing"), "user not found") +} + +func TestUserHardDeleteByOrgID_RemovesTheirFavorites(t *testing.T) { + mock, cleanup := setupSystemFavoritesMock(t) + defer cleanup() + + mock.ExpectQuery(`WITH deleted AS \(\s+DELETE FROM users WHERE organization_id = \$1 RETURNING logto_id\s+\), favorites AS \(\s+DELETE FROM system_favorites\s+WHERE user_logto_id IN \(SELECT logto_id FROM deleted WHERE logto_id IS NOT NULL\)\s+\)\s+SELECT logto_id FROM deleted WHERE logto_id IS NOT NULL`). + WithArgs("org-1"). + WillReturnRows(sqlmock.NewRows([]string{"logto_id"}).AddRow("user-1").AddRow("user-2")) + + ids, err := NewLocalUserRepository().HardDeleteByOrgID("org-1") + require.NoError(t, err) + assert.Equal(t, []string{"user-1", "user-2"}, ids) + assert.NoError(t, mock.ExpectationsWereMet()) +} diff --git a/backend/entities/local_systems.go b/backend/entities/local_systems.go index b630f3aaf..3b65bc585 100644 --- a/backend/entities/local_systems.go +++ b/backend/entities/local_systems.go @@ -420,6 +420,22 @@ func (r *LocalSystemRepository) ListByCreatedByOrganizations(ctx context.Context args = append(args, addonArgs...) } + // The caller's favorites: a LEFT JOIN on their own rows only, so it adds + // no row and never widens the RBAC scope built above. + favoriteJoin := "" + favoriteExpr := "FALSE" + // sorts favorites first in ascending order, the sort's default direction + favoriteSortExpr := "TRUE" + if f.FavoritesOf != "" { + args = append(args, f.FavoritesOf) + favoriteJoin = fmt.Sprintf("LEFT JOIN system_favorites sf ON sf.system_id = s.id AND sf.user_logto_id = $%d", len(args)) + favoriteExpr = "(sf.system_id IS NOT NULL)" + favoriteSortExpr = "(sf.system_id IS NULL)" + } + if f.FavoritesOnly { + whereClause += " AND " + favoriteExpr + } + // Build ORDER BY clause orderBy := "s.created_at DESC" if sortBy != "" { @@ -435,6 +451,7 @@ func (r *LocalSystemRepository) ListByCreatedByOrganizations(ctx context.Context "creator_name": "LOWER(s.created_by ->> 'name')", "organization_name": "LOWER(uo.name)", "managed_by": systemManagedBySortExpression, + "favorite": favoriteSortExpr, } if column, exists := columnMap[sortBy]; exists { @@ -443,9 +460,10 @@ func (r *LocalSystemRepository) ListByCreatedByOrganizations(ctx context.Context direction = "DESC" } orderBy = fmt.Sprintf("%s %s", column, direction) - // many systems share one manager: fall back to their name, so - // OFFSET paging does not repeat or skip a row across a tie - if sortBy == "managed_by" { + // many systems share one manager, or one favorite flag: fall + // back to their name, so OFFSET paging does not repeat or skip + // a row across a tie + if sortBy == "managed_by" || sortBy == "favorite" { orderBy += ", LOWER(s.name), s.id" } } @@ -458,14 +476,16 @@ func (r *LocalSystemRepository) ListByCreatedByOrganizations(ctx context.Context COALESCE(uo.name, 'Owner') as organization_name, COALESCE(uo.org_type, 'owner') as organization_type, COALESCE(uo.db_id, '') as organization_db_id, + %s as is_favorite, COUNT(*) OVER() as total_count FROM systems s LEFT JOIN system_heartbeats h ON s.id = h.system_id LEFT JOIN unified_organizations uo ON s.organization_id = uo.logto_id + %s WHERE %s ORDER BY %s LIMIT $%d OFFSET $%d - `, whereClause, orderBy, len(args)+1, len(args)+2) + `, favoriteExpr, favoriteJoin, whereClause, orderBy, len(args)+1, len(args)+2) listArgs := make([]interface{}, len(args)+2) copy(listArgs, args) @@ -493,6 +513,7 @@ func (r *LocalSystemRepository) ListByCreatedByOrganizations(ctx context.Context &ipv4Address, &ipv6Address, &version, &system.SystemKey, &system.Organization.LogtoID, &customDataJSON, &system.Notes, &system.CreatedAt, &system.UpdatedAt, &deletedAt, ®isteredAt, &unregisteredAt, &suspendedAt, &suspendedByOrgID, &createdByJSON, &lastHeartbeat, &lastInventory, &system.UpdateAvailable, &organizationName, &organizationType, &organizationDBID, + &system.IsFavorite, &totalCount, ) if err != nil { diff --git a/backend/entities/local_users.go b/backend/entities/local_users.go index 48075f483..eba4afe95 100644 --- a/backend/entities/local_users.go +++ b/backend/entities/local_users.go @@ -1525,35 +1525,43 @@ func (r *LocalUserRepository) Restore(logtoID string) error { return nil } -// HardDelete permanently deletes a user by logto_id +// HardDelete permanently deletes a user by logto_id, together with the +// systems the user starred: system_favorites has no foreign key to users +// (the Owner has no users row), so the same statement removes them. func (r *LocalUserRepository) HardDelete(logtoID string) error { - query := `DELETE FROM users WHERE logto_id = $1` - - result, err := r.db.Exec(query, logtoID) - if err != nil { + query := `WITH deleted AS ( + DELETE FROM users WHERE logto_id = $1 RETURNING logto_id + ), favorites AS ( + DELETE FROM system_favorites WHERE user_logto_id IN (SELECT logto_id FROM deleted) + ) + SELECT COUNT(*) FROM deleted` + + var deleted int + if err := r.db.QueryRow(query, logtoID).Scan(&deleted); err != nil { return fmt.Errorf("failed to hard-delete user: %w", err) } - rowsAffected, err := result.RowsAffected() - if err != nil { - return fmt.Errorf("failed to get rows affected: %w", err) - } - - if rowsAffected == 0 { + if deleted == 0 { return fmt.Errorf("user not found") } return nil } -// HardDeleteByOrgID permanently deletes all users belonging to an organization +// HardDeleteByOrgID permanently deletes all users belonging to an organization, +// together with the systems they starred (see HardDelete). // Returns the logto_ids of deleted users for Logto cleanup func (r *LocalUserRepository) HardDeleteByOrgID(orgLogtoID string) ([]string, error) { - // First get the logto_ids of users that will be deleted (for Logto cleanup) - selectQuery := `SELECT logto_id FROM users WHERE organization_id = $1 AND logto_id IS NOT NULL` - rows, err := r.db.Query(selectQuery, orgLogtoID) + query := `WITH deleted AS ( + DELETE FROM users WHERE organization_id = $1 RETURNING logto_id + ), favorites AS ( + DELETE FROM system_favorites + WHERE user_logto_id IN (SELECT logto_id FROM deleted WHERE logto_id IS NOT NULL) + ) + SELECT logto_id FROM deleted WHERE logto_id IS NOT NULL` + rows, err := r.db.Query(query, orgLogtoID) if err != nil { - return nil, fmt.Errorf("failed to query users for hard-delete: %w", err) + return nil, fmt.Errorf("failed to hard-delete users by org: %w", err) } defer func() { _ = rows.Close() }() @@ -1569,13 +1577,6 @@ func (r *LocalUserRepository) HardDeleteByOrgID(orgLogtoID string) ([]string, er return nil, fmt.Errorf("error iterating users: %w", err) } - // Hard-delete all users for this org - deleteQuery := `DELETE FROM users WHERE organization_id = $1` - _, err = r.db.Exec(deleteQuery, orgLogtoID) - if err != nil { - return nil, fmt.Errorf("failed to hard-delete users by org: %w", err) - } - return logtoIDs, nil } diff --git a/backend/main.go b/backend/main.go index e4d9c986d..96ba08748 100644 --- a/backend/main.go +++ b/backend/main.go @@ -248,6 +248,20 @@ func main() { // =========================================== // SYSTEMS - resource-based permission validation (read:systems for GET, manage:systems for POST/PUT/DELETE) // =========================================== + // Favorites: personal stars on a system. Starring changes nothing on the + // system, so read:systems is enough for every verb. Interactive sessions + // only: an API key is for automation, and an impersonator must not leave + // stars in the target's account. + systemFavoritesGroup := customAuthWithAudit.Group("/systems/:id/favorite", + middleware.RejectAPIKey(), + middleware.DisableOnImpersonate(), + middleware.RequirePermission("read:systems"), + ) + { + systemFavoritesGroup.PUT("", methods.AddSystemFavorite) + systemFavoritesGroup.DELETE("", methods.RemoveSystemFavorite) + } + systemsGroup := customAuthWithAudit.Group("/systems", middleware.RequireResourcePermission("systems")) { // CRUD operations diff --git a/backend/methods/system_favorites.go b/backend/methods/system_favorites.go new file mode 100644 index 000000000..053564ad9 --- /dev/null +++ b/backend/methods/system_favorites.go @@ -0,0 +1,104 @@ +/* +Copyright (C) 2026 Nethesis S.r.l. +SPDX-License-Identifier: AGPL-3.0-or-later +*/ + +package methods + +import ( + "net/http" + + "github.com/gin-gonic/gin" + + "github.com/nethesis/my/backend/entities" + "github.com/nethesis/my/backend/helpers" + "github.com/nethesis/my/backend/logger" + "github.com/nethesis/my/backend/models" + "github.com/nethesis/my/backend/response" + "github.com/nethesis/my/backend/services/local" +) + +// favoriteUserID is the key system_favorites rows are stored under: the Logto +// ID, which every principal has (the bootstrap Owner has no local users row). +func favoriteUserID(user *models.User) string { + if user == nil { + return "" + } + if user.LogtoID != nil && *user.LogtoID != "" { + return *user.LogtoID + } + return user.ID +} + +// applySystemFavoriteFilters scopes the favorite flag, filter and sort of a +// systems list to the caller. With an impersonation token the caller is the +// target, so the impersonator sees the target's favorites. +func applySystemFavoriteFilters(c *gin.Context, filters *models.SystemListFilters) { + if value, exists := c.Get("user"); exists { + if user, ok := value.(*models.User); ok { + filters.FavoritesOf = favoriteUserID(user) + } + } + filters.FavoritesOnly = c.Query("favorite") == "true" +} + +// AddSystemFavorite handles PUT /api/systems/:id/favorite - stars a system for +// the caller. Starring is personal and changes nothing on the system, so it +// needs only read access to it. +func AddSystemFavorite(c *gin.Context) { + setSystemFavorite(c, true) +} + +// RemoveSystemFavorite handles DELETE /api/systems/:id/favorite - unstars a +// system for the caller. It skips the access check: it only deletes the +// caller's own row, and a system that left the caller's scope (or was +// archived) must still be removable from their favorites. +func RemoveSystemFavorite(c *gin.Context) { + setSystemFavorite(c, false) +} + +func setSystemFavorite(c *gin.Context, favorite bool) { + systemID := c.Param("id") + if systemID == "" { + c.JSON(http.StatusBadRequest, response.BadRequest("system ID required", nil)) + return + } + + user, ok := helpers.GetUserFromContext(c) + if !ok { + return + } + userKey := favoriteUserID(user) + + operation := "unfavorite" + if favorite { + operation = "favorite" + if _, err := local.NewSystemsService().GetSystem(systemID, user.OrgRole, user.OrganizationID); helpers.HandleAccessError(c, err, "system", systemID) { + return + } + } + + repo := entities.NewLocalSystemFavoriteRepository() + var err error + if favorite { + err = repo.Add(userKey, systemID) + } else { + err = repo.Remove(userKey, systemID) + } + if err != nil { + logger.LogBusinessOperation(c, "systems", operation, "system", systemID, false, err) + c.JSON(http.StatusInternalServerError, response.InternalServerError("failed to update favorite system", nil)) + return + } + + logger.LogBusinessOperation(c, "systems", operation, "system", systemID, true, nil) + + message := "system removed from favorites" + if favorite { + message = "system added to favorites" + } + c.JSON(http.StatusOK, response.OK(message, gin.H{ + "system_id": systemID, + "is_favorite": favorite, + })) +} diff --git a/backend/methods/system_favorites_unit_test.go b/backend/methods/system_favorites_unit_test.go new file mode 100644 index 000000000..171881cbe --- /dev/null +++ b/backend/methods/system_favorites_unit_test.go @@ -0,0 +1,69 @@ +/* +Copyright (C) 2026 Nethesis S.r.l. +SPDX-License-Identifier: AGPL-3.0-or-later +*/ + +package methods + +import ( + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" + + "github.com/nethesis/my/backend/models" +) + +func TestFavoriteUserID(t *testing.T) { + logtoID := "logto-1" + empty := "" + tests := []struct { + name string + user *models.User + expected string + }{ + {"logto id wins over the local id", &models.User{ID: "local-1", LogtoID: &logtoID}, "logto-1"}, + {"owner without local row", &models.User{ID: "logto-1"}, "logto-1"}, + {"empty logto id falls back to the local id", &models.User{ID: "local-1", LogtoID: &empty}, "local-1"}, + {"nil user", nil, ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.expected, favoriteUserID(tt.user)) + }) + } +} + +func TestApplySystemFavoriteFilters(t *testing.T) { + gin.SetMode(gin.TestMode) + logtoID := "logto-1" + + tests := []struct { + name string + url string + user *models.User + wantOf string + wantFilter bool + }{ + {"caller scopes the flag", "/api/systems", &models.User{ID: "local-1", LogtoID: &logtoID}, "logto-1", false}, + {"favorite=true filters", "/api/systems?favorite=true", &models.User{LogtoID: &logtoID}, "logto-1", true}, + {"any other value does not filter", "/api/systems?favorite=1", &models.User{LogtoID: &logtoID}, "logto-1", false}, + {"no user in context stars nothing", "/api/systems?favorite=true", nil, "", true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest("GET", tt.url, nil) + if tt.user != nil { + c.Set("user", tt.user) + } + + var f models.SystemListFilters + applySystemFavoriteFilters(c, &f) + + assert.Equal(t, tt.wantOf, f.FavoritesOf) + assert.Equal(t, tt.wantFilter, f.FavoritesOnly) + }) + } +} diff --git a/backend/methods/systems.go b/backend/methods/systems.go index 87aec091c..8ee4950bd 100644 --- a/backend/methods/systems.go +++ b/backend/methods/systems.go @@ -195,6 +195,7 @@ func GetSystems(c *gin.Context) { Statuses: filterStatuses, Addons: filterAddons, } + applySystemFavoriteFilters(c, &filters) systems, totalCount, err := systemsService.GetSystemsByOrganizationPaginated( c.Request.Context(), userID, userOrgID, userOrgRole, page, pageSize, search, sortBy, sortDirection, filters, ) @@ -212,6 +213,7 @@ func GetSystems(c *gin.Context) { Strs("filter_organization_ids", filterOrgIDs). Strs("filter_statuses", filterStatuses). Strs("filter_addons", filterAddons). + Bool("filter_favorite", filters.FavoritesOnly). Str("sort_by", sortBy). Str("sort_direction", sortDirection). Msg("Failed to retrieve systems") @@ -263,6 +265,7 @@ func GetSystems(c *gin.Context) { Strs("filter_organization_ids", filterOrgIDs). Strs("filter_statuses", filterStatuses). Strs("filter_addons", filterAddons). + Bool("filter_favorite", filters.FavoritesOnly). Str("sort_by", sortBy). Str("sort_direction", sortDirection). Msg("Systems list requested") @@ -303,6 +306,14 @@ func GetSystem(c *gin.Context) { system.RebrandingEnabled, system.RebrandingOrgID = resolveRebranding(system.Organization.LogtoID) } + isFavorite, err := entities.NewLocalSystemFavoriteRepository().IsFavorite(favoriteUserID(user), system.ID) + if err != nil { + logger.RequestLogger(c, "systems").Warn().Err(err). + Str("system_id", systemID). + Msg("Failed to resolve favorite flag") + } + system.IsFavorite = isFavorite + // Log the action logger.RequestLogger(c, "systems").Info(). Str("operation", "get_system"). diff --git a/backend/methods/systems_export.go b/backend/methods/systems_export.go index 6bf040fbd..06de21f15 100644 --- a/backend/methods/systems_export.go +++ b/backend/methods/systems_export.go @@ -87,20 +87,22 @@ func ExportSystems(c *gin.Context) { // Create systems service systemsService := local.NewSystemsService() + listFilters := models.SystemListFilters{ + Name: filterName, + SystemKeys: filterSystemKey, + Types: filterTypes, + CreatedBy: filterCreatedBy, + Versions: filterVersions, + OrganizationIDs: filterOrgIDs, + ParentOrganizationIDs: filterParentOrgIDs, + Statuses: filterStatuses, + Addons: filterAddons, + } + applySystemFavoriteFilters(c, &listFilters) + // Get systems without pagination limit (but with max export limit) systems, totalCount, err := systemsService.GetSystemsByOrganizationPaginated( - c.Request.Context(), userID, userOrgID, userOrgRole, 1, MaxExportLimit, search, sortBy, sortDirection, - models.SystemListFilters{ - Name: filterName, - SystemKeys: filterSystemKey, - Types: filterTypes, - CreatedBy: filterCreatedBy, - Versions: filterVersions, - OrganizationIDs: filterOrgIDs, - ParentOrganizationIDs: filterParentOrgIDs, - Statuses: filterStatuses, - Addons: filterAddons, - }, + c.Request.Context(), userID, userOrgID, userOrgRole, 1, MaxExportLimit, search, sortBy, sortDirection, listFilters, ) if err != nil { @@ -139,6 +141,9 @@ func ExportSystems(c *gin.Context) { if parents := c.QueryArray("parent_organization_id"); len(parents) > 0 { filters["parent_organization_id"] = strings.Join(parents, ", ") } + if listFilters.FavoritesOnly { + filters["favorite"] = true + } // Create export service exportService := export.NewSystemsExportService() diff --git a/backend/models/systems.go b/backend/models/systems.go index 13278548f..1a9aa6664 100644 --- a/backend/models/systems.go +++ b/backend/models/systems.go @@ -107,6 +107,10 @@ type System struct { RebrandingEnabled bool `json:"rebranding_enabled"` RebrandingOrgID *string `json:"rebranding_org_id,omitempty"` + // IsFavorite reports whether the caller starred the system. It is + // personal: two users reading the same system can get different values. + IsFavorite bool `json:"is_favorite"` + // Addons lists the catalog ids of the add-ons granted and still valid on // the system. The list endpoint fills it only when asked // (include_addons=true): it costs one extra query per page, which an @@ -128,6 +132,11 @@ type SystemListFilters struct { ParentOrganizationIDs []string // "Managed by": owning organization within these subtrees Statuses []string // unified status, including suspended/no_inventory Addons []string // catalog ids of add-ons the system must hold + + // FavoritesOf is the Logto ID of the caller: it fills IsFavorite and + // enables the favorite sort. Empty leaves every system unstarred. + FavoritesOf string + FavoritesOnly bool // only the systems FavoritesOf starred } // IsSuspended returns true if the system is suspended diff --git a/backend/openapi.yaml b/backend/openapi.yaml index a37b79bff..a7a21a65c 100644 --- a/backend/openapi.yaml +++ b/backend/openapi.yaml @@ -2224,6 +2224,25 @@ components: description: Cumulative count at this date example: 15 + SystemFavoriteResponse: + type: object + properties: + code: + type: integer + example: 200 + message: + type: string + example: "system added to favorites" + data: + type: object + properties: + system_id: + type: string + example: "sys_123456789" + is_favorite: + type: boolean + example: true + System: type: object properties: @@ -2369,6 +2388,10 @@ components: nullable: true description: Logto organization ID (logto_id) that provides the rebranding assets (the org itself or an ancestor). Use this value as the :org_id parameter in /api/rebranding/:org_id/* endpoints. example: "org_dist001" + is_favorite: + type: boolean + description: Whether the caller starred the system. Personal, so two users reading the same system can get different values. + example: false addons: type: array description: | @@ -4743,11 +4766,13 @@ components: SystemSortByParam: name: sort_by in: query - description: Field to sort systems by + description: >- + Field to sort systems by. `favorite` lists the caller's favorites first + in ascending order, last in descending order. required: false schema: type: string - enum: ["name", "type", "status", "fqdn", "version", "system_key", "created_at", "updated_at", "creator_name", "organization_name", "managed_by"] + enum: ["name", "type", "status", "fqdn", "version", "system_key", "created_at", "updated_at", "creator_name", "organization_name", "managed_by", "favorite"] example: "name" TrendPeriodParam: @@ -4983,6 +5008,18 @@ components: style: form explode: true + SystemFavoriteFilterParam: + name: favorite + in: query + description: | + Only the systems the caller starred (see PUT /api/systems/{id}/favorite). + Favorites are personal: with an impersonation token they are the + target's. + required: false + schema: + type: boolean + example: true + IncludeAddonsParam: name: include_addons in: query @@ -11227,6 +11264,7 @@ paths: - $ref: '#/components/parameters/ParentOrganizationFilterParam' - $ref: '#/components/parameters/SystemStatusFilterParam' - $ref: '#/components/parameters/SystemAddonFilterParam' + - $ref: '#/components/parameters/SystemFavoriteFilterParam' - $ref: '#/components/parameters/IncludeAddonsParam' responses: '200': @@ -11545,6 +11583,89 @@ paths: '404': $ref: '#/components/responses/NotFound' + /systems/{id}/favorite: + put: + operationId: addSystemFavorite + servers: + - url: https://my.nethesis.it/backend/api + description: Backend API server + tags: + - Backend - Systems + summary: /systems/{id}/favorite - Star a system + description: | + Add the system to the caller's favorites. Favorites are personal and + change nothing on the system, so read:systems is enough. Starring a + system already starred succeeds without changes. The system must be + visible to the caller and not archived. + + Refused with an API key and with an impersonation token. + parameters: + - name: id + in: path + required: true + description: System ID + schema: + type: string + example: "sys_123456789" + responses: + '200': + description: System added to favorites + content: + application/json: + schema: + $ref: '#/components/schemas/SystemFavoriteResponse' + example: + code: 200 + message: "system added to favorites" + data: + system_id: "sys_123456789" + is_favorite: true + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + delete: + operationId: removeSystemFavorite + servers: + - url: https://my.nethesis.it/backend/api + description: Backend API server + tags: + - Backend - Systems + summary: /systems/{id}/favorite - Unstar a system + description: | + Remove the system from the caller's favorites. It succeeds when the + system was not starred, and also for a system the caller can no longer + see or that was archived, so a stale favorite can always be removed. + + Refused with an API key and with an impersonation token. + parameters: + - name: id + in: path + required: true + description: System ID + schema: + type: string + example: "sys_123456789" + responses: + '200': + description: System removed from favorites + content: + application/json: + schema: + $ref: '#/components/schemas/SystemFavoriteResponse' + example: + code: 200 + message: "system removed from favorites" + data: + system_id: "sys_123456789" + is_favorite: false + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + /systems/{id}/destroy: delete: operationId: destroySystem @@ -12011,6 +12132,7 @@ paths: - $ref: '#/components/parameters/ParentOrganizationFilterParam' - $ref: '#/components/parameters/SystemStatusFilterParam' - $ref: '#/components/parameters/SystemAddonFilterParam' + - $ref: '#/components/parameters/SystemFavoriteFilterParam' responses: '200': description: Export file generated successfully diff --git a/docs/docs/systems/management.md b/docs/docs/systems/management.md index 9cd043043..b51e32326 100644 --- a/docs/docs/systems/management.md +++ b/docs/docs/systems/management.md @@ -88,7 +88,7 @@ The `system_secret` is shown **only once** during creation. Copy and save it imm Navigate to **Systems** to see: -- System name +- System name, with a star to add it to your [favorites](#favorite-systems) - Type (ns8, nsec, etc.) - Version, with an update icon when an update is available - FQDN and IP addresses @@ -107,14 +107,36 @@ Use filters to find specific systems: - **Organization**: Filter by customer organization - **Created By**: Filter by user who created the system - **Add-on**: Filter by purchased add-on (see [Add-ons](../features/entitlements.md)) +- **Favorites**: all systems, or only the ones you starred (see [Favorite Systems](#favorite-systems)) - **Status**: unknown, active, inactive, suspended, deleted -- **Sort By**: Name, version, FQDN/IP address, Organization, Created By, Status +- **Sort By**: Name, version, FQDN/IP address, Organization, Created By, Status, Favorite The **Add-on** menu lists the add-ons held by at least one of your systems, so an option never comes back empty. Selecting more than one widens the search: a system matches when it holds any of them. Only add-ons that are valid at that moment count, so an expired or cancelled one leaves the system out. +### Favorite Systems + +Star the systems you work on most to find them quickly. Click the star next to +the system name, in the systems list or in the header of the system page; click +it again to remove the system from your favorites. In the systems list, the +star of a system that is not a favorite shows when you point at its row; the +**Add to favorites** and **Remove from favorites** options of the row's menu +do the same. + +- Favorites are personal: each user has their own, and starring a system + changes nothing for anyone else +- Every user who can see a system can star it, read-only roles included +- Your favorites follow you on every browser and device +- An archived system leaves your favorites list and comes back when it is + restored; a permanently deleted one is removed for good +- While impersonating another user, their favorites are shown but cannot be + changed + +Use the **Favorites** filter to list only your favorites, or sort by +**Favorite** to bring them to the top. + ### System Details Click on a system to view comprehensive information: diff --git a/docs/i18n/it/docusaurus-plugin-content-docs/current/systems/management.md b/docs/i18n/it/docusaurus-plugin-content-docs/current/systems/management.md index 9f5b50c93..54dcf22e8 100644 --- a/docs/i18n/it/docusaurus-plugin-content-docs/current/systems/management.md +++ b/docs/i18n/it/docusaurus-plugin-content-docs/current/systems/management.md @@ -83,7 +83,7 @@ Il `system_secret` viene mostrato **una sola volta**, alla creazione. Copialo e La pagina **Sistemi** mostra tutti i sistemi visibili con: -- Nome del sistema +- Nome del sistema, con una stella per aggiungerlo ai [preferiti](#sistemi-preferiti) - Tipo (NethServer o NethSecurity) - Versione, con un'icona di aggiornamento quando è disponibile un aggiornamento - Organizzazione @@ -100,8 +100,9 @@ Usa i filtri per trovare sistemi specifici: - **Organizzazione**: filtra per organizzazione cliente - **Creato da**: filtra per utente che ha creato il sistema - **Add-on**: filtra per add-on acquistato (vedi [Add-on](../features/entitlements.md)) +- **Preferiti**: tutti i sistemi, o solo quelli che hai aggiunto ai preferiti (vedi [Sistemi preferiti](#sistemi-preferiti)) - **Stato**: unknown, active, inactive, suspended, deleted -- **Ordinamento**: nome, versione, FQDN/indirizzo IP, organizzazione, creato da, stato +- **Ordinamento**: nome, versione, FQDN/indirizzo IP, organizzazione, creato da, stato, preferito Il menu **Add-on** elenca gli add-on posseduti da almeno uno dei tuoi sistemi, quindi un'opzione non restituisce mai un elenco vuoto. Selezionandone più di uno @@ -109,6 +110,28 @@ la ricerca si allarga: un sistema corrisponde se ne possiede almeno uno. Contano solo gli add-on validi in quel momento, quindi uno scaduto o annullato esclude il sistema. +### Sistemi Preferiti + +Aggiungi ai preferiti i sistemi su cui lavori più spesso per trovarli subito. +Fai clic sulla stella accanto al nome del sistema, nell'elenco dei sistemi o +nell'intestazione della pagina del sistema; fai clic di nuovo per rimuoverlo dai +preferiti. Nell'elenco dei sistemi, la stella di un sistema che non è tra i +preferiti appare quando passi il mouse sulla sua riga; le opzioni **Aggiungi ai +preferiti** e **Rimuovi dai preferiti** del menu della riga fanno lo stesso. + +- I preferiti sono personali: ogni utente ha i suoi, e aggiungere un sistema ai + preferiti non cambia nulla per gli altri +- Ogni utente che vede un sistema può aggiungerlo ai preferiti, anche con un + ruolo di sola lettura +- I preferiti ti seguono su ogni browser e dispositivo +- Un sistema archiviato esce dall'elenco dei preferiti e ci torna quando viene + ripristinato; uno eliminato definitivamente viene rimosso per sempre +- Mentre impersoni un altro utente vedi i suoi preferiti, ma non puoi + modificarli + +Usa il filtro **Preferiti** per elencare solo i tuoi preferiti, oppure ordina per +**Preferito** per portarli in cima. + ### Dettagli Sistema Cliccando su un sistema si accede alle informazioni complete: diff --git a/frontend/src/assets/main.css b/frontend/src/assets/main.css index d4f47bbd3..3efcd1964 100644 --- a/frontend/src/assets/main.css +++ b/frontend/src/assets/main.css @@ -56,6 +56,8 @@ --animate-spin-relaxed: spin 1.5s linear infinite; --animate-fade-in: fade-in 0.3s ease-in; --animate-fade-in-relaxed: fade-in 0.6s ease-in; + /* one-shot feedback when a system is starred, so it follows the duration scale */ + --animate-favorite-pop: favorite-pop var(--duration-large-enter) ease-out; @keyframes fade-in { from { @@ -65,6 +67,21 @@ opacity: 1; } } + + @keyframes favorite-pop { + 0% { + transform: scale(1) rotate(0deg); + } + 40% { + transform: scale(1.35) rotate(-12deg); + } + 70% { + transform: scale(0.95) rotate(4deg); + } + 100% { + transform: scale(1) rotate(0deg); + } + } } /* inline, so the utility carries the value itself and each element resolves its own delay: a diff --git a/frontend/src/components/systems/SystemFavoriteToggle.test.ts b/frontend/src/components/systems/SystemFavoriteToggle.test.ts new file mode 100644 index 000000000..05ec9875e --- /dev/null +++ b/frontend/src/components/systems/SystemFavoriteToggle.test.ts @@ -0,0 +1,116 @@ +// Copyright (C) 2026 Nethesis S.r.l. +// SPDX-License-Identifier: GPL-3.0-or-later + +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import { createI18n } from 'vue-i18n' +import { createPinia, setActivePinia } from 'pinia' +import { PiniaColada } from '@pinia/colada' +import SystemFavoriteToggle from './SystemFavoriteToggle.vue' +import { useLoginStore } from '@/stores/login' + +const setSystemFavorite = vi.fn() + +vi.mock('@/lib/systems/systems', () => ({ + SYSTEMS_KEY: 'systems', + setSystemFavorite: (systemId: string, favorite: boolean) => setSystemFavorite(systemId, favorite), +})) + +vi.mock('@/stores/login', async () => { + const { defineStore } = await import('pinia') + const { ref } = await import('vue') + return { + useLoginStore: defineStore('login', () => ({ isImpersonating: ref(false) })), + } +}) + +const i18n = createI18n({ legacy: false, locale: 'en', missingWarn: false, fallbackWarn: false }) + +let pinia: ReturnType + +beforeEach(() => { + setSystemFavorite.mockReset() + pinia = createPinia() + setActivePinia(pinia) + vi.spyOn(console, 'error').mockImplementation(() => {}) +}) + +const mountToggle = (isFavorite = false, revealOnRowHover = false) => + mount(SystemFavoriteToggle, { + props: { systemId: 'sys-1', systemName: 'Alpha', isFavorite, revealOnRowHover }, + global: { plugins: [i18n, pinia, PiniaColada] }, + }) + +describe('SystemFavoriteToggle', () => { + it('stars the system at once and plays the pop', async () => { + setSystemFavorite.mockResolvedValue({}) + const wrapper = mountToggle(false) + + await wrapper.find('button').trigger('click') + + expect(setSystemFavorite).toHaveBeenCalledWith('sys-1', true) + expect(wrapper.find('button').attributes('aria-pressed')).toBe('true') + expect(wrapper.find('svg').classes()).toContain('animate-favorite-pop') + }) + + it('unstars without the pop', async () => { + setSystemFavorite.mockResolvedValue({}) + const wrapper = mountToggle(true) + + await wrapper.find('button').trigger('click') + + expect(setSystemFavorite).toHaveBeenCalledWith('sys-1', false) + expect(wrapper.find('button').attributes('aria-pressed')).toBe('false') + expect(wrapper.find('svg').classes()).not.toContain('animate-favorite-pop') + }) + + it('pops when the system is starred elsewhere, such as the kebab menu', async () => { + const wrapper = mountToggle(false) + + await wrapper.setProps({ isFavorite: true }) + + expect(wrapper.find('button').attributes('aria-pressed')).toBe('true') + expect(wrapper.find('svg').classes()).toContain('animate-favorite-pop') + }) + + it('does not pop on render, even when starred', () => { + const wrapper = mountToggle(true) + + expect(wrapper.find('svg').classes()).not.toContain('animate-favorite-pop') + }) + + it('reverts the star when the request fails', async () => { + setSystemFavorite.mockRejectedValue(new Error('network')) + const wrapper = mountToggle(false) + + await wrapper.find('button').trigger('click') + await flushPromises() + + expect(wrapper.find('button').attributes('aria-pressed')).toBe('false') + expect(wrapper.find('svg').classes()).not.toContain('animate-favorite-pop') + }) + + it('cannot be toggled while impersonating', async () => { + const wrapper = mountToggle(true) + useLoginStore().isImpersonating = true + await wrapper.vm.$nextTick() + + const button = wrapper.find('button') + expect(button.attributes('disabled')).toBeDefined() + await button.trigger('click') + expect(setSystemFavorite).not.toHaveBeenCalled() + }) + + it('hides the outline star until the row is hovered', () => { + const wrapper = mountToggle(false, true) + + expect(wrapper.find('button').classes()).toContain('opacity-0') + expect(wrapper.find('button').classes()).toContain('group-hover/row:opacity-100') + }) + + it('always shows the full star', () => { + const wrapper = mountToggle(true, true) + + expect(wrapper.find('button').classes()).not.toContain('opacity-0') + }) +}) diff --git a/frontend/src/components/systems/SystemFavoriteToggle.vue b/frontend/src/components/systems/SystemFavoriteToggle.vue new file mode 100644 index 000000000..4314ad6c3 --- /dev/null +++ b/frontend/src/components/systems/SystemFavoriteToggle.vue @@ -0,0 +1,131 @@ + + + + + diff --git a/frontend/src/components/systems/SystemsTable.vue b/frontend/src/components/systems/SystemsTable.vue index 56af7530f..5f38dd7a9 100644 --- a/frontend/src/components/systems/SystemsTable.vue +++ b/frontend/src/components/systems/SystemsTable.vue @@ -20,6 +20,7 @@ import { faCirclePlay, faBomb, faTriangleExclamation, + faStar, } from '@fortawesome/free-solid-svg-icons' import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome' import { @@ -48,6 +49,8 @@ import { useI18n } from 'vue-i18n' import { savePageSizeToStorage } from '@/lib/tablePageSize' import { canManageSystems, canDestroySystems } from '@/lib/permissions' import { useSystems } from '@/queries/systems/systems' +import { useSetSystemFavorite } from '@/queries/systems/favoriteSystems' +import { useLoginStore } from '@/stores/login' import { exportSystem, getProductName, @@ -79,6 +82,7 @@ import { import OrganizationIconAndLink from '../organizations/OrganizationIconAndLink.vue' import ParentCompanyLink from '@/components/organizations/ParentCompanyLink.vue' import SystemLogoAndLink from './SystemLogoAndLink.vue' +import SystemFavoriteToggle from './SystemFavoriteToggle.vue' const { isShownCreateSystemDrawer = false } = defineProps<{ isShownCreateSystemDrawer: boolean @@ -99,13 +103,17 @@ const { organizationFilter, parentOrganizationFilter, addonFilter, + favoriteFilter, sortBy, sortDescending, areDefaultFiltersApplied, resetFilters, + resetFavoriteFilter, resetStatusFilter, } = useSystems() const { state: systemFiltersState } = useSystemFilters() +const { mutate: setSystemFavorite } = useSetSystemFavorite() +const loginStore = useLoginStore() const currentSystem = ref() const isShownCreateOrEditSystemDrawer = ref(false) @@ -138,6 +146,11 @@ const statusFilterOptions = ref([ { id: 'deleted', label: t('systems.status_deleted') }, ]) +const favoriteFilterOptions = ref([ + { id: 'all', label: t('systems.all_systems') }, + { id: 'favorites', label: t('systems.favorites_only') }, +]) + const systemsPage = computed(() => { return state.value.data?.systems }) @@ -283,6 +296,19 @@ function getKebabMenuItems(system: System) { }) } + // an archived system cannot be starred, and favorites belong to the real + // account: the star tells the impersonator why, the menu just omits it + if (!isDeleted && !loginStore.isImpersonating) { + items.push({ + id: 'toggleFavorite', + label: system.is_favorite + ? t('systems.remove_from_favorites') + : t('systems.add_to_favorites'), + icon: faStar, + action: () => setSystemFavorite({ systemId: system.id, favorite: !system.is_favorite }), + }) + } + items.push( { id: 'exportToPdf', @@ -402,6 +428,22 @@ function onCloseSecretRegeneratedModal() { :placeholder="$t('systems.filter_systems')" class="max-w-48 sm:max-w-sm" /> + + - + -
+
+ +
diff --git a/frontend/src/i18n/en/translation.json b/frontend/src/i18n/en/translation.json index 5919b926a..e33e36ffd 100644 --- a/frontend/src/i18n/en/translation.json +++ b/frontend/src/i18n/en/translation.json @@ -872,7 +872,16 @@ "open_legacy_my": "Open legacy My Nethesis", "organization_systems": "Systems", "organization_id_system_not_registered": "Company cannot be changed until the system is registered. To change it now, delete and re-create the system.", - "cannot_check_addon_renewals": "Cannot check add-on renewals" + "cannot_check_addon_renewals": "Cannot check add-on renewals", + "favorites": "Favorites", + "favorite": "Favorite", + "all_systems": "All systems", + "favorites_only": "Favorites only", + "add_to_favorites": "Add to favorites", + "remove_from_favorites": "Remove from favorites", + "add_system_to_favorites": "Add {name} to favorites", + "remove_system_from_favorites": "Remove {name} from favorites", + "favorites_not_available_impersonating": "You cannot change favorites while impersonating another user" }, "system_detail": { "title": "System detail", diff --git a/frontend/src/i18n/it/translation.json b/frontend/src/i18n/it/translation.json index 48400ee23..c701d48c5 100644 --- a/frontend/src/i18n/it/translation.json +++ b/frontend/src/i18n/it/translation.json @@ -790,7 +790,16 @@ "open_legacy_my": "Apri My Nethesis legacy", "organization_systems": "Sistemi", "organization_id_system_not_registered": "L'azienda non può essere modificata finché il sistema non è registrato. Per modificarla ora, elimina e ricrea il sistema.", - "cannot_check_addon_renewals": "Impossibile verificare i rinnovi degli add-on" + "cannot_check_addon_renewals": "Impossibile verificare i rinnovi degli add-on", + "favorites": "Preferiti", + "favorite": "Preferito", + "all_systems": "Tutti i sistemi", + "favorites_only": "Solo preferiti", + "add_to_favorites": "Aggiungi ai preferiti", + "remove_from_favorites": "Rimuovi dai preferiti", + "add_system_to_favorites": "Aggiungi {name} ai preferiti", + "remove_system_from_favorites": "Rimuovi {name} dai preferiti", + "favorites_not_available_impersonating": "Non puoi modificare i preferiti mentre impersoni un altro utente" }, "system_detail": { "title": "Dettaglio sistema", diff --git a/frontend/src/lib/systems/systems.test.ts b/frontend/src/lib/systems/systems.test.ts index ae02147c2..3ccdbcd7a 100644 --- a/frontend/src/lib/systems/systems.test.ts +++ b/frontend/src/lib/systems/systems.test.ts @@ -227,3 +227,37 @@ describe('systems Managed by filter', () => { expect(params.has('parent_organization_id')).toBe(false) }) }) + +describe('systems favorites filter', () => { + it('sends favorite=true on the list only when asked', () => { + const favorites = parse( + getQueryStringParams(1, 50, '', [], [], [], [], [], [], 'name', false, [], true), + ) + const all = parse(getQueryStringParams(1, 50, '', [], [], [], [], [], [], 'name', false)) + + expect(favorites.get('favorite')).toBe('true') + expect(all.has('favorite')).toBe(false) + }) + + it('sends the same filter on the export', () => { + const params = parse( + getQueryStringParamsForExport( + 'pdf', + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + true, + ), + ) + + expect(params.get('favorite')).toBe('true') + }) +}) diff --git a/frontend/src/lib/systems/systems.ts b/frontend/src/lib/systems/systems.ts index 8d862e781..30562814b 100644 --- a/frontend/src/lib/systems/systems.ts +++ b/frontend/src/lib/systems/systems.ts @@ -64,6 +64,9 @@ export const SystemSchema = v.object({ first_heartbeat: v.optional(v.string()), first_inventory: v.optional(v.string()), rebranding_enabled: v.optional(v.boolean()), + // Whether the signed-in user starred the system: personal, not a property + // of the system + is_favorite: v.optional(v.boolean()), // Add-on catalog ids granted and valid right now. The list endpoint sends // them only when asked with include_addons, and omits the key for a system // holding none. @@ -99,7 +102,8 @@ export type EditSystem = v.InferOutput export type System = v.InferOutput // organization_name: the assigned company; managed_by: the company getManagedBy // returns for it -export type SystemSortBy = keyof System | 'organization_name' | 'managed_by' +// favorite: the systems the signed-in user starred first (or last) +export type SystemSortBy = keyof System | 'organization_name' | 'managed_by' | 'favorite' export type SystemStatus = v.InferOutput interface SystemsResponse { @@ -151,6 +155,7 @@ export const getQueryStringParams = ( sortBy: string | null, sortDescending: boolean, parentOrganizationFilter: string[] = [], + favoritesOnly = false, ) => { const searchParams = new URLSearchParams({ page: pageNum.toString(), @@ -191,6 +196,10 @@ export const getQueryStringParams = ( addonFilter.forEach((addon) => { searchParams.append('addon', addon) }) + + if (favoritesOnly) { + searchParams.append('favorite', 'true') + } return searchParams.toString() } @@ -207,6 +216,7 @@ export const getQueryStringParamsForExport = ( sortBy: string | undefined, sortDescending: boolean | undefined, parentOrganizationFilter: string[] | undefined = undefined, + favoritesOnly = false, ) => { const searchParams = new URLSearchParams({ format: format, @@ -269,6 +279,10 @@ export const getQueryStringParamsForExport = ( if (sortDescending !== undefined) { searchParams.append('sort_direction', sortDescending ? 'desc' : 'asc') } + + if (favoritesOnly) { + searchParams.append('favorite', 'true') + } return searchParams.toString() } @@ -285,6 +299,7 @@ export const getSystems = ( sortBy: string, sortDescending: boolean, parentOrganizationFilter: string[] = [], + favoritesOnly = false, ) => { const loginStore = useLoginStore() const params = getQueryStringParams( @@ -300,6 +315,7 @@ export const getSystems = ( sortBy, sortDescending, parentOrganizationFilter, + favoritesOnly, ) return axios @@ -377,6 +393,15 @@ export const restoreSystem = (system: System) => { ) } +// Stars or unstars a system for the signed-in user. Both calls are idempotent. +export const setSystemFavorite = (systemId: string, favorite: boolean) => { + const loginStore = useLoginStore() + const url = `${API_URL}/systems/${systemId}/favorite` + const headers = { Authorization: `Bearer ${loginStore.jwtToken}` } + + return favorite ? axios.put(url, {}, { headers }) : axios.delete(url, { headers }) +} + export const regenerateSystemSecret = (systemId: string) => { const loginStore = useLoginStore() @@ -454,6 +479,7 @@ export const getExport = ( sortBy: string | undefined = undefined, sortDescending: boolean | undefined = undefined, parentOrganizationFilter: string[] | undefined = undefined, + favoritesOnly = false, ) => { const loginStore = useLoginStore() const params = getQueryStringParamsForExport( @@ -469,6 +495,7 @@ export const getExport = ( sortBy, sortDescending, parentOrganizationFilter, + favoritesOnly, ) return axios diff --git a/frontend/src/queries/systems/favoriteSystems.ts b/frontend/src/queries/systems/favoriteSystems.ts new file mode 100644 index 000000000..0a3bf3881 --- /dev/null +++ b/frontend/src/queries/systems/favoriteSystems.ts @@ -0,0 +1,24 @@ +// Copyright (C) 2026 Nethesis S.r.l. +// SPDX-License-Identifier: GPL-3.0-or-later + +import { setSystemFavorite, SYSTEMS_KEY } from '@/lib/systems/systems' +import { useMutation, useQueryCache } from '@pinia/colada' + +// stars or unstars a system: the star next to its name and the kebab menu of +// the table share it +export function useSetSystemFavorite() { + const queryCache = useQueryCache() + + return useMutation({ + mutation: ({ systemId, favorite }: { systemId: string; favorite: boolean }) => + setSystemFavorite(systemId, favorite), + onError: (error) => { + // the axios interceptor already notifies the failure + console.error('Cannot update favorite system:', error) + }, + onSettled: () => { + // lists, detail and the dashboard card all carry the flag + queryCache.invalidateQueries({ key: [SYSTEMS_KEY] }) + }, + }) +} diff --git a/frontend/src/queries/systems/systems.ts b/frontend/src/queries/systems/systems.ts index c339ea615..58d8133ac 100644 --- a/frontend/src/queries/systems/systems.ts +++ b/frontend/src/queries/systems/systems.ts @@ -36,6 +36,9 @@ export const useSystems = defineQuery(() => { // these organizations (ANDed with organizationFilter) const parentOrganizationFilter = ref([]) const addonFilter = ref([]) + // radio filter: 'all' or 'favorites', the systems the signed-in user starred + const favoriteFilter = ref([{ id: 'all', label: 'all' }]) + const favoritesOnly = computed(() => favoriteFilter.value.some((o) => o.id === 'favorites')) const sortBy = ref('name') const sortDescending = ref(false) @@ -52,6 +55,7 @@ export const useSystems = defineQuery(() => { organizationFilter: organizationFilter.value.map((o) => o.id), parentOrganizationFilter: parentOrganizationFilter.value.map((o) => o.id), addonFilter: addonFilter.value.map((o) => o.id), + favoritesOnly: favoritesOnly.value, sortBy: sortBy.value, sortDirection: sortDescending.value, }, @@ -71,6 +75,7 @@ export const useSystems = defineQuery(() => { sortBy.value, sortDescending.value, parentOrganizationFilter.value.map((o) => o.id), + favoritesOnly.value, ), }) @@ -82,6 +87,7 @@ export const useSystems = defineQuery(() => { organizationFilter.value.length === 0 && parentOrganizationFilter.value.length === 0 && addonFilter.value.length === 0 && + !favoritesOnly.value && statusFilter.value.length === 4 && statusFilter.value.some((o) => o.id === 'active') && statusFilter.value.some((o) => o.id === 'inactive') && @@ -163,6 +169,14 @@ export const useSystems = defineQuery(() => { }, ) + // reset to first page when favorite filter changes + watch( + () => favoritesOnly.value, + () => { + pageNum.value = 1 + }, + ) + // watch the selected org ids by value (not the array reference): reset to the // first page when the assigned company selection changes watch( @@ -179,9 +193,14 @@ export const useSystems = defineQuery(() => { organizationFilter.value = [] parentOrganizationFilter.value = [] addonFilter.value = [] + resetFavoriteFilter() resetStatusFilter() } + const resetFavoriteFilter = () => { + favoriteFilter.value = [{ id: 'all', label: 'all' }] + } + const resetStatusFilter = () => { statusFilter.value = [ { id: 'active', label: 'active' }, @@ -204,11 +223,14 @@ export const useSystems = defineQuery(() => { organizationFilter, parentOrganizationFilter, addonFilter, + favoriteFilter, + favoritesOnly, debouncedTextFilter, sortBy, sortDescending, areDefaultFiltersApplied, resetFilters, + resetFavoriteFilter, resetStatusFilter, } }) diff --git a/frontend/src/views/SystemDetailView.vue b/frontend/src/views/SystemDetailView.vue index eb4e91d39..87d3faf6a 100644 --- a/frontend/src/views/SystemDetailView.vue +++ b/frontend/src/views/SystemDetailView.vue @@ -29,6 +29,7 @@ import SystemChangeHistoryPanel from '@/components/systems/SystemChangeHistoryPa import SystemBackupsPanel from '@/components/systems/SystemBackupsPanel.vue' import SystemAlertsPanel from '@/components/systems/SystemAlertsPanel.vue' import SystemAddonsPanel from '@/components/systems/SystemAddonsPanel.vue' +import SystemFavoriteToggle from '@/components/systems/SystemFavoriteToggle.vue' import { useLatestInventory } from '@/queries/systems/latestInventory' import { useLoginStore } from '@/stores/login' @@ -91,9 +92,17 @@ const { tabs, selectedTab } = useTabs(tabsConfig)
- - {{ systemDetail.data?.name }} - +
+ + {{ systemDetail.data?.name }} + + +
o.id), + favoritesOnly.value, ) const fileName = exportFileName(t('systems.title'), format) downloadFile(exportData, fileName, format) From a8d86ec1420b097a0a527578eed2459413b5ecc0 Mon Sep 17 00:00:00 2001 From: Andrea Leardini Date: Fri, 20 Nov 2026 16:36:44 +0100 Subject: [PATCH 02/17] feat(systems): show system notes in the list Notes were visible only on the system page. An icon next to the name in the systems list now shows them in a tooltip, cut at ten lines, so the list tells which systems carry notes. Assisted-by: Claude Code:claude-sonnet-5-5 --- docs/docs/systems/management.md | 2 +- .../current/systems/management.md | 2 +- .../components/systems/SystemNotesIcon.vue | 35 +++++++++++++++++++ .../src/components/systems/SystemsTable.vue | 2 ++ 4 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 frontend/src/components/systems/SystemNotesIcon.vue diff --git a/docs/docs/systems/management.md b/docs/docs/systems/management.md index b51e32326..ae72d6b35 100644 --- a/docs/docs/systems/management.md +++ b/docs/docs/systems/management.md @@ -88,7 +88,7 @@ The `system_secret` is shown **only once** during creation. Copy and save it imm Navigate to **Systems** to see: -- System name, with a star to add it to your [favorites](#favorite-systems) +- System name, with a star to add it to your [favorites](#favorite-systems) and, when it has notes, an icon that shows them on hover (up to 10 lines) - Type (ns8, nsec, etc.) - Version, with an update icon when an update is available - FQDN and IP addresses diff --git a/docs/i18n/it/docusaurus-plugin-content-docs/current/systems/management.md b/docs/i18n/it/docusaurus-plugin-content-docs/current/systems/management.md index 54dcf22e8..a9d9f8df4 100644 --- a/docs/i18n/it/docusaurus-plugin-content-docs/current/systems/management.md +++ b/docs/i18n/it/docusaurus-plugin-content-docs/current/systems/management.md @@ -83,7 +83,7 @@ Il `system_secret` viene mostrato **una sola volta**, alla creazione. Copialo e La pagina **Sistemi** mostra tutti i sistemi visibili con: -- Nome del sistema, con una stella per aggiungerlo ai [preferiti](#sistemi-preferiti) +- Nome del sistema, con una stella per aggiungerlo ai [preferiti](#sistemi-preferiti) e, se ha delle note, un'icona che le mostra al passaggio del mouse (fino a 10 righe) - Tipo (NethServer o NethSecurity) - Versione, con un'icona di aggiornamento quando è disponibile un aggiornamento - Organizzazione diff --git a/frontend/src/components/systems/SystemNotesIcon.vue b/frontend/src/components/systems/SystemNotesIcon.vue new file mode 100644 index 000000000..7dea3d370 --- /dev/null +++ b/frontend/src/components/systems/SystemNotesIcon.vue @@ -0,0 +1,35 @@ + + + + + diff --git a/frontend/src/components/systems/SystemsTable.vue b/frontend/src/components/systems/SystemsTable.vue index 5f38dd7a9..e802875a2 100644 --- a/frontend/src/components/systems/SystemsTable.vue +++ b/frontend/src/components/systems/SystemsTable.vue @@ -83,6 +83,7 @@ import OrganizationIconAndLink from '../organizations/OrganizationIconAndLink.vu import ParentCompanyLink from '@/components/organizations/ParentCompanyLink.vue' import SystemLogoAndLink from './SystemLogoAndLink.vue' import SystemFavoriteToggle from './SystemFavoriteToggle.vue' +import SystemNotesIcon from './SystemNotesIcon.vue' const { isShownCreateSystemDrawer = false } = defineProps<{ isShownCreateSystemDrawer: boolean @@ -612,6 +613,7 @@ function onCloseSecretRegeneratedModal() { :system-name="item.name" :system-type="item.type" /> + Date: Fri, 20 Nov 2026 17:13:05 +0100 Subject: [PATCH 03/17] feat: show notes in company and application lists Distributors, resellers, customers and applications carry notes too, but the lists did not tell which ones have them. Their tables now show the same notes icon as the systems list, next to the name: its tooltip shows the notes, cut at ten lines. The icon moves to the common components, since five tables share it. Assisted-by: Claude Code:claude-opus-5-5 --- docs/docs/features/applications.md | 2 ++ docs/docs/platform/organizations.md | 2 +- .../current/features/applications.md | 2 ++ .../current/platform/organizations.md | 2 +- .../applications/ApplicationsTable.vue | 16 ++++++++----- .../NotesIcon.vue} | 4 ++-- .../components/customers/CustomersTable.vue | 24 +++++++++++-------- .../distributors/DistributorsTable.vue | 24 +++++++++++-------- .../components/resellers/ResellersTable.vue | 24 +++++++++++-------- .../src/components/systems/SystemsTable.vue | 4 ++-- 10 files changed, 62 insertions(+), 42 deletions(-) rename frontend/src/components/{systems/SystemNotesIcon.vue => common/NotesIcon.vue} (88%) diff --git a/docs/docs/features/applications.md b/docs/docs/features/applications.md index 82ad25fc3..a8930075e 100644 --- a/docs/docs/features/applications.md +++ b/docs/docs/features/applications.md @@ -76,6 +76,8 @@ You can add notes to applications to record additional context or operational in 3. Add or edit your notes 4. Save changes +In the applications list, an icon next to the name of an application with notes shows them on hover (up to 10 lines). + ## Totals and Trends The [Dashboard](./dashboard.md) displays the total count of applications visible to your account, with a badge linking to the unassigned ones. Growth over time is available from the API through `/backend/api/applications/trend`. diff --git a/docs/docs/platform/organizations.md b/docs/docs/platform/organizations.md index 2848faed3..48d870231 100644 --- a/docs/docs/platform/organizations.md +++ b/docs/docs/platform/organizations.md @@ -153,7 +153,7 @@ Each organization type has its own list view: 1. Navigate to **[Type]** (Distributors/Resellers/Customers) 2. View the list with the following information: - - Organization name + - Organization name, with an icon that shows its notes on hover (up to 10 lines) when it has any - Description - Number of users - Number of systems diff --git a/docs/i18n/it/docusaurus-plugin-content-docs/current/features/applications.md b/docs/i18n/it/docusaurus-plugin-content-docs/current/features/applications.md index 1d6a54d0d..0bbdc9646 100644 --- a/docs/i18n/it/docusaurus-plugin-content-docs/current/features/applications.md +++ b/docs/i18n/it/docusaurus-plugin-content-docs/current/features/applications.md @@ -73,6 +73,8 @@ Un'applicazione senza assegnazione non sparisce: torna a essere conteggiata sull 3. Aggiungi o modifica le note 4. Salva le modifiche +Nell'elenco delle applicazioni, un'icona accanto al nome di un'applicazione con note le mostra al passaggio del mouse (fino a 10 righe). + ## Totali e Trend La [Dashboard](./dashboard.md) mostra il totale delle applicazioni visibili al tuo account, con un badge che porta a quelle non assegnate. I dati di crescita nel tempo sono disponibili da API tramite `/backend/api/applications/trend`. diff --git a/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/organizations.md b/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/organizations.md index 5fba6f38d..fb353d539 100644 --- a/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/organizations.md +++ b/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/organizations.md @@ -153,7 +153,7 @@ Ogni tipo di organizzazione ha il proprio elenco: 1. Vai su **[Tipo]** (Distributori/Rivenditori/Clienti) 2. L'elenco mostra: - - Nome dell'organizzazione + - Nome dell'organizzazione, con un'icona che ne mostra le note al passaggio del mouse (fino a 10 righe), se ne ha - Descrizione - Numero di utenti - Numero di sistemi diff --git a/frontend/src/components/applications/ApplicationsTable.vue b/frontend/src/components/applications/ApplicationsTable.vue index bf13a88ca..707820139 100644 --- a/frontend/src/components/applications/ApplicationsTable.vue +++ b/frontend/src/components/applications/ApplicationsTable.vue @@ -48,6 +48,7 @@ import ApplicationLogo from './ApplicationLogo.vue' import { faGridOne } from '@nethesis/nethesis-solid-svg-icons' import AssignOrganizationDrawer from './AssignOrganizationDrawer.vue' import SetNotesDrawer from './SetNotesDrawer.vue' +import NotesIcon from '@/components/common/NotesIcon.vue' import { useApplicationFilters } from '@/queries/applications/applicationFilters' import { buildVersionFilterOptions } from '@/lib/applications/applicationFilters' import router from '@/router' @@ -344,12 +345,15 @@ const goToApplicationDetails = (application: Application) => { - - {{ getDisplayName(item) }} - +
+ + {{ getDisplayName(item) }} + + +
diff --git a/frontend/src/components/systems/SystemNotesIcon.vue b/frontend/src/components/common/NotesIcon.vue similarity index 88% rename from frontend/src/components/systems/SystemNotesIcon.vue rename to frontend/src/components/common/NotesIcon.vue index 7dea3d370..697a3ec47 100644 --- a/frontend/src/components/systems/SystemNotesIcon.vue +++ b/frontend/src/components/common/NotesIcon.vue @@ -2,8 +2,8 @@ Copyright (C) 2026 Nethesis S.r.l. SPDX-License-Identifier: GPL-3.0-or-later - Next to a system name, shows the system notes in a tooltip. Long notes are - cropped: the system details show them in full. + Next to the name of an object in a table, shows its notes in a tooltip. Long + notes are cropped: the detail page of the object shows them in full. --> diff --git a/frontend/src/i18n/en/translation.json b/frontend/src/i18n/en/translation.json index 754076017..d2907c588 100644 --- a/frontend/src/i18n/en/translation.json +++ b/frontend/src/i18n/en/translation.json @@ -514,6 +514,8 @@ "impersonation_ended": "Impersonation ended", "impersonation_expired_message": "The impersonation session has expired, you are now logged in as yourself.", "impersonation_timer_tooltip": "The impersonation session will end automatically in {timer}", + "extend_impersonation": "Extend session", + "impersonation_extended": "Impersonation session extended", "you_are_now_logged_in_as_yourself": "You are now logged in as yourself", "reset_password_confirmation": "Reset the password for user {name}? This will update the user's sign-in information.", "password_reset": "Password reset", @@ -745,6 +747,7 @@ "http_method": "HTTP method", "request_data": "Request data", "response_status": "Response status", + "action_session_extended": "Session extended", "action_session_start": "Impersonation started", "action_session_end": "Impersonation ended", "action_api_call": "API call", diff --git a/frontend/src/i18n/it/translation.json b/frontend/src/i18n/it/translation.json index 7fd702438..84273a53f 100644 --- a/frontend/src/i18n/it/translation.json +++ b/frontend/src/i18n/it/translation.json @@ -432,6 +432,8 @@ "impersonation_ended": "Impersonificazione terminata", "impersonation_expired_message": "La sessione di impersonificazione è scaduta, sei tornato ad usare il tuo account.", "impersonation_timer_tooltip": "La sessione di impersonificazione terminerà automaticamente tra {timer}", + "extend_impersonation": "Estendi sessione", + "impersonation_extended": "Sessione di impersonificazione estesa", "you_are_now_logged_in_as_yourself": "Sei tornato ad usare il tuo account", "reset_password_confirmation": "Reimpostare la password per l'utente {name}? Questo aggiornerà le informazioni di accesso dell'utente.", "password_reset": "Password reimpostata", @@ -663,6 +665,7 @@ "http_method": "Metodo HTTP", "request_data": "Dati della richiesta", "response_status": "Stato della risposta", + "action_session_extended": "Sessione estesa", "action_session_start": "Impersonificazione avviata", "action_session_end": "Impersonificazione terminata", "action_api_call": "Chiamata API", diff --git a/frontend/src/lib/impersonation.ts b/frontend/src/lib/impersonation.ts index f1db96bc0..6dc9a5032 100644 --- a/frontend/src/lib/impersonation.ts +++ b/frontend/src/lib/impersonation.ts @@ -16,6 +16,7 @@ interface ImpersonateResponse { impersonator: UserInfo session_id: string token: string + expires_in: number expires_at: string } } @@ -65,6 +66,23 @@ export const postImpersonate = (userId: string) => { }) } +// restarts the current session for a full duration: a new token, same session +export const postExtendImpersonation = () => { + const loginStore = useLoginStore() + + return axios + .post(`${API_URL}/${IMPERSONATE_PATH}/extend`, null, { + headers: { + Authorization: `Bearer ${loginStore.jwtToken}`, + }, + }) + .then((res) => res.data.data) + .catch((error) => { + console.error('Cannot extend impersonation:', error) + throw error + }) +} + export const deleteImpersonate = () => { const loginStore = useLoginStore() diff --git a/frontend/src/stores/login.ts b/frontend/src/stores/login.ts index 5e53cd326..0914b5395 100644 --- a/frontend/src/stores/login.ts +++ b/frontend/src/stores/login.ts @@ -16,7 +16,12 @@ import { useStorage } from '@vueuse/core' import { getPreference } from '@nethesis/vue-components' import { getBrowserLocale, setLocale } from '@/i18n' import router from '@/router' -import { deleteImpersonate, getImpersonationStatus, postImpersonate } from '@/lib/impersonation' +import { + deleteImpersonate, + getImpersonationStatus, + postExtendImpersonation, + postImpersonate, +} from '@/lib/impersonation' import { canImpersonateUsers } from '@/lib/permissions' import { organizationDetailRoute } from '@/lib/organizations/organizationDetailRoute' @@ -563,6 +568,16 @@ export const useLoginStore = defineStore('login', () => { } } + // the previous impersonation token is revoked: switch to the new one at once + const extendImpersonation = async () => { + const res = await postExtendImpersonation() + jwtToken.value = res.token + impersonatedUser.value = res.impersonated_user as UserInfo + userInfo.value = impersonatedUser.value + impersonateExpiration.value = new Date(res.expires_at) + return res + } + const exitImpersonation = async () => { try { const res = await deleteImpersonate() @@ -611,6 +626,7 @@ export const useLoginStore = defineStore('login', () => { pendingRefresh, refreshIdToken, impersonateUser, + extendImpersonation, exitImpersonation, login, logout, From cb8b0f04584d80a709cb4a3ec91416cfcf8718cc Mon Sep 17 00:00:00 2001 From: Andrea Leardini Date: Mon, 23 Nov 2026 14:46:55 +0100 Subject: [PATCH 10/17] fix: say delete, keep deleted objects to staff The design system calls the soft delete "Delete", not "Archive": the action, its status, modals and toasts now say Delete with the trash icon, Italian Destroy becomes "Distruggi" so it no longer clashes with "Elimina", and the delete, destroy and restore confirmations follow the writing guidelines. Deleted objects belong to the Owner organization: elsewhere the status filters drop "Deleted", the API refuses lists and exports filtered on status=deleted, and the restore routes refuse any other caller. The authz suite and the user manual follow. Assisted-by: Claude Code:claude-opus-5-5 --- AGENTS.md | 1 + backend/authz/routes.yml | 10 ++ backend/authz/scenarios.yml | 67 +++++++++++ backend/cmd/apitool/authz_lifecycle.go | 14 ++- backend/main.go | 10 +- backend/methods/customers.go | 3 + backend/methods/customers_export.go | 3 + backend/methods/deleted_objects.go | 33 ++++++ backend/methods/deleted_objects_unit_test.go | 49 ++++++++ backend/methods/distributors.go | 3 + backend/methods/distributors_export.go | 3 + backend/methods/resellers.go | 3 + backend/methods/resellers_export.go | 3 + backend/methods/systems.go | 5 +- backend/methods/systems_export.go | 3 + backend/methods/users.go | 3 + backend/methods/users_export.go | 3 + backend/openapi.yaml | 19 ++-- docs/docs/platform/organizations.md | 12 +- docs/docs/platform/users.md | 17 +-- docs/docs/systems/management.md | 18 +-- .../current/platform/organizations.md | 16 +-- .../current/platform/users.md | 17 +-- .../current/systems/management.md | 18 +-- frontend/e2e/fixtures/users.ts | 6 +- frontend/e2e/fullstack/users.spec.ts | 32 +++--- .../components/customers/CustomerInfoCard.vue | 6 +- .../components/customers/CustomersTable.vue | 30 ++--- .../customers/DeleteCustomerModal.vue | 12 +- .../distributors/DeleteDistributorModal.vue | 12 +- .../distributors/DistributorInfoCard.vue | 6 +- .../distributors/DistributorsTable.vue | 29 ++--- .../resellers/DeleteResellerModal.vue | 12 +- .../components/resellers/ResellerInfoCard.vue | 6 +- .../components/resellers/ResellersTable.vue | 24 ++-- .../components/systems/DeleteSystemModal.vue | 14 +-- .../src/components/systems/SystemInfoCard.vue | 6 +- .../components/systems/SystemStatusIcon.vue | 4 +- .../src/components/systems/SystemsTable.vue | 18 +-- .../src/components/users/DeleteUserModal.vue | 12 +- frontend/src/components/users/UsersTable.vue | 30 ++--- frontend/src/i18n/en/translation.json | 79 +++++++------ frontend/src/i18n/it/translation.json | 107 +++++++++--------- .../organizationTransfer.test.ts | 2 +- frontend/src/lib/permissions.ts | 4 + 45 files changed, 503 insertions(+), 281 deletions(-) create mode 100644 backend/methods/deleted_objects.go create mode 100644 backend/methods/deleted_objects_unit_test.go diff --git a/AGENTS.md b/AGENTS.md index 9230c84cc..ea5f07801 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -226,6 +226,7 @@ Embedded in the custom JWT at exchange time. No external calls during request ha - `middleware.RequireResourcePermission("systems")` — HTTP-verb-aware: `read:` on GET, `manage:` on **POST/PUT/PATCH/DELETE alike** (`middleware/rbac.go`). `destroy:` is never derived from the verb — an endpoint that needs it says so explicitly, e.g. `middleware.RequirePermission("destroy:systems")` on `/systems/:id/destroy` - `middleware.RequireResourcePermissionOrSelf("resellers")` — as above, plus a GET on the caller's own organization is always allowed (org roles carry permissions for the levels *below*, so without this a reseller could not read itself) - `middleware.PreventSelfModification()` — blocks a user from acting on their own account for dangerous verbs +- Soft-deleted objects belong to the Owner organization: outside it, a list or export with `status=deleted` gets 403 (`methods.rejectDeletedStatusOutsideOwnerOrg`) and the `/:id/restore` routes are gated by `middleware.RequireOrgRole(models.OwnerOrgRole)`. For everyone else, Delete is final - Hierarchy check for cross-org reads/writes: `local.UserService.IsOrganizationInHierarchy(orgRole, userOrgID, targetOrgID)` - RBAC filtering in SQL: `helpers.AppendOrgFilter(query, orgRole, orgID, tableAlias, args, nextArgIdx)` uses `GetAllowedOrgIDsForFilter` (cached org-ID set) for non-owner roles diff --git a/backend/authz/routes.yml b/backend/authz/routes.yml index 74975c00c..230ef6a23 100644 --- a/backend/authz/routes.yml +++ b/backend/authz/routes.yml @@ -226,6 +226,8 @@ routes: - method: PATCH path: /api/systems/:id/restore intent: manage:systems + org_role: owner + note: soft-deleted objects are seen and restored by the Owner organization only - method: DELETE path: /api/systems/:id/destroy intent: destroy:systems @@ -658,6 +660,8 @@ routes: - method: PATCH path: /api/distributors/:id/restore intent: manage:distributors + org_role: owner + note: soft-deleted objects are seen and restored by the Owner organization only - method: DELETE path: /api/distributors/:id/destroy intent: destroy:distributors @@ -716,6 +720,8 @@ routes: - method: PATCH path: /api/resellers/:id/restore intent: manage:resellers + org_role: owner + note: soft-deleted objects are seen and restored by the Owner organization only - method: DELETE path: /api/resellers/:id/destroy intent: destroy:resellers @@ -804,6 +810,8 @@ routes: - method: PATCH path: /api/customers/:id/restore intent: manage:customers + org_role: owner + note: soft-deleted objects are seen and restored by the Owner organization only - method: DELETE path: /api/customers/:id/destroy intent: destroy:customers @@ -882,6 +890,8 @@ routes: - method: PATCH path: /api/users/:id/restore intent: manage:users + org_role: owner + note: soft-deleted objects are seen and restored by the Owner organization only - method: DELETE path: /api/users/:id/destroy intent: destroy:users diff --git a/backend/authz/scenarios.yml b/backend/authz/scenarios.yml index e48886af3..a9c781d95 100644 --- a/backend/authz/scenarios.yml +++ b/backend/authz/scenarios.yml @@ -276,6 +276,73 @@ scenarios: path: /api/customers/{org:d1r2c1}/suspend expect: denied + # =========================================================================== + # Soft-deleted objects belong to the Owner organization: it alone sees and + # restores them, and for everyone else a Delete is final. Outside it, a list + # or an export filtered on status=deleted is refused, and so is a restore, + # even of an object inside the caller's own hierarchy. + # =========================================================================== + - name: distributor cannot list deleted resellers + as: d1-admin + method: GET + path: /api/resellers?status=deleted + expect_status: [403] + - name: reseller cannot list deleted customers + as: d1r1-admin + method: GET + path: /api/customers?status=deleted + expect_status: [403] + - name: reseller cannot list deleted users + as: d1r1-admin + method: GET + path: /api/users?status=deleted + expect_status: [403] + - name: customer cannot list deleted systems + as: d1r1c1-admin + method: GET + path: /api/systems?status=deleted + expect_status: [403] + - name: reseller cannot list deleted systems among other statuses + as: d1r1-admin + method: GET + path: /api/systems?status=active&status=deleted + expect_status: [403] + - name: reseller cannot export deleted customers + as: d1r1-admin + method: GET + path: /api/customers/export?format=csv&status=deleted + expect_status: [403] + - name: distributor cannot export deleted systems + as: d1-admin + method: GET + path: /api/systems/export?format=csv&status=deleted + expect_status: [403] + - name: staff can list deleted customers + as: owner-staff + method: GET + path: /api/customers?status=deleted + expect: allowed + - name: staff can list deleted users + as: owner-staff + method: GET + path: /api/users?status=deleted + expect: allowed + - name: reseller cannot restore its own customer + as: d1r1-admin + method: PATCH + path: /api/customers/{org:d1r1c1}/restore + expect_status: [403] + - name: reseller cannot restore its own user + as: d1r1-admin + method: PATCH + path: /api/users/{user:d1r1c1-admin}/restore + expect_status: [403] + - name: customer cannot restore its own system + as: d1r1c1-admin + method: PATCH + path: /api/systems/{system:s-d1r1c1}/restore + expect_status: [403] + - name: reseller cannot restore an organization outside its hierarchy as: d1r1-admin method: PATCH diff --git a/backend/cmd/apitool/authz_lifecycle.go b/backend/cmd/apitool/authz_lifecycle.go index eb4985777..1dd50c91e 100644 --- a/backend/cmd/apitool/authz_lifecycle.go +++ b/backend/cmd/apitool/authz_lifecycle.go @@ -231,7 +231,13 @@ func (lc *lcRun) systemDeleteRestore() error { "PATCH", "/api/systems/"+s+"/restore", nil, "denied"); err != nil { return err } - if _, err := lc.expect("customer admin restores its own system", "d1r1c1-admin", + // Restoring is the Owner organization's alone: for a partner, a Delete is + // final, even on its own system. + if _, err := lc.expect("customer admin cannot restore its own system", "d1r1c1-admin", + "PATCH", "/api/systems/"+s+"/restore", nil, "denied"); err != nil { + return err + } + if _, err := lc.expect("staff restores the system", "owner-staff", "PATCH", "/api/systems/"+s+"/restore", nil, "allowed"); err != nil { return err } @@ -301,7 +307,11 @@ func (lc *lcRun) customerDeleteRestoreAndPromotion() error { return err } lc.routed("customer: no route while deleted", lcr, "lc-c@", false) - if _, err := lc.expect("reseller admin restores its customer", adminKey, + if _, err := lc.expect("reseller admin cannot restore its own customer", adminKey, + "PATCH", "/api/customers/"+lcc+"/restore", nil, "denied"); err != nil { + return err + } + if _, err := lc.expect("staff restores the customer", "owner-staff", "PATCH", "/api/customers/"+lcc+"/restore", nil, "allowed"); err != nil { return err } diff --git a/backend/main.go b/backend/main.go index 22679f2b6..c6c5ad311 100644 --- a/backend/main.go +++ b/backend/main.go @@ -267,7 +267,7 @@ func main() { systemsGroup.GET("/:id/transfer", middleware.RequirePermission("manage:systems"), methods.GetSystemTransferPreview) // Restore and destroy endpoints - systemsGroup.PATCH("/:id/restore", methods.RestoreSystem) // Restore soft-deleted system (manage:systems required) + systemsGroup.PATCH("/:id/restore", middleware.RequireOrgRole(models.OwnerOrgRole), methods.RestoreSystem) // Restore soft-deleted system (manage:systems required) systemsGroup.DELETE("/:id/destroy", middleware.RequirePermission("destroy:systems"), methods.DestroySystem) // Permanently delete system (destroy:systems required) // Suspend and reactivate endpoints @@ -480,7 +480,7 @@ func main() { distributorsGroup.DELETE("/:id", methods.DeleteDistributor) // Soft-delete distributor (manage:distributors required) // Restore and destroy endpoints (cascade to users and systems) - distributorsGroup.PATCH("/:id/restore", methods.RestoreDistributor) // Restore soft-deleted distributor and cascade-deleted users/systems + distributorsGroup.PATCH("/:id/restore", middleware.RequireOrgRole(models.OwnerOrgRole), methods.RestoreDistributor) // Restore soft-deleted distributor and cascade-deleted users/systems distributorsGroup.DELETE("/:id/destroy", middleware.RequirePermission("destroy:distributors"), methods.DestroyDistributor) // Permanently delete distributor and all hierarchy (destroy:distributors required) // Suspend and reactivate endpoints (cascade to users) @@ -515,7 +515,7 @@ func main() { resellersGroup.DELETE("/:id", methods.DeleteReseller) // Soft-delete reseller (manage:resellers required) // Restore and destroy endpoints (cascade to users and systems) - resellersGroup.PATCH("/:id/restore", methods.RestoreReseller) // Restore soft-deleted reseller and cascade-deleted users/systems + resellersGroup.PATCH("/:id/restore", middleware.RequireOrgRole(models.OwnerOrgRole), methods.RestoreReseller) // Restore soft-deleted reseller and cascade-deleted users/systems resellersGroup.DELETE("/:id/destroy", middleware.RequirePermission("destroy:resellers"), methods.DestroyReseller) // Permanently delete reseller and all hierarchy (destroy:resellers required) // Suspend and reactivate endpoints (cascade to users) @@ -559,7 +559,7 @@ func main() { customersGroup.DELETE("/:id", methods.DeleteCustomer) // Soft-delete customer (manage:customers required) // Restore and destroy endpoints (cascade to users and systems) - customersGroup.PATCH("/:id/restore", methods.RestoreCustomer) // Restore soft-deleted customer and cascade-deleted users/systems + customersGroup.PATCH("/:id/restore", middleware.RequireOrgRole(models.OwnerOrgRole), methods.RestoreCustomer) // Restore soft-deleted customer and cascade-deleted users/systems customersGroup.DELETE("/:id/destroy", middleware.RequirePermission("destroy:customers"), methods.DestroyCustomer) // Permanently delete customer and all hierarchy (destroy:customers required) // Suspend and reactivate endpoints (cascade to users) @@ -599,7 +599,7 @@ func main() { usersGroup.DELETE("/:id", middleware.PreventSelfModification(), methods.DeleteUser) // Soft-delete user (manage:users required, prevent self-modification) // Restore and destroy endpoints - usersGroup.PATCH("/:id/restore", middleware.PreventSelfModification(), methods.RestoreUser) // Restore soft-deleted user (manage:users required, prevent self-modification) + usersGroup.PATCH("/:id/restore", middleware.RequireOrgRole(models.OwnerOrgRole), middleware.PreventSelfModification(), methods.RestoreUser) // Restore soft-deleted user (manage:users required, prevent self-modification) usersGroup.DELETE("/:id/destroy", middleware.RequirePermission("destroy:users"), middleware.PreventSelfModification(), methods.DestroyUser) // Permanently delete user (destroy:users required, prevent self-modification) // Suspend and reactivate endpoints (manage:users required, prevent self-modification) diff --git a/backend/methods/customers.go b/backend/methods/customers.go index 705201c98..6e3eb89b3 100644 --- a/backend/methods/customers.go +++ b/backend/methods/customers.go @@ -197,6 +197,9 @@ func GetCustomers(c *gin.Context) { // Parse search and status parameters search := c.Query("search") statuses := c.QueryArray("status") + if rejectDeletedStatusOutsideOwnerOrg(c, user.OrgRole, statuses) { + return + } createdBy := c.QueryArray("created_by") ownedBy := c.QueryArray("organization_id") diff --git a/backend/methods/customers_export.go b/backend/methods/customers_export.go index 9d64995d1..fb3f48ea3 100644 --- a/backend/methods/customers_export.go +++ b/backend/methods/customers_export.go @@ -47,6 +47,9 @@ func ExportCustomers(c *gin.Context) { // Parse search and status parameters search := c.Query("search") statuses := c.QueryArray("status") + if rejectDeletedStatusOutsideOwnerOrg(c, user.OrgRole, statuses) { + return + } // For export, we don't use pagination - get all matching customers (with limit) sortBy := c.DefaultQuery("sort_by", "created_at") diff --git a/backend/methods/deleted_objects.go b/backend/methods/deleted_objects.go new file mode 100644 index 000000000..75ecd55e6 --- /dev/null +++ b/backend/methods/deleted_objects.go @@ -0,0 +1,33 @@ +/* +Copyright (C) 2026 Nethesis S.r.l. +SPDX-License-Identifier: AGPL-3.0-or-later +*/ + +package methods + +import ( + "net/http" + "strings" + + "github.com/gin-gonic/gin" + + "github.com/nethesis/my/backend/models" + "github.com/nethesis/my/backend/response" +) + +// rejectDeletedStatusOutsideOwnerOrg refuses a listing or an export filtered +// on soft-deleted objects to a caller outside the Owner organization. Seeing +// them, and restoring them, belongs to the Owner organization: for everyone +// else a Delete is final. It reports whether it wrote the refusal. +func rejectDeletedStatusOutsideOwnerOrg(c *gin.Context, orgRole string, statuses []string) bool { + if models.IsGlobalOrgRole(orgRole) { + return false + } + for _, status := range statuses { + if strings.EqualFold(status, "deleted") { + c.JSON(http.StatusForbidden, response.Forbidden("deleted objects are visible to the owner organization only", nil)) + return true + } + } + return false +} diff --git a/backend/methods/deleted_objects_unit_test.go b/backend/methods/deleted_objects_unit_test.go new file mode 100644 index 000000000..2acaa673d --- /dev/null +++ b/backend/methods/deleted_objects_unit_test.go @@ -0,0 +1,49 @@ +/* +Copyright (C) 2026 Nethesis S.r.l. +SPDX-License-Identifier: AGPL-3.0-or-later +*/ + +package methods + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" +) + +func TestRejectDeletedStatusOutsideOwnerOrg(t *testing.T) { + gin.SetMode(gin.TestMode) + + tests := []struct { + name string + orgRole string + statuses []string + rejected bool + }{ + {"owner organization asks for deleted", "owner", []string{"deleted"}, false}, + {"owner organization in another case", "Owner", []string{"enabled", "deleted"}, false}, + {"distributor asks for deleted", "distributor", []string{"deleted"}, true}, + {"reseller asks for deleted among others", "reseller", []string{"enabled", "DELETED"}, true}, + {"customer asks for active systems", "customer", []string{"active", "suspended"}, false}, + {"customer asks for no status", "customer", nil, false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + + rejected := rejectDeletedStatusOutsideOwnerOrg(c, tt.orgRole, tt.statuses) + + assert.Equal(t, tt.rejected, rejected) + if tt.rejected { + assert.Equal(t, http.StatusForbidden, w.Code) + } else { + assert.False(t, c.Writer.Written()) + } + }) + } +} diff --git a/backend/methods/distributors.go b/backend/methods/distributors.go index d54db334c..7cee9a0c2 100644 --- a/backend/methods/distributors.go +++ b/backend/methods/distributors.go @@ -164,6 +164,9 @@ func GetDistributors(c *gin.Context) { // Parse search and status parameters search := c.Query("search") statuses := c.QueryArray("status") + if rejectDeletedStatusOutsideOwnerOrg(c, user.OrgRole, statuses) { + return + } createdBy := c.QueryArray("created_by") // Create service diff --git a/backend/methods/distributors_export.go b/backend/methods/distributors_export.go index 550557a37..e2a43e40e 100644 --- a/backend/methods/distributors_export.go +++ b/backend/methods/distributors_export.go @@ -47,6 +47,9 @@ func ExportDistributors(c *gin.Context) { // Parse search and status parameters search := c.Query("search") statuses := c.QueryArray("status") + if rejectDeletedStatusOutsideOwnerOrg(c, user.OrgRole, statuses) { + return + } // For export, we don't use pagination - get all matching distributors (with limit) sortBy := c.DefaultQuery("sort_by", "created_at") diff --git a/backend/methods/resellers.go b/backend/methods/resellers.go index 3c8bdf98c..8d2a1257b 100644 --- a/backend/methods/resellers.go +++ b/backend/methods/resellers.go @@ -201,6 +201,9 @@ func GetResellers(c *gin.Context) { // Parse search and status parameters search := c.Query("search") statuses := c.QueryArray("status") + if rejectDeletedStatusOutsideOwnerOrg(c, user.OrgRole, statuses) { + return + } createdBy := c.QueryArray("created_by") ownedBy := c.QueryArray("organization_id") diff --git a/backend/methods/resellers_export.go b/backend/methods/resellers_export.go index 004c4a066..40b912650 100644 --- a/backend/methods/resellers_export.go +++ b/backend/methods/resellers_export.go @@ -47,6 +47,9 @@ func ExportResellers(c *gin.Context) { // Parse search and status parameters search := c.Query("search") statuses := c.QueryArray("status") + if rejectDeletedStatusOutsideOwnerOrg(c, user.OrgRole, statuses) { + return + } // For export, we don't use pagination - get all matching resellers (with limit) sortBy := c.DefaultQuery("sort_by", "created_at") diff --git a/backend/methods/systems.go b/backend/methods/systems.go index 8ee4950bd..b6cc371d8 100644 --- a/backend/methods/systems.go +++ b/backend/methods/systems.go @@ -161,7 +161,10 @@ func GetSystems(c *gin.Context) { filterVersions := c.QueryArray("version") // Version filter (multiple values) filterOrgIDs := c.QueryArray("organization_id") // Organization filter (multiple IDs) filterStatuses := c.QueryArray("status") // Status filter (multiple values) - filterAddons := c.QueryArray("addon") // Add-on filter (multiple catalog ids) + if rejectDeletedStatusOutsideOwnerOrg(c, userOrgRole, filterStatuses) { + return + } + filterAddons := c.QueryArray("addon") // Add-on filter (multiple catalog ids) // include_hierarchy expands each organization_id filter to the org plus its // whole subtree (resellers/customers); the systems RBAC scope still applies diff --git a/backend/methods/systems_export.go b/backend/methods/systems_export.go index 06de21f15..64c7973bb 100644 --- a/backend/methods/systems_export.go +++ b/backend/methods/systems_export.go @@ -77,6 +77,9 @@ func ExportSystems(c *gin.Context) { return } filterStatuses := c.QueryArray("status") + if rejectDeletedStatusOutsideOwnerOrg(c, user.OrgRole, filterStatuses) { + return + } filterAddons := c.QueryArray("addon") // For export, we don't use pagination - get all matching systems (with limit) diff --git a/backend/methods/users.go b/backend/methods/users.go index 90a5e0757..5042e5b43 100644 --- a/backend/methods/users.go +++ b/backend/methods/users.go @@ -263,6 +263,9 @@ func GetUsers(c *gin.Context) { // Parse filter parameters organizationFilter := c.QueryArray("organization_id") statuses := c.QueryArray("status") + if rejectDeletedStatusOutsideOwnerOrg(c, user.OrgRole, statuses) { + return + } roleFilter := c.QueryArray("role") createdByFilter := c.QueryArray("created_by") diff --git a/backend/methods/users_export.go b/backend/methods/users_export.go index 721b6ba24..6721f3d9c 100644 --- a/backend/methods/users_export.go +++ b/backend/methods/users_export.go @@ -49,6 +49,9 @@ func ExportUsers(c *gin.Context) { // Parse filter parameters organizationFilter := c.QueryArray("organization_id") statuses := c.QueryArray("status") + if rejectDeletedStatusOutsideOwnerOrg(c, user.OrgRole, statuses) { + return + } roleFilter := c.QueryArray("role") createdByFilter := c.QueryArray("created_by") diff --git a/backend/openapi.yaml b/backend/openapi.yaml index 5c96b0ade..0b9c87942 100644 --- a/backend/openapi.yaml +++ b/backend/openapi.yaml @@ -4717,6 +4717,8 @@ components: - deleted: soft-deleted When "deleted" is combined with other statuses, both deleted and non-deleted matching records are returned. + + Only the Owner organization may ask for "deleted": any other caller gets 403. required: false schema: type: array @@ -4947,6 +4949,7 @@ components: Special value "deleted" shows soft-deleted systems (where deleted_at IS NOT NULL). When "deleted" is combined with other statuses, both deleted and non-deleted systems matching the other statuses are returned. + Only the Owner organization may ask for "deleted": any other caller gets 403. "no_inventory" is additive rather than exclusive: such a system is also active or inactive, so it matches both filters. Selecting it alone yields @@ -5406,7 +5409,8 @@ paths: - enabled: not suspended and not deleted - suspended: suspended but not deleted - - deleted: soft-deleted + - deleted: soft-deleted, for the Owner organization only (any other + caller gets 403) - no_login: virtual status matching accounts that never signed in (latest_login_at IS NULL) @@ -5909,7 +5913,7 @@ paths: tags: - Backend - Users summary: /users/{id}/restore - Restore soft-deleted user - description: Restore a soft-deleted user (requires manage:users permission and hierarchical validation) + description: Restore a soft-deleted user (Owner organization only; requires manage:users permission and hierarchical validation) parameters: - name: id in: path @@ -6107,7 +6111,8 @@ paths: - enabled: not suspended and not deleted - suspended: suspended but not deleted - - deleted: soft-deleted + - deleted: soft-deleted, for the Owner organization only (any other + caller gets 403) - no_login: virtual status matching accounts that never signed in (latest_login_at IS NULL) @@ -8526,7 +8531,7 @@ paths: tags: - Backend - Customers summary: /customers/{id}/restore - Restore soft-deleted customer - description: Restore a soft-deleted customer (requires manage:customers permission and hierarchical validation) + description: Restore a soft-deleted customer (Owner organization only; requires manage:customers permission and hierarchical validation) parameters: - name: id in: path @@ -9161,7 +9166,7 @@ paths: tags: - Backend - Distributors summary: /distributors/{id}/restore - Restore soft-deleted distributor - description: Restore a soft-deleted distributor (requires manage:distributors permission and hierarchical validation) + description: Restore a soft-deleted distributor (Owner organization only; requires manage:distributors permission and hierarchical validation) parameters: - name: id in: path @@ -10863,7 +10868,7 @@ paths: tags: - Backend - Resellers summary: /resellers/{id}/restore - Restore soft-deleted reseller - description: Restore a soft-deleted reseller (requires manage:resellers permission and hierarchical validation) + description: Restore a soft-deleted reseller (Owner organization only; requires manage:resellers permission and hierarchical validation) parameters: - name: id in: path @@ -11448,7 +11453,7 @@ paths: tags: - Backend - Systems summary: /systems/{id}/restore - Restore soft-deleted system - description: Restore a soft-deleted system. Users can restore systems they have permission to delete based on hierarchical permissions. + description: Restore a soft-deleted system (Owner organization only; requires manage:systems permission and hierarchical validation). parameters: - name: id in: path diff --git a/docs/docs/platform/organizations.md b/docs/docs/platform/organizations.md index 48d870231..61ffd3582 100644 --- a/docs/docs/platform/organizations.md +++ b/docs/docs/platform/organizations.md @@ -189,13 +189,13 @@ Click on an organization to view detailed information: ### Deleting Organizations -**Delete archives, it does not erase.** The organization is soft-deleted and +**Delete keeps the data.** The organization is soft-deleted and disappears from the lists, and the same operation cascades down the hierarchy: -- Every **user** of the organization is archived -- Every **system** of the organization is archived +- Every **user** of the organization is deleted +- Every **system** of the organization is deleted - For a distributor or a reseller, every **child organization** in its - hierarchy is archived too, together with their users and systems + hierarchy is deleted too, together with their users and systems To delete an organization: @@ -205,7 +205,9 @@ To delete an organization: :::tip Reversible A deleted organization can be brought back with **Restore**, which -cascade-restores the users and systems archived along with it. +cascade-restores the users and systems deleted along with it. Only the Owner +organization sees deleted organizations and can restore them: for everyone +else, deletion is final. ::: :::danger Permanent deletion diff --git a/docs/docs/platform/users.md b/docs/docs/platform/users.md index 7eb70a087..556c1a7e6 100644 --- a/docs/docs/platform/users.md +++ b/docs/docs/platform/users.md @@ -14,7 +14,7 @@ My uses a dual-role system combining business hierarchy with technical capabilit Automatically inherited from user's organization: -- **Owner**: Complete platform access (Nethesis only). Every member of the Owner organization has global visibility on all companies, systems and users, including archiving and destroying distributors, resellers and customers +- **Owner**: Complete platform access (Nethesis only). Every member of the Owner organization has global visibility on all companies, systems and users, including deleting, restoring and destroying distributors, resellers and customers - **Distributor**: Manages resellers and customers - **Reseller**: Manages customers - **Customer**: Views own organization data @@ -138,7 +138,7 @@ Use filters to find specific users: - **Search by name or email**: Type in the search box - **Search by organization**: Select one or more organizations - **Search by role**: Admin, Backoffice, Support, Reader, Staff -- **Filter by status**: Enabled, Suspended, Archived, No login. "No login" selects +- **Filter by status**: Enabled, Suspended, Deleted (Owner organization only), No login. "No login" selects the accounts that never signed in since the invitation, the same ones flagged with the badge next to the name; it adds to the other statuses rather than narrowing them @@ -237,9 +237,9 @@ Re-enable a suspended account: ### Deleting a User -**Delete archives, it does not erase.** The user is soft-deleted: it disappears -from the lists and can no longer sign in, but the record is kept and can be -brought back with **Restore**. +**Delete keeps the record.** The user is soft-deleted: it disappears from the +lists and can no longer sign in, but the record is kept and the Owner +organization can bring it back with **Restore**. To delete a user: @@ -249,7 +249,8 @@ To delete a user: **Effects of deletion:** - The user can no longer sign in -- The account is archived, not erased -- **Restore** brings it back +- The account is kept, not erased -- the Owner organization can bring it back + with **Restore** - All audit logs are preserved - Systems created by this user remain @@ -258,7 +259,7 @@ To delete a user: - You need `manage:users` (Admin, Backoffice or Staff) :::danger Permanent deletion -Erasing a user for good is a separate operation and requires `destroy:users`, +**Destroy**, which erases a user for good, is a separate operation and requires `destroy:users`, which no assignable role holds -- only the bootstrap `owner` account. That one cannot be undone. ::: @@ -302,7 +303,7 @@ hierarchy. | Create and edit users | `manage:users` | Yes | Yes | Yes | No | No | | Reset a user's password | `manage:users` | Yes | Yes | Yes | No | No | | Suspend / reactivate a user | `manage:users` | Yes | Yes | Yes | No | No | -| Delete a user (archive) | `manage:users` | Yes | Yes | Yes | No | No | +| Delete a user (soft delete) | `manage:users` | Yes | Yes | Yes | No | No | | View systems | `read:systems` | Yes | Yes | Yes | Yes | Yes | | Create, edit and delete systems | `manage:systems` | Yes | Yes | No | Yes | No | | Silence alerts | `manage:systems` | Yes | Yes | No | Yes | No | diff --git a/docs/docs/systems/management.md b/docs/docs/systems/management.md index 9e5954e9f..5aa191e56 100644 --- a/docs/docs/systems/management.md +++ b/docs/docs/systems/management.md @@ -129,8 +129,8 @@ do the same. changes nothing for anyone else - Every user who can see a system can star it, read-only roles included - Your favorites follow you on every browser and device -- An archived system leaves your favorites list and comes back when it is - restored; a permanently deleted one is removed for good +- A deleted system leaves your favorites list and comes back when it is + restored; a destroyed one is removed for good - While impersonating another user, their favorites are shown but cannot be changed @@ -249,27 +249,27 @@ Soft delete marks a system as deleted without removing data: - Cannot send inventory or heartbeat - Hidden from normal views - Its applications are hidden from lists, totals and organization counters until the system is restored (they are kept, not deleted) -- Can be restored if needed +- Can be restored by the Owner organization - All historical data is preserved -**To view deleted systems:** -1. Apply filter: Status = "deleted" +**To view deleted systems** (Owner organization only): +1. Apply filter: Status = Deleted 2. Select the deleted system 3. Click **Restore** to undelete -### Permanent Delete +### Destroy :::danger This operation is irreversible! ::: -To permanently delete: +To destroy a system: 1. Soft delete the system first 2. Navigate to deleted systems view 3. Select the system -4. Click **Permanent Delete** +4. Click **Destroy** 5. Type system name to confirm -6. Click **Delete** +6. Click **Destroy** **This will remove:** - System record diff --git a/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/organizations.md b/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/organizations.md index fb353d539..5f19d8676 100644 --- a/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/organizations.md +++ b/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/organizations.md @@ -189,13 +189,13 @@ Cliccando su un'organizzazione si accede alle informazioni di dettaglio: ### Eliminazione -**L'eliminazione archivia, non cancella.** L'organizzazione viene eliminata in +**L'eliminazione conserva i dati.** L'organizzazione viene eliminata in modo soft e sparisce dagli elenchi, e la stessa operazione si propaga lungo la gerarchia: -- Ogni **utente** dell'organizzazione viene archiviato -- Ogni **sistema** dell'organizzazione viene archiviato -- Per un distributore o un rivenditore, viene archiviata anche ogni +- Ogni **utente** dell'organizzazione viene eliminato +- Ogni **sistema** dell'organizzazione viene eliminato +- Per un distributore o un rivenditore, viene eliminata anche ogni **organizzazione figlia** della sua gerarchia, con i relativi utenti e sistemi Per eliminare un'organizzazione: @@ -207,11 +207,13 @@ Per eliminare un'organizzazione: :::tip Reversibile Un'organizzazione eliminata può essere recuperata con **Ripristina**, che -ripristina a cascata anche gli utenti e i sistemi archiviati insieme a lei. +ripristina a cascata anche gli utenti e i sistemi eliminati insieme a lei. Solo +l'organizzazione Owner vede le organizzazioni eliminate e può ripristinarle: per +tutti gli altri l'eliminazione è definitiva. ::: -:::danger Eliminazione definitiva -**Elimina definitivamente** è l'operazione irreversibile: cancella +:::danger Distruzione +**Distruggi** è l'operazione irreversibile: cancella l'organizzazione per sempre e non si può annullare. Richiede il permesso `destroy:` su quella risorsa, che ha solo l'organizzazione Owner. ::: diff --git a/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/users.md b/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/users.md index f71d76446..454ad54f2 100644 --- a/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/users.md +++ b/docs/i18n/it/docusaurus-plugin-content-docs/current/platform/users.md @@ -14,7 +14,7 @@ My usa un sistema a doppio ruolo che combina la gerarchia commerciale con le cap Ereditati automaticamente dall'organizzazione dell'utente: -- **Owner**: accesso completo alla piattaforma (solo Nethesis). Ogni membro dell'organizzazione Owner ha visibilità globale su tutte le aziende, i sistemi e gli utenti, inclusa l'archiviazione e l'eliminazione definitiva di distributori, rivenditori e clienti +- **Owner**: accesso completo alla piattaforma (solo Nethesis). Ogni membro dell'organizzazione Owner ha visibilità globale su tutte le aziende, i sistemi e gli utenti, inclusi l'eliminazione, il ripristino e la distruzione di distributori, rivenditori e clienti - **Distributore**: gestisce rivenditori e clienti - **Rivenditore**: gestisce i clienti - **Cliente**: vede i dati della propria organizzazione @@ -138,7 +138,7 @@ Usa i filtri per trovare utenti specifici: - **Ricerca per nome o email**: digita nella casella di ricerca - **Ricerca per organizzazione**: seleziona una o più organizzazioni - **Ricerca per ruolo**: Admin, Backoffice, Support, Reader, Staff -- **Filtro per stato**: Abilitato, Sospeso, Archiviato, Nessun accesso. "Nessun +- **Filtro per stato**: Abilitato, Sospeso, Eliminato (solo organizzazione Owner), Nessun accesso. "Nessun accesso" seleziona gli account che non hanno mai effettuato l'accesso dall'invito, gli stessi segnalati dal badge accanto al nome; si somma agli altri stati invece di restringerli @@ -237,7 +237,7 @@ Riabilita un account sospeso: ### Eliminazione -**L'eliminazione archivia, non cancella.** L'utente viene eliminato in modo +**L'eliminazione conserva il record.** L'utente viene eliminato in modo soft: sparisce dagli elenchi e non può più accedere, ma il record resta e può essere recuperato con **Ripristina**. @@ -249,7 +249,8 @@ Per eliminare un utente: **Effetti dell'eliminazione:** - L'utente non può più accedere -- L'account viene archiviato, non cancellato -- **Ripristina** lo riporta indietro +- L'account viene conservato, non cancellato -- l'organizzazione Owner può + riportarlo indietro con **Ripristina** - I log di audit vengono conservati - I sistemi creati da quell'utente restano @@ -257,8 +258,8 @@ Per eliminare un utente: - Non è possibile eliminare il proprio account - Serve `manage:users` (Admin, Backoffice o Staff) -:::danger Eliminazione definitiva -Cancellare un utente per sempre è un'operazione separata e richiede +:::danger Distruzione +**Distruggi**, che cancella un utente per sempre, è un'operazione separata e richiede `destroy:users`, che non appartiene a nessun ruolo assegnabile: solo l'account `owner` creato all'installazione. Quella non è reversibile. ::: @@ -302,7 +303,7 @@ ruolo utente -- con una sola eccezione: al Reader vengono tolti i permessi | Crea e modifica utenti | `manage:users` | Sì | Sì | Sì | No | No | | Reset password di un utente | `manage:users` | Sì | Sì | Sì | No | No | | Sospendi / riattiva un utente | `manage:users` | Sì | Sì | Sì | No | No | -| Elimina un utente (archiviazione) | `manage:users` | Sì | Sì | Sì | No | No | +| Elimina un utente (eliminazione soft) | `manage:users` | Sì | Sì | Sì | No | No | | Visualizza sistemi | `read:systems` | Sì | Sì | Sì | Sì | Sì | | Crea, modifica ed elimina sistemi | `manage:systems` | Sì | Sì | No | Sì | No | | Silenzia allarmi | `manage:systems` | Sì | Sì | No | Sì | No | @@ -325,7 +326,7 @@ Per esportare un elenco basta il permesso `read:` di quella risorsa, quindi ogni ruolo può esportare ciò che vede -- Support compreso, tranne gli utenti, che non può leggere. -:::note Eliminazione definitiva +:::note Distruzione `destroy:systems` e `destroy:users` non appartengono a nessun ruolo assegnabile, Staff incluso. Sono solo dell'account `owner` creato all'installazione, che è anche l'unico a poter creare e gestire gli utenti dell'organizzazione Owner. diff --git a/docs/i18n/it/docusaurus-plugin-content-docs/current/systems/management.md b/docs/i18n/it/docusaurus-plugin-content-docs/current/systems/management.md index 3a420419d..2da98570c 100644 --- a/docs/i18n/it/docusaurus-plugin-content-docs/current/systems/management.md +++ b/docs/i18n/it/docusaurus-plugin-content-docs/current/systems/management.md @@ -124,8 +124,8 @@ preferiti** e **Rimuovi dai preferiti** del menu della riga fanno lo stesso. - Ogni utente che vede un sistema può aggiungerlo ai preferiti, anche con un ruolo di sola lettura - I preferiti ti seguono su ogni browser e dispositivo -- Un sistema archiviato esce dall'elenco dei preferiti e ci torna quando viene - ripristinato; uno eliminato definitivamente viene rimosso per sempre +- Un sistema eliminato esce dall'elenco dei preferiti e ci torna quando viene + ripristinato; uno distrutto viene rimosso per sempre - Mentre impersoni un altro utente vedi i suoi preferiti, ma non puoi modificarli @@ -240,27 +240,27 @@ L'eliminazione soft marca il sistema come eliminato senza rimuovere i dati: - Non può più inviare inventario o heartbeat - Sparisce dalle viste normali - Le sue applicazioni spariscono da elenchi, totali e contatori delle organizzazioni finché il sistema non viene ripristinato (vengono conservate, non cancellate) -- Può essere ripristinato in qualsiasi momento +- Può essere ripristinato dall'organizzazione Owner - Tutti i dati storici vengono conservati -**Per vedere i sistemi eliminati:** -1. Applica il filtro Stato = "deleted" +**Per vedere i sistemi eliminati** (solo organizzazione Owner): +1. Applica il filtro Stato = Eliminato 2. Seleziona il sistema eliminato 3. Clicca su **Ripristina** -### Eliminazione Permanente +### Distruzione :::danger Questa operazione è irreversibile! ::: -Per eliminare definitivamente: +Per distruggere un sistema: 1. Elimina prima il sistema in modo soft 2. Vai alla vista dei sistemi eliminati 3. Seleziona il sistema -4. Clicca su **Elimina definitivamente** +4. Clicca su **Distruggi** 5. Digita il nome del sistema per confermare -6. Clicca su **Elimina** +6. Clicca su **Distruggi** **Viene rimosso:** - Il record del sistema diff --git a/frontend/e2e/fixtures/users.ts b/frontend/e2e/fixtures/users.ts index 911d77745..362de1bd4 100644 --- a/frontend/e2e/fixtures/users.ts +++ b/frontend/e2e/fixtures/users.ts @@ -83,12 +83,12 @@ export async function roleIdByName(name: string): Promise { * load-bearing for teardown: `/users` adds `AND u.deleted_at IS NULL` unless * `status=deleted` is among the query parameters * (`entities/local_users.go`, `deletedClause`). A default listing therefore - * cannot see an archived user, so the sweep would walk straight past one and - * leave it in the tenant for ever — which is exactly what the archive spec + * cannot see an deleted user, so the sweep would walk straight past one and + * leave it in the tenant for ever — which is exactly what the delete spec * creates. * * Pass a narrower list to ask a question instead of to clean up, e.g. - * `listE2eUsers(['deleted'])` for "did the archive really happen". + * `listE2eUsers(['deleted'])` for "did the deletion really happen". */ export async function listE2eUsers( statuses: string[] = ['enabled', 'suspended', 'deleted'], diff --git a/frontend/e2e/fullstack/users.spec.ts b/frontend/e2e/fullstack/users.spec.ts index 579e03e20..fccea5214 100644 --- a/frontend/e2e/fullstack/users.spec.ts +++ b/frontend/e2e/fullstack/users.spec.ts @@ -2,13 +2,13 @@ // SPDX-License-Identifier: GPL-3.0-or-later /** - * Creating, editing and archiving a user, and assigning technical roles. + * Creating, editing and deleting a user, and assigning technical roles. * * The lifecycle runs as one serial sequence rather than as independent tests, * for a reason that is not tidiness: creating a user makes the backend send a * welcome email with a temporary password * (`services/local/users.go:351`). Sharing one user across create, edit and - * archive keeps that to a single message per run instead of one per test. + * delete keeps that to a single message per run instead of one per test. * * Everything created is plus sub-addressed with the reserved tag and destroyed * afterwards; teardown refuses any address without it. See @@ -104,7 +104,7 @@ async function filterTo(page: Page, email: string): Promise { test.describe('user lifecycle', () => { // Serial for the reason in the file docstring: one account covers create, - // edit and archive, so each step depends on the one before. Scoped to this + // edit and delete, so each step depends on the one before. Scoped to this // describe rather than the file, so a failure here does not skip the // independent validation test below. // @@ -163,44 +163,44 @@ test.describe('user lifecycle', () => { ]) }) - test('archives the user', async ({ page }) => { + test('deletes the user', async ({ page }) => { await openUsers(page) const row = await filterTo(page, email) await row.getByRole('button', { name: /menu/i }).click() - await page.getByRole('menuitem', { name: t('common.archive') }).click() + await page.getByRole('menuitem', { name: t('common.delete') }).click() // The confirmation is type-to-confirm, and that is load-bearing: // `DeleteObjectModal.vue` only emits primary-click when the typed text - // matches the name exactly, so clicking Archive without it shows a - // validation error and archives nothing. + // matches the name exactly, so clicking Delete without it shows a + // validation error and deletes nothing. // // Asserted on the heading rather than on the dialog itself: the element // carrying role="dialog" is a zero-size wrapper around fixed-position // children, which Playwright reports as hidden however open the modal is. const confirm = page.getByRole('dialog') - const title = confirm.getByRole('heading', { name: t('users.archive_user') }) + const title = confirm.getByRole('heading', { name: t('users.delete_user') }) await expect(title).toBeVisible() await confirm.getByRole('textbox').fill(name) - await confirm.getByRole('button', { name: t('common.archive') }).click() + await confirm.getByRole('button', { name: t('common.delete') }).click() // Wait for the modal to go before looking at the table, and not only for // tidiness: while it is open the rest of the page is aria-hidden, so // `getByRole('row')` matches nothing and the assertion below would pass - // against an archive that never happened. + // against a deletion that never happened. await expect(title).toBeHidden({ timeout: 30_000 }) - // Archived users drop out of the listing, which asks for enabled and + // Deleted users drop out of the listing, which asks for enabled and // suspended only. await expect(rowOf(page, email)).toHaveCount(0, { timeout: 30_000 }) - // The row leaving the page is not the same as the account being archived. - // Ask the backend for the archived ones and it is there. - const archived = await listE2eUsers(['deleted']) + // The row leaving the page is not the same as the account being deleted. + // Ask the backend for the deleted ones and it is there. + const deleted = await listE2eUsers(['deleted']) expect( - archived.map((u) => u.email), - `${email} should be listed once the archived are asked for`, + deleted.map((u) => u.email), + `${email} should be listed once the deleted are asked for`, ).toContain(email) }) }) diff --git a/frontend/src/components/customers/CustomerInfoCard.vue b/frontend/src/components/customers/CustomerInfoCard.vue index 4a39a5996..9b62e5ff2 100644 --- a/frontend/src/components/customers/CustomerInfoCard.vue +++ b/frontend/src/components/customers/CustomerInfoCard.vue @@ -26,7 +26,7 @@ import { faCirclePause, faCirclePlay, faCircleCheck, - faBoxArchive, + faTrash, faShuffle, } from '@fortawesome/free-solid-svg-icons' import { useI18n } from 'vue-i18n' @@ -127,11 +127,11 @@ function getKebabMenuItems() {