diff --git a/docs/superpowers/specs/2026-12-02-e2e-followups-design.md b/docs/superpowers/specs/2026-12-02-e2e-followups-design.md new file mode 100644 index 0000000..84a0f0d --- /dev/null +++ b/docs/superpowers/specs/2026-12-02-e2e-followups-design.md @@ -0,0 +1,25 @@ +# E2E follow-ups: login hint, password hint, soft delete, dashboard labels, phone cards + +Date: 2026-12-02. Source: the owner's manual click-every-button e2e of the production build, and the owner's answers the same day. + +## Decisions (owner) + +1. Login: say a company is needed. Done without leaking whether a username exists: the hint is chosen from the empty company field, not from the server's answer. +2. Password: follow the Login security rules, which are already enforced, and make sure admins have screens to set them (they do, under Login security, Settings). What changes is that the hint is built from the switched-on rules instead of a fixed sentence, and a refusal names the failed rule. +3. Attended default on staff-added leads: follow my recommendation and keep it. The `event-attendance` spec already says a staff capture during the event days is attended, and outside the event days it is not. +4. Dashboard "Won in period" against the funnel: checked first. Both follow the `lead-dashboard` spec (wins in the period whenever captured, against the period's captures by current stage). Fix by explaining each figure on screen. +5. Soft delete for interests and roles. Guests already have removal for invited-only guests; registered guests stay, per `event-invitations`. +6. Phone cards: every shared-table listing becomes cards below `md`. +7. Translations: a separate change (`add-zh-cn-messages`). + +## Approaches + +- Phone cards: generic cards inside `DataTable` (chosen: one place, every listing) against hand-made cards per page (nicer but nine pages of work, and new pages would forget them). +- Soft delete: `deleted_at` column (chosen: keeps history and audit names) against hard delete with checks (loses lead tag names) or reusing `active` (already means "not offered" and stays listed). +- Password hint: rules read from the server (chosen: the hint can never disagree with the check) against a portal copy of the rules. + +## Non-goals + +Hard delete, undelete in the UI, per-company password rules, changing attendance or guest-removal rules. + +OpenSpec: `openspec/changes/polish-e2e-followups/`. diff --git a/local/seed/03-colite.sql b/local/seed/03-colite.sql index d8c1d8c..99553eb 100644 --- a/local/seed/03-colite.sql +++ b/local/seed/03-colite.sql @@ -343,3 +343,7 @@ USE `service-system`; INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES (41150000, 'BO_EVENT_GUESTS', 'Event guests', 'BO', 'M', 40000000, NULL, NULL); + +-- polish-e2e-followups/sql/01-soft-delete.sql +ALTER TABLE `service-counter`.`interest` ADD COLUMN `deleted_at` datetime NULL; +ALTER TABLE `service-system`.`role` ADD COLUMN `deleted_at` datetime NULL; diff --git a/openspec/changes/polish-e2e-followups/.openspec.yaml b/openspec/changes/polish-e2e-followups/.openspec.yaml new file mode 100644 index 0000000..eb2b21e --- /dev/null +++ b/openspec/changes/polish-e2e-followups/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-12-02 diff --git a/openspec/changes/polish-e2e-followups/design.md b/openspec/changes/polish-e2e-followups/design.md new file mode 100644 index 0000000..6003c60 --- /dev/null +++ b/openspec/changes/polish-e2e-followups/design.md @@ -0,0 +1,64 @@ +## Context + +These come from the owner's e2e of 2026-12-02 and the owner's answers on the same day. The codebase facts: + +- **Admin password rules:** + - They live in `service-system`.`system_property`, type `ADMIN_PWD_FORMAT`, with status `Y`/`N` and a value. + - `UserController.adminPasswordRuleFailures` checks them, and is called through `/user/validatePasswordFromRulesForAdmin`. + - The portal hint is the fixed key `AdminPasswordHint`. +- **The symbol rule** shows a value of 3, but it is switched off. That is why passwords without symbols were accepted, which is correct. +- **Interests** (`service-counter`.`interest`) have an `active` flag. **Roles** (`service-system`.`role`) have no status column. +- **Dashboard:** the "Won in period" count and the funnel already behave as the `lead-dashboard` spec says. Only the labels mislead. +- **Listings:** `DataTable` (`app/components/ui/data-table.tsx`) backs Users, Leads, Events, Interests, Roles, Emails, Audit log, Companies and Login security. Event leads already has its own phone cards. + +## Goals / Non-Goals + +**Goals:** the spec deltas. + +**Non-goals:** +- hard delete; +- restoring deleted records from the UI; +- per-company password rules; +- translations (a separate change); +- changing attendance or guest removal rules. + +## Decisions + +1. **Empty-company hint.** + - When the login fails and the company field was empty, the page shows the invalid-credentials message plus "Staff sign in with their company code." + - The hint is chosen in the portal from the form state alone, not from the server's answer, so it cannot reveal whether a username exists. +2. **Password hint from rules.** + - mobile-api reads the switched-on rules from the system service: + - `GET /api/admin/password-rules/active`, for signed-in admins; + - `GET /api/public/password-rules`, for the reset-password page, which is reached by email link with no session. The rule set is not secret; it is what the hint shows anyway. + - Both return `[{param, value}]` for status `Y` rules only. + - The portal builds the sentence from message keys `PwdHint_` with `{n}`. + - A refused password returns `PASSWORD_RULE` with the failing `param` and `value` in the ProblemDetail, so the form names the rule. +3. **Soft delete.** + - The column is `deleted_at datetime NULL`. + - The list endpoints, pickers, capture forms and filters exclude deleted rows. + - Existing leads keep showing a deleted interest's name, because history must not change. The same applies to the audit log and to role names in past records. + - The name stays reserved: the unique key is unchanged, and adding a deleted name is refused with "This name belongs to a deleted interest/role". + - Role delete is refused with 409 `ROLE_IN_USE` while any user (enabled or not) holds the role. + - Delete is super admin only, like the other writes, is audited, and needs a confirm dialog. +4. **Dashboard explanations.** The KPI tile and the funnel each get a one-line description under the title. This uses the existing tile subtitle style, or a muted line if none exists. No tooltip, because a tooltip is hidden on phones. +5. **Phone cards in `DataTable`.** + - Below `md`, `DataTable` renders a list of cards instead of the table. + - Each card shows the first column as its title. The other visible columns are label/value rows, with the label from the column header. + - Action cells (meta `actions: true` or an existing actions column marker) go in the card footer. + - Sorting stays reachable through a small "Sort by" select above the cards when columns are sortable. + - Pagination is shared. + - Pages with custom phone cards (event leads) keep them. + - The scroll cue requirement still holds above `md`. + +## Risks / Trade-offs + +- **Generic cards are plainer than hand-made ones.** That is acceptable for admin lists, and a page can still opt into a custom card later. +- **The public rules endpoint** lets anyone read the password policy. That is low risk, because the policy is shown on the page anyway. It gets the per-IP limit used by the other public routes. + +## Migration Plan + +1. Run `sql/01-soft-delete.sql`, which adds the two nullable columns and is additive. +2. Deploy system, counter, mobile-api and the portal. + +Rollback: `sql/99-rollback.sql` drops the columns. Redeploy the previous images. diff --git a/openspec/changes/polish-e2e-followups/proposal.md b/openspec/changes/polish-e2e-followups/proposal.md new file mode 100644 index 0000000..bc9344a --- /dev/null +++ b/openspec/changes/polish-e2e-followups/proposal.md @@ -0,0 +1,47 @@ +## Why + +The owner's click-every-button test of the production build (2026-12-02) turned up gaps that are not plain bugs: messages that confuse staff, records that cannot be removed, and listings that scroll sideways on phones. The owner decided how each one should behave. The plain bugs from the same test are fixed separately on `fix-e2e-findings`. + +## What Changes + +- **Login:** when the company is left empty and sign-in fails, the page also says that staff sign in with their company code. It still never says whether a username exists. +- **Password hint:** every screen that sets an admin password shows a hint built from the password rules that are switched on in Login security, instead of a fixed sentence. A refused password names the rule it failed. The rules screen already exists and stays the one place to change them. +- **Interests and roles:** a super admin can delete an interest or a role. Deletion is soft: the record is hidden from lists and pickers but kept for history. A role still held by a user cannot be deleted. Deactivating an interest asks for confirmation, and the add and edit dialogs get a Cancel button. +- **Dashboard labels:** "Won in period" and the funnel explain what they count, because they count different sets (wins in the period, whenever captured, against the period's captures by current stage). +- **Phone cards:** every listing built on the shared data table shows one card per row below the `md` width, instead of a table that scrolls sideways. + +Unchanged, by the owner's decision on the recommendation: +- A lead captured by staff during the event days stays Attended by default (`event-attendance`). +- A guest who has registered stays non-removable (`event-invitations`). + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `admin-access`: Staff login (the empty-company hint). +- `admin-login-security`: a new requirement for the password hint and named refusals. +- `lead-interests`: Interest list (soft delete, confirmation on deactivate). +- `admin-roles`: Role list and edit (soft delete). +- `lead-dashboard`: a new requirement for figure explanations. +- `admin-visual-design`: a new requirement for phone cards on listings. + +## Impact + +- **Database:** + - `service-counter`.`interest.deleted_at` + - `service-system`.`role.deleted_at` + - SQL in this change folder, mirrored into `local/seed/`. +- **Services:** + - counter (interest delete and filters); + - system (role delete and filters, the enabled admin rules, the named failure); + - mobile-api (admin endpoints, and a public read of the enabled admin rules for the reset-password page). +- **Portal:** + - login; + - the password screens (first login, change, set temporary, reset); + - interests, roles, dashboard; + - the shared `DataTable`. +- **No breaking API change.** Delete endpoints and the rules read are new. diff --git a/openspec/changes/polish-e2e-followups/specs/admin-access/spec.md b/openspec/changes/polish-e2e-followups/specs/admin-access/spec.md new file mode 100644 index 0000000..3c91e3d --- /dev/null +++ b/openspec/changes/polish-e2e-followups/specs/admin-access/spec.md @@ -0,0 +1,47 @@ +## MODIFIED Requirements + +### Requirement: Staff login + +The system SHALL let an active admin user log in through the admin portal with company code, username and password, or with username and password and no company for a super admin, and SHALL return the user's name, roles, company, menu and whether a password change is required. When a login fails and the company field was left empty, the login page SHALL also say that staff sign in with their company code, decided from the form alone so that it never reveals whether the username exists. + +#### Scenario: Correct credentials + +- **GIVEN** an active admin user `sales1` of active company `ins` +- **WHEN** they submit company `ins`, username `sales1` and their password on the login page +- **THEN** they are signed in and land on the portal home +- **AND** the sidebar shows only the menu entries their roles grant + +#### Scenario: Super admin + +- **GIVEN** the super admin `admin`, who belongs to no company +- **WHEN** they submit username `admin` and their password with the company left empty +- **THEN** they are signed in + +#### Scenario: Wrong password + +- **WHEN** a user submits a wrong password +- **THEN** `/api/admin/auth/login` responds 401 +- **AND** the login page shows an invalid-credentials message without saying whether the company or username exists + +#### Scenario: Staff user without company + +- **GIVEN** an active admin user `sales1` of company `ins` +- **WHEN** they submit username `sales1` and their correct password with the company left empty +- **THEN** login is refused with a 401 +- **AND** the page shows the invalid-credentials message and that staff sign in with their company code + +#### Scenario: Unknown username without company + +- **WHEN** someone submits a username that does not exist with the company left empty +- **THEN** the page shows exactly the same messages as for `sales1` without a company + +#### Scenario: Deactivated user + +- **GIVEN** an admin user whose account is deactivated +- **WHEN** they submit their correct password +- **THEN** login is refused with a 401 and the page shows the same invalid-credentials message + +#### Scenario: Member account + +- **WHEN** a member (non-admin) account submits its correct credentials to the admin login +- **THEN** login is refused with a 401 diff --git a/openspec/changes/polish-e2e-followups/specs/admin-login-security/spec.md b/openspec/changes/polish-e2e-followups/specs/admin-login-security/spec.md new file mode 100644 index 0000000..cd8cd38 --- /dev/null +++ b/openspec/changes/polish-e2e-followups/specs/admin-login-security/spec.md @@ -0,0 +1,19 @@ +## ADDED Requirements + +### Requirement: Password hint from the rules + +Every screen that sets an admin password (first-login change, change own password, set a temporary password, reset password by email link) SHALL show a hint listing the admin password rules that are switched on, with their values, read from the same rules the server checks. A refused password SHALL name the rule it failed. + +#### Scenario: Hint follows the switched-on rules + +- **GIVEN** the switched-on admin rules are minimum length 8, at least 1 capital and at least 1 small letter, and the symbol rule is off +- **WHEN** a user opens the change password dialog +- **THEN** the hint lists at least 8 characters, 1 capital letter and 1 small letter +- **AND** it says nothing about symbols + +#### Scenario: Rule switched on + +- **GIVEN** a super admin switches on the symbol rule with value 2 under Login security +- **WHEN** a user opens the reset password page from an email link +- **THEN** the hint also lists at least 2 symbols +- **AND** a new password with one symbol is refused with a message naming the symbol rule diff --git a/openspec/changes/polish-e2e-followups/specs/admin-roles/spec.md b/openspec/changes/polish-e2e-followups/specs/admin-roles/spec.md new file mode 100644 index 0000000..aac5e18 --- /dev/null +++ b/openspec/changes/polish-e2e-followups/specs/admin-roles/spec.md @@ -0,0 +1,46 @@ +## MODIFIED Requirements + +### Requirement: Role list and edit + +The system SHALL let any admin with `BO_ROLES` list admin roles, and SHALL let only a super admin create, rename and delete them, because roles are shared by every company. Role names SHALL be unique, including against deleted roles. The member role and `ROLE_ADMIN` SHALL NOT appear in the list (`ROLE_ADMIN` is attached to every admin automatically and grants no modules). + +#### Scenario: Create role + +- **WHEN** a super admin creates role `ROLE_SALES` +- **THEN** it appears in the role list and can be assigned to users of any company + +#### Scenario: Duplicate name + +- **GIVEN** role `ROLE_SALES` exists +- **WHEN** a super admin creates another role named `ROLE_SALES` +- **THEN** the save is refused with a message + +#### Scenario: Company user edits a role + +- **WHEN** an INS user with `BO_ROLES` creates, renames or deletes a role +- **THEN** the request is refused with 403 and nothing changes + +## ADDED Requirements + +### Requirement: Role deletion + +A super admin SHALL be able to delete a role after confirming. The delete SHALL be refused while any user, enabled or not, holds the role. Deleting SHALL be soft: a deleted role SHALL disappear from the role list and the user role picker. + +#### Scenario: Delete an unused role + +- **GIVEN** role `ROLE_TEMP` that no user holds +- **WHEN** a super admin deletes it and confirms +- **THEN** it is no longer in the role list or the user role picker + +#### Scenario: Delete a role in use + +- **GIVEN** role `ROLE_SALES` held by 3 users, one of them disabled +- **WHEN** a super admin deletes it +- **THEN** the delete is refused with a message that 3 users hold the role +- **AND** the role is unchanged + +#### Scenario: Name of a deleted role + +- **GIVEN** `ROLE_TEMP` was deleted +- **WHEN** a super admin creates a role named `ROLE_TEMP` +- **THEN** the save is refused with a message that the name belongs to a deleted role diff --git a/openspec/changes/polish-e2e-followups/specs/admin-visual-design/spec.md b/openspec/changes/polish-e2e-followups/specs/admin-visual-design/spec.md new file mode 100644 index 0000000..db38390 --- /dev/null +++ b/openspec/changes/polish-e2e-followups/specs/admin-visual-design/spec.md @@ -0,0 +1,21 @@ +## ADDED Requirements + +### Requirement: Phone Cards For Listings + +Every listing built on the shared data table SHALL show one card per row below the `md` width instead of a table, with the row's first column as the card title, the other columns as labelled values, and the row actions at the bottom of the card. Sorting and paging SHALL stay available. A page with its own phone cards SHALL keep them. + +#### Scenario: Users on a phone + +- **WHEN** a super admin opens Users at 360 px +- **THEN** each user is a card with the name as title and labelled username, company, roles and status +- **AND** the page does not scroll sideways + +#### Scenario: Actions on a card + +- **WHEN** a user opens Events at 360 px +- **THEN** each event card has the row's actions at its bottom + +#### Scenario: Wide screen unchanged + +- **WHEN** a user opens Users at 1280 px +- **THEN** the listing is the table, as before diff --git a/openspec/changes/polish-e2e-followups/specs/lead-dashboard/spec.md b/openspec/changes/polish-e2e-followups/specs/lead-dashboard/spec.md new file mode 100644 index 0000000..7491d57 --- /dev/null +++ b/openspec/changes/polish-e2e-followups/specs/lead-dashboard/spec.md @@ -0,0 +1,13 @@ +## ADDED Requirements + +### Requirement: Figure explanations + +The dashboard SHALL explain, in a visible line under its title, what the won-in-period figure and the funnel count, so that a period where they differ does not look wrong. The explanation SHALL be visible at phone width, not only on hover. + +#### Scenario: Win of an older capture explained + +- **GIVEN** a lead captured in October and changed to WON in November +- **WHEN** the user views November +- **THEN** won in period shows 1 and the funnel shows WON 0 +- **AND** won in period says it counts leads won in the period whenever they were captured +- **AND** the funnel says it counts the period's captures by their current stage diff --git a/openspec/changes/polish-e2e-followups/specs/lead-interests/spec.md b/openspec/changes/polish-e2e-followups/specs/lead-interests/spec.md new file mode 100644 index 0000000..b416c6b --- /dev/null +++ b/openspec/changes/polish-e2e-followups/specs/lead-interests/spec.md @@ -0,0 +1,58 @@ +## MODIFIED Requirements + +### Requirement: Interest list + +The system SHALL keep one interest list shared by all companies. Admins with `BO_INTERESTS` SHALL see the list, and only a super admin SHALL add, rename, reorder, deactivate, reactivate and delete interests. An interest name SHALL be required, at most 100 characters, and unique ignoring case, including against deleted interests. Deactivating SHALL ask for confirmation. + +#### Scenario: Add interest + +- **WHEN** a super admin adds `Kitchen appliances` +- **THEN** it is listed as active +- **AND** staff of every company can tag leads with it + +#### Scenario: Duplicate name + +- **GIVEN** an interest `Kitchen appliances` +- **WHEN** a super admin adds `kitchen APPLIANCES` +- **THEN** the save is refused and the name is reported as a duplicate + +#### Scenario: Deactivate + +- **GIVEN** an active interest `Cookware` +- **WHEN** a super admin deactivates it and confirms +- **THEN** it is still listed, marked inactive +- **AND** it is no longer offered when capturing a lead in any company + +#### Scenario: Cancel deactivate + +- **WHEN** a super admin chooses Deactivate on `Cookware` and then Cancel +- **THEN** `Cookware` stays active + +#### Scenario: Company user edits + +- **WHEN** an INS user with `BO_INTERESTS` adds, renames, deactivates or deletes an interest +- **THEN** the request is refused with 403 and the list is unchanged + +#### Scenario: No module + +- **WHEN** an admin without `BO_INTERESTS` opens the Interests page or calls an interests endpoint +- **THEN** the page shows not-authorised and the endpoint responds 403 + +## ADDED Requirements + +### Requirement: Interest deletion + +A super admin SHALL be able to delete an interest after confirming. Deleting SHALL be soft: a deleted interest SHALL disappear from the list, the capture forms and the filters, while leads already tagged with it SHALL keep showing its name. + +#### Scenario: Delete + +- **GIVEN** an interest `Cookware` that two leads are tagged with +- **WHEN** a super admin deletes it and confirms +- **THEN** it is no longer listed or offered anywhere +- **AND** the two leads still show `Cookware` + +#### Scenario: Name of a deleted interest + +- **GIVEN** `Cookware` was deleted +- **WHEN** a super admin adds `Cookware` +- **THEN** the save is refused with a message that the name belongs to a deleted interest diff --git a/openspec/changes/polish-e2e-followups/sql/01-soft-delete.sql b/openspec/changes/polish-e2e-followups/sql/01-soft-delete.sql new file mode 100644 index 0000000..34fc3c8 --- /dev/null +++ b/openspec/changes/polish-e2e-followups/sql/01-soft-delete.sql @@ -0,0 +1,4 @@ +-- Co-Lite change polish-e2e-followups: soft delete for interests and roles. Additive only. +-- A deleted row keeps its name (the unique keys are unchanged) and its history; lists and pickers hide it. +ALTER TABLE `service-counter`.`interest` ADD COLUMN `deleted_at` datetime NULL; +ALTER TABLE `service-system`.`role` ADD COLUMN `deleted_at` datetime NULL; diff --git a/openspec/changes/polish-e2e-followups/sql/99-rollback.sql b/openspec/changes/polish-e2e-followups/sql/99-rollback.sql new file mode 100644 index 0000000..c69e0af --- /dev/null +++ b/openspec/changes/polish-e2e-followups/sql/99-rollback.sql @@ -0,0 +1,3 @@ +-- Co-Lite change polish-e2e-followups: rollback of 01. Deleted interests and roles come back. +ALTER TABLE `service-counter`.`interest` DROP COLUMN `deleted_at`; +ALTER TABLE `service-system`.`role` DROP COLUMN `deleted_at`; diff --git a/openspec/changes/polish-e2e-followups/tasks.md b/openspec/changes/polish-e2e-followups/tasks.md new file mode 100644 index 0000000..0720783 --- /dev/null +++ b/openspec/changes/polish-e2e-followups/tasks.md @@ -0,0 +1,61 @@ +# Tasks: polish-e2e-followups + +Every task is TDD, followed by the review gate. Tasks run serially (the WhatsApp change holds the other worker slot). + +Verify commands: +- **Backend:** `mvn -T 1C -q -pl verify` +- **Portal:** `cd solvway-admin-portal && npx vitest run; echo VITEST=$? && npx tsc --noEmit && npm run lint` + +- [x] 1. SQL: `sql/01-soft-delete.sql` and `sql/99-rollback.sql`, mirrored into `local/seed/` and applied to the running local database. + - Depends on: none + - Scope: `openspec/changes/polish-e2e-followups/sql/**`, `local/seed/**` + - Verify: seed load in a throwaway MySQL with the compose flags; `SHOW COLUMNS` lists `deleted_at` on both tables. +- [x] 2. Soft delete backend: + - Interest delete in counter. Lists, capture options and filters exclude deleted rows. Lead views keep the name. The deleted-name duplicate error is a distinct reason. + - Role delete in system, refused with `ROLE_IN_USE` and a count while any user holds the role. The role list and user role picker exclude deleted rows. Deleted-name reason. + - mobile-api admin endpoints `DELETE /api/admin/interests/{id}` and `DELETE /api/admin/roles/{id}`, super admin only, audited. + - Depends on: 1 + - Scope: `solvway-services-counter/**`, `solvway-services-system/**`, `solvway-mobile-api/**` + - Verify: `mvn -T 1C -q -pl solvway-services-counter,solvway-services-system,solvway-mobile-api verify` +- [x] 3. Password rules backend: + - Switched-on admin rules `[{param, value}]` from system. + - mobile-api `GET /api/admin/password-rules/active` (any signed-in admin) and `GET /api/public/password-rules` (public, per-IP limited, gateway and public-path exemptions exact). + - The named refusal: `PASSWORD_RULE` with `param` and `value` on every admin password path (create user, set temporary, change own, first login, reset by link). + - Depends on: 2 + - Scope: `solvway-services-system/**`, `solvway-mobile-api/**`, `solvway-api-gateway/**` (security: controller reads the whole diff) + - Verify: `mvn -T 1C -q -pl solvway-services-system,solvway-mobile-api,solvway-api-gateway verify` +- [x] 4. Portal behaviour: + - the login hint when the company is empty; + - `PasswordRulesHint`, built from the rules, on the four password screens, with the named refusal message; + - interest Delete and Deactivate confirmations; + - role Delete with the in-use message; + - Cancel buttons in the add and edit dialogs; + - the dashboard explanation lines; + - the message keys. + - Depends on: 3 + - Scope: `solvway-admin-portal/**` except `app/components/ui/data-table*` + - Verify: portal verify +- [x] 5. Phone cards in `DataTable` below `md`: + - title from the first column, labelled values, actions at the bottom; + - a sort select when columns sort, and shared paging; + - opt-out for pages with their own cards. + - Depends on: 4 + - Scope: `solvway-admin-portal/app/components/ui/data-table*`, and pages only where a column needs a card label or actions marker + - Verify: portal verify +- [x] 6. Live check on the local stack with Playwright at 1280 and 360 px: + - login without a company as staff; + - the hint with the symbol rule on and off; + - a named refusal; + - delete an e2e interest and an e2e role (and the refusal for a role in use); + - the dashboard lines; + - cards on Users, Leads, Events, Interests, Roles, Emails, Audit log, Companies and Login security. + + Record the result here. + + Result (2026-12-02, port 3011, local stack): + - Passed: the login company hint; the dashboard figure notes; deleting an e2e interest (soft-deleted); deleting a throwaway role `e2e-DelRole` (row gone, `deleted_at` set); the refusal for `e2e-Role`, which `e2e-sales1@INS` still holds ("Users holding this role: 1. Remove it from them first."). + - Password hint on New user: with the symbol rule off it lists capital, small and length; with "Minimum symbols 1" on it adds "Symbols: at least 1". The rule was put back to off afterwards. + - Named refusal: `abcdefgh1` gets a server 400 shown under the field as `Password does not meet the rule "Capital letters: at least 1"`. + - Cards at 360 px with no sideways scroll: Users, Roles, Interests, Leads, Events, Emails, Audit log, Companies and Login security. + - Fixed during the check: on a refused delete there is no Retry, and phones show a "Sort by" placeholder (7533163). The Companies action buttons were clipped at 360 px because the page's own `flex gap-2` button group did not wrap; the shared actions cell now wraps its button group. + - Left open: Leads shows two "Company" labels, one for the tenant code and one for the lead's own company (keys `Company` and `LeadCompany`). This is a wording decision for the owner. diff --git a/solvway-admin-portal/app/api/interests/[id]/route.delete.test.ts b/solvway-admin-portal/app/api/interests/[id]/route.delete.test.ts new file mode 100644 index 0000000..c0cdde6 --- /dev/null +++ b/solvway-admin-portal/app/api/interests/[id]/route.delete.test.ts @@ -0,0 +1,31 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); +vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); +vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); + +import { DELETE } from "./route"; + +const call = () => DELETE(new Request("http://localhost/api/interests/7", { method: "DELETE" }) as never, { params: Promise.resolve({ id: "7" }) }); + +beforeEach(() => { + mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: undefined }); + mocks.getToken.mockReset().mockResolvedValue("tok"); +}); + +describe("DELETE /api/interests/[id]", () => { + it("is 401 without a session", async () => { + mocks.getToken.mockResolvedValue(null); + expect((await call()).status).toBe(401); + }); + + it("deletes upstream and answers ok", async () => { + expect((await call()).status).toBe(200); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/interests/7", { method: "DELETE", token: "tok" }); + }); + + it("passes the upstream refusal through", async () => { + mocks.callMobileApi.mockResolvedValue({ ok: false, error: "x", status: 404 }); + expect((await call()).status).toBe(404); + }); +}); diff --git a/solvway-admin-portal/app/api/interests/[id]/route.ts b/solvway-admin-portal/app/api/interests/[id]/route.ts index b06b8d7..5dd07ca 100644 --- a/solvway-admin-portal/app/api/interests/[id]/route.ts +++ b/solvway-admin-portal/app/api/interests/[id]/route.ts @@ -33,3 +33,12 @@ export async function PUT(req: NextRequest, { params }: Ctx) { if (!result.ok) return errorResponse(result); return NextResponse.json(result.data); } + +export async function DELETE(_req: NextRequest, { params }: Ctx) { + const token = await getToken(); + if (!token) return unauthorized(); + const { id } = await params; + const result = await callMobileApi(`/api/admin/interests/${encodeURIComponent(id)}`, { method: "DELETE", token }); + if (!result.ok) return errorResponse(result); + return NextResponse.json({ ok: true }); +} diff --git a/solvway-admin-portal/app/api/password-rules/route.test.ts b/solvway-admin-portal/app/api/password-rules/route.test.ts new file mode 100644 index 0000000..e60a865 --- /dev/null +++ b/solvway-admin-portal/app/api/password-rules/route.test.ts @@ -0,0 +1,26 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); +vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); +vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); + +import { GET } from "./route"; + +beforeEach(() => { + mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: [{ param: "NO_OTHER_LANGUAGE", value: null }] }); + mocks.getToken.mockReset().mockResolvedValue("tok"); +}); + +describe("GET /api/password-rules", () => { + it("is 401 without a session", async () => { + mocks.getToken.mockResolvedValue(null); + expect((await GET()).status).toBe(401); + expect(mocks.callMobileApi).not.toHaveBeenCalled(); + }); + + it("returns the active rules from the admin endpoint", async () => { + const res = await GET(); + expect(await res.json()).toEqual([{ param: "NO_OTHER_LANGUAGE", value: null }]); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/password-rules/active", { token: "tok" }); + }); +}); diff --git a/solvway-admin-portal/app/api/password-rules/route.ts b/solvway-admin-portal/app/api/password-rules/route.ts new file mode 100644 index 0000000..01bdca4 --- /dev/null +++ b/solvway-admin-portal/app/api/password-rules/route.ts @@ -0,0 +1,12 @@ +import { NextResponse } from "next/server"; +import { callMobileApi } from "@/app/lib/server/mobileApi"; +import { getToken } from "@/app/lib/server/session"; +import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; + +export async function GET() { + const token = await getToken(); + if (!token) return unauthorized(); + const result = await callMobileApi("/api/admin/password-rules/active", { token }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} diff --git a/solvway-admin-portal/app/api/public/password-rules/route.test.ts b/solvway-admin-portal/app/api/public/password-rules/route.test.ts new file mode 100644 index 0000000..25824fb --- /dev/null +++ b/solvway-admin-portal/app/api/public/password-rules/route.test.ts @@ -0,0 +1,25 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn() })); +vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); + +import { GET } from "./route"; + +type Req = Parameters[0]; +const req = (init: RequestInit = {}) => new Request("http://localhost/api/public/password-rules", init) as unknown as Req; + +beforeEach(() => mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: [{ param: "INPUT_LENGTH_MIN", value: 8 }] })); + +describe("/api/public/password-rules", () => { + it("forwards without a session, with only the last-hop visitor IP, and returns the rules", async () => { + const res = await GET(req({ headers: { "x-forwarded-for": "6.6.6.6, 203.0.113.7" } })); + expect(res.status).toBe(200); + expect(await res.json()).toEqual([{ param: "INPUT_LENGTH_MIN", value: 8 }]); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/public/password-rules", { headers: { "X-Forwarded-For": "203.0.113.7" } }); + }); + + it("passes upstream failures with their status", async () => { + mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Too many requests", status: 429 }); + expect((await GET(req())).status).toBe(429); + }); +}); diff --git a/solvway-admin-portal/app/api/public/password-rules/route.ts b/solvway-admin-portal/app/api/public/password-rules/route.ts new file mode 100644 index 0000000..704fa1b --- /dev/null +++ b/solvway-admin-portal/app/api/public/password-rules/route.ts @@ -0,0 +1,4 @@ +import type { NextRequest } from "next/server"; +import { forwardPublic } from "@/app/lib/server/publicProxy"; + +export const GET = (req: NextRequest) => forwardPublic(req, "/api/public/password-rules", "GET"); diff --git a/solvway-admin-portal/app/api/roles/[id]/route.delete.test.ts b/solvway-admin-portal/app/api/roles/[id]/route.delete.test.ts new file mode 100644 index 0000000..ac95889 --- /dev/null +++ b/solvway-admin-portal/app/api/roles/[id]/route.delete.test.ts @@ -0,0 +1,31 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); +vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); +vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); + +import { DELETE } from "./route"; + +const call = () => DELETE(new Request("http://localhost/api/roles/7", { method: "DELETE" }) as never, { params: Promise.resolve({ id: "7" }) }); + +beforeEach(() => { + mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: undefined }); + mocks.getToken.mockReset().mockResolvedValue("tok"); +}); + +describe("DELETE /api/roles/[id]", () => { + it("is 401 without a session", async () => { + mocks.getToken.mockResolvedValue(null); + expect((await call()).status).toBe(401); + }); + + it("deletes upstream and answers ok", async () => { + expect((await call()).status).toBe(200); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/roles/7", { method: "DELETE", token: "tok" }); + }); + + it("passes the upstream refusal through", async () => { + mocks.callMobileApi.mockResolvedValue({ ok: false, error: "x", status: 404 }); + expect((await call()).status).toBe(404); + }); +}); diff --git a/solvway-admin-portal/app/api/roles/[id]/route.ts b/solvway-admin-portal/app/api/roles/[id]/route.ts index 2a413d6..f239daf 100644 --- a/solvway-admin-portal/app/api/roles/[id]/route.ts +++ b/solvway-admin-portal/app/api/roles/[id]/route.ts @@ -33,3 +33,12 @@ export async function PUT(req: NextRequest, { params }: Ctx) { if (!result.ok) return errorResponse(result); return NextResponse.json(result.data); } + +export async function DELETE(_req: NextRequest, { params }: Ctx) { + const token = await getToken(); + if (!token) return unauthorized(); + const { id } = await params; + const result = await callMobileApi(`/api/admin/roles/${encodeURIComponent(id)}`, { method: "DELETE", token }); + if (!result.ok) return errorResponse(result); + return NextResponse.json({ ok: true }); +} diff --git a/solvway-admin-portal/app/companies/page.cancel.test.tsx b/solvway-admin-portal/app/companies/page.cancel.test.tsx new file mode 100644 index 0000000..25b28f3 --- /dev/null +++ b/solvway-admin-portal/app/companies/page.cancel.test.tsx @@ -0,0 +1,37 @@ +import { render, screen, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), getPrivacyNotice: vi.fn(), savePrivacyNotice: vi.fn() })); +vi.mock("@/app/lib/clientApi", async (importOriginal) => ({ + ApiError: (await importOriginal()).ApiError, + apiGet: mocks.apiGet, + apiPost: mocks.apiPost, +})); +vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ loading: false, isSuper: true }) })); +vi.mock("@/app/lib/services/adminRegistration", () => ({ + getPrivacyNotice: mocks.getPrivacyNotice, + savePrivacyNotice: mocks.savePrivacyNotice, +})); + +import CompaniesPage from "./page"; + +beforeEach(() => { + mocks.apiGet.mockReset().mockResolvedValue([{ id: 1, name: "Insight", code: "ins", status: "A" }]); + mocks.apiPost.mockReset(); + mocks.getPrivacyNotice.mockReset().mockResolvedValue(null); + mocks.savePrivacyNotice.mockReset(); +}); + +describe.each(["Edit", "Change code", "Privacy notice"])("Companies %s dialog", (action) => { + it("Cancel closes it without saving", async () => { + render(); + const row = (await screen.findByText("Insight")).closest("tr")!; + await userEvent.click(within(row).getByRole("button", { name: action })); + const dialog = await screen.findByRole("dialog"); + await userEvent.click(within(dialog).getByRole("button", { name: "Cancel" })); + expect(screen.queryByRole("dialog")).toBeNull(); + expect(mocks.apiPost).not.toHaveBeenCalled(); + expect(mocks.savePrivacyNotice).not.toHaveBeenCalled(); + }); +}); diff --git a/solvway-admin-portal/app/companies/page.tsx b/solvway-admin-portal/app/companies/page.tsx index 1cd3340..1daa15b 100644 --- a/solvway-admin-portal/app/companies/page.tsx +++ b/solvway-admin-portal/app/companies/page.tsx @@ -103,6 +103,9 @@ function CompanyDialog({ state, onClose, onSaved }: { state: DialogState; onClos )} + @@ -170,6 +173,9 @@ function PrivacyNoticeDialog({ company, onClose }: { company: AdminCompany; onCl

)} + diff --git a/solvway-admin-portal/app/components/app/ChangePasswordDialog.tsx b/solvway-admin-portal/app/components/app/ChangePasswordDialog.tsx index ac8e5e6..845e3f3 100644 --- a/solvway-admin-portal/app/components/app/ChangePasswordDialog.tsx +++ b/solvway-admin-portal/app/components/app/ChangePasswordDialog.tsx @@ -6,6 +6,7 @@ import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from " import { Input } from "@/app/components/ui/input"; import { Label } from "@/app/components/ui/label"; import { PasswordFields } from "@/app/components/users/PasswordFields"; +import { passwordRuleError } from "@/app/components/users/PasswordRulesHint"; import { changeOwnPassword } from "@/app/lib/services/adminUsers"; import { useT } from "@/app/lib/i18n/MessagesProvider"; @@ -17,6 +18,7 @@ export default function ChangePasswordDialog({ onClose, onDone }: { onClose: () const [confirmPassword, setConfirmPassword] = useState(""); const [error, setError] = useState(null); const [saving, setSaving] = useState(false); + const [ruleError, setRuleError] = useState(); async function submit(event: FormEvent) { event.preventDefault(); @@ -24,12 +26,15 @@ export default function ChangePasswordDialog({ onClose, onDone }: { onClose: () if (password !== confirmPassword) return setError("UsrPasswordMismatch"); setSaving(true); setError(null); + setRuleError(undefined); try { await changeOwnPassword(current, password, confirmPassword); onClose(); onDone(); } catch (err) { - setError(err instanceof Error ? err.message : "PwdChangeRequired"); + const rule = passwordRuleError(err, t); + if (rule) setRuleError(rule); + else setError(err instanceof Error ? err.message : "PwdChangeRequired"); setSaving(false); } } @@ -59,6 +64,7 @@ export default function ChangePasswordDialog({ onClose, onDone }: { onClose: () onPassword={setPassword} onConfirmPassword={setConfirmPassword} disabled={saving} + passwordError={ruleError} /> {error && (
diff --git a/solvway-admin-portal/app/components/dashboard/LeadDashboard.tsx b/solvway-admin-portal/app/components/dashboard/LeadDashboard.tsx index 0765bb2..3a94395 100644 --- a/solvway-admin-portal/app/components/dashboard/LeadDashboard.tsx +++ b/solvway-admin-portal/app/components/dashboard/LeadDashboard.tsx @@ -38,11 +38,12 @@ function bucketLabel(bucket: string, kind: "DAY" | "MONTH"): string { return new Date(Date.UTC(Number(y), Number(m) - 1, 1)).toLocaleString("en-GB", { month: "short", year: "numeric", timeZone: "UTC" }); } -function Tile({ label, value }: { label: string; value: string }) { +function Tile({ label, value, note }: { label: string; value: string; note?: string }) { return (
{label}
{value}
+ {note &&
{note}
}
); } @@ -138,7 +139,7 @@ export function LeadDashboard() {
- + @@ -146,7 +147,10 @@ export function LeadDashboard() {
- {t("DashFunnel")} + + {t("DashFunnel")} +

{t("DashFunnelNote")}

+
    {funnelRows.map(([key, label]) => { diff --git a/solvway-admin-portal/app/components/ui/confirm-dialog.tsx b/solvway-admin-portal/app/components/ui/confirm-dialog.tsx new file mode 100644 index 0000000..fa353d8 --- /dev/null +++ b/solvway-admin-portal/app/components/ui/confirm-dialog.tsx @@ -0,0 +1,36 @@ +"use client"; + +import { Button } from "@/app/components/ui/button"; +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog"; +import { useT } from "@/app/lib/i18n/MessagesProvider"; + +/** Cancel / confirm prompt; `onConfirm` is the caller's job to close it (it decides what stays open on failure). */ +export function ConfirmDialog(props: { + title: string; + message: string; + confirmLabel: string; + destructive?: boolean; + busy?: boolean; + onConfirm: () => void; + onCancel: () => void; +}) { + const t = useT(); + return ( + !open && props.onCancel()}> + + + {props.title} + {props.message} + + + + + + + + ); +} diff --git a/solvway-admin-portal/app/components/ui/data-table.cards.test.tsx b/solvway-admin-portal/app/components/ui/data-table.cards.test.tsx new file mode 100644 index 0000000..f03c365 --- /dev/null +++ b/solvway-admin-portal/app/components/ui/data-table.cards.test.tsx @@ -0,0 +1,87 @@ +import { describe, it, expect, vi } from "vitest"; +import { render, screen, fireEvent } from "@testing-library/react"; +import type { ColumnDef } from "@tanstack/react-table"; +import { DataTable } from "./data-table"; + +type Row = { id: string; name: string; company: string; tag: string }; +const columns: ColumnDef[] = [ + { accessorKey: "name", header: "Name" }, + { accessorKey: "company", header: "Company" }, + { accessorKey: "tag", header: () => Tag, enableSorting: false }, + { id: "actions", header: "Actions", enableSorting: false, cell: () => }, +]; +const data: Row[] = [{ id: "1", name: "Alpha", company: "INS", tag: "x" }]; + +function renderTable(extra: Partial>> = {}) { + return render( + label="t" columns={columns} data={data} total={1} page={1} pageSize={20} + onPageChange={() => {}} rowKey={r => r.id} {...extra} />, + ); +} +const cells = () => Array.from(screen.getByText("Alpha").closest("tr")!.querySelectorAll("td")); + +describe("DataTable phone cards", () => { + it("labels non-first cells with the header, leaves the title cell unlabelled", () => { + renderTable(); + const [title, company] = cells(); + expect(title).not.toHaveAttribute("data-label"); + expect(company).toHaveAttribute("data-label", "Company"); + }); + + it("gives a non-string header no label", () => { + renderTable(); + expect(cells()[2]).not.toHaveAttribute("data-label"); + }); + + it("puts the actions cell last, unlabelled", () => { + renderTable(); + const actions = cells()[3]; + expect(actions).not.toHaveAttribute("data-label"); + expect(actions.className).toContain("max-md:order-last"); + }); + + // jsdom applies no CSS, so these guard the classes that keep a card from overflowing at 360 px. + it("lets the card grow past the table row height", () => { + renderTable(); + expect(screen.getByText("Alpha").closest("tr")!.className).toContain("max-md:h-auto"); + }); + + it("wraps long title and values instead of scrolling sideways", () => { + renderTable(); + const [title, company] = cells(); + expect(title.className).toContain("max-md:whitespace-normal"); + expect(title.className).toContain("max-md:[overflow-wrap:anywhere]"); + expect(company.className).toContain("max-md:[overflow-wrap:anywhere]"); + }); + + // Pages wrap their buttons in one `flex gap-2` div; that div must wrap too, or the row clips at 360 px. + it("wraps the page's own button group inside the actions cell", () => { + renderTable(); + const actions = cells()[3]; + expect(actions.className).toContain("max-md:[&>div]:flex-wrap"); + expect(actions.className).toContain("max-md:[&>div]:justify-end"); + }); +}); + +describe("DataTable phone sort select", () => { + it("is absent without onSortingChange", () => { + renderTable(); + expect(screen.queryByRole("combobox", { name: "Sort by" })).toBeNull(); + }); + + it("lists sortable columns only, both directions", () => { + renderTable({ onSortingChange: () => {} }); + const select = screen.getByRole("combobox", { name: "Sort by" }); + const texts = Array.from(select.querySelectorAll("option")).map(o => o.textContent); + expect(texts).toEqual(["Sort by", "Name ↑", "Name ↓", "Company ↑", "Company ↓"]); + }); + + it("reflects the current sorting and reports changes", () => { + const onSortingChange = vi.fn(); + renderTable({ onSortingChange, sorting: [{ id: "company", desc: true }] }); + const select = screen.getByRole("combobox", { name: "Sort by" }) as HTMLSelectElement; + expect(select.value).toBe("company:desc"); + fireEvent.change(select, { target: { value: "name:asc" } }); + expect(onSortingChange).toHaveBeenCalledWith([{ id: "name", desc: false }]); + }); +}); diff --git a/solvway-admin-portal/app/components/ui/data-table.tsx b/solvway-admin-portal/app/components/ui/data-table.tsx index 7463b2a..1c8b336 100644 --- a/solvway-admin-portal/app/components/ui/data-table.tsx +++ b/solvway-admin-portal/app/components/ui/data-table.tsx @@ -50,6 +50,13 @@ const ROW_CONTROLS = 'a, button, input, select, textarea, label, [role="checkbox const PINNED_CELL = 'sticky left-0 z-[1] bg-card shadow-[inset_-1px_0_0_var(--border)] group-hover:bg-muted group-focus-visible:bg-muted group-aria-selected:bg-accent' +// Below md the table becomes one card per row (one DOM, CSS only; same technique as DashTable). +const CARD_CELL = + 'max-md:flex max-md:justify-between max-md:gap-4 max-md:whitespace-normal max-md:[overflow-wrap:anywhere] max-md:px-1 max-md:py-1 max-md:before:shrink-0 max-md:before:font-medium max-md:before:text-muted-foreground max-md:before:content-[attr(data-label)]' +// The title cell is the pinned one; below md it is a plain block, not pinned. +const CARD_TITLE = 'max-md:static max-md:bg-transparent max-md:shadow-none max-md:block max-md:whitespace-normal max-md:[overflow-wrap:anywhere] max-md:px-1 max-md:py-1 max-md:text-base max-md:font-semibold' +const CARD_ACTIONS = 'max-md:order-last max-md:flex max-md:flex-wrap max-md:justify-end max-md:gap-2 max-md:px-1 max-md:pt-2 max-md:[&>div]:flex-wrap max-md:[&>div]:justify-end' + /** * Data table for server-paginated, server-sorted result sets — which is what * every `src/services/*` list function returns. Pagination and sorting state are @@ -128,6 +135,12 @@ export function DataTable({ }) const visibleColumnCount = table.getVisibleLeafColumns().length + // Phone-card labels come from string headers only; other headers get no label. + const labelOf = (column: { columnDef: ColumnDef }) => + typeof column.columnDef.header === 'string' ? column.columnDef.header : undefined + const sortableColumns = onSortingChange + ? table.getVisibleLeafColumns().filter(c => c.getCanSort()) + : [] const hideableColumns = table.getAllLeafColumns().filter(c => c.getCanHide()) return ( @@ -159,10 +172,28 @@ export function DataTable({
)} + {sortableColumns.length > 0 && ( + + )} +
- - +
+ {table.getHeaderGroups().map(headerGroup => ( {headerGroup.headers.map((header, index) => { @@ -192,7 +223,7 @@ export function DataTable({ ))} - + {isLoading ? ( Array.from({ length: Math.min(pageSize, 8) }).map((_, rowIndex) => ( @@ -214,7 +245,7 @@ export function DataTable({ ({ {row.getVisibleCells().map((cell, index) => ( {flexRender(cell.column.columnDef.cell, cell.getContext())} diff --git a/solvway-admin-portal/app/components/ui/states.tsx b/solvway-admin-portal/app/components/ui/states.tsx index 77de151..95c2546 100644 --- a/solvway-admin-portal/app/components/ui/states.tsx +++ b/solvway-admin-portal/app/components/ui/states.tsx @@ -37,10 +37,13 @@ export function EmptyState({ export function ErrorState({ message, + hint, onRetry, className, }: { message: string + /** A second, muted line under the message. */ + hint?: string onRetry?: () => void className?: string }) { @@ -61,7 +64,10 @@ export function ErrorState({ >
{onRetry && ( @@ -137,12 +143,15 @@ function InterestFormDialog({ function InterestsPageContent() { const t = useT(); - const readOnly = useAdminAuth().isSuper === false; // super-admin-only writes; server returns 403 anyway + const { isSuper } = useAdminAuth(); + const readOnly = isSuper === false; // super-admin-only writes; server returns 403 anyway const [interests, setInterests] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); + const [actionError, setActionError] = useState(null); const [reloadKey, setReloadKey] = useState(0); const [dialog, setDialog] = useState(null); + const [confirm, setConfirm] = useState<{ kind: "delete" | "deactivate"; item: AdminInterestEntity } | null>(null); const refetch = useCallback(() => setReloadKey((k) => k + 1), []); @@ -206,18 +215,7 @@ function InterestsPageContent() { {t("Edit")} {row.original.active ? ( - ) : ( @@ -229,20 +227,39 @@ function InterestsPageContent() { await saveAdminInterest({ id: row.original.id, active: true }); refetch(); } catch { - setError("IntActivateFailed"); + setActionError("IntActivateFailed"); } }} > {t("IntActivate")} )} + {isSuper === true && ( + + )} ), }]), ], - [t, refetch, readOnly], + [t, refetch, readOnly, isSuper], ); + async function runConfirmed() { + if (!confirm) return; + const { kind, item } = confirm; + setConfirm(null); + setActionError(null); + try { + if (kind === "delete") await deleteAdminInterest(item.id!); + else await saveAdminInterest({ id: item.id, active: false }); + refetch(); + } catch { + setActionError(kind === "delete" ? "IntDeleteFailed" : "IntDeactivateFailed"); + } + } + return ( <> {error && } + {/* An action that failed: retrying the list would not help, so no Retry. */} + {actionError && } } /> + {confirm && ( + setConfirm(null)} + /> + )} + {dialog && ( setDialog(null)} onSaved={refetch} /> )} diff --git a/solvway-admin-portal/app/lib/i18n/defaultMessages.ts b/solvway-admin-portal/app/lib/i18n/defaultMessages.ts index d9988b1..8682827 100644 --- a/solvway-admin-portal/app/lib/i18n/defaultMessages.ts +++ b/solvway-admin-portal/app/lib/i18n/defaultMessages.ts @@ -95,6 +95,7 @@ export const DEFAULT_MESSAGES: Record = { UiColumns: "Columns", UiVisibleColumns: "Visible columns", UiNoResults: "No results.", + UiSortBy: "Sort by", UiRetry: "Retry", UiLoading: "Loading", NotAuthorizedTitle: "Not authorised", @@ -199,7 +200,22 @@ export const DEFAULT_MESSAGES: Record = { UsrSetPasswordSubmit: "Set password", UsrSetPasswordFailed: "Failed to set the password.", UsrTempPasswordSet: "Temporary password set. The user must change it at next sign-in.", - AdminPasswordHint: "At least 8 characters, with at least one capital letter and one small letter.", + PwdHint_ALPHABET_LENGTH_MIN: "Letters: at least {n}", + PwdHint_ALPHABET_LENGTH_MAX: "Letters: at most {n}", + PwdHint_NUMERIC_LENGTH_MIN: "Digits: at least {n}", + PwdHint_NUMERIC_LENGTH_MAX: "Digits: at most {n}", + PwdHint_UPPERCASE_LENGTH_MIN: "Capital letters: at least {n}", + PwdHint_UPPERCASE_LENGTH_MAX: "Capital letters: at most {n}", + PwdHint_LOWERCASE_LENGTH_MIN: "Small letters: at least {n}", + PwdHint_LOWERCASE_LENGTH_MAX: "Small letters: at most {n}", + PwdHint_SYMBOLIC_LENGTH_MIN: "Symbols: at least {n}", + PwdHint_SYMBOLIC_LENGTH_MAX: "Symbols: at most {n}", + PwdHint_INPUT_LENGTH_MIN: "Length: at least {n}", + PwdHint_INPUT_LENGTH_MAX: "Length: at most {n}", + PwdHint_NO_OTHER_LANGUAGE: "English letters only", + PwdHint_SPACE_NOT_ALLOWED: "No spaces", + PwdRuleRefused: 'Password does not meet the rule "{rule}"', + LoginStaffCompanyHint: "Staff sign in with their company code.", UiDatePlaceholder: "DD/MM/YYYY", UiOpenCalendarFor: "Open calendar for {label}", UiOpenCalendar: "Open calendar", @@ -297,6 +313,22 @@ export const DEFAULT_MESSAGES: Record = { IntDeactivate: "Deactivate", IntActivateFailed: "Failed to activate interest.", IntDeactivateFailed: "Failed to deactivate interest.", + IntDelete: "Delete", + IntDeleteTitle: "Delete interest", + IntDeleteConfirm: "Delete \"{name}\"? It disappears from the list and can no longer be chosen.", + IntDeleteFailed: "Failed to delete interest.", + IntDeactivateTitle: "Deactivate interest", + IntDeactivateConfirm: "Deactivate \"{name}\"? It can no longer be chosen until activated again.", + IntNameDeleted: "This name belongs to a deleted interest.", + RolDelete: "Delete", + RolDeleteTitle: "Delete role", + RolDeleteConfirm: "Delete role \"{name}\"?", + RolDeleteFailed: "Failed to delete role.", + RolInUse: "Users holding this role: {n}. Remove it from them first.", + RolProtected: "This role is built in and cannot be deleted.", + RolNameDeleted: "This name belongs to a deleted role.", + DashWonInPeriodNote: "Leads won in this period, whenever they were captured.", + DashFunnelNote: "This period's captures, by their current stage.", // Event leads messages BO_EVENT_LEADS: "Event leads", LeadName: "Name", diff --git a/solvway-admin-portal/app/lib/server/mobileApi.problemProps.test.ts b/solvway-admin-portal/app/lib/server/mobileApi.problemProps.test.ts new file mode 100644 index 0000000..7d1dd2f --- /dev/null +++ b/solvway-admin-portal/app/lib/server/mobileApi.problemProps.test.ts @@ -0,0 +1,33 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { callMobileApi } from "./mobileApi"; + +let fetchMock: ReturnType; +const fail = (body: unknown) => + fetchMock.mockResolvedValue({ ok: false, status: 400, text: async () => JSON.stringify(body) } as Response); + +beforeEach(() => { + vi.stubEnv("MOBILE_API_BASE_URL", "https://mobile.example.test"); + vi.stubEnv("MOBILE_API_KEY", "k"); + fetchMock = vi.fn(); + vi.stubGlobal("fetch", fetchMock); +}); +afterEach(() => { + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); +}); + +describe("callMobileApi — ProblemDetail properties", () => { + it("surfaces param, value and users as details", async () => { + fail({ detail: "PASSWORD_RULE", code: "PASSWORD_RULE", param: "INPUT_LENGTH_MIN", value: 8 }); + expect(await callMobileApi("/x", { token: "t" })).toMatchObject({ code: "PASSWORD_RULE", details: { param: "INPUT_LENGTH_MIN", value: 8 } }); + fail({ detail: "ROLE_IN_USE", code: "ROLE_IN_USE", users: 3 }); + expect(await callMobileApi("/x", { token: "t" })).toMatchObject({ code: "ROLE_IN_USE", details: { users: 3 } }); + }); + + it("omits a null value (flag rules)", async () => { + fail({ detail: "PASSWORD_RULE", code: "PASSWORD_RULE", param: "SPACE_NOT_ALLOWED", value: null }); + const r = await callMobileApi("/x", { token: "t" }); + expect(r).toMatchObject({ details: { param: "SPACE_NOT_ALLOWED" } }); + expect((r as { details: object }).details).not.toHaveProperty("value"); + }); +}); diff --git a/solvway-admin-portal/app/lib/server/mobileApi.ts b/solvway-admin-portal/app/lib/server/mobileApi.ts index 0915463..ac67f59 100644 --- a/solvway-admin-portal/app/lib/server/mobileApi.ts +++ b/solvway-admin-portal/app/lib/server/mobileApi.ts @@ -29,16 +29,24 @@ function isExpiredSignal(status: number, raw: string): boolean { ); } -/** An upstream `details` object, kept only when it is a flat object of string/number/boolean values. */ +/** + * An upstream `details` object, kept only when it is a flat object of string/number/boolean values, + * plus the scalar problem properties the portal turns into messages (`param`, `value`, `users`). + */ function extractDetails(parsed: unknown): Record | undefined { if (!parsed || typeof parsed !== "object") return undefined; - const details = (parsed as { details?: unknown }).details; - if (!details || typeof details !== "object" || Array.isArray(details)) return undefined; - const values = Object.values(details as Record); - const scalar = values.every(v => typeof v === "string" || typeof v === "number" || typeof v === "boolean"); - return scalar ? (details as Record) : undefined; + const o = parsed as Record; + const details = o.details; + const base = details && typeof details === "object" && !Array.isArray(details) ? (details as Record) : undefined; + if (base && !Object.values(base).every(isScalar)) return undefined; + const props: Record = {}; + for (const k of ["param", "value", "users"]) if (isScalar(o[k])) props[k] = o[k]; + const merged = { ...props, ...base }; + return Object.keys(merged).length ? (merged as Record) : undefined; } +const isScalar = (v: unknown) => typeof v === "string" || typeof v === "number" || typeof v === "boolean"; + function extractError(parsed: unknown): string | undefined { if (parsed && typeof parsed === "object") { const o = parsed as Record; diff --git a/solvway-admin-portal/app/lib/services/adminInterests.ts b/solvway-admin-portal/app/lib/services/adminInterests.ts index 6dd0a1e..86d4ee0 100644 --- a/solvway-admin-portal/app/lib/services/adminInterests.ts +++ b/solvway-admin-portal/app/lib/services/adminInterests.ts @@ -1,4 +1,4 @@ -import { apiGet, apiPost, apiPut } from "@/app/lib/clientApi"; +import { apiGet, apiPost, apiPut, apiDelete } from "@/app/lib/clientApi"; import type { AdminInterestEntity } from "@/app/lib/types"; export async function listAdminInterests(): Promise { @@ -10,3 +10,5 @@ export async function saveAdminInterest(payload: AdminInterestEntity): Promise(`/api/interests/${payload.id}`, payload) : apiPost("/api/interests", payload); } + +export const deleteAdminInterest = (id: number) => apiDelete(`/api/interests/${id}`); diff --git a/solvway-admin-portal/app/lib/services/adminRoles.ts b/solvway-admin-portal/app/lib/services/adminRoles.ts index 3bbd0d7..87dfcee 100644 --- a/solvway-admin-portal/app/lib/services/adminRoles.ts +++ b/solvway-admin-portal/app/lib/services/adminRoles.ts @@ -1,4 +1,4 @@ -import { apiGet, apiPost, apiPut } from "@/app/lib/clientApi"; +import { apiGet, apiPost, apiPut, apiDelete } from "@/app/lib/clientApi"; import type { AdminRoleEntity } from "@/app/lib/types"; export async function listAdminRoles(): Promise { @@ -14,3 +14,5 @@ export async function saveAdminRole(payload: AdminRoleEntity): Promise(`/api/roles/${payload.id}`, payload) : apiPost("/api/roles", payload); } + +export const deleteAdminRole = (id: number) => apiDelete(`/api/roles/${id}`); diff --git a/solvway-admin-portal/app/login/page.companyHint.test.tsx b/solvway-admin-portal/app/login/page.companyHint.test.tsx new file mode 100644 index 0000000..bd57c50 --- /dev/null +++ b/solvway-admin-portal/app/login/page.companyHint.test.tsx @@ -0,0 +1,65 @@ +import { render, screen, waitFor, fireEvent } from "@testing-library/react"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }) })); +vi.mock("@/app/lib/clientApi", () => ({ + apiPost: vi.fn(), + ApiError: class ApiError extends Error { + constructor(m: string, public status = 0, public data?: unknown) { + super(m); + } + }, +})); +vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ refresh: vi.fn() }) })); + +import LoginPage from "./page"; +import { apiPost, ApiError } from "@/app/lib/clientApi"; + +const mockPost = apiPost as unknown as ReturnType; +const HINT = "Staff sign in with their company code."; + +function submit(username: string, company = "") { + fireEvent.change(screen.getByLabelText("Company"), { target: { value: company } }); + fireEvent.change(screen.getByLabelText("Username"), { target: { value: username } }); + fireEvent.change(screen.getByLabelText("Password"), { target: { value: "x" } }); + fireEvent.submit(screen.getByRole("button", { name: /log in/i })); +} + +beforeEach(() => { + mockPost.mockReset().mockRejectedValue(new ApiError("LoginInvalidCredentials", 401)); +}); + +describe("LoginPage company hint", () => { + it("adds the company-code hint to a failed sign-in with no company", async () => { + render(); + submit("staff1"); + const alert = await screen.findByRole("alert"); + expect(alert).toHaveTextContent("Invalid"); + expect(alert).toHaveTextContent(HINT); + }); + + it("shows the same text for an unknown username and a staff username", async () => { + const { unmount } = render(); + submit("nobody"); + const unknown = (await screen.findByRole("alert")).textContent; + unmount(); + render(); + submit("staff1"); + expect((await screen.findByRole("alert")).textContent).toBe(unknown); + }); + + it.each([0, 429, 500])("does not add the hint when the failure is HTTP %i, not bad credentials", async (status) => { + mockPost.mockRejectedValue(new ApiError("Something went wrong", status)); + render(); + submit("staff1"); + await waitFor(() => expect(screen.getByRole("alert")).toBeInTheDocument()); + expect(screen.queryByText(HINT)).toBeNull(); + }); + + it("does not add the hint when a company was typed", async () => { + render(); + submit("staff1", "ins"); + await waitFor(() => expect(screen.getByRole("alert")).toBeInTheDocument()); + expect(screen.queryByText(HINT)).toBeNull(); + }); +}); diff --git a/solvway-admin-portal/app/login/page.tsx b/solvway-admin-portal/app/login/page.tsx index 6ade404..a61c087 100644 --- a/solvway-admin-portal/app/login/page.tsx +++ b/solvway-admin-portal/app/login/page.tsx @@ -36,10 +36,12 @@ export default function LoginPage() { // Read after hydration (the server renders without it), so server and client markup agree. const elsewhere = useSyncExternalStore(noSubscription, () => signedInElsewhere(document.cookie), () => false); const [submitting, setSubmitting] = useState(false); + const [companyHint, setCompanyHint] = useState(false); async function handleSubmit(event: React.FormEvent) { event.preventDefault(); setError(null); + setCompanyHint(false); setSubmitting(true); try { const res = await apiPost<{ name: string; resetPasswordRequired: boolean }>("/api/auth/login", { @@ -60,6 +62,8 @@ export default function LoginPage() { router.refresh(); } catch (err) { const locked = err instanceof ApiError && (err.data as { code?: unknown } | undefined)?.code === "ACCOUNT_LOCKED"; + // From form state only, so an unknown username and a staff user without a company read the same. + setCompanyHint(err instanceof ApiError && err.status === 401 && !locked && !company.trim()); setError(locked ? "LoginAccountLocked" : err instanceof Error ? err.message : "LoginInvalidCredentials"); } finally { setSubmitting(false); @@ -73,7 +77,7 @@ export default function LoginPage() {

{t("BackOfficeSubtitle")}

- {error ? : elsewhere && } + {error ? : elsewhere && }
diff --git a/solvway-admin-portal/app/page.dashboard.lines.test.tsx b/solvway-admin-portal/app/page.dashboard.lines.test.tsx new file mode 100644 index 0000000..f9714e1 --- /dev/null +++ b/solvway-admin-portal/app/page.dashboard.lines.test.tsx @@ -0,0 +1,37 @@ +import { render, screen, within } from "@testing-library/react"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ getLeadDashboard: vi.fn(), useAdminAuth: vi.fn(), useCompanyScope: vi.fn() })); +vi.mock("@/app/lib/services/adminDashboard", () => ({ getLeadDashboard: mocks.getLeadDashboard })); +vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth })); +vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope })); +vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock); + +import HomePage from "./page"; + +const DATA = { + from: "2026-12-01", to: "2026-12-01", bucket: "DAY", + captures: 40, newLeads: 25, wonInPeriod: 8, medianDaysToWin: 4.5, overdueFollowUps: 3, + funnel: { OPEN: 11, CONTACTED: 12, QUALIFIED: 13, WON: 8, LOST: 6 }, + trend: [], events: [], salespeople: [], interests: [], +}; + +beforeEach(() => { + mocks.getLeadDashboard.mockReset().mockResolvedValue(DATA); + mocks.useAdminAuth.mockReset().mockReturnValue({ name: "Alice", loading: false, isSuper: false, hasModule: (m: string) => m === "BO_DASHBOARD" }); + mocks.useCompanyScope.mockReset().mockReturnValue({ companyId: undefined, companies: [], showCompanyColumn: false, codeOf: () => "", setCompanyId: vi.fn() }); +}); + +describe("dashboard explanation lines", () => { + it("explains Won in period as visible text inside its tile", async () => { + render(); + const tile = within(await screen.findByRole("group", { name: "Won in period" })); + expect(tile.getByText("Leads won in this period, whenever they were captured.")).toBeVisible(); + }); + + it("explains the funnel as visible text", async () => { + render(); + await screen.findByRole("group", { name: "Captures" }); + expect(screen.getByText("This period's captures, by their current stage.")).toBeVisible(); + }); +}); diff --git a/solvway-admin-portal/app/reset-password/page.rules.test.tsx b/solvway-admin-portal/app/reset-password/page.rules.test.tsx new file mode 100644 index 0000000..9eb0a4a --- /dev/null +++ b/solvway-admin-portal/app/reset-password/page.rules.test.tsx @@ -0,0 +1,61 @@ +import { render, screen, fireEvent, within, waitFor } from "@testing-library/react"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn() }) })); +vi.mock("@/app/lib/clientApi", async (importOriginal) => ({ + ApiError: (await importOriginal()).ApiError, + apiGet: vi.fn(), + apiPost: vi.fn(), +})); +vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ refresh: vi.fn() }) })); + +import ResetPasswordPage from "./page"; +import { apiGet, apiPost, ApiError } from "@/app/lib/clientApi"; + +const get = apiGet as unknown as ReturnType; +const post = apiPost as unknown as ReturnType; + +beforeEach(() => { + get.mockReset().mockResolvedValue([{ param: "INPUT_LENGTH_MIN", value: 10 }, { param: "SPACE_NOT_ALLOWED", value: null }]); + post.mockReset(); +}); + +describe("ResetPasswordPage rules", () => { + it("lists the switched-on rules from the public route", async () => { + render(); + expect(await screen.findByText("Length: at least 10")).toBeInTheDocument(); + expect(screen.getByText("No spaces")).toBeInTheDocument(); + expect(get).toHaveBeenCalledWith("/api/public/password-rules"); + }); + + it("ties the hint and the refusal to the password input with aria-describedby", async () => { + post.mockRejectedValue(new ApiError("PASSWORD_RULE", 400, { code: "PASSWORD_RULE", details: { param: "INPUT_LENGTH_MIN", value: 10 } })); + render(); + await screen.findByText("No spaces"); + const input = screen.getByLabelText("New password"); + // onShown reaches the parent one render after the hint appears. + await waitFor(() => expect(input.getAttribute("aria-describedby")).toBe("newPasswordRules")); + fireEvent.change(input, { target: { value: "Short1" } }); + fireEvent.change(screen.getByLabelText("Confirm new password"), { target: { value: "Short1" } }); + fireEvent.submit(screen.getByRole("button", { name: /set password/i })); + const alert = await screen.findByRole("alert"); + expect(input.getAttribute("aria-describedby")).toBe(`newPasswordRules ${alert.id}`); + }); + + it("sets no aria-describedby when the rules cannot be loaded", async () => { + get.mockRejectedValue(new Error("down")); + render(); + await new Promise((r) => setTimeout(r, 0)); + expect(screen.getByLabelText("New password")).not.toHaveAttribute("aria-describedby"); + }); + + it("names the refused rule at the password field", async () => { + post.mockRejectedValue(new ApiError("PASSWORD_RULE", 400, { code: "PASSWORD_RULE", details: { param: "INPUT_LENGTH_MIN", value: 10 } })); + render(); + fireEvent.change(screen.getByLabelText("New password"), { target: { value: "Short1" } }); + fireEvent.change(screen.getByLabelText("Confirm new password"), { target: { value: "Short1" } }); + fireEvent.submit(screen.getByRole("button", { name: /set password/i })); + const alert = await screen.findByRole("alert"); + expect(within(alert).getByText('Password does not meet the rule "Length: at least 10"')).toBeInTheDocument(); + }); +}); diff --git a/solvway-admin-portal/app/reset-password/page.test.tsx b/solvway-admin-portal/app/reset-password/page.test.tsx index 232d1a0..99979d0 100644 --- a/solvway-admin-portal/app/reset-password/page.test.tsx +++ b/solvway-admin-portal/app/reset-password/page.test.tsx @@ -5,6 +5,7 @@ const nav = vi.hoisted(() => ({ push: vi.fn() })); vi.mock("next/navigation", () => ({ useRouter: () => ({ push: nav.push }) })); vi.mock("@/app/lib/clientApi", () => ({ apiPost: vi.fn(), + apiGet: vi.fn().mockResolvedValue([{ param: "INPUT_LENGTH_MIN", value: 8 }, { param: "UPPERCASE_LENGTH_MIN", value: 1 }]), ApiError: class ApiError extends Error {}, })); const refresh = vi.fn(); @@ -35,9 +36,10 @@ describe("ResetPasswordPage (first sign-in)", () => { expect(screen.getByLabelText("Confirm new password")).toBeInTheDocument(); }); - it("states the password rules under the new password field", () => { + it("states the password rules under the new password field", async () => { render(); - expect(screen.getByText("At least 8 characters, with at least one capital letter and one small letter.")).toBeInTheDocument(); + expect(await screen.findByText("Length: at least 8")).toBeInTheDocument(); + expect(screen.getByText("Capital letters: at least 1")).toBeInTheDocument(); }); it("shows the choose-a-new-password intro, not the temporary-password one", () => { diff --git a/solvway-admin-portal/app/reset-password/page.tsx b/solvway-admin-portal/app/reset-password/page.tsx index a369c07..19e2ed1 100644 --- a/solvway-admin-portal/app/reset-password/page.tsx +++ b/solvway-admin-portal/app/reset-password/page.tsx @@ -10,6 +10,7 @@ import { ErrorState } from "@/app/components/ui/states"; import { apiPost } from "@/app/lib/clientApi"; import { useAdminAuth } from "@/app/lib/AdminAuthContext"; import { useT } from "@/app/lib/i18n/MessagesProvider"; +import { PasswordRulesHint, passwordRuleError } from "@/app/components/users/PasswordRulesHint"; import AuthFrame from "@/app/components/app/AuthFrame"; // First sign-in: login answered resetPasswordRequired (the account is still on the temporary @@ -21,11 +22,14 @@ export default function ResetPasswordPage() { const [newPassword, setNewPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState(""); const [error, setError] = useState(null); + const [ruleError, setRuleError] = useState(null); + const [hintShown, setHintShown] = useState(false); const [submitting, setSubmitting] = useState(false); async function handleSubmit(event: React.FormEvent) { event.preventDefault(); setError(null); + setRuleError(null); if (!newPassword || !confirmPassword) { setError("ResetAllRequired"); return; @@ -40,7 +44,9 @@ export default function ResetPasswordPage() { await refresh(); router.push("/"); } catch (err) { - setError(err instanceof Error ? err.message : "ResetFailed"); + const rule = passwordRuleError(err, t); + if (rule) setRuleError(rule); + else setError(err instanceof Error ? err.message : "ResetFailed"); } finally { setSubmitting(false); } @@ -63,10 +69,11 @@ export default function ResetPasswordPage() { value={newPassword} onChange={(e) => setNewPassword(e.target.value)} disabled={submitting} - aria-describedby="newPasswordRules" + aria-describedby={[hintShown && "newPasswordRules", ruleError && "newPasswordError"].filter(Boolean).join(" ") || undefined} className="h-11 bg-card" /> -

{t("AdminPasswordHint")}

+ + {ruleError && }
diff --git a/solvway-admin-portal/app/roles/page.delete.test.tsx b/solvway-admin-portal/app/roles/page.delete.test.tsx new file mode 100644 index 0000000..9f2e756 --- /dev/null +++ b/solvway-admin-portal/app/roles/page.delete.test.tsx @@ -0,0 +1,106 @@ +import { render, screen, waitFor, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ list: vi.fn(), apiPost: vi.fn(), apiPut: vi.fn(), apiDelete: vi.fn(), useAdminAuth: vi.fn() })); +vi.mock("@/app/lib/clientApi", async (importOriginal) => ({ + ApiError: (await importOriginal()).ApiError, + apiGet: vi.fn(), + apiPost: mocks.apiPost, + apiPut: mocks.apiPut, + apiDelete: mocks.apiDelete, +})); +vi.mock("@/app/lib/services/adminRoles", async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, listAdminRoles: mocks.list }; +}); +vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth })); + +import RolesPage from "./page"; +import { ApiError } from "@/app/lib/clientApi"; + +const ROWS = [ + { id: 1, name: "ROLE_SUPER_ADMIN" }, + { id: 4, name: "ROLE_HQ", parent: { id: 1 } }, +]; + +beforeEach(() => { + mocks.list.mockReset().mockResolvedValue(ROWS); + mocks.apiPost.mockReset(); + mocks.apiPut.mockReset(); + mocks.apiDelete.mockReset().mockResolvedValue({}); + mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true, hasModule: () => true }); +}); + +const rowOf = async (code: string) => (await screen.findByText(code)).closest("tr")!; +const openDelete = async () => userEvent.click(within(await rowOf("ROLE_HQ")).getByRole("button", { name: "Delete" })); + +describe("Roles delete", () => { + it("deletes after confirming", async () => { + render(); + await openDelete(); + expect(mocks.apiDelete).not.toHaveBeenCalled(); + await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Delete" })); + await waitFor(() => expect(mocks.apiDelete).toHaveBeenCalledWith("/api/roles/4")); + }); + + it("cancel closes the confirmation without deleting", async () => { + render(); + await openDelete(); + await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Cancel" })); + expect(screen.queryByRole("dialog")).toBeNull(); + expect(mocks.apiDelete).not.toHaveBeenCalled(); + }); + + it("names how many users hold a role that is in use", async () => { + mocks.apiDelete.mockRejectedValue(new ApiError("ROLE_IN_USE", 409, { code: "ROLE_IN_USE", details: { users: 3 } })); + render(); + await openDelete(); + await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Delete" })); + expect(await screen.findByText("Users holding this role: 3. Remove it from them first.")).toBeInTheDocument(); + }); + + it("offers no Retry on a refused delete: retrying cannot succeed", async () => { + mocks.apiDelete.mockRejectedValue(new ApiError("ROLE_IN_USE", 409, { code: "ROLE_IN_USE", details: { users: 3 } })); + render(); + await openDelete(); + await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Delete" })); + await screen.findByText("Users holding this role: 3. Remove it from them first."); + expect(screen.queryByRole("button", { name: /retry/i })).toBeNull(); + }); + + it("styles the row Delete as destructive-outline", async () => { + render(); + expect(within(await rowOf("ROLE_HQ")).getByRole("button", { name: "Delete" })).toHaveAttribute("data-variant", "destructive-outline"); + }); + + it("offers no Delete on a protected role, and none to non-super staff", async () => { + render(); + expect(within(await rowOf("ROLE_SUPER_ADMIN")).queryByRole("button", { name: "Delete" })).toBeNull(); + expect(within(await rowOf("ROLE_HQ")).getByRole("button", { name: "Delete" })).toBeInTheDocument(); + }); + + it("hides Delete from staff who are not super admins", async () => { + mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper: false, hasModule: () => true }); + render(); + await screen.findByText("ROLE_HQ"); + expect(screen.queryByRole("button", { name: "Delete" })).toBeNull(); + }); + + it("says a role name belongs to a deleted role", async () => { + mocks.apiPost.mockRejectedValue(new ApiError("ROLE_NAME_DELETED", 409, { error: "ROLE_NAME_DELETED", code: "ROLE_NAME_DELETED" })); + render(); + await userEvent.click(await screen.findByRole("button", { name: /add role/i })); + await userEvent.type(screen.getByLabelText(/role name/i), "ROLE_OLD"); + await userEvent.click(screen.getByRole("button", { name: "Save" })); + expect(await screen.findByText("This name belongs to a deleted role.")).toBeInTheDocument(); + }); + + it("Cancel in the add dialog closes it without saving", async () => { + render(); + await userEvent.click(await screen.findByRole("button", { name: /add role/i })); + await userEvent.click(screen.getByRole("button", { name: "Cancel" })); + expect(screen.queryByLabelText(/role name/i)).toBeNull(); + expect(mocks.apiPost).not.toHaveBeenCalled(); + }); +}); diff --git a/solvway-admin-portal/app/roles/page.tsx b/solvway-admin-portal/app/roles/page.tsx index ae7c3c5..ab9beba 100644 --- a/solvway-admin-portal/app/roles/page.tsx +++ b/solvway-admin-portal/app/roles/page.tsx @@ -7,6 +7,7 @@ import { useAdminAuth } from "@/app/lib/AdminAuthContext"; import { Button } from "@/app/components/ui/button"; import { Input } from "@/app/components/ui/input"; import { Label } from "@/app/components/ui/label"; +import { ConfirmDialog } from "@/app/components/ui/confirm-dialog"; import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog"; import { DataTable } from "@/app/components/ui/data-table"; import { sortRows } from "@/app/components/ui/sortable-head"; @@ -14,7 +15,7 @@ import { PageHeader } from "@/app/components/ui/page-header"; import { EmptyState, ErrorState } from "@/app/components/ui/states"; import { RequireModule } from "@/app/lib/RequireModule"; import { roleLabel } from "@/app/lib/roleLabel"; -import { listAdminRoles, saveAdminRole } from "@/app/lib/services/adminRoles"; +import { deleteAdminRole, listAdminRoles, saveAdminRole } from "@/app/lib/services/adminRoles"; import type { AdminRoleEntity } from "@/app/lib/types"; import { useT } from "@/app/lib/i18n/MessagesProvider"; @@ -23,6 +24,9 @@ interface FormState { name: string; } +// ponytail: mirrors the server list (ROLE_PROTECTED); a role flag from the API would replace it. +const PROTECTED_ROLES = ["ROLE_SUPER_ADMIN", "ROLE_ADMIN", "ROLE_MEMBER"]; + const EMPTY_FORM: FormState = { name: "" }; function RoleFormDialog({ @@ -52,7 +56,8 @@ function RoleFormDialog({ onSaved(); onClose(); } catch (err) { - setError(err instanceof Error ? err.message : "RolSaveFailed"); + const code = (err as { data?: { code?: string } }).data?.code; + setError(code === "ROLE_NAME_DELETED" ? "RolNameDeleted" : err instanceof Error ? err.message : "RolSaveFailed"); } finally { setSaving(false); } @@ -77,6 +82,9 @@ function RoleFormDialog({ />
+ @@ -89,13 +97,16 @@ function RoleFormDialog({ function RolesPageContent() { const t = useT(); - const readOnly = useAdminAuth().isSuper === false; // super-admin-only writes; server returns 403 anyway + const { isSuper } = useAdminAuth(); + const readOnly = isSuper === false; // super-admin-only writes; server returns 403 anyway const [roles, setRoles] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); + const [actionError, setActionError] = useState(null); const [reloadKey, setReloadKey] = useState(0); const [sorting, setSorting] = useState([]); const [dialog, setDialog] = useState(null); + const [confirmDelete, setConfirmDelete] = useState(null); const refetch = useCallback(() => setReloadKey((k) => k + 1), []); @@ -165,13 +176,34 @@ function RolesPageContent() {
+ {isSuper === true && !PROTECTED_ROLES.includes(row.original.name) && ( + + )} ), }]), ], - [parentLabel, t, readOnly], + [parentLabel, t, readOnly, isSuper], ); + async function runDelete() { + if (!confirmDelete) return; + const role = confirmDelete; + setConfirmDelete(null); + setActionError(null); + try { + await deleteAdminRole(role.id!); + refetch(); + } catch (err) { + const data = (err as { data?: { code?: string; details?: { users?: number } } }).data; + if (data?.code === "ROLE_IN_USE") setActionError(t("RolInUse", { n: data.details?.users ?? 0 })); + else if (data?.code === "ROLE_PROTECTED") setActionError("RolProtected"); + else setActionError("RolDeleteFailed"); + } + } + return ( <> {error && } + {/* An action that failed: retrying the list would not help, so no Retry. */} + {actionError && } } /> + {confirmDelete && ( + setConfirmDelete(null)} + /> + )} + {dialog && ( setDialog(null)} onSaved={refetch} /> )} diff --git a/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java b/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java index a485a77..95946f1 100644 --- a/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java +++ b/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java @@ -55,7 +55,9 @@ public class JWTAuthFilter implements GlobalFilter, Ordered { publicPath(HttpMethod.POST, "/counter/eventGuest/register"), publicPath(HttpMethod.GET, "/counter/checkin/findEvent/[A-Za-z0-9_-]{22}"), publicPath(HttpMethod.POST, "/counter/checkin/lookup"), - publicPath(HttpMethod.POST, "/counter/checkin/byGuest")); + publicPath(HttpMethod.POST, "/counter/checkin/byGuest"), + // Password hint on public password screens: switched-on rule names and numbers only, no user data + publicPath(HttpMethod.GET, "/passwordRule/adminActive")); private static Map.Entry publicPath(HttpMethod method, String regex) { return Map.entry(method, Pattern.compile(regex)); diff --git a/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterPasswordRulePathTest.java b/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterPasswordRulePathTest.java new file mode 100644 index 0000000..36b4c39 --- /dev/null +++ b/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterPasswordRulePathTest.java @@ -0,0 +1,74 @@ +package com.solvway.gateway.filter; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.solvway.gateway.model.AuthAppKey; +import com.solvway.gateway.model.AuthAppKeyMap; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; +import org.springframework.test.util.ReflectionTestUtils; +import reactor.core.publisher.Mono; + +import java.net.InetSocketAddress; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.assertj.core.api.Assertions.assertThat; + +/** The public password hint opens exactly GET /passwordRule/adminActive without a user token; nothing else opens. */ +class JWTAuthFilterPasswordRulePathTest { + + private static final String KEY = "gateway-test-key"; + + private JWTAuthFilter filter; + + @BeforeEach + void setUp() throws Exception { + AuthAppKey key = new ObjectMapper().readValue( + "{\"key\":\"" + KEY + "\",\"type\":\"BO\",\"ipList\":[\"0.0.0.0/0\"],\"allowList\":[\"/\"]}", + AuthAppKey.class); + AuthAppKeyMap map = new AuthAppKeyMap(); + map.add(KEY, key); + filter = new JWTAuthFilter(); + ReflectionTestUtils.setField(filter, "authAppKeyMap", map); + } + + private MockServerWebExchange call(HttpMethod method, String path) { + return MockServerWebExchange.from(MockServerHttpRequest.method(method, path) + .header("api-key", KEY) + .remoteAddress(new InetSocketAddress("127.0.0.1", 40000))); + } + + private boolean passes(MockServerWebExchange exchange) { + AtomicBoolean called = new AtomicBoolean(false); + GatewayFilterChain chain = ex -> { + called.set(true); + return Mono.empty(); + }; + filter.filter(exchange, chain).block(); + return called.get(); + } + + @Test + void adminActiveRulesNeedNoUserToken() { + assertThat(passes(call(HttpMethod.GET, "/passwordRule/adminActive"))).isTrue(); + } + + @Test + void everythingElseOnTheRuleControllerStillNeedsAToken() { + for (String[] c : new String[][] { + {"POST", "/passwordRule/adminActive"}, + {"GET", "/passwordRule/adminActive/x"}, + {"GET", "/passwordRule/adminActive/"}, + {"GET", "/passwordRule/adminActiveX"}, + {"GET", "/passwordRule/findByType/ADMIN_PWD_FORMAT"}, + {"POST", "/passwordRule/save"} }) { + MockServerWebExchange ex = call(HttpMethod.valueOf(c[0]), c[1]); + assertThat(passes(ex)).as(c[0] + " " + c[1]).isFalse(); + assertThat(ex.getResponse().getStatusCode()).as(c[0] + " " + c[1]).isEqualTo(HttpStatus.UNAUTHORIZED); + } + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java index dfea03d..1bb4194 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java @@ -50,6 +50,7 @@ public class RestApiCounterServiceConstants { public static final String API_REST_COUNTER_EVENT_SALESPERSON_REPLACE="/counter/eventSalesperson/replace"; public static final String API_REST_COUNTER_INTEREST_FIND_BY_COMPANY="/counter/interest/findByCompany/{companyId}"; public static final String API_REST_COUNTER_INTEREST_SAVE="/counter/interest/save"; + public static final String API_REST_COUNTER_INTEREST_DELETE="/counter/interest/delete"; public static final String API_REST_COUNTER_INTEREST_FIND_BY_IDS="/counter/interest/findByIds"; public static final String API_REST_COUNTER_LEAD_FIND_MATCHES="/counter/lead/findMatches"; public static final String API_REST_COUNTER_LEAD_SEARCH="/counter/lead/search"; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java index 942cf85..ab15e24 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java @@ -14,6 +14,7 @@ public class RestApiSystemServiceConstants { public static final String API_REST_SYSTEM_USER_FIND_BY_PROPERTY_AND_PAGEABLE = "/user/findByPropertyAndPageable"; public static final String API_REST_SYSTEM_ROLE_FIND_ALL = "/role/findAll"; public static final String API_REST_SYSTEM_ROLE_SAVE = "/role/save"; + public static final String API_REST_SYSTEM_ROLE_DELETE = "/role/delete"; public static final String API_REST_SYSTEM_MODULE_FIND_ALL_BY_AREA = "/module/findAllByArea/{area}"; public static final String API_REST_SYSTEM_MODULE_ADD_MODULE_ROLE = "/module/addModuleRole/{moduleId}/{roleId}"; public static final String API_REST_SYSTEM_MODULE_DELETE_MODULE_ROLE = "/module/deleteModuleRole/{moduleId}/{roleId}"; @@ -55,6 +56,8 @@ public class RestApiSystemServiceConstants { //Race + public static final String API_REST_SYSTEM_ADMIN_ACTIVE_PASSWORD_RULES = "/passwordRule/adminActive"; + //Message public static final String API_REST_SYSTEM_MESSAGE_JSON_BY_AREA_AND_LOCALE = "/message/getMessageJsonByAreaAndLocale/{area}/{locale}"; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/PasswordRuleController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/PasswordRuleController.java new file mode 100644 index 0000000..225de52 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/PasswordRuleController.java @@ -0,0 +1,31 @@ +package com.solvway.mobile.api.controller; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.service.PasswordRuleHintService; +import com.solvway.mobile.api.useraccess.AdminModule; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; +import java.util.Map; + +/** Switched-on admin password rules. Must stay under {@code controller..} for AppAccessAspect. */ +@RestController +@RequiredArgsConstructor +public class PasswordRuleController { + private final PasswordRuleHintService rules; + + @AdminModule(AdminModule.ANY_ADMIN) + @AppAuth + @GetMapping("/api/admin/password-rules/active") + public List> adminActive() { + return rules.active(); + } + + @AppAuth(skipValidate = true) + @GetMapping("/api/public/password-rules") + public List> publicActive() { + return rules.publicActive(); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminAuthController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminAuthController.java index c7b539a..90b77c7 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminAuthController.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminAuthController.java @@ -104,6 +104,7 @@ public class AdminAuthController { return ResponseEntity.badRequest().body(Map.of("message", "New password is required.")); } if (!adminAuthenticationService.firstTimeLogin(u.getId(), request.newPassword())) { + adminAuthenticationService.requirePasswordRules(request.newPassword()); // throws PASSWORD_RULE naming the rule return ResponseEntity.badRequest().body(Map.of("message", "New password does not meet the password policy.")); } return ResponseEntity.ok(Map.of("result", "true")); @@ -140,7 +141,10 @@ public class AdminAuthController { throw coded(HttpStatus.BAD_REQUEST, "Current password is incorrect", "CURRENT_PASSWORD_WRONG"); } case "PASSWORD_SAME" -> throw coded(HttpStatus.BAD_REQUEST, "The new password must differ from the current one", "PASSWORD_SAME"); - case "PASSWORD_POLICY" -> throw coded(HttpStatus.BAD_REQUEST, "Password does not meet the password policy", "PASSWORD_POLICY"); + case "PASSWORD_POLICY" -> { + adminAuthenticationService.requirePasswordRules(request.newPassword()); // throws PASSWORD_RULE naming the rule + throw coded(HttpStatus.BAD_REQUEST, "Password does not meet the password policy", "PASSWORD_POLICY"); + } default -> throw coded(HttpStatus.INTERNAL_SERVER_ERROR, "The password was not changed", "SAVE_FAILED"); } } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminInterestController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminInterestController.java index a2be84d..b1342dc 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminInterestController.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminInterestController.java @@ -6,6 +6,7 @@ import com.solvway.mobile.api.service.AdminInterestService; import com.solvway.mobile.api.useraccess.AdminModule; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; @@ -44,4 +45,12 @@ public class AdminInterestController { public ResponseEntity> update(@PathVariable long id, @RequestBody AdminInterestRequest request) { return ResponseEntity.ok(adminInterestService.update(id, request)); } + + @AppAuth + @AdminModule("BO_INTERESTS") + @DeleteMapping("/interests/{id}") + public ResponseEntity delete(@PathVariable long id) { + adminInterestService.delete(id); + return ResponseEntity.noContent().build(); + } } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminRoleController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminRoleController.java index 18ce80e..45a1bce 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminRoleController.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminRoleController.java @@ -49,6 +49,13 @@ public class AdminRoleController { } @AppAuth @AdminModule("BO_ROLES") + @DeleteMapping("/roles/{id}") + public ResponseEntity delete(@PathVariable Long id) { + adminRoleService.delete(id); + return ResponseEntity.noContent().build(); + } + @AppAuth + @AdminModule("BO_ROLES") @GetMapping("/roles/{id}/modules") public ResponseEntity> getModules(@PathVariable Long id) { return ResponseEntity.ok(adminAclService.getGrantTree(id)); diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAuthenticationService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAuthenticationService.java index a442ab0..b09b468 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAuthenticationService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAuthenticationService.java @@ -5,6 +5,7 @@ import com.solvway.mobile.api.constant.api.RestApiAuthServiceConstants; import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants; import com.solvway.mobile.api.model.AuthRequest; import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -56,6 +57,18 @@ public class AdminAuthenticationService { return ent.getBody() != null && ent.getBody().isEmpty(); } + /** Throws 400 PASSWORD_RULE naming the first failed rule (param, value) when the password breaks a switched-on rule. */ + public void requirePasswordRules(String password) { + ResponseEntity ent = restTemplateUtil.postForEntity( + restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_ADMIN_VALIDATE_PASSWORD_RULES), + List.class, Map.of("password", password)); + if (ent.getBody() == null || ent.getBody().isEmpty() || !(ent.getBody().get(0) instanceof Map first)) return; + CodedResponseStatusException e = new CodedResponseStatusException(HttpStatus.BAD_REQUEST, "PASSWORD_RULE", "PASSWORD_RULE"); + e.getBody().setProperty("param", first.get("param")); + e.getBody().setProperty("value", first.get("value")); + throw e; + } + /** Stores an admin-typed password with a forced change at next login; returns rows updated (0 = refused). */ public int setAdminPassword(Long id, String password) { ResponseEntity ent = restTemplateUtil.postForEntity( diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java index 3322348..adadb71 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java @@ -386,7 +386,7 @@ public class AdminEventLeadService { Map> out = new LinkedHashMap<>(); if (rows != null) for (Map r : rows) { long id = ((Number) r.get("id")).longValue(); - out.put(id, Map.of("id", id, "name", String.valueOf(r.get("name")), "active", Boolean.TRUE.equals(r.get("active")))); + out.put(id, Map.of("id", id, "name", String.valueOf(r.get("name")), "active", Boolean.TRUE.equals(r.get("active")) && r.get("deletedAt") == null)); // a deleted interest keeps its name but is never offered or accepted } return out; } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminInterestService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminInterestService.java index 76962ce..3720582 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminInterestService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminInterestService.java @@ -32,7 +32,7 @@ public class AdminInterestService { public List> list() { caller(); - return load().stream().map(AdminInterestService::row).toList(); + return load().stream().filter(m -> m.get("deletedAt") == null).map(AdminInterestService::row).toList(); } public Map create(AdminInterestRequest r) { @@ -47,7 +47,7 @@ public class AdminInterestService { public Map update(long id, AdminInterestRequest r) { scope.requireSuper(caller()); Map stored = load().stream() - .filter(m -> m.get("id") instanceof Number n && n.longValue() == id).findFirst() + .filter(m -> m.get("deletedAt") == null && m.get("id") instanceof Number n && n.longValue() == id).findFirst() .orElseThrow(() -> error(HttpStatus.NOT_FOUND, "Interest not found", "INTEREST_NOT_FOUND", null)); Map body = new LinkedHashMap<>(); body.put("id", id); @@ -61,10 +61,22 @@ public class AdminInterestService { try { return row(restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_INTEREST_SAVE), MAP, body).getBody()); } catch (HttpClientErrorException.Conflict e) { + if (e.getResponseBodyAsString().contains("INTEREST_NAME_DELETED")) { + throw error(HttpStatus.CONFLICT, "This name belongs to a deleted interest", "INTEREST_NAME_DELETED", "name"); + } throw error(HttpStatus.CONFLICT, "An interest with this name already exists", "DUPLICATE_NAME", "name"); } } + public void delete(long id) { + scope.requireSuper(caller()); + try { + restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_INTEREST_DELETE), Void.class, id); + } catch (HttpClientErrorException.NotFound e) { + throw error(HttpStatus.NOT_FOUND, "Interest not found", "INTEREST_NOT_FOUND", null); + } + } + // ponytail: the counter ignores the company id (one shared list); 0 is a placeholder for its path variable. private List> load() { List> rows = restTemplateUtil.getForEntity( diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminRoleService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminRoleService.java index 7410dcc..43f3a3a 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminRoleService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminRoleService.java @@ -1,5 +1,7 @@ package com.solvway.mobile.api.service; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import com.solvway.core.model.User; import com.solvway.core.utils.HttpReqRespUtils; import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants; @@ -13,6 +15,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; +import org.springframework.web.client.HttpClientErrorException; import java.util.ArrayList; import java.util.HashMap; @@ -30,6 +33,7 @@ import java.util.Map; public class AdminRoleService { private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() {}; private static final ParameterizedTypeReference>> MAP_LIST = new ParameterizedTypeReference<>() {}; + private static final ObjectMapper JSON = new ObjectMapper(); private static final long SUPER_ADMIN_ROLE_ID = 1L; private static final List HIDDEN = List.of("ROLE_MEMBER", "ROLE_ADMIN"); private static final List PROTECTED = List.of("ROLE_SUPER_ADMIN", "ROLE_ADMIN", "ROLE_MEMBER"); @@ -95,6 +99,28 @@ public class AdminRoleService { return clean(reread); } + public void delete(Long id) { + scope.requireSuper(caller()); + if (isProtected(find(id))) throw error(HttpStatus.CONFLICT, "ROLE_PROTECTED", "ROLE_PROTECTED"); + try { + restTemplateUtil.postForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_ROLE_DELETE), Void.class, id); + } catch (HttpClientErrorException.NotFound e) { + throw notFound(); + } catch (HttpClientErrorException.Conflict e) { + // services-system reports ROLE_IN_USE / ROLE_PROTECTED in the ProblemDetail detail; relay it with the user count + Map body; + try { + body = JSON.readValue(e.getResponseBodyAsString(), Map.class); + } catch (JsonProcessingException x) { + body = Map.of(); + } + String reason = body.get("detail") == null ? "ROLE_DELETE_REFUSED" : String.valueOf(body.get("detail")); + CodedResponseStatusException out = error(HttpStatus.CONFLICT, reason, reason); + if (body.get("users") != null) out.getBody().setProperty("users", body.get("users")); + throw out; + } + } + public static boolean isProtected(Map role) { return PROTECTED.contains(role.get("name")); } @@ -127,7 +153,12 @@ public class AdminRoleService { } private Map save(Map role) { - ResponseEntity> ent = restTemplateUtil.postForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_ROLE_SAVE), MAP, role); + ResponseEntity> ent; + try { + ent = restTemplateUtil.postForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_ROLE_SAVE), MAP, role); + } catch (HttpClientErrorException.Conflict e) { + throw error(HttpStatus.CONFLICT, "This name belongs to a deleted role", "ROLE_NAME_DELETED"); + } // services-system swallows save errors and returns the unsaved entity, so a missing id means it failed. if (ent.getBody() == null || ent.getBody().get("id") == null) { throw error(HttpStatus.INTERNAL_SERVER_ERROR, "Role could not be saved", "SAVE_FAILED"); diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminUserService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminUserService.java index 3f8ef52..fbbc9cd 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminUserService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminUserService.java @@ -218,6 +218,7 @@ public class AdminUserService { if (!StringUtils.hasText(password)) throw error(HttpStatus.BAD_REQUEST, "Password is required", "REQUIRED_FIELD"); if (!password.equals(confirmPassword)) throw error(HttpStatus.BAD_REQUEST, "Passwords do not match", "PASSWORD_MISMATCH"); if (!adminAuthenticationService.passesAdminPasswordRules(password)) { + adminAuthenticationService.requirePasswordRules(password); // throws PASSWORD_RULE naming the rule throw error(HttpStatus.BAD_REQUEST, "Password does not meet the password policy", "PASSWORD_POLICY"); } } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PasswordRuleHintService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PasswordRuleHintService.java new file mode 100644 index 0000000..8db0da0 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PasswordRuleHintService.java @@ -0,0 +1,33 @@ +package com.solvway.mobile.api.service; + +import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** The switched-on admin password rules, for the hint on password screens. */ +@Service +@RequiredArgsConstructor +public class PasswordRuleHintService { + private static final ParameterizedTypeReference>> RULES = new ParameterizedTypeReference<>() {}; + private static final int PUBLIC_LIMIT = 60; + + private final RestTemplateCustomUtil rest; + private final PublicRegistrationService limiter; + + public List> active() { + List> body = rest.getForEntity( + rest.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_ADMIN_ACTIVE_PASSWORD_RULES), RULES).getBody(); + return body == null ? List.of() : body; + } + + /** Same list with no sign-in, counted per IP in the registration limiter (fixed 10-minute window). */ + public List> publicActive() { + limiter.limit("pwr:" + PublicRegistrationService.ip(), PUBLIC_LIMIT, "Too many requests from this device. Try again later."); + return active(); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/PasswordRuleControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/PasswordRuleControllerTest.java new file mode 100644 index 0000000..6bd1c6e --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/PasswordRuleControllerTest.java @@ -0,0 +1,53 @@ +package com.solvway.mobile.api.controller; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.service.PasswordRuleHintService; +import com.solvway.mobile.api.useraccess.AdminModule; +import org.junit.jupiter.api.Test; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +class PasswordRuleControllerTest { + + private final PasswordRuleHintService service = mock(PasswordRuleHintService.class); + private final MockMvc mvc = MockMvcBuilders.standaloneSetup(new PasswordRuleController(service)).build(); + + private static Method handler(String name) { + return Arrays.stream(PasswordRuleController.class.getDeclaredMethods()).filter(m -> m.getName().equals(name)).findFirst().orElseThrow(); + } + + @Test + void adminRoute_needsASignedInAdmin_noModule() throws Exception { + Method m = handler("adminActive"); + assertThat(m.getAnnotation(AppAuth.class).skipValidate()).isFalse(); + assertThat(m.getAnnotation(AdminModule.class).value()).containsExactly(AdminModule.ANY_ADMIN); + when(service.active()).thenReturn(List.of(Map.of("param", "INPUT_LENGTH_MIN", "value", "8"))); + + mvc.perform(get("/api/admin/password-rules/active")).andExpect(status().isOk()) + .andExpect(jsonPath("$[0].param").value("INPUT_LENGTH_MIN")).andExpect(jsonPath("$[0].value").value("8")); + } + + @Test + void publicRoute_skipsSignIn_andGoesThroughTheRateLimitedService() throws Exception { + assertThat(handler("publicActive").getAnnotation(AppAuth.class).skipValidate()).isTrue(); + assertThat(handler("publicActive").getAnnotation(AdminModule.class)).isNull(); + when(service.publicActive()).thenReturn(List.of(Map.of("param", "SPACE_NOT_ALLOWED"))); + + mvc.perform(get("/api/public/password-rules")).andExpect(status().isOk()) + .andExpect(jsonPath("$[0].param").value("SPACE_NOT_ALLOWED")); + verify(service).publicActive(); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminInterestControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminInterestControllerTest.java index ee90782..53ef518 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminInterestControllerTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminInterestControllerTest.java @@ -45,7 +45,7 @@ class AdminInterestControllerTest { void everyHandlerIsAuthenticatedAndGuardedByBoInterests() { List handlers = Arrays.stream(AdminInterestController.class.getDeclaredMethods()) .filter(m -> Modifier.isPublic(m.getModifiers()) && !m.isSynthetic()).toList(); - assertThat(handlers).hasSize(3); + assertThat(handlers).hasSize(4); for (Method m : handlers) { assertThat(m.isAnnotationPresent(AppAuth.class)).as(m.getName() + " @AppAuth").isTrue(); assertThat(Arrays.asList(m.getAnnotation(AdminModule.class).value())).as(m.getName()).containsExactly("BO_INTERESTS"); diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadDeletedInterestTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadDeletedInterestTest.java new file mode 100644 index 0000000..41974dc --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadDeletedInterestTest.java @@ -0,0 +1,56 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.useraccess.AdminCompanyScope; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.ResponseEntity; + +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminEventLeadDeletedInterestTest { + + private MockedStatic http; + private AdminEventLeadService service; + + @BeforeEach + void setUp() { + RestTemplateCustomUtil rest = mock(RestTemplateCustomUtil.class); + AdminAuthenticationService auth = mock(AdminAuthenticationService.class); + service = new AdminEventLeadService(rest, auth, new AdminCompanyScope()); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + User caller = new User(); + caller.setUsername("sales1"); + caller.setCompanyId(5L); + when(auth.loadUserByToken("tok")).thenReturn(caller); + when(rest.getForEntity(eq("/counter/interest/findByCompany/{companyId}"), any(ParameterizedTypeReference.class), eq(5L))) + .thenReturn(ResponseEntity.ok(List.of( + Map.of("id", 1, "name", "Kitchen", "active", true), + Map.of("id", 2, "name", "Old", "active", true, "deletedAt", "2026-12-01T10:00:00")))); + } + + @AfterEach + void close() { http.close(); } + + @Test + void deletedInterestIsNotOfferedButItsNameStillResolves() { + assertThat(service.interestOptions()).extracting(m -> m.get("name")).containsExactly("Kitchen"); + assertThat(service.interests(5L).get(2L)).containsEntry("name", "Old").containsEntry("active", false); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminInterestDeleteTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminInterestDeleteTest.java new file mode 100644 index 0000000..c07a682 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminInterestDeleteTest.java @@ -0,0 +1,138 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.dto.admin.AdminInterestRequest; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminInterestDeleteTest { + + private static final String LIST = "/counter/interest/findByCompany/{companyId}"; + private static final String SAVE = "/counter/interest/save"; + private static final String DELETE = "/counter/interest/delete"; + + private RestTemplateCustomUtil rest; + private AdminAuthenticationService auth; + private AdminInterestService service; + private MockedStatic http; + private User caller; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + auth = mock(AdminAuthenticationService.class); + service = new AdminInterestService(rest, auth); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + caller = new User(); + caller.setUsername("boss"); + com.solvway.core.model.Role r = new com.solvway.core.model.Role(); + r.setId(1L); + caller.setRoles(new ArrayList<>(List.of(r))); + when(auth.loadUserByToken("tok")).thenReturn(caller); + } + + @AfterEach + void close() { http.close(); } + + private static Map row(long id, String name, String deletedAt) { + Map m = new java.util.HashMap<>(); + m.put("id", id); + m.put("name", name); + m.put("active", true); + m.put("sortOrder", 0); + m.put("deletedAt", deletedAt); + return m; + } + + private static HttpClientErrorException conflict(String body) { + return HttpClientErrorException.create(HttpStatus.CONFLICT, "Conflict", HttpHeaders.EMPTY, + body.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8); + } + + private static void assertCoded(Runnable call, HttpStatus status, String code) { + assertThatThrownBy(call::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(status); + assertThat(e.getBody().getProperties()).containsEntry("code", code); + }); + } + + @Test + void listSkipsDeletedInterests() { + when(rest.getForEntity(eq(LIST), any(ParameterizedTypeReference.class), eq(0L))) + .thenReturn(ResponseEntity.ok(List.of(row(1, "Kitchen", null), row(2, "Old", "2026-12-01T10:00:00")))); + assertThat(service.list()).extracting(m -> m.get("name")).containsExactly("Kitchen"); + } + + @Test + void updateOfDeletedInterestIsNotFound() { + when(rest.getForEntity(eq(LIST), any(ParameterizedTypeReference.class), eq(0L))) + .thenReturn(ResponseEntity.ok(List.of(row(2, "Old", "2026-12-01T10:00:00")))); + assertCoded(() -> service.update(2L, new AdminInterestRequest("New", null, null)), HttpStatus.NOT_FOUND, "INTEREST_NOT_FOUND"); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void createWithDeletedNameReportsNameDeleted() { + when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any())) + .thenThrow(conflict("{\"detail\":\"INTEREST_NAME_DELETED\"}")); + assertCoded(() -> service.create(new AdminInterestRequest("Old", null, null)), HttpStatus.CONFLICT, "INTEREST_NAME_DELETED"); + } + + @Test + void createWithDuplicateNameStillReportsDuplicate() { + when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any())) + .thenThrow(conflict("{\"detail\":\"DUPLICATE_NAME\"}")); + assertCoded(() -> service.create(new AdminInterestRequest("Kitchen", null, null)), HttpStatus.CONFLICT, "DUPLICATE_NAME"); + } + + @Test + void superAdminDeletesThroughTheCounter() { + service.delete(5L); + verify(rest).postForEntity(eq(DELETE), eq(Void.class), eq(5L)); + } + + @Test + void companyUserIsRefusedAndNothingIsPosted() { + caller.setCompanyId(7L); + com.solvway.core.model.Role staff = new com.solvway.core.model.Role(); + staff.setId(4L); + caller.setRoles(new ArrayList<>(List.of(staff))); + assertCoded(() -> service.delete(5L), HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED"); + verify(rest, never()).postForEntity(eq(DELETE), any(Class.class), any()); + } + + @Test + void unknownOrDeletedInterestIsNotFound() { + when(rest.postForEntity(eq(DELETE), eq(Void.class), any())).thenThrow( + HttpClientErrorException.create(HttpStatus.NOT_FOUND, "Not Found", HttpHeaders.EMPTY, new byte[0], StandardCharsets.UTF_8)); + assertCoded(() -> service.delete(9L), HttpStatus.NOT_FOUND, "INTEREST_NOT_FOUND"); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminRoleDeleteTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminRoleDeleteTest.java new file mode 100644 index 0000000..e3e3a52 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminRoleDeleteTest.java @@ -0,0 +1,145 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.dto.admin.AdminRoleRequest; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.web.client.HttpClientErrorException; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminRoleDeleteTest { + + private static final String DELETE = "/role/delete"; + private static final String SAVE = "/role/save"; + private static final String FIND_ALL = "/role/findAll"; + + private RestTemplateCustomUtil rest; + private AdminRoleService service; + private MockedStatic http; + private User caller; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + AdminAuthenticationService auth = mock(AdminAuthenticationService.class); + service = new AdminRoleService(rest, auth); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + caller = new User(); + caller.setUsername("boss"); + com.solvway.core.model.Role r = new com.solvway.core.model.Role(); + r.setId(1L); + caller.setRoles(new ArrayList<>(List.of(r))); + when(auth.loadUserByToken("tok")).thenReturn(caller); + when(rest.getForEntity(eq(FIND_ALL), any(ParameterizedTypeReference.class))).thenReturn(org.springframework.http.ResponseEntity.ok( + List.of(java.util.Map.of("id", 5, "name", "Sales"), java.util.Map.of("id", 9, "name", "Ops")))); + } + + @AfterEach + void close() { http.close(); } + + private static HttpClientErrorException http(HttpStatus status, String body) { + return HttpClientErrorException.create(status, status.getReasonPhrase(), HttpHeaders.EMPTY, + body.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8); + } + + private static CodedResponseStatusException thrown(Runnable call) { + assertThatThrownBy(call::run).isInstanceOf(CodedResponseStatusException.class); + try { + call.run(); + } catch (CodedResponseStatusException e) { + return e; + } + throw new AssertionError(); + } + + @Test + void superAdminDeletesThroughSystem() { + service.delete(5L); + verify(rest).postForEntity(eq(DELETE), eq(Void.class), eq(5L)); + } + + @Test + void companyUserIsRefusedAndNothingIsPosted() { + caller.setCompanyId(7L); + com.solvway.core.model.Role staff = new com.solvway.core.model.Role(); + staff.setId(4L); + caller.setRoles(new ArrayList<>(List.of(staff))); + CodedResponseStatusException e = thrown(() -> service.delete(5L)); + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); + assertThat(e.getBody().getProperties()).containsEntry("code", "SUPER_ADMIN_REQUIRED"); + verify(rest, never()).postForEntity(eq(DELETE), any(Class.class), any()); + } + + @Test + void unknownOrDeletedRoleIsNotFound() { + when(rest.postForEntity(eq(DELETE), eq(Void.class), any())).thenThrow(http(HttpStatus.NOT_FOUND, "")); + CodedResponseStatusException e = thrown(() -> service.delete(9L)); + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(e.getBody().getProperties()).containsEntry("code", "ROLE_NOT_FOUND"); + } + + @Test + void protectedNamedRolesAreRefusedBeforeCallingSystem() { + for (String name : List.of("ROLE_MEMBER", "ROLE_ADMIN", "ROLE_SUPER_ADMIN")) { + when(rest.getForEntity(eq(FIND_ALL), any(ParameterizedTypeReference.class))) + .thenReturn(org.springframework.http.ResponseEntity.ok(List.of(java.util.Map.of("id", 3, "name", name)))); + CodedResponseStatusException e = thrown(() -> service.delete(3L)); + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); + assertThat(e.getBody().getProperties()).containsEntry("code", "ROLE_PROTECTED"); + } + verify(rest, never()).postForEntity(eq(DELETE), any(Class.class), any()); + } + + @Test + void roleInUseRelaysReasonAndUserCount() { + when(rest.postForEntity(eq(DELETE), eq(Void.class), any())) + .thenThrow(http(HttpStatus.CONFLICT, "{\"detail\":\"ROLE_IN_USE\",\"users\":3}")); + CodedResponseStatusException e = thrown(() -> service.delete(5L)); + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); + assertThat(e.getReason()).isEqualTo("ROLE_IN_USE"); + assertThat(e.getBody().getProperties()).containsEntry("code", "ROLE_IN_USE").containsEntry("users", 3); + } + + @Test + void protectedRoleRelaysReason() { + when(rest.postForEntity(eq(DELETE), eq(Void.class), any())) + .thenThrow(http(HttpStatus.CONFLICT, "{\"detail\":\"ROLE_PROTECTED\"}")); + CodedResponseStatusException e = thrown(() -> service.delete(5L)); + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); + assertThat(e.getBody().getProperties()).containsEntry("code", "ROLE_PROTECTED"); + } + + @Test + void createWithDeletedNameReportsNameDeleted() { + when(rest.getForEntity(eq(FIND_ALL), any(ParameterizedTypeReference.class))).thenReturn(org.springframework.http.ResponseEntity.ok(List.of())); + when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any())) + .thenThrow(http(HttpStatus.CONFLICT, "{\"detail\":\"ROLE_NAME_DELETED\"}")); + CodedResponseStatusException e = thrown(() -> service.create(new AdminRoleRequest("Old"))); + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); + assertThat(e.getBody().getProperties()).containsEntry("code", "ROLE_NAME_DELETED"); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PasswordRuleHintServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PasswordRuleHintServiceTest.java new file mode 100644 index 0000000..740772e --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PasswordRuleHintServiceTest.java @@ -0,0 +1,54 @@ +package com.solvway.mobile.api.service; + +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.Test; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.ResponseEntity; + +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@SuppressWarnings({"unchecked", "rawtypes"}) +class PasswordRuleHintServiceTest { + + private final RestTemplateCustomUtil rest = mock(RestTemplateCustomUtil.class); + private final PublicRegistrationService reg = mock(PublicRegistrationService.class); + private final PasswordRuleHintService service = new PasswordRuleHintService(rest, reg); + + PasswordRuleHintServiceTest() { + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + when(rest.getForEntity(eq("/passwordRule/adminActive"), any(ParameterizedTypeReference.class))) + .thenReturn(ResponseEntity.ok(List.of(Map.of("param", "INPUT_LENGTH_MIN", "value", "8")))); + } + + @Test + void active_readsTheSwitchedOnAdminRules() { + assertThat(service.active()).containsExactly(Map.of("param", "INPUT_LENGTH_MIN", "value", "8")); + } + + @Test + void publicActive_isRateLimitedPerIp_beforeAnyRead() { + service.publicActive(); + verify(reg).limit(startsWith("pwr:"), eq(60), anyString()); + } + + @Test + void active_nullBodyIsEmptyList() { + when(rest.getForEntity(eq("/passwordRule/adminActive"), any(ParameterizedTypeReference.class))) + .thenReturn(ResponseEntity.ok().build()); + assertThat(service.active()).isEmpty(); + } + + private static String startsWith(String p) { + return org.mockito.ArgumentMatchers.startsWith(p); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PasswordRuleRefusalTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PasswordRuleRefusalTest.java new file mode 100644 index 0000000..b290996 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PasswordRuleRefusalTest.java @@ -0,0 +1,165 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.controller.admin.AdminAuthController; +import com.solvway.mobile.api.dto.admin.AdminRoleRef; +import com.solvway.mobile.api.dto.admin.AdminUserRequest; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; + +/** + * Spec: symbol rule on with value 2 and a password with one symbol -> 400 PASSWORD_RULE naming + * SYMBOLIC_LENGTH_MIN and 2, on every admin password path. The real AdminAuthenticationService runs + * over a mocked services-system, which refuses the password (setAdminPassword 0 / firstTimeLogin false / + * changeAdminPassword PASSWORD_POLICY) and lists the failing rules. + */ +@SuppressWarnings({"unchecked", "rawtypes"}) +class PasswordRuleRefusalTest { + + private static final String PW = "Onesymbol#1"; + + private RestTemplateCustomUtil rest; + private AdminAuthenticationService auth; + private MockedStatic http; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + auth = new AdminAuthenticationService(rest); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + // services-system lists the failing rules: the symbol rule first, then a later one + when(rest.postForEntity(eq("/user/validatePasswordFromRulesForAdmin"), eq(List.class), any())) + .thenReturn(ResponseEntity.ok(List.of( + Map.of("param", "SYMBOLIC_LENGTH_MIN", "value", "2"), + Map.of("param", "INPUT_LENGTH_MIN", "value", "12")))); + } + + @AfterEach + void close() { http.close(); } + + private static void assertRule(Throwable t) { + assertThat(t).isInstanceOf(CodedResponseStatusException.class); + CodedResponseStatusException e = (CodedResponseStatusException) t; + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); + assertThat(e.getReason()).isEqualTo("PASSWORD_RULE"); + assertThat(e.getBody().getDetail()).isEqualTo("PASSWORD_RULE"); + assertThat(e.getBody().getProperties()).containsEntry("param", "SYMBOLIC_LENGTH_MIN").containsEntry("value", "2"); + } + + @Test + void requirePasswordRules_namesTheFirstFailedRule() { + assertThatThrownBy(() -> auth.requirePasswordRules(PW)).satisfies(PasswordRuleRefusalTest::assertRule); + } + + @Test + void requirePasswordRules_passesWhenNoRuleFails() { + when(rest.postForEntity(eq("/user/validatePasswordFromRulesForAdmin"), eq(List.class), any())) + .thenReturn(ResponseEntity.ok(List.of())); + auth.requirePasswordRules(PW); // no throw + } + + @Test + void createUser_withPassword_isRefusedByName() { + AdminUserService users = new AdminUserService(rest, auth); + AdminUserRequest req = new AdminUserRequest("N", null, "n", "n@x.com", true, List.of(new AdminRoleRef(4L, "ROLE_SALES")), + PW, PW, null, null); + assertThatThrownBy(() -> users.create(req)).satisfies(PasswordRuleRefusalTest::assertRule); + } + + @Test + void setTemporaryPassword_isRefusedByName() { + AdminAuthenticationService spy = org.mockito.Mockito.spy(auth); + User boss = new User(); + boss.setId(1L); + com.solvway.core.model.Role superRole = new com.solvway.core.model.Role(); + superRole.setId(1L); + boss.setRoles(List.of(superRole)); + org.mockito.Mockito.doReturn(boss).when(spy).loadUserByToken("tok"); + Map row = new HashMap<>(Map.of("id", 5L, "type", "A", "username", "u", "enabled", true)); + when(rest.getForEntity(eq("/user/findById/{id}"), any(ParameterizedTypeReference.class), eq(5L))) + .thenReturn(ResponseEntity.ok(row)); + AdminUserService users = new AdminUserService(rest, spy); + assertThatThrownBy(() -> users.setTemporaryPassword(5L, PW, PW)).satisfies(PasswordRuleRefusalTest::assertRule); + } + + @Test + void changeOwnPassword_policyRefusal_isNamed() throws Exception { + User u = new User(); + u.setId(9L); + u.setUsername("admin.user"); + AdminAuthenticationService spy = org.mockito.Mockito.spy(auth); + org.mockito.Mockito.doReturn(u).when(spy).loadUserByToken("tok"); + org.mockito.Mockito.doReturn(false).when(spy).isLocked("admin.user"); + when(rest.postForEntity(eq("/user/changeAdminPassword"), eq(String.class), any())) + .thenReturn(ResponseEntity.ok("PASSWORD_POLICY")); + MockMvc mvc = MockMvcBuilders.standaloneSetup(new AdminAuthController(spy, mock(AuthenticationService.class))).build(); + + Exception ex = mvc.perform(post("/api/admin/auth/change-password").contentType(MediaType.APPLICATION_JSON) + .content("{\"currentPassword\":\"old\",\"newPassword\":\"" + PW + "\",\"confirmPassword\":\"" + PW + "\"}")) + .andReturn().getResolvedException(); + assertRule(ex); + } + + @Test + void changeOwnPassword_wrongCurrent_keepsItsReason() throws Exception { + User u = new User(); + u.setId(9L); + u.setUsername("admin.user"); + AdminAuthenticationService spy = org.mockito.Mockito.spy(auth); + org.mockito.Mockito.doReturn(u).when(spy).loadUserByToken("tok"); + org.mockito.Mockito.doReturn(false).when(spy).isLocked("admin.user"); + org.mockito.Mockito.doNothing().when(spy).record(any(), any(), any()); + when(rest.postForEntity(eq("/user/changeAdminPassword"), eq(String.class), any())) + .thenReturn(ResponseEntity.ok("CURRENT_PASSWORD_WRONG")); + MockMvc mvc = MockMvcBuilders.standaloneSetup(new AdminAuthController(spy, mock(AuthenticationService.class))).build(); + + Exception ex = mvc.perform(post("/api/admin/auth/change-password").contentType(MediaType.APPLICATION_JSON) + .content("{\"currentPassword\":\"old\",\"newPassword\":\"" + PW + "\",\"confirmPassword\":\"" + PW + "\"}")) + .andReturn().getResolvedException(); + assertThat(((CodedResponseStatusException) ex).getCode()).isEqualTo("CURRENT_PASSWORD_WRONG"); + verify(rest, never()).postForEntity(eq("/user/validatePasswordFromRulesForAdmin"), any(Class.class), any()); + } + + @Test + void firstLogin_isRefusedByName() throws Exception { + User u = new User(); + u.setId(9L); + u.setLogin(com.solvway.core.enums.GeneralEnum.LoginStatus.N); + AdminAuthenticationService spy = org.mockito.Mockito.spy(auth); + org.mockito.Mockito.doReturn(u).when(spy).loadUserByToken("tok"); + when(rest.postForEntity(eq("/user/firstTimeLogin"), eq(Boolean.class), any())).thenReturn(ResponseEntity.ok(false)); + MockMvc mvc = MockMvcBuilders.standaloneSetup(new AdminAuthController(spy, mock(AuthenticationService.class))).build(); + + Exception ex = mvc.perform(post("/api/admin/auth/first-login").contentType(MediaType.APPLICATION_JSON) + .content("{\"newPassword\":\"" + PW + "\"}")).andReturn().getResolvedException(); + assertRule(ex); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/DeleteAuditActionTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/DeleteAuditActionTest.java new file mode 100644 index 0000000..daa204f --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/DeleteAuditActionTest.java @@ -0,0 +1,13 @@ +package com.solvway.mobile.api.useraccess; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class DeleteAuditActionTest { + @Test + void deleteHandlersAuditAsInterestAndRoleDelete() { + assertThat(AppAccessAspect.defaultAuditAction("AdminInterestController", "delete")).isEqualTo("INTEREST_DELETE"); + assertThat(AppAccessAspect.defaultAuditAction("AdminRoleController", "delete")).isEqualTo("ROLE_DELETE"); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/InterestController.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/InterestController.java index 040ab0f..51211ea 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/InterestController.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/InterestController.java @@ -24,6 +24,11 @@ public class InterestController { return interestService.save(interest); } + @PostMapping("/delete") + public void delete(@RequestBody Long id) { + interestService.delete(id); + } + @PostMapping("/findByIds") public List findByIds(@RequestBody InterestFindByIdsRequest body) { return interestService.findByIds(body.companyId(), body.ids()); diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Interest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Interest.java index 3701179..26d0b02 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Interest.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Interest.java @@ -4,6 +4,8 @@ import jakarta.persistence.*; import lombok.Getter; import lombok.Setter; +import java.time.LocalDateTime; + @Getter @Setter @Entity @@ -21,4 +23,7 @@ public class Interest { private boolean active = true; private int sortOrder; + + /** Soft delete: the row stays so tagged leads keep resolving the name, and the name stays reserved. */ + private LocalDateTime deletedAt; } diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/InterestRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/InterestRepository.java index 5f17eb1..ca48ce0 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/InterestRepository.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/InterestRepository.java @@ -13,5 +13,7 @@ public interface InterestRepository extends JpaRepository { boolean existsByNameIgnoreCase(String name); + boolean existsByNameIgnoreCaseAndDeletedAtIsNotNull(String name); + List findByIdIn(Collection ids); } diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/InterestService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/InterestService.java index bcc74a5..5350f2b 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/InterestService.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/InterestService.java @@ -9,6 +9,7 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.server.ResponseStatusException; +import java.time.LocalDateTime; import java.util.List; @Service @@ -16,6 +17,7 @@ import java.util.List; public class InterestService { private final InterestRepository interestRepository; + /** Every row, deleted ones included (flagged by deletedAt): lead views resolve a deleted interest's name through this list. Consumers filter what they offer. */ public List findByCompany(long companyId) { return interestRepository.findAllByOrderBySortOrderAscNameAsc(); } @@ -39,7 +41,7 @@ public class InterestService { // Create: names are unique across the one shared list interest.setCompanyId(null); if (interestRepository.existsByNameIgnoreCase(trimmedName)) { - throw new ResponseStatusException(HttpStatus.CONFLICT, "DUPLICATE_NAME"); + throw nameTaken(trimmedName); } return interestRepository.saveAndFlush(interest); } else { @@ -48,7 +50,7 @@ public class InterestService { interest.setCompanyId(existing.getCompanyId()); if (!existing.getName().equalsIgnoreCase(trimmedName) && interestRepository.existsByNameIgnoreCase(trimmedName)) { - throw new ResponseStatusException(HttpStatus.CONFLICT, "DUPLICATE_NAME"); + throw nameTaken(trimmedName); } return interestRepository.saveAndFlush(interest); } @@ -57,6 +59,20 @@ public class InterestService { } } + @Transactional + public void delete(Long id) { + Interest interest = interestRepository.findById(id) + .filter(i -> i.getDeletedAt() == null) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); + interest.setDeletedAt(LocalDateTime.now()); + interestRepository.save(interest); + } + + private ResponseStatusException nameTaken(String name) { + return new ResponseStatusException(HttpStatus.CONFLICT, + interestRepository.existsByNameIgnoreCaseAndDeletedAtIsNotNull(name) ? "INTEREST_NAME_DELETED" : "DUPLICATE_NAME"); + } + public List findByIds(long companyId, List ids) { if (ids == null || ids.isEmpty()) { return List.of(); diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/controller/InterestControllerDeleteTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/controller/InterestControllerDeleteTest.java new file mode 100644 index 0000000..344218e --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/controller/InterestControllerDeleteTest.java @@ -0,0 +1,23 @@ +package com.solvway.services.counter.controller; + +import com.solvway.services.counter.service.InterestService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.mockito.Mockito.verify; + +@ExtendWith(MockitoExtension.class) +class InterestControllerDeleteTest { + + @Mock + private InterestService interestService; + + @Test + void deleteDelegatesToService() { + new InterestController(interestService).delete(7L); + + verify(interestService).delete(7L); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/InterestServiceDeleteTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/InterestServiceDeleteTest.java new file mode 100644 index 0000000..1670fcf --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/InterestServiceDeleteTest.java @@ -0,0 +1,109 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.model.Interest; +import com.solvway.services.counter.repo.InterestRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; + +import java.time.LocalDateTime; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** Soft delete of interests: delete, 404s, and names of deleted interests staying reserved. */ +@ExtendWith(MockitoExtension.class) +class InterestServiceDeleteTest { + + @Mock + private InterestRepository repository; + + private InterestService service; + + @BeforeEach + void setUp() { + service = new InterestService(repository); + } + + @Test + void deleteStampsDeletedAt() { + Interest row = interest(5L, "Cookware"); + when(repository.findById(5L)).thenReturn(Optional.of(row)); + + service.delete(5L); + + assertThat(row.getDeletedAt()).isNotNull(); + verify(repository).save(row); + } + + @Test + void deleteUnknownIs404() { + when(repository.findById(9L)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.delete(9L)) + .isInstanceOf(ResponseStatusException.class) + .hasFieldOrPropertyWithValue("statusCode", HttpStatus.NOT_FOUND); + verify(repository, never()).save(any()); + } + + @Test + void deleteAlreadyDeletedIs404() { + Interest row = interest(5L, "Cookware"); + LocalDateTime when = LocalDateTime.of(2026, 1, 1, 0, 0); + row.setDeletedAt(when); + when(repository.findById(5L)).thenReturn(Optional.of(row)); + + assertThatThrownBy(() -> service.delete(5L)) + .isInstanceOf(ResponseStatusException.class) + .hasFieldOrPropertyWithValue("statusCode", HttpStatus.NOT_FOUND); + assertThat(row.getDeletedAt()).isEqualTo(when); + verify(repository, never()).save(any()); + } + + @Test + void createWithDeletedNameIsRefusedAsNameDeleted() { + when(repository.existsByNameIgnoreCase("Cookware")).thenReturn(true); + when(repository.existsByNameIgnoreCaseAndDeletedAtIsNotNull("Cookware")).thenReturn(true); + + assertThatThrownBy(() -> service.save(interest(null, "Cookware"))) + .isInstanceOf(ResponseStatusException.class) + .hasFieldOrPropertyWithValue("statusCode", HttpStatus.CONFLICT) + .hasMessageContaining("INTEREST_NAME_DELETED"); + } + + @Test + void renameToDeletedNameIsRefusedAsNameDeleted() { + when(repository.findById(10L)).thenReturn(Optional.of(interest(10L, "Old"))); + when(repository.existsByNameIgnoreCase("Cookware")).thenReturn(true); + when(repository.existsByNameIgnoreCaseAndDeletedAtIsNotNull("Cookware")).thenReturn(true); + + assertThatThrownBy(() -> service.save(interest(10L, "Cookware"))) + .isInstanceOf(ResponseStatusException.class) + .hasMessageContaining("INTEREST_NAME_DELETED"); + } + + @Test + void liveDuplicateStaysDuplicateName() { + when(repository.existsByNameIgnoreCase("Cookware")).thenReturn(true); + + assertThatThrownBy(() -> service.save(interest(null, "Cookware"))) + .isInstanceOf(ResponseStatusException.class) + .hasMessageContaining("DUPLICATE_NAME"); + } + + private static Interest interest(Long id, String name) { + Interest i = new Interest(); + i.setId(id); + i.setName(name); + return i; + } +} diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/controller/PasswordRuleController.java b/solvway-services-system/src/main/java/com/solvway/services/system/controller/PasswordRuleController.java index 5e642af..24808dc 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/controller/PasswordRuleController.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/controller/PasswordRuleController.java @@ -25,6 +25,11 @@ public class PasswordRuleController { return systemProperties; } + @RequestMapping("/adminActive") + public List adminActive() { + return passwordRuleService.adminActive(); + } + @RequestMapping("/findById/{id}") public Optional findById(@PathVariable("id") Long id) { Optional systemProperty = passwordRuleService.findById(id); diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/controller/RoleController.java b/solvway-services-system/src/main/java/com/solvway/services/system/controller/RoleController.java index afe24c7..2047c95 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/controller/RoleController.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/controller/RoleController.java @@ -6,6 +6,7 @@ import com.solvway.services.system.service.RoleService; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @@ -43,8 +44,14 @@ public class RoleController { return role.get(); } + @PostMapping("/delete") + public void delete(@RequestBody Long id) { + roleService.delete(id); + } + @RequestMapping("/save") public Role save(@RequestBody Role role) { + roleService.requireNameNotDeleted(role); try { RoleParent roleParent= modelMapper.map(findById(role.getParent().getId()),RoleParent.class); role.setParent(roleParent); diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/model/Role.java b/solvway-services-system/src/main/java/com/solvway/services/system/model/Role.java index 2bded53..8870254 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/model/Role.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/model/Role.java @@ -41,4 +41,7 @@ public class Role { private String doneBy; private Timestamp createDate; + /** Soft delete: the row stays and its name stays reserved. */ + private Timestamp deletedAt; + } diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/repo/RoleRepository.java b/solvway-services-system/src/main/java/com/solvway/services/system/repo/RoleRepository.java index bf95be9..028c20a 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/repo/RoleRepository.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/repo/RoleRepository.java @@ -8,6 +8,11 @@ import java.util.List; public interface RoleRepository extends JpaRepository { Role findByName(String name); + + List findByDeletedAtIsNull(); + + boolean existsByNameIgnoreCaseAndDeletedAtIsNotNull(String name); + @Query("SELECT r FROM Role r where parent.id = :parentId") List findByParent(String parentId); } diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/repo/UserRepository.java b/solvway-services-system/src/main/java/com/solvway/services/system/repo/UserRepository.java index 881e163..e5ba8d3 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/repo/UserRepository.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/repo/UserRepository.java @@ -110,4 +110,7 @@ public interface UserRepository extends JpaRepository, JpaRepository @Query("select u from User u join u.roles r where r.name= :roleName") List findUserByRoleName(@Param("roleName")String roleName); + + @Query("select count(u) from User u join u.roles r where r.id = :roleId") + long countByRoleId(@Param("roleId") Long roleId); } diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/service/PasswordRuleService.java b/solvway-services-system/src/main/java/com/solvway/services/system/service/PasswordRuleService.java index 29dbfcc..adc6780 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/service/PasswordRuleService.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/service/PasswordRuleService.java @@ -15,6 +15,16 @@ public class PasswordRuleService { @Autowired private PasswordRuleRepository passwordRuleRepository; + public record ActiveRule(String param, String value) {} + + /** Switched-on admin rules (status Y) as param and value; value is null for flag rules. */ + public List adminActive() { + return passwordRuleRepository.findByType("ADMIN_PWD_FORMAT").stream() + .filter(r -> "Y".equals(r.getStatus())) + .map(r -> new ActiveRule(r.getParam(), r.getValue())) + .toList(); + } + public List findByType(String name){ return passwordRuleRepository.findByType(name); } diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/service/RoleService.java b/solvway-services-system/src/main/java/com/solvway/services/system/service/RoleService.java index 9a2593a..2ec3fe8 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/service/RoleService.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/service/RoleService.java @@ -4,10 +4,14 @@ import com.solvway.services.system.model.Role; import com.solvway.services.system.model.RoleParent; import com.solvway.services.system.repo.ModuleRepository; import com.solvway.services.system.repo.RoleRepository; +import com.solvway.services.system.repo.UserRepository; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; +import org.springframework.web.server.ResponseStatusException; +import java.sql.Timestamp; import java.util.List; import java.util.Optional; @@ -21,9 +25,35 @@ public class RoleService { @Autowired private ModelMapper modelMapper; + + @Autowired + private UserRepository userRepository; + /** Live roles only: deleted ones leave the role list and the user role picker. */ public List findAll() { - return roleRepository.findAll(); + return roleRepository.findByDeletedAtIsNull(); + } + + public void delete(Long id) { + Role role = roleRepository.findById(id).filter(r -> r.getDeletedAt() == null) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); + if (id == 1L || List.of("ROLE_ADMIN", "ROLE_MEMBER").contains(role.getName())) { // 1 = ROLE_SUPER_ADMIN, seeded + throw new ResponseStatusException(HttpStatus.CONFLICT, "ROLE_PROTECTED"); + } + long users = userRepository.countByRoleId(id); + if (users > 0) { + ResponseStatusException e = new ResponseStatusException(HttpStatus.CONFLICT, "ROLE_IN_USE"); + e.getBody().setProperty("users", users); + throw e; + } + role.setDeletedAt(new Timestamp(System.currentTimeMillis())); + roleRepository.save(role); + } + + public void requireNameNotDeleted(Role role) { + if (role.getName() != null && roleRepository.existsByNameIgnoreCaseAndDeletedAtIsNotNull(role.getName())) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "ROLE_NAME_DELETED"); + } } public Role findByName(String name) { diff --git a/solvway-services-system/src/test/java/com/solvway/services/system/service/PasswordRuleServiceAdminActiveTest.java b/solvway-services-system/src/test/java/com/solvway/services/system/service/PasswordRuleServiceAdminActiveTest.java new file mode 100644 index 0000000..c576000 --- /dev/null +++ b/solvway-services-system/src/test/java/com/solvway/services/system/service/PasswordRuleServiceAdminActiveTest.java @@ -0,0 +1,44 @@ +package com.solvway.services.system.service; + +import com.solvway.services.system.model.PasswordRuleProperty; +import com.solvway.services.system.repo.PasswordRuleRepository; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +/** The admin password hint lists only the switched-on ADMIN rules, in the order the check runs them. */ +@ExtendWith(MockitoExtension.class) +class PasswordRuleServiceAdminActiveTest { + + @Mock private PasswordRuleRepository repo; + @InjectMocks private PasswordRuleService service; + + private static PasswordRuleProperty rule(String param, String status, String value) { + PasswordRuleProperty r = new PasswordRuleProperty(); + r.setParam(param); + r.setStatus(status); + r.setValue(value); + return r; + } + + @Test + void adminActive_onlyYRules_withValues_nullForFlags() { + when(repo.findByType("ADMIN_PWD_FORMAT")).thenReturn(List.of( + rule("INPUT_LENGTH_MIN", "Y", "8"), + rule("INPUT_LENGTH_MAX", "N", "20"), + rule("SYMBOLIC_LENGTH_MIN", "Y", "2"), + rule("SPACE_NOT_ALLOWED", "Y", null))); + + assertThat(service.adminActive()).containsExactly( + new PasswordRuleService.ActiveRule("INPUT_LENGTH_MIN", "8"), + new PasswordRuleService.ActiveRule("SYMBOLIC_LENGTH_MIN", "2"), + new PasswordRuleService.ActiveRule("SPACE_NOT_ALLOWED", null)); + } +} diff --git a/solvway-services-system/src/test/java/com/solvway/services/system/service/RoleServiceDeleteTest.java b/solvway-services-system/src/test/java/com/solvway/services/system/service/RoleServiceDeleteTest.java new file mode 100644 index 0000000..68c5338 --- /dev/null +++ b/solvway-services-system/src/test/java/com/solvway/services/system/service/RoleServiceDeleteTest.java @@ -0,0 +1,135 @@ +package com.solvway.services.system.service; + +import com.solvway.services.system.model.Role; +import com.solvway.services.system.repo.RoleRepository; +import com.solvway.services.system.repo.UserRepository; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; + +import java.sql.Timestamp; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** Soft delete of roles: list exclusion, in-use and protected refusals, 404s, reserved names. */ +@ExtendWith(MockitoExtension.class) +class RoleServiceDeleteTest { + + @Mock + private RoleRepository roleRepository; + @Mock + private UserRepository userRepository; + @InjectMocks + private RoleService service; + + @Test + void findAllExcludesDeletedRoles() { + Role live = role(5L, "ROLE_SALES"); + when(roleRepository.findByDeletedAtIsNull()).thenReturn(List.of(live)); + + assertThat(service.findAll()).containsExactly(live); + } + + @Test + void deleteUnusedRoleStampsDeletedAt() { + Role r = role(5L, "ROLE_TEMP"); + when(roleRepository.findById(5L)).thenReturn(Optional.of(r)); + when(userRepository.countByRoleId(5L)).thenReturn(0L); + + service.delete(5L); + + assertThat(r.getDeletedAt()).isNotNull(); + verify(roleRepository).save(r); + } + + @Test + void deleteRoleInUseIsRefusedWithUserCount() { + Role r = role(5L, "ROLE_SALES"); + when(roleRepository.findById(5L)).thenReturn(Optional.of(r)); + when(userRepository.countByRoleId(5L)).thenReturn(3L); + + assertThatThrownBy(() -> service.delete(5L)) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); + assertThat(e.getBody().getDetail()).isEqualTo("ROLE_IN_USE"); + assertThat(e.getBody().getProperties()).containsEntry("users", 3L); + }); + assertThat(r.getDeletedAt()).isNull(); + verify(roleRepository, never()).save(any()); + } + + @Test + void superAdminAndRoleAdminAreProtected() { + when(roleRepository.findById(1L)).thenReturn(Optional.of(role(1L, "ROLE_SUPER_ADMIN"))); + when(roleRepository.findById(2L)).thenReturn(Optional.of(role(2L, "ROLE_ADMIN"))); + + for (long id : new long[]{1L, 2L}) { + assertThatThrownBy(() -> service.delete(id)) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); + assertThat(e.getBody().getDetail()).isEqualTo("ROLE_PROTECTED"); + }); + } + verify(roleRepository, never()).save(any()); + } + + @Test + void roleMemberIsProtected() { + when(roleRepository.findById(3L)).thenReturn(Optional.of(role(3L, "ROLE_MEMBER"))); + assertThatThrownBy(() -> service.delete(3L)) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); + assertThat(e.getBody().getDetail()).isEqualTo("ROLE_PROTECTED"); + }); + verify(roleRepository, never()).save(any()); + } + + @Test + void unknownOrDeletedRoleIs404() { + Role gone = role(6L, "ROLE_OLD"); + gone.setDeletedAt(new Timestamp(1L)); + when(roleRepository.findById(9L)).thenReturn(Optional.empty()); + when(roleRepository.findById(6L)).thenReturn(Optional.of(gone)); + + for (long id : new long[]{9L, 6L}) { + assertThatThrownBy(() -> service.delete(id)) + .isInstanceOf(ResponseStatusException.class) + .hasFieldOrPropertyWithValue("statusCode", HttpStatus.NOT_FOUND); + } + verify(roleRepository, never()).save(any()); + } + + @Test + void savingADeletedRolesNameIsRefused() { + when(roleRepository.existsByNameIgnoreCaseAndDeletedAtIsNotNull("ROLE_TEMP")).thenReturn(true); + + assertThatThrownBy(() -> service.requireNameNotDeleted(role(null, "ROLE_TEMP"))) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); + assertThat(e.getBody().getDetail()).isEqualTo("ROLE_NAME_DELETED"); + }); + } + + @Test + void savingALiveNameIsAllowed() { + service.requireNameNotDeleted(role(null, "ROLE_NEW")); + } + + private static Role role(Long id, String name) { + Role r = new Role(); + r.setId(id); + r.setName(name); + return r; + } +}