Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cd0a0458a4 | ||
|
|
bee1da9a7e | ||
|
|
ae756e554f | ||
|
|
d9b6bb04c1 | ||
|
|
a9f647589f | ||
|
|
7533163931 | ||
|
|
1b8110dbbf | ||
|
|
82e6ddc3e6 | ||
|
|
8ce9fcf471 | ||
|
|
5e68478670 | ||
|
|
0b201a51ca | ||
|
|
0f83e9cc08 | ||
|
|
a9e2232686 | ||
|
|
a106bc798f | ||
|
|
b4d36175d3 | ||
|
|
4b1645ff64 | ||
|
|
099390c5c6 | ||
|
|
e3efc67c26 | ||
|
|
75e243f3bb | ||
|
|
2c663f4ad5 | ||
|
|
89eb9b4aae |
No files matched your search
@@ -0,0 +1,30 @@
|
||||
# Sidebar categories
|
||||
|
||||
Date: 2026-12-01. Owner approved the grouping below on 2026-12-01.
|
||||
|
||||
## Intent
|
||||
|
||||
The sidebar is a flat list of work pages with one "Administration" section. The owner wants the modules grouped into clear categories and the menu cleaned up before go-live, and the WhatsApp inbox will need a home in it next.
|
||||
|
||||
## Decisions (owner-approved)
|
||||
|
||||
- Always-open labelled sections, not collapsible groups: 12 items do not need extra clicks.
|
||||
- Categories and order:
|
||||
- Dashboard (no label, first)
|
||||
- **Events:** Events, Event leads
|
||||
- **Leads:** Leads, Interests (the WhatsApp inbox joins here later)
|
||||
- **Access:** Users, Roles, Login security
|
||||
- **System:** Companies, Emails, Audit log
|
||||
- Each section has the existing thin divider and small muted label. The collapsed rail shows dividers only.
|
||||
- A section with nothing the user may open does not show.
|
||||
- Within a section, items follow the order above, not the server's order. A module missing from the map goes into a final unlabelled section at the end, so nothing disappears.
|
||||
- Every item has a distinct icon: Login security moves from `Shield` (too close to Roles' `ShieldCheck`) to `LockKeyhole`.
|
||||
|
||||
## Approach (my call)
|
||||
|
||||
The server's menu tree is flat, so the grouping stays in the portal as one fixed category map. It replaces the single admin list. The icon override for Login security lives in the same map, so no database change is needed. The portal icon map, which still carries babyboo icons for inventory, POS and catalogue modules Co-Lite does not have, is trimmed to the icons Co-Lite seeds plus the fallback.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Renaming modules, changing permissions or the server menu.
|
||||
- Collapsible groups.
|
||||
@@ -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/`.
|
||||
@@ -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;
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-12-01
|
||||
@@ -0,0 +1,20 @@
|
||||
## Context
|
||||
|
||||
See `docs/superpowers/specs/2026-12-01-sidebar-categories-design.md`. Task 1.2 of `refine-visitor-pages-and-shell` introduced `ADMIN_MODULES` and a two-way split in `SidebarNav`, with a visible label naming each list (`aria-labelledby`, plus `aria-label` in the rail).
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:** fixed categories and order, a distinct icon for every item, and a trimmed icon map.
|
||||
|
||||
**Non-Goals:** server menu changes, collapsible groups, renames.
|
||||
|
||||
## Decisions
|
||||
|
||||
- **The category map replaces `ADMIN_MODULES`.** `SIDEBAR_SECTIONS` in `aclSidebar.ts` is an ordered list of `{ label?: string; modules: string[] }`, with Dashboard as the first entry without a label. A helper `groupSidebar(links)` returns the sections in map order, each with its links in map order. Links not in the map go into a trailing section without a label. Empty sections are dropped. `SidebarNav` renders each section with the existing divider, label and list pattern; the first section has no divider.
|
||||
- **Icon override in the portal.** `SIDEBAR_ICONS: Record<string, string>` (module name to lucide name), holding `BO_LOGIN_SECURITY: "LockKeyhole"`, is applied in `groupSidebar` over the server's `iconName`. No SQL change.
|
||||
- **Icon map trim.** Keep only the icon names Co-Lite seeds (`local/seed/03-colite.sql` and the archived change SQL), `Store` (Companies, added by `useAclSidebar`), `LockKeyhole`, and the fallback. Check `icon-map` tests before removing anything; an existing test asserting a babyboo icon is a conflict to report.
|
||||
- **Labels** are new keys in `defaultMessages.ts` (`SidebarSectionEvents`, `SidebarSectionLeads`, `SidebarSectionAccess`, `SidebarSectionSystem`). `SidebarAdministration` is removed.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- A new server module shows in the trailing section until it is added to the map. That is visible and harmless. Keep the `ponytail:` note.
|
||||
@@ -0,0 +1,27 @@
|
||||
## Why
|
||||
|
||||
The sidebar lists work pages and then one "Administration" section. The owner asked for the modules to be grouped into categories and cleaned up before go-live. The WhatsApp inbox, which comes next, needs a clear place in the menu.
|
||||
|
||||
## What Changes
|
||||
|
||||
- The sidebar shows labelled sections: Dashboard on its own, then Events, Leads, Access and System.
|
||||
- Items follow a fixed order within each section. A module missing from the map goes into a final section, so nothing disappears.
|
||||
- Login security gets its own icon (`LockKeyhole`).
|
||||
- The portal icon map drops babyboo icons for modules Co-Lite does not have.
|
||||
- The "Administration" label is replaced by the new section labels.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
None.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `admin-visual-design`: the Sidebar Sections requirement now describes the categories.
|
||||
|
||||
## Impact
|
||||
|
||||
- Portal only: `app/lib/aclSidebar.ts`, `app/components/app/Sidebar.tsx`, the icon map, `defaultMessages.ts` (section labels), and DESIGN.md (Navigation).
|
||||
- No server, database or API change.
|
||||
- Design: `docs/superpowers/specs/2026-12-01-sidebar-categories-design.md`.
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Sidebar Sections
|
||||
|
||||
The sidebar SHALL show Dashboard first, then the labelled sections Events, Leads, Access and System, each with a fixed set and order of pages. A page not in any section SHALL appear in a final section without a label. A section SHALL be marked by a divider and a small muted label, with only the divider in the collapsed rail, and SHALL NOT show when it has no page the user may open. Every page SHALL have a distinct icon.
|
||||
|
||||
#### Scenario: Super admin sidebar
|
||||
|
||||
- **WHEN** a super admin opens the portal
|
||||
- **THEN** the sidebar shows Dashboard, then "Events" with Events and Event leads, "Leads" with Leads and Interests, "Access" with Users, Roles and Login security, and "System" with Companies, Emails and Audit log
|
||||
|
||||
#### Scenario: Staff without admin pages
|
||||
|
||||
- **WHEN** a staff user who can open only Events and Event leads opens the portal
|
||||
- **THEN** the sidebar shows only the "Events" section
|
||||
- **AND** no "Leads", "Access" or "System" label
|
||||
|
||||
#### Scenario: Unknown page
|
||||
|
||||
- **WHEN** the server menu has a page that is not in the category map
|
||||
- **THEN** it is listed after the System section, without a label
|
||||
|
||||
#### Scenario: Collapsed rail
|
||||
|
||||
- **WHEN** an admin collapses the sidebar to the icon rail
|
||||
- **THEN** the sections are separated by dividers and no section label shows
|
||||
@@ -0,0 +1,14 @@
|
||||
# Tasks: group-sidebar-categories
|
||||
|
||||
Portal only. TDD, then the review gate. Verify: `cd solvway-admin-portal && npx vitest run; echo VITEST=$? && npx tsc --noEmit && npm run lint` (check the vitest exit code).
|
||||
|
||||
- [x] 1.1 Category map, `groupSidebar`, the icon override, section rendering in `SidebarNav` (full, drawer and rail), and the label keys. The "Administration" label and `ADMIN_MODULES` go.
|
||||
- Scope: `solvway-admin-portal/app/lib/aclSidebar*`, `solvway-admin-portal/app/components/app/Sidebar*`, `solvway-admin-portal/app/lib/i18n/defaultMessages.ts`
|
||||
- [x] 1.2 Trim the icon map to the icons Co-Lite uses.
|
||||
- Scope: the icon map file and its tests
|
||||
- [x] 1.3 DESIGN.md Navigation updated, and a Playwright check at 1280 px (full and rail) and 360 px (drawer) as a super admin, plus a staff user with event pages only.
|
||||
- Done 2026-12-02 on the local stack:
|
||||
- Playwright as super admin: the full sidebar at 1280 px (Dashboard, then Events, Leads, Access and System with labels and dividers), the collapsed rail (dividers only, Login security with its lock icon), and the drawer at 360 px.
|
||||
- The staff-only scenario (event pages only) is covered by `Sidebar.sections.test.tsx`. No browser sign-in was done for it, because no local staff user has only those modules.
|
||||
- Icon map trimmed to Co-Lite's 12 icons. The babyboo-only icon tests were removed, and the Activity-group test file was deleted.
|
||||
- Portal verify: vitest 1572 passed (exit 0), tsc 0, lint 0 errors.
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-12-02
|
||||
@@ -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_<param>` 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.
|
||||
@@ -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.
|
||||
@@ -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
|
||||
+19
@@ -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
|
||||
@@ -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
|
||||
+21
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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;
|
||||
@@ -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`;
|
||||
@@ -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 <modules> 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.
|
||||
@@ -8,7 +8,7 @@ Staff log in to the Co-Lite admin portal, and every admin page and `/api/admin/*
|
||||
|
||||
### 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.
|
||||
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
|
||||
|
||||
@@ -29,6 +29,18 @@ The system SHALL let an active admin user log in through the admin portal with c
|
||||
- **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
|
||||
|
||||
@@ -142,3 +142,21 @@ The system SHALL let an admin with `BO_LOGIN_SECURITY` read the lockout settings
|
||||
|
||||
- **WHEN** an INS user with `BO_LOGIN_SECURITY` changes a lockout setting or a password rule
|
||||
- **THEN** the change is refused with 403 and the settings stay as they were
|
||||
|
||||
### 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
|
||||
@@ -8,7 +8,7 @@ Admins with the Roles module define roles and choose which back-office modules e
|
||||
|
||||
### 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 and rename them, because roles are shared by every company. Role names SHALL be unique. The member role and `ROLE_ADMIN` SHALL NOT appear in the list (`ROLE_ADMIN` is attached to every admin automatically and grants no modules).
|
||||
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
|
||||
|
||||
@@ -23,7 +23,7 @@ The system SHALL let any admin with `BO_ROLES` list admin roles, and SHALL let o
|
||||
|
||||
#### Scenario: Company user edits a role
|
||||
|
||||
- **WHEN** an INS user with `BO_ROLES` creates or renames 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
|
||||
|
||||
### Requirement: Role permissions
|
||||
@@ -51,3 +51,26 @@ The system SHALL hold Co-Lite's back-office modules in the module table, with a
|
||||
|
||||
- **WHEN** the local stack starts from an empty database
|
||||
- **THEN** the super admin's sidebar shows Users and Roles and no Tastefully back-office entries
|
||||
|
||||
### 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
|
||||
@@ -127,15 +127,45 @@ A table wider than its container SHALL show a fade on each edge where more colum
|
||||
|
||||
### Requirement: Sidebar Sections
|
||||
|
||||
The sidebar SHALL list the work pages first, then an "Administration" section for Users, Roles, Emails, Login security, Audit log and Companies. The section SHALL be marked by a divider and a small muted label, and only the divider SHALL show in the collapsed rail. A section with no item the admin may open SHALL NOT show.
|
||||
The sidebar SHALL show Dashboard first, then the labelled sections Events, Leads, Access and System, each with a fixed set and order of pages. A page not in any section SHALL appear in a final section without a label. A section SHALL be marked by a divider and a small muted label, with only the divider in the collapsed rail, and SHALL NOT show when it has no page the user may open. Every page SHALL have a distinct icon.
|
||||
|
||||
#### Scenario: Super admin sidebar
|
||||
|
||||
- **WHEN** a super admin opens the portal
|
||||
- **THEN** Dashboard, Events, Event leads, Interests and Leads are listed above the "Administration" label
|
||||
- **AND** Users, Roles, Emails, Login security, Audit log and Companies are listed below it
|
||||
- **THEN** the sidebar shows Dashboard, then "Events" with Events and Event leads, "Leads" with Leads and Interests, "Access" with Users, Roles and Login security, and "System" with Companies, Emails and Audit log
|
||||
|
||||
#### Scenario: Staff without admin pages
|
||||
|
||||
- **WHEN** a staff user who can open only Events and Event leads opens the portal
|
||||
- **THEN** the sidebar shows no "Administration" label
|
||||
- **THEN** the sidebar shows only the "Events" section
|
||||
- **AND** no "Leads", "Access" or "System" label
|
||||
|
||||
#### Scenario: Unknown page
|
||||
|
||||
- **WHEN** the server menu has a page that is not in the category map
|
||||
- **THEN** it is listed after the System section, without a label
|
||||
|
||||
#### Scenario: Collapsed rail
|
||||
|
||||
- **WHEN** an admin collapses the sidebar to the icon rail
|
||||
- **THEN** the sections are separated by dividers and no section label shows
|
||||
|
||||
### 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
|
||||
@@ -156,3 +156,15 @@ The dashboard SHALL count only the records of the caller's company for company s
|
||||
|
||||
- **WHEN** a super admin picks CV in the company picker
|
||||
- **THEN** every figure counts CV records only
|
||||
|
||||
### 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
|
||||
@@ -8,7 +8,7 @@ Admins with the Interests module maintain the list of products and services that
|
||||
|
||||
### 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 and reactivate interests. An interest name SHALL be required, at most 100 characters, and unique ignoring case. Interests SHALL NOT be deletable.
|
||||
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
|
||||
|
||||
@@ -25,16 +25,38 @@ The system SHALL keep one interest list shared by all companies. Admins with `BO
|
||||
#### Scenario: Deactivate
|
||||
|
||||
- **GIVEN** an active interest `Cookware`
|
||||
- **WHEN** a super admin deactivates it
|
||||
- **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 or deactivates an interest
|
||||
- **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
|
||||
|
||||
### 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
|
||||
@@ -237,7 +237,7 @@ Quiet, compact, unmistakable.
|
||||
- Live inside a card or an 8px framed container. Header row in slate tint, 40px tall, 12px semibold uppercase muted labels with sort chevrons; cells 14px with 8px padding; rows separated by hairlines, hovering at 50% slate tint. The pager below reads "1-7 of 7" left and outline Previous / Next right.
|
||||
|
||||
### Navigation
|
||||
- **Sidebar:** white, right hairline. Items are 44px tall, 8px radius, 20px outline icon plus 14px medium label. Idle: muted slate, hover slate tint with ink. Active: blue tint with deep blue ink, `aria-current="page"`. Groups expand with a rotating chevron and indent children behind a left hairline. The collapsed rail shows icons only, with groups opening as a side popover. Admin pages (Users, Roles, Emails, Login security, Audit log, Companies) sit below a hairline divider and a 12px semibold muted "Administration" label; the rail keeps the divider only, and a section with nothing to open is not drawn.
|
||||
- **Sidebar:** white, right hairline. Items are 44px tall, 8px radius, 20px outline icon plus 14px medium label. Idle: muted slate, hover slate tint with ink. Active: blue tint with deep blue ink, `aria-current="page"`. Groups expand with a rotating chevron and indent children behind a left hairline. The collapsed rail shows icons only, with groups opening as a side popover. Pages are grouped into always-open sections: Dashboard alone, then Events (Events, Event leads), Leads (Leads, Interests), Access (Users, Roles, Login security) and System (Companies, Emails, Audit log). Each later section starts with a hairline divider and a 12px semibold muted label; the rail keeps the dividers only, a section with nothing to open is not drawn, and a page the map does not know trails in a last unlabelled section. Every page has its own icon.
|
||||
- **Header:** white, bottom hairline, 56px; the link back to the parent page left (sub-pages only); company picker (a styled select), locale switcher, theme toggle and user menu (blue avatar initial) right.
|
||||
|
||||
### Data States
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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<unknown>(`/api/admin/interests/${encodeURIComponent(id)}`, { method: "DELETE", token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -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" });
|
||||
});
|
||||
});
|
||||
@@ -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<unknown>("/api/admin/password-rules/active", { token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -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<typeof GET>[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);
|
||||
});
|
||||
});
|
||||
@@ -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");
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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<unknown>(`/api/admin/roles/${encodeURIComponent(id)}`, { method: "DELETE", token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ getCheckin: vi.fn(), lookupCheckin: vi.fn(), registerWalkIn: vi.fn() }));
|
||||
vi.mock("@/app/lib/services/publicInvite", () => mocks);
|
||||
vi.mock("next/navigation", () => ({ useParams: () => ({ token: "chk1" }) }));
|
||||
|
||||
import CheckinPage from "./page";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.getCheckin.mockReset().mockResolvedValue({
|
||||
state: "OPEN", eventName: "Expo 2026", startDate: "2026-12-01", endDate: "2026-12-02", location: "KLCC", companyName: "INS",
|
||||
notice: { id: 7, textEn: "We keep your data safe.", textMs: "Data anda selamat." }, interests: [],
|
||||
});
|
||||
mocks.lookupCheckin.mockReset().mockResolvedValue({ result: "FORM" });
|
||||
});
|
||||
|
||||
describe("/c/[token] lookup", () => {
|
||||
it("shows a visible error and does not look up when the field is empty", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<CheckinPage />);
|
||||
await user.click(await screen.findByRole("button", { name: "Check in" }));
|
||||
expect(await screen.findByText("Enter a mobile number or an email.")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Mobile number or email")).toHaveAttribute("aria-invalid", "true");
|
||||
expect(mocks.lookupCheckin).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("carries a looked-up email into the walk-in form", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<CheckinPage />);
|
||||
await user.type(await screen.findByLabelText("Mobile number or email"), "w@b.co");
|
||||
await user.click(screen.getByRole("button", { name: "Check in" }));
|
||||
expect(await screen.findByLabelText("Email")).toHaveValue("w@b.co");
|
||||
expect(screen.getByLabelText("Mobile number")).toHaveValue("");
|
||||
});
|
||||
|
||||
it("carries a looked-up mobile into the walk-in form", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<CheckinPage />);
|
||||
await user.type(await screen.findByLabelText("Mobile number or email"), "0123456789");
|
||||
await user.click(screen.getByRole("button", { name: "Check in" }));
|
||||
expect(await screen.findByLabelText("Mobile number")).toHaveValue("0123456789");
|
||||
expect(screen.getByLabelText("Email")).toHaveValue("");
|
||||
});
|
||||
});
|
||||
@@ -41,7 +41,10 @@ export default function CheckinPage() {
|
||||
|
||||
async function lookup(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!value.trim()) return;
|
||||
if (!value.trim()) {
|
||||
setError(t("RegContactRequired"));
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
@@ -71,14 +74,14 @@ export default function CheckinPage() {
|
||||
if (phase === "welcome") body = <VisitorState icon={CheckCircle2} heading={firstName ? t("InviteWelcome", { name: firstName }) : t("InviteWelcomeAnon")} role="status" />;
|
||||
else if (phase === "done") body = <VisitorState icon={CheckCircle2} heading={t("ChkDone", { event: open.eventName })} role="status" />;
|
||||
else if (phase === "form") {
|
||||
body = <RegistrationForm tooManyKey="InviteTooMany" info={open} submit={(b) => registerWalkIn(token, b)} onDone={() => setPhase("done")} onInactive={() => setPhase("inactive")} />;
|
||||
body = <RegistrationForm tooManyKey="InviteTooMany" info={open} initial={value.includes("@") ? { email: value.trim() } : { mobile: value.trim() }} submit={(b) => registerWalkIn(token, b)} onDone={() => setPhase("done")} onInactive={() => setPhase("inactive")} />;
|
||||
} else {
|
||||
body = (
|
||||
<form onSubmit={lookup} className="space-y-4" noValidate>
|
||||
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="chk-value">{t("ChkLookup")}</Label>
|
||||
<Input id="chk-value" className="h-11" value={value} onChange={(e) => setValue(e.target.value)} disabled={busy} />
|
||||
<Input id="chk-value" className="h-11" value={value} onChange={(e) => setValue(e.target.value)} disabled={busy} aria-invalid={!!error} />
|
||||
</div>
|
||||
<Button type="submit" className="h-11 w-full" disabled={busy}>{t("InviteCheckin")}</Button>
|
||||
</form>
|
||||
|
||||
@@ -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<typeof import("@/app/lib/clientApi")>()).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(<CompaniesPage />);
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -103,6 +103,9 @@ function CompanyDialog({ state, onClose, onSaved }: { state: DialogState; onClos
|
||||
</>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button type="submit" disabled={saving}>
|
||||
{mode === "code" ? t("CompConfirm") : t("Save")}
|
||||
</Button>
|
||||
@@ -170,6 +173,9 @@ function PrivacyNoticeDialog({ company, onClose }: { company: AdminCompany; onCl
|
||||
</p>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button type="submit" disabled={saving}>
|
||||
{t("PrivSave")}
|
||||
</Button>
|
||||
|
||||
@@ -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<string | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [ruleError, setRuleError] = useState<string | undefined>();
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
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 && (
|
||||
<div role="alert" className="rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">
|
||||
|
||||
@@ -9,46 +9,70 @@ vi.mock("@/app/lib/useAclSidebar", () => ({ useAclSidebar: () => state.links }))
|
||||
|
||||
import { SidebarNav } from "./Sidebar";
|
||||
|
||||
const link = (name: string): SidebarLink => ({ name, url: `/${name}`, children: [] });
|
||||
const link = (name: string): SidebarLink => ({ name, url: `/${name}`, iconName: "Users", children: [] });
|
||||
const names = (...n: string[]) => n.map(link);
|
||||
|
||||
const ALL = names(
|
||||
"BO_DASHBOARD", "BO_EVENTS", "BO_EVENT_LEADS", "BO_INTERESTS", "BO_LEADS",
|
||||
"BO_USERS", "BO_ROLES", "BO_EMAILS", "BO_LOGIN_SECURITY", "BO_AUDIT_LOG", "BO_COMPANIES",
|
||||
);
|
||||
const linkNames = (list: HTMLElement) => within(list).getAllByRole("link").map((a) => a.getAttribute("href")?.slice(1));
|
||||
|
||||
describe("Sidebar sections", () => {
|
||||
it("lists work pages above the Administration label and admin pages below it", () => {
|
||||
state.links = ALL;
|
||||
it("lists Dashboard, then Events, Leads, Access and System sections in order", () => {
|
||||
state.links = [...ALL].reverse();
|
||||
render(<SidebarNav />);
|
||||
const label = screen.getByText("Administration");
|
||||
const before = (el: HTMLElement) => label.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_PRECEDING;
|
||||
const after = (el: HTMLElement) => label.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING;
|
||||
const hrefs = (re: RegExp) => screen.getAllByRole("link").filter((a) => re.test(a.getAttribute("href") ?? ""));
|
||||
for (const a of hrefs(/DASHBOARD|EVENTS|EVENT_LEADS|INTERESTS|LEADS/)) expect(before(a)).toBeTruthy();
|
||||
for (const a of hrefs(/USERS|ROLES|EMAILS|LOGIN_SECURITY|AUDIT_LOG|COMPANIES/)) expect(after(a)).toBeTruthy();
|
||||
const lists = screen.getAllByRole("list");
|
||||
expect(lists).toHaveLength(5);
|
||||
expect(linkNames(lists[0])).toEqual(["BO_DASHBOARD"]);
|
||||
expect(linkNames(screen.getByRole("list", { name: "Events" }))).toEqual(["BO_EVENTS", "BO_EVENT_LEADS"]);
|
||||
expect(linkNames(screen.getByRole("list", { name: "Leads" }))).toEqual(["BO_LEADS", "BO_INTERESTS"]);
|
||||
expect(linkNames(screen.getByRole("list", { name: "Access" }))).toEqual(["BO_USERS", "BO_ROLES", "BO_LOGIN_SECURITY"]);
|
||||
expect(linkNames(screen.getByRole("list", { name: "System" }))).toEqual(["BO_COMPANIES", "BO_EMAILS", "BO_AUDIT_LOG"]);
|
||||
expect(screen.getAllByRole("link")).toHaveLength(11);
|
||||
});
|
||||
|
||||
it("names the admin list by the label", () => {
|
||||
state.links = ALL;
|
||||
render(<SidebarNav />);
|
||||
const list = screen.getByRole("list", { name: "Administration" });
|
||||
expect(within(list).getAllByRole("link")).toHaveLength(6);
|
||||
});
|
||||
|
||||
it("shows no Administration label or divider when no admin module is available", () => {
|
||||
it("shows only the sections the user has pages in", () => {
|
||||
state.links = names("BO_EVENTS", "BO_EVENT_LEADS");
|
||||
const { container } = render(<SidebarNav />);
|
||||
expect(screen.queryByText("Administration")).toBeNull();
|
||||
expect(screen.getByRole("list", { name: "Events" })).toBeTruthy();
|
||||
for (const label of ["Leads", "Access", "System"]) expect(screen.queryByText(label)).toBeNull();
|
||||
expect(container.querySelector("[data-slot='sidebar-divider']")).toBeNull();
|
||||
});
|
||||
|
||||
it("shows only the divider in the collapsed rail", () => {
|
||||
it("puts a divider between sections but not above the first", () => {
|
||||
state.links = ALL;
|
||||
const { container } = render(<SidebarNav />);
|
||||
expect(container.querySelectorAll("[data-slot='sidebar-divider']")).toHaveLength(4);
|
||||
expect(container.querySelector("nav")!.firstElementChild!.tagName).toBe("UL");
|
||||
});
|
||||
|
||||
it("lists an unknown page after System without a label", () => {
|
||||
state.links = [...ALL, link("BO_NEW_THING")];
|
||||
const { container } = render(<SidebarNav />);
|
||||
const lists = screen.getAllByRole("list");
|
||||
expect(lists).toHaveLength(6);
|
||||
const last = lists[5];
|
||||
expect(linkNames(last)).toEqual(["BO_NEW_THING"]);
|
||||
expect(last.getAttribute("aria-labelledby")).toBeNull();
|
||||
expect(last.getAttribute("aria-label")).toBeNull();
|
||||
expect(container.querySelectorAll("[data-slot='sidebar-divider']")).toHaveLength(5);
|
||||
});
|
||||
|
||||
it("shows dividers and no labels in the collapsed rail", () => {
|
||||
state.links = ALL;
|
||||
const { container } = render(<SidebarNav collapsed />);
|
||||
expect(screen.queryByText("Administration")).toBeNull();
|
||||
expect(container.querySelector("[data-slot='sidebar-divider']")).not.toBeNull();
|
||||
for (const label of ["Events", "Leads", "Access", "System"]) expect(screen.queryByText(label)).toBeNull();
|
||||
expect(container.querySelectorAll("[data-slot='sidebar-divider']")).toHaveLength(4);
|
||||
expect(screen.getByRole("list", { name: "Access" })).toBeTruthy();
|
||||
expect(screen.getAllByRole("link")).toHaveLength(11);
|
||||
});
|
||||
|
||||
it("renders Login security with a different icon than Roles", () => {
|
||||
state.links = [{ ...link("BO_ROLES"), iconName: "Shield" }, { ...link("BO_LOGIN_SECURITY"), iconName: "Shield" }];
|
||||
render(<SidebarNav />);
|
||||
const icon = (name: string) => document.querySelector(`a[href='/${name}'] svg`)!.getAttribute("class");
|
||||
expect(icon("BO_ROLES")).toContain("lucide-shield");
|
||||
expect(icon("BO_LOGIN_SECURITY")).toContain("lucide-lock-keyhole");
|
||||
});
|
||||
});
|
||||
@@ -24,12 +24,13 @@ vi.mock("@/app/lib/useAclSidebar", () => ({
|
||||
|
||||
import Sidebar from "./Sidebar";
|
||||
|
||||
// Icons are Co-Lite seed icons (group-sidebar-categories trimmed the babyboo-only ones).
|
||||
const BO_FIXTURE: SidebarLink[] = [
|
||||
{ name: "Dashboard", url: "/", iconName: "LayoutDashboard", children: [] },
|
||||
{ name: "Members", url: "/members", iconName: "Users", children: [] },
|
||||
{ name: "Reports", url: "/reports", iconName: "FileText", children: [] },
|
||||
{ name: "Network", url: "/network", iconName: "Network", children: [] },
|
||||
{ name: "Messages", url: "/messages", iconName: "Languages", children: [] },
|
||||
{ name: "Reports", url: "/reports", iconName: "Mail", children: [] },
|
||||
{ name: "Network", url: "/network", iconName: "ScrollText", children: [] },
|
||||
{ name: "Messages", url: "/messages", iconName: "Tags", children: [] },
|
||||
];
|
||||
|
||||
describe("Sidebar icon rendering", () => {
|
||||
@@ -41,9 +42,9 @@ describe("Sidebar icon rendering", () => {
|
||||
expect(screen.getByText("Messages")).toBeInTheDocument();
|
||||
expect(container.querySelector("svg.lucide-layout-dashboard")).not.toBeNull();
|
||||
expect(container.querySelector("svg.lucide-users")).not.toBeNull();
|
||||
expect(container.querySelector("svg.lucide-file-text")).not.toBeNull();
|
||||
expect(container.querySelector("svg.lucide-network")).not.toBeNull();
|
||||
expect(container.querySelector("svg.lucide-languages")).not.toBeNull();
|
||||
expect(container.querySelector("svg.lucide-mail")).not.toBeNull();
|
||||
expect(container.querySelector("svg.lucide-scroll-text")).not.toBeNull();
|
||||
expect(container.querySelector("svg.lucide-tags")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("renders the neutral fallback icon, and does not throw, for an unknown or absent iconName", () => {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useId, useState } from "react";
|
||||
import { Fragment, useEffect, useId, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { ChevronDown, PanelLeftClose, PanelLeftOpen } from "lucide-react";
|
||||
import { useAclSidebar } from "@/app/lib/useAclSidebar";
|
||||
import { ADMIN_MODULES, currentTrail, type SidebarLink } from "@/app/lib/aclSidebar";
|
||||
import { currentTrail, groupSidebar, type SidebarLink } from "@/app/lib/aclSidebar";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { iconFor } from "./icon-map";
|
||||
import { cn } from "@/app/lib/utils";
|
||||
@@ -215,39 +215,48 @@ function RailGroup({
|
||||
export function SidebarNav({ onNavigate, collapsed = false }: { onNavigate?: () => void; collapsed?: boolean }) {
|
||||
const t = useT();
|
||||
const links = useAclSidebar();
|
||||
const trail = currentTrail(links, usePathname());
|
||||
const adminLabelId = useId();
|
||||
|
||||
const work = links.filter((l) => !ADMIN_MODULES.includes(l.name));
|
||||
const admin = links.filter((l) => ADMIN_MODULES.includes(l.name));
|
||||
const sections = groupSidebar(links);
|
||||
// Trail from the grouped links: groupSidebar copies them, and active matching is by identity.
|
||||
const trail = currentTrail(sections.flatMap((s) => s.links), usePathname());
|
||||
const idBase = useId();
|
||||
const render = (link: SidebarLink) =>
|
||||
collapsed ? (
|
||||
<RailNode key={link.url || link.name} link={link} trail={trail} />
|
||||
) : (
|
||||
<NavNode key={link.url || link.name} link={link} depth={0} trail={trail} onNavigate={onNavigate} />
|
||||
);
|
||||
const listClass = cn("space-y-1", collapsed ? "px-2 py-3" : "p-3");
|
||||
|
||||
return (
|
||||
<nav aria-label={t("SidebarMainNav")} className="scrollable flex-1 overflow-x-hidden overflow-y-auto">
|
||||
{work.length > 0 && <ul className={cn(listClass, admin.length > 0 && "pb-0")}>{work.map(render)}</ul>}
|
||||
{admin.length > 0 && (
|
||||
<>
|
||||
<div data-slot="sidebar-divider" className={cn("mt-3 border-t border-border", collapsed ? "mx-3" : "mx-4")} />
|
||||
{/* The visible label names the list; the rail has no label, so the list carries the name itself. */}
|
||||
{!collapsed && (
|
||||
<p id={adminLabelId} className="px-6 pt-3 text-xs font-semibold text-muted-foreground">
|
||||
{t("SidebarAdministration")}
|
||||
</p>
|
||||
)}
|
||||
<ul
|
||||
aria-labelledby={collapsed ? undefined : adminLabelId}
|
||||
aria-label={collapsed ? t("SidebarAdministration") : undefined}
|
||||
className={cn(listClass, collapsed ? "pt-3" : "pt-2")}>
|
||||
{admin.map(render)}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
{sections.map(({ label, links: items }, i) => {
|
||||
const labelId = `${idBase}-${i}`;
|
||||
const name = label ? t(label) : undefined;
|
||||
return (
|
||||
<Fragment key={label ?? `section-${i}`}>
|
||||
{i > 0 && (
|
||||
<div data-slot="sidebar-divider" className={cn("mt-3 border-t border-border", collapsed ? "mx-3" : "mx-4")} />
|
||||
)}
|
||||
{/* The visible label names the list; the rail has no label, so the list carries the name itself. */}
|
||||
{name && !collapsed && (
|
||||
<p id={labelId} className="px-6 pt-3 text-xs font-semibold text-muted-foreground">
|
||||
{name}
|
||||
</p>
|
||||
)}
|
||||
<ul
|
||||
aria-labelledby={name && !collapsed ? labelId : undefined}
|
||||
aria-label={name && collapsed ? name : undefined}
|
||||
className={cn(
|
||||
"space-y-1",
|
||||
collapsed ? "px-2 py-3" : "p-3",
|
||||
i < sections.length - 1 && "pb-0",
|
||||
i > 0 && (collapsed || !name ? "pt-3" : "pt-2"),
|
||||
)}
|
||||
>
|
||||
{items.map(render)}
|
||||
</ul>
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
import { render } from "@testing-library/react";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { iconFor } from "./icon-map";
|
||||
|
||||
// add-online-users: the Activity group (BO_NAV_ACTIVITY), Online users and Audit log seed icons.
|
||||
describe("iconFor — Activity group", () => {
|
||||
it.each(["Activity", "UserCheck", "ScrollText"])("resolves %s to a real (non-fallback) icon", (name) => {
|
||||
const Icon = iconFor(name);
|
||||
const { container } = render(<Icon aria-hidden="true" />);
|
||||
expect(container.querySelector("svg")).not.toBeNull();
|
||||
expect(container.querySelector("svg.lucide-circle")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -3,8 +3,9 @@ import { describe, it, expect } from "vitest";
|
||||
import { iconFor } from "./icon-map";
|
||||
|
||||
// Covers spec "The Sidebar Renders Lucide Icons From icon_name":
|
||||
// - a seeded icon name renders as a lucide icon
|
||||
// - every icon Co-Lite seeds (or overrides in the sidebar) renders as a real lucide icon
|
||||
// - an unknown/absent icon name falls back safely (no throw)
|
||||
// group-sidebar-categories: the map holds only Co-Lite's icons; babyboo-only entries were removed.
|
||||
|
||||
describe("iconFor", () => {
|
||||
it("resolves a seeded lucide icon name (LayoutDashboard) to a component that renders", () => {
|
||||
@@ -13,55 +14,21 @@ describe("iconFor", () => {
|
||||
expect(container.querySelector("svg.lucide-layout-dashboard")).not.toBeNull();
|
||||
});
|
||||
|
||||
it.each(["Users", "FileText", "Network", "Languages", "Shield", "Settings", "Bell"])(
|
||||
"resolves seeded icon name %s to its matching lucide component",
|
||||
(name) => {
|
||||
const Icon = iconFor(name);
|
||||
const { container } = render(<Icon aria-hidden="true" />);
|
||||
expect(container.querySelector("svg")).not.toBeNull();
|
||||
expect(container.querySelector("svg.lucide-circle")).toBeNull();
|
||||
},
|
||||
);
|
||||
it.each([
|
||||
"LayoutDashboard", "CalendarDays", "ClipboardList", "Tags", "Users", "UserCog",
|
||||
"ShieldCheck", "Shield", "LockKeyhole", "Mail", "ScrollText", "Store",
|
||||
])("resolves Co-Lite icon name %s to a real (non-fallback) lucide component", (name) => {
|
||||
const Icon = iconFor(name);
|
||||
const { container } = render(<Icon aria-hidden="true" />);
|
||||
expect(container.querySelector("svg")).not.toBeNull();
|
||||
expect(container.querySelector("svg.lucide-circle")).toBeNull();
|
||||
});
|
||||
|
||||
it.each(["Calendar"])(
|
||||
"resolves Events sidebar seed icon %s to a real (non-fallback) lucide component",
|
||||
(name) => {
|
||||
const Icon = iconFor(name);
|
||||
const { container } = render(<Icon aria-hidden="true" />);
|
||||
expect(container.querySelector("svg")).not.toBeNull();
|
||||
expect(container.querySelector("svg.lucide-circle")).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["ShoppingCart"])(
|
||||
"resolves POS counter-sales sidebar seed icon %s to a real (non-fallback) lucide component",
|
||||
(name) => {
|
||||
const Icon = iconFor(name);
|
||||
const { container } = render(<Icon aria-hidden="true" />);
|
||||
expect(container.querySelector("svg")).not.toBeNull();
|
||||
expect(container.querySelector("svg.lucide-circle")).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["Store"])(
|
||||
"resolves Branch Counter sidebar seed icon %s to a real (non-fallback) lucide component",
|
||||
(name) => {
|
||||
const Icon = iconFor(name);
|
||||
const { container } = render(<Icon aria-hidden="true" />);
|
||||
expect(container.querySelector("svg")).not.toBeNull();
|
||||
expect(container.querySelector("svg.lucide-circle")).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["ArrowDownToLine", "BarChart2", "ArrowLeftRight", "History", "SlidersHorizontal"])(
|
||||
"resolves Inventory sidebar seed icon %s to a real (non-fallback) lucide component",
|
||||
(name) => {
|
||||
const Icon = iconFor(name);
|
||||
const { container } = render(<Icon aria-hidden="true" />);
|
||||
expect(container.querySelector("svg")).not.toBeNull();
|
||||
expect(container.querySelector("svg.lucide-circle")).toBeNull();
|
||||
},
|
||||
);
|
||||
it("no longer maps babyboo-only icons such as ShoppingCart (they fall back)", () => {
|
||||
const Icon = iconFor("ShoppingCart");
|
||||
const { container } = render(<Icon aria-hidden="true" />);
|
||||
expect(container.querySelector("svg.lucide-circle")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("falls back to a neutral icon, without throwing, for an unknown name", () => {
|
||||
expect(() => iconFor("NotARealLucideIconName")).not.toThrow();
|
||||
@@ -81,22 +48,4 @@ describe("iconFor", () => {
|
||||
const { container } = render(<Icon aria-hidden="true" />);
|
||||
expect(container.querySelector("svg.lucide-circle")).not.toBeNull();
|
||||
});
|
||||
|
||||
// fix-admin-sidebar-groups-icons: icon_name values on live BO module rows that used to
|
||||
// render the fallback circle.
|
||||
it.each(["ShieldCheck", "Wallet", "Mail", "Coins", "Megaphone", "Warehouse", "UserCog", "GalleryHorizontalEnd", "MessagesSquare", "Wrench"])(
|
||||
"resolves live BO module icon name %s to a real (non-fallback) lucide component",
|
||||
(name) => {
|
||||
const Icon = iconFor(name);
|
||||
const { container } = render(<Icon aria-hidden="true" />);
|
||||
expect(container.querySelector("svg")).not.toBeNull();
|
||||
expect(container.querySelector("svg.lucide-circle")).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it("resolves the Collections seed icon Layers to a real lucide component (add-storefront-collections)", () => {
|
||||
const Icon = iconFor("Layers");
|
||||
const { container } = render(<Icon aria-hidden="true" />);
|
||||
expect(container.querySelector("svg.lucide-layers")).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Activity, ArrowDownToLine, ArrowLeftRight, BarChart2, Bell, Box, Calendar, CalendarDays, Circle, ClipboardList, Coins, CreditCard, FileText, GalleryHorizontalEnd, Gift, History, LayoutDashboard, Languages, Layers, Mail, Megaphone, Menu, MessagesSquare, Network, Package, Settings, Shield, ShieldCheck, ShoppingCart, SlidersHorizontal, Star, Store, Tags, ScrollText, Undo2, UserCheck, UserCog, Users, Wallet, Warehouse, Wrench } from "lucide-react";
|
||||
import { CalendarDays, Circle, ClipboardList, LayoutDashboard, LockKeyhole, Mail, ScrollText, Shield, ShieldCheck, Store, Tags, UserCog, Users } from "lucide-react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
|
||||
// Maps the aclMenu tree's `iconName` (a plain string served by
|
||||
@@ -6,78 +6,23 @@ import type { LucideIcon } from "lucide-react";
|
||||
// component. A curated map, not `import * as Icons from "lucide-react"`: the
|
||||
// old src/components/app/nav-config.ts imported icon components directly, and
|
||||
// pulling in the whole icon set here would ship every lucide icon to the
|
||||
// browser for a handful of nav entries. Extend this map as more modules are
|
||||
// seeded with new iconName values.
|
||||
// browser for a handful of nav entries. Add an entry when a module is seeded
|
||||
// with a new iconName value.
|
||||
const ICONS: Record<string, LucideIcon> = {
|
||||
// Icons Co-Lite seeds (local/seed/03-colite.sql and the archived change SQL), plus Companies (Store)
|
||||
// and Login security (LockKeyhole, a sidebar override).
|
||||
LayoutDashboard,
|
||||
// Activity group (add-online-users): BO_NAV_ACTIVITY, Online users and Audit log seed icons.
|
||||
Activity,
|
||||
UserCheck,
|
||||
ScrollText,
|
||||
Users,
|
||||
FileText,
|
||||
Network,
|
||||
Languages,
|
||||
// Collapsible nav group headers (add-admin-portal-nav-groups).
|
||||
Shield,
|
||||
Settings,
|
||||
// Notifications module (add-admin-internal-notifications, seed id 41300000).
|
||||
Bell,
|
||||
// Catalogue Setup module (add-admin-catalog-setup): BO_CATALOG nav group and
|
||||
// BO_CATALOG_SETUP page.
|
||||
Package,
|
||||
Tags,
|
||||
Layers,
|
||||
// Product Setup module (add-admin-product-setup): BO_PRODUCTS page seed icon.
|
||||
Box,
|
||||
// Inventory module (add-inventory-stock-in): Stock In and Stock on Hand seed icons.
|
||||
ArrowDownToLine,
|
||||
BarChart2,
|
||||
// Inventory transfers + movement history (add-inventory-transfers-movement-history, I3):
|
||||
// Transfers and Movement History seed icons.
|
||||
ArrowLeftRight,
|
||||
History,
|
||||
// Inventory adjustments (add-inventory-adjustments, I4):
|
||||
// Adjustments seed icon.
|
||||
SlidersHorizontal,
|
||||
// Events module (add-event-module-pickup-e1, E1):
|
||||
// Events page seed icon.
|
||||
Calendar,
|
||||
// add-admin-events: BO_EVENTS seed icon_name = 'CalendarDays'.
|
||||
CalendarDays,
|
||||
// POS counter-sales module (add-event-pos-counter-sales):
|
||||
// POS page seed icon (sql/02-seed-bo-module-pos.sql icon_name = 'ShoppingCart').
|
||||
ShoppingCart,
|
||||
// Payment Methods module (add-payment-method-config, 2a):
|
||||
// seed icon_name = 'CreditCard'.
|
||||
CreditCard,
|
||||
// Branch Counter POS module (add-branch-counter-sale):
|
||||
// seed icon_name = 'Store'.
|
||||
Store,
|
||||
// Refund Requests (add-refund-requests, seed id 44300000).
|
||||
Undo2,
|
||||
// Gift Cards (add-gift-card-core, seed id 45000000, icon_name 'Gift').
|
||||
Gift,
|
||||
// Live BO module icon_name values that rendered the fallback circle
|
||||
// (fix-admin-sidebar-groups-icons).
|
||||
ShieldCheck,
|
||||
Wallet,
|
||||
Mail,
|
||||
Coins,
|
||||
Megaphone,
|
||||
Warehouse,
|
||||
UserCog,
|
||||
GalleryHorizontalEnd,
|
||||
// add-member-messaging: BO_MEMBER_MESSAGES seed icon_name = 'MessagesSquare'.
|
||||
MessagesSquare,
|
||||
// BO_RANK_REFERRAL seed icon_name = 'Wrench'.
|
||||
Wrench,
|
||||
// Product reviews (add-product-reviews, seed id 44800000).
|
||||
Star,
|
||||
// Forms (add-cms-forms, seed id 45200000).
|
||||
ClipboardList,
|
||||
// Menus (add-storefront-menus, seed id 45300000).
|
||||
Menu,
|
||||
Tags,
|
||||
Users,
|
||||
UserCog,
|
||||
ShieldCheck,
|
||||
Shield,
|
||||
LockKeyhole,
|
||||
Mail,
|
||||
ScrollText,
|
||||
Store,
|
||||
};
|
||||
|
||||
/** Neutral fallback for an absent or unrecognised `iconName` (spec: "The
|
||||
|
||||
@@ -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 (
|
||||
<div role="group" aria-label={label} className="flex flex-col rounded-lg border bg-card shadow-card p-4">
|
||||
<div className="text-sm text-muted-foreground">{label}</div>
|
||||
<div className="mt-auto pt-1 text-2xl font-semibold tabular">{value}</div>
|
||||
{note && <div className="mt-1 text-xs text-muted-foreground">{note}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -138,7 +139,7 @@ export function LeadDashboard() {
|
||||
<div className="grid grid-cols-2 gap-3 lg:grid-cols-6">
|
||||
<Tile label={t("DashCaptures")} value={String(data.captures)} />
|
||||
<Tile label={t("DashNewLeads")} value={String(data.newLeads)} />
|
||||
<Tile label={t("DashWonInPeriod")} value={String(data.wonInPeriod)} />
|
||||
<Tile label={t("DashWonInPeriod")} value={String(data.wonInPeriod)} note={t("DashWonInPeriodNote")} />
|
||||
<Tile label={t("DashConversionRate")} value={pct(data.funnel.WON, data.captures)} />
|
||||
<Tile label={t("DashMedianDays")} value={data.medianDaysToWin == null ? DASH : String(data.medianDaysToWin)} />
|
||||
<Tile label={t("DashOverdue")} value={String(data.overdueFollowUps)} />
|
||||
@@ -146,7 +147,10 @@ export function LeadDashboard() {
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<Card>
|
||||
<CardHeader><CardTitle className="text-base">{t("DashFunnel")}</CardTitle></CardHeader>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">{t("DashFunnel")}</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">{t("DashFunnelNote")}</p>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ul aria-label={t("DashLeadFunnelLabel")} className="space-y-2">
|
||||
{funnelRows.map(([key, label]) => {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
|
||||
vi.mock("@/app/lib/services/adminEvents", () => ({ listSalespersonOptions: vi.fn().mockResolvedValue([]) }));
|
||||
|
||||
import { EventForm } from "./EventForm";
|
||||
import { pickDate } from "@/test/pickDate";
|
||||
|
||||
describe("EventForm error clearing", () => {
|
||||
it("clears a field's error as soon as that field is filled", async () => {
|
||||
render(<EventForm onSubmit={vi.fn()} />);
|
||||
await userEvent.click(screen.getByRole("button", { name: /create/i }));
|
||||
expect(await screen.findByText("Name is required.")).toBeInTheDocument();
|
||||
|
||||
await userEvent.type(screen.getByLabelText("Name"), "A");
|
||||
expect(screen.queryByText("Name is required.")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("Location is required.")).toBeInTheDocument();
|
||||
|
||||
pickDate("Start date", "2026-12-10");
|
||||
await waitFor(() => expect(screen.queryByText("Start date is required.")).not.toBeInTheDocument());
|
||||
});
|
||||
});
|
||||
@@ -59,6 +59,9 @@ export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
|
||||
const [pickersError, setPickersError] = useState<string | null>(null);
|
||||
|
||||
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
|
||||
// A field's error goes away as soon as the user edits that field; the next submit re-validates.
|
||||
const clearError = (k: string) => setFieldErrors((e) => (k in e ? Object.fromEntries(Object.entries(e).filter(([f]) => f !== k)) : e));
|
||||
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
@@ -197,6 +200,7 @@ export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
|
||||
value={companyChoice}
|
||||
onValueChange={(v) => {
|
||||
setCompanyChoice(v);
|
||||
clearError("company");
|
||||
setSelectedIds(new Set()); // the team is company-specific
|
||||
}}
|
||||
disabled={saving}
|
||||
@@ -224,7 +228,7 @@ export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
|
||||
id="evt-name"
|
||||
required
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
onChange={(e) => { setName(e.target.value); clearError("name"); }}
|
||||
disabled={saving}
|
||||
aria-invalid={!!fieldErrors.name}
|
||||
/>
|
||||
@@ -241,7 +245,7 @@ export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
|
||||
id="evt-location"
|
||||
required
|
||||
value={location}
|
||||
onChange={(e) => setLocation(e.target.value)}
|
||||
onChange={(e) => { setLocation(e.target.value); clearError("location"); }}
|
||||
disabled={saving}
|
||||
aria-invalid={!!fieldErrors.location}
|
||||
/>
|
||||
@@ -257,7 +261,7 @@ export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
|
||||
<DatePicker
|
||||
id="evt-start"
|
||||
value={startDate}
|
||||
onChange={setStartDate}
|
||||
onChange={(v) => { setStartDate(v); clearError("startDate"); }}
|
||||
aria-label={t("EvtStartDate")}
|
||||
required
|
||||
disabled={saving}
|
||||
@@ -275,7 +279,7 @@ export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
|
||||
<DatePicker
|
||||
id="evt-end"
|
||||
value={endDate}
|
||||
onChange={setEndDate}
|
||||
onChange={(v) => { setEndDate(v); clearError("endDate"); }}
|
||||
aria-label={t("EvtEndDate")}
|
||||
required
|
||||
disabled={saving}
|
||||
@@ -312,7 +316,7 @@ export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
|
||||
type="number"
|
||||
min={1}
|
||||
value={capacity}
|
||||
onChange={(e) => setCapacity(e.target.value)}
|
||||
onChange={(e) => { setCapacity(e.target.value); clearError("capacity"); }}
|
||||
disabled={saving || !canSetLimits}
|
||||
aria-invalid={!!fieldErrors.capacity}
|
||||
/>
|
||||
@@ -329,7 +333,7 @@ export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
|
||||
type="number"
|
||||
min={1}
|
||||
value={invitationCap}
|
||||
onChange={(e) => setInvitationCap(e.target.value)}
|
||||
onChange={(e) => { setInvitationCap(e.target.value); clearError("invitationCap"); }}
|
||||
disabled={saving || !canSetLimits}
|
||||
aria-invalid={!!fieldErrors.invitationCap}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listGuests: vi.fn(),
|
||||
addGuests: vi.fn(),
|
||||
removeGuest: vi.fn(),
|
||||
sendInvites: vi.fn(),
|
||||
getAttendance: vi.fn(),
|
||||
useAdminAuth: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminGuests", () => mocks);
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
|
||||
import { GuestsCard } from "./GuestsCard";
|
||||
|
||||
describe("GuestsCard send to all unsent", () => {
|
||||
it("says so when nothing was sent or skipped", async () => {
|
||||
mocks.listGuests.mockResolvedValue([]);
|
||||
mocks.getAttendance.mockResolvedValue({});
|
||||
mocks.sendInvites.mockResolvedValue({ sent: 0, skippedNoEmail: 0 });
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => true });
|
||||
render(<GuestsCard eventUuid="u1" />);
|
||||
await userEvent.click(await screen.findByRole("button", { name: "Send to all unsent" }));
|
||||
expect(await screen.findByRole("status")).toHaveTextContent("No unsent invitations");
|
||||
});
|
||||
});
|
||||
@@ -131,7 +131,7 @@ export function GuestsCard({ eventUuid, team = [] }: { eventUuid: string; team?:
|
||||
const send = (target: { guestIds: number[] } | { allUnsent: true }) =>
|
||||
run(async () => {
|
||||
const res = await sendInvites(eventUuid, target);
|
||||
setNotice(t("GuestSendResult", { sent: res.sent, skipped: res.skippedNoEmail }));
|
||||
setNotice(res.sent + res.skippedNoEmail === 0 ? t("GuestNoUnsent") : t("GuestSendResult", { sent: res.sent, skipped: res.skippedNoEmail }));
|
||||
await load();
|
||||
}, t("GuestSendFailed"));
|
||||
|
||||
|
||||
@@ -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 (
|
||||
<Dialog open onOpenChange={(open) => !open && props.onCancel()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{props.title}</DialogTitle>
|
||||
<DialogDescription>{props.message}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={props.onCancel} disabled={props.busy}>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button type="button" variant={props.destructive ? "destructive" : "default"} onClick={props.onConfirm} disabled={props.busy}>
|
||||
{props.confirmLabel}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -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<Row, unknown>[] = [
|
||||
{ accessorKey: "name", header: "Name" },
|
||||
{ accessorKey: "company", header: "Company" },
|
||||
{ accessorKey: "tag", header: () => <span>Tag</span>, enableSorting: false },
|
||||
{ id: "actions", header: "Actions", enableSorting: false, cell: () => <button>Act</button> },
|
||||
];
|
||||
const data: Row[] = [{ id: "1", name: "Alpha", company: "INS", tag: "x" }];
|
||||
|
||||
function renderTable(extra: Partial<React.ComponentProps<typeof DataTable<Row>>> = {}) {
|
||||
return render(
|
||||
<DataTable<Row> 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 }]);
|
||||
});
|
||||
});
|
||||
@@ -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<TData>({
|
||||
})
|
||||
|
||||
const visibleColumnCount = table.getVisibleLeafColumns().length
|
||||
// Phone-card labels come from string headers only; other headers get no label.
|
||||
const labelOf = (column: { columnDef: ColumnDef<TData, unknown> }) =>
|
||||
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<TData>({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{sortableColumns.length > 0 && (
|
||||
<select
|
||||
aria-label={t("UiSortBy")}
|
||||
className="h-9 w-full rounded-md border bg-card px-2 text-sm md:hidden"
|
||||
value={sorting[0] ? `${sorting[0].id}:${sorting[0].desc ? 'desc' : 'asc'}` : ''}
|
||||
onChange={e => {
|
||||
const [id, dir] = e.target.value.split(':')
|
||||
onSortingChange!(id ? [{ id, desc: dir === 'desc' }] : [])
|
||||
}}
|
||||
>
|
||||
<option value="">{t("UiSortBy")}</option>
|
||||
{sortableColumns.flatMap(c => [
|
||||
<option key={`${c.id}:asc`} value={`${c.id}:asc`}>{labelOf(c) ?? c.id} ↑</option>,
|
||||
<option key={`${c.id}:desc`} value={`${c.id}:desc`}>{labelOf(c) ?? c.id} ↓</option>,
|
||||
])}
|
||||
</select>
|
||||
)}
|
||||
|
||||
<div className="overflow-hidden rounded-table border bg-card">
|
||||
<div className="overflow-x-auto">
|
||||
<Table aria-label={label}>
|
||||
<TableHeader className="sticky top-0 z-10">
|
||||
<Table aria-label={label} className="max-md:block">
|
||||
<TableHeader className="sticky top-0 z-10 max-md:hidden">
|
||||
{table.getHeaderGroups().map(headerGroup => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header, index) => {
|
||||
@@ -192,7 +223,7 @@ export function DataTable<TData>({
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableBody className="max-md:block max-md:[&_tr:last-child]:border">
|
||||
{isLoading ? (
|
||||
Array.from({ length: Math.min(pageSize, 8) }).map((_, rowIndex) => (
|
||||
<TableRow key={`skeleton-${rowIndex}`} data-testid="table-skeleton-row">
|
||||
@@ -214,7 +245,7 @@ export function DataTable<TData>({
|
||||
<TableRow
|
||||
key={seen ? `${key}~${seen}` : key}
|
||||
className={cn(
|
||||
'group h-9 transition-colors hover:bg-muted',
|
||||
'group h-9 transition-colors max-md:h-auto max-md:m-2 max-md:flex max-md:flex-col max-md:rounded-lg max-md:border max-md:p-2 hover:bg-muted',
|
||||
interactive && 'cursor-pointer focus-visible:bg-muted focus-visible:outline-none',
|
||||
interactive && key === selectedKey && 'bg-accent text-accent-foreground hover:bg-accent',
|
||||
)}
|
||||
@@ -244,10 +275,11 @@ export function DataTable<TData>({
|
||||
{row.getVisibleCells().map((cell, index) => (
|
||||
<TableCell
|
||||
key={cell.id}
|
||||
data-label={index === 0 || cell.column.id === 'actions' ? undefined : labelOf(cell.column)}
|
||||
className={cn(
|
||||
'py-1.5',
|
||||
cell.column.columnDef.meta?.numeric && 'text-right tabular',
|
||||
index === 0 && PINNED_CELL,
|
||||
cell.column.columnDef.meta?.numeric && 'text-right tabular max-md:text-left',
|
||||
index === 0 ? cn(PINNED_CELL, CARD_TITLE) : cell.column.id === 'actions' ? CARD_ACTIONS : CARD_CELL,
|
||||
)}
|
||||
>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
|
||||
@@ -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({
|
||||
>
|
||||
<div className="flex items-start gap-2">
|
||||
<AlertCircle aria-hidden="true" className="mt-0.5 size-4 shrink-0 text-destructive" />
|
||||
<p className="text-sm text-foreground">{message}</p>
|
||||
<div>
|
||||
<p className="text-sm text-foreground">{message}</p>
|
||||
{hint && <p className="text-sm text-muted-foreground">{hint}</p>}
|
||||
</div>
|
||||
</div>
|
||||
{onRetry && (
|
||||
<Button variant="outline" size="sm" onClick={onRetry} className="h-9">
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Input } from "@/app/components/ui/input";
|
||||
import { Label } from "@/app/components/ui/label";
|
||||
import { PasswordRulesHint } from "./PasswordRulesHint";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
/** Password + confirmation inputs shared by the create form and "Set temporary password". */
|
||||
@@ -17,6 +19,7 @@ export function PasswordFields(props: {
|
||||
passwordLabel?: string;
|
||||
}) {
|
||||
const t = useT();
|
||||
const [hintShown, setHintShown] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<div className="space-y-1.5">
|
||||
@@ -29,10 +32,10 @@ export function PasswordFields(props: {
|
||||
onChange={(e) => props.onPassword(e.target.value)}
|
||||
disabled={props.disabled}
|
||||
aria-invalid={!!props.passwordError}
|
||||
aria-describedby="user-password-hint"
|
||||
aria-describedby={[hintShown && "user-password-hint", props.passwordError && "user-password-error"].filter(Boolean).join(" ") || undefined}
|
||||
/>
|
||||
<p id="user-password-hint" className="text-sm text-muted-foreground">{t("AdminPasswordHint")}</p>
|
||||
{props.passwordError && <p role="alert" className="text-sm text-destructive">{props.passwordError}</p>}
|
||||
<PasswordRulesHint source="admin" id="user-password-hint" onShown={setHintShown} />
|
||||
{props.passwordError && <p id="user-password-error" role="alert" className="text-sm text-destructive">{props.passwordError}</p>}
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="user-confirm-password">{t("UsrConfirmPassword")}</Label>
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { render, screen, waitFor } 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(), changeOwnPassword: vi.fn() }));
|
||||
vi.mock("@/app/lib/clientApi", async (importOriginal) => ({
|
||||
ApiError: (await importOriginal<typeof import("@/app/lib/clientApi")>()).ApiError,
|
||||
apiGet: mocks.apiGet,
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminUsers", () => ({ changeOwnPassword: mocks.changeOwnPassword }));
|
||||
|
||||
import { PasswordRulesHint } from "./PasswordRulesHint";
|
||||
import ChangePasswordDialog from "@/app/components/app/ChangePasswordDialog";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
const RULES = [
|
||||
{ param: "INPUT_LENGTH_MIN", value: 8 },
|
||||
{ param: "UPPERCASE_LENGTH_MIN", value: 1 },
|
||||
{ param: "SPACE_NOT_ALLOWED", value: null },
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.apiGet.mockReset().mockResolvedValue(RULES);
|
||||
mocks.changeOwnPassword.mockReset();
|
||||
});
|
||||
|
||||
describe("PasswordRulesHint", () => {
|
||||
it("lists only the switched-on rules, with their numbers", async () => {
|
||||
render(<PasswordRulesHint source="admin" />);
|
||||
expect(await screen.findByText("Length: at least 8")).toBeInTheDocument();
|
||||
expect(screen.getByText("Capital letters: at least 1")).toBeInTheDocument();
|
||||
expect(screen.getByText("No spaces")).toBeInTheDocument();
|
||||
expect(screen.getAllByRole("listitem")).toHaveLength(3);
|
||||
expect(screen.queryByText(/symbol/i)).toBeNull();
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/password-rules");
|
||||
});
|
||||
|
||||
it("reads the public route on the signed-out page", async () => {
|
||||
render(<PasswordRulesHint source="public" />);
|
||||
await screen.findByText("No spaces");
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/public/password-rules");
|
||||
});
|
||||
|
||||
it("shows nothing when the rules fail to load", async () => {
|
||||
mocks.apiGet.mockRejectedValue(new Error("down"));
|
||||
const { container } = render(<PasswordRulesHint source="admin" />);
|
||||
await waitFor(() => expect(mocks.apiGet).toHaveBeenCalled());
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
});
|
||||
});
|
||||
|
||||
describe("PASSWORD_RULE refusal", () => {
|
||||
it("names the broken rule at the password field of the change-password dialog", async () => {
|
||||
mocks.changeOwnPassword.mockRejectedValue(
|
||||
new ApiError("PASSWORD_RULE", 400, { error: "PASSWORD_RULE", code: "PASSWORD_RULE", details: { param: "UPPERCASE_LENGTH_MIN", value: 1 } }),
|
||||
);
|
||||
render(<ChangePasswordDialog onClose={() => {}} onDone={() => {}} />);
|
||||
await userEvent.type(screen.getByLabelText("Current password"), "old");
|
||||
await userEvent.type(screen.getByLabelText("New password"), "abcdefgh");
|
||||
await userEvent.type(screen.getByLabelText("Confirm password"), "abcdefgh");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Change password" }));
|
||||
expect(await screen.findByText('Password does not meet the rule "Capital letters: at least 1"')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { ApiError, apiGet } from "@/app/lib/clientApi";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
type Rule = { param: string; value: number | null };
|
||||
type Translate = ReturnType<typeof useT>;
|
||||
|
||||
const sentence = (t: Translate, param: string, value: unknown) => t(`PwdHint_${param}`, { n: value == null ? "" : String(value) });
|
||||
|
||||
/**
|
||||
* The refusal text when the API answered 400 PASSWORD_RULE, else null.
|
||||
* ponytail: relies on the BFF forwarding `param`/`value` in details (mobileApi.extractDetails).
|
||||
*/
|
||||
export function passwordRuleError(err: unknown, t: Translate): string | null {
|
||||
const data = err instanceof ApiError ? (err.data as { code?: string; details?: { param?: string; value?: unknown } } | undefined) : undefined;
|
||||
if (data?.code !== "PASSWORD_RULE" || !data.details?.param) return null;
|
||||
return t("PwdRuleRefused", { rule: sentence(t, data.details.param, data.details.value) });
|
||||
}
|
||||
|
||||
/** The switched-on password rules as a short list; shows nothing while loading or if they cannot be loaded. */
|
||||
export function PasswordRulesHint({ source, id, onShown }: { source: "admin" | "public"; id?: string; onShown?: (shown: boolean) => void }) {
|
||||
const t = useT();
|
||||
const [rules, setRules] = useState<Rule[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const loaded = await apiGet<Rule[]>(source === "admin" ? "/api/password-rules" : "/api/public/password-rules");
|
||||
if (!cancelled && Array.isArray(loaded)) setRules(loaded);
|
||||
} catch {
|
||||
// no banner: the hint is optional, a refusal still names the rule
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [source]);
|
||||
|
||||
useEffect(() => onShown?.(rules.length > 0), [rules.length, onShown]);
|
||||
|
||||
if (!rules.length) return null;
|
||||
return (
|
||||
<ul id={id} className="list-disc pl-5 text-sm text-muted-foreground">
|
||||
{rules.map((r) => (
|
||||
<li key={r.param}>{sentence(t, r.param, r.value)}</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "
|
||||
import { setAdminUserPassword } from "@/app/lib/services/adminUsers";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { PasswordFields } from "./PasswordFields";
|
||||
import { passwordRuleError } from "./PasswordRulesHint";
|
||||
|
||||
/** "Set temporary password" on the user edit page: the admin types it; the user must change it at next sign-in. */
|
||||
export function SetPasswordButton({ userId, onDone }: { userId: number; onDone: () => void }) {
|
||||
@@ -15,6 +16,7 @@ export function SetPasswordButton({ userId, onDone }: { userId: number; onDone:
|
||||
const [confirmPassword, setConfirmPassword] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [ruleError, setRuleError] = useState<string | undefined>();
|
||||
|
||||
function close() {
|
||||
// The password lives only in this state; clear it whenever the dialog closes.
|
||||
@@ -22,6 +24,7 @@ export function SetPasswordButton({ userId, onDone }: { userId: number; onDone:
|
||||
setPassword("");
|
||||
setConfirmPassword("");
|
||||
setError(null);
|
||||
setRuleError(undefined);
|
||||
}
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
@@ -30,12 +33,15 @@ export function SetPasswordButton({ userId, onDone }: { userId: number; onDone:
|
||||
if (password !== confirmPassword) return setError("UsrPasswordMismatch");
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
setRuleError(undefined);
|
||||
try {
|
||||
await setAdminUserPassword(userId, password, confirmPassword);
|
||||
close();
|
||||
onDone();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "UsrSetPasswordFailed");
|
||||
const rule = passwordRuleError(err, t);
|
||||
if (rule) setRuleError(rule);
|
||||
else setError(err instanceof Error ? err.message : "UsrSetPasswordFailed");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -60,6 +66,7 @@ export function SetPasswordButton({ userId, onDone }: { userId: number; onDone:
|
||||
onPassword={setPassword}
|
||||
onConfirmPassword={setConfirmPassword}
|
||||
disabled={saving}
|
||||
passwordError={ruleError}
|
||||
/>
|
||||
{error && (
|
||||
<div role="alert" className="rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
|
||||
vi.mock("@/app/lib/services/adminRoles", () => ({ listAdminRoles: vi.fn().mockResolvedValue([]) }));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: vi.fn().mockReturnValue({ id: null }) }));
|
||||
|
||||
import { UserForm } from "./UserForm";
|
||||
|
||||
describe("UserForm error clearing", () => {
|
||||
it("clears a field's error as soon as that field is filled", async () => {
|
||||
render(<UserForm onSubmit={vi.fn()} />);
|
||||
await userEvent.click(screen.getByRole("button", { name: /save|create|add/i }));
|
||||
expect(await screen.findByText("Name is required.")).toBeInTheDocument();
|
||||
|
||||
await userEvent.type(screen.getByLabelText("Name"), "A");
|
||||
await waitFor(() => expect(screen.queryByText("Name is required.")).not.toBeInTheDocument());
|
||||
expect(screen.getByText("Email is required.")).toBeInTheDocument();
|
||||
await userEvent.type(screen.getByLabelText("Email"), "a@x.my");
|
||||
expect(screen.queryByText("Email is required.")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -18,6 +18,7 @@ import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import type { AdminUser } from "@/app/lib/types";
|
||||
import { PasswordFields } from "./PasswordFields";
|
||||
import { passwordRuleError } from "./PasswordRulesHint";
|
||||
|
||||
// Shared create/edit form for /users/new and /users/[id] (plan: "Build the admin
|
||||
// add/edit-user form"). The Roles picker is populated from the admin roles list
|
||||
@@ -68,6 +69,9 @@ export function UserForm({ initial, onSubmit, submitLabel, withPassword }: UserF
|
||||
const [loadingPickers, setLoadingPickers] = useState(true);
|
||||
|
||||
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
|
||||
// A field's error goes away as soon as the user edits that field; the next submit re-validates.
|
||||
const clearError = (k: string) => setFieldErrors((e) => (k in e ? Object.fromEntries(Object.entries(e).filter(([f]) => f !== k)) : e));
|
||||
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
@@ -144,7 +148,9 @@ export function UserForm({ initial, onSubmit, submitLabel, withPassword }: UserF
|
||||
...(showCompany ? (company === "super" ? { superAdmin: true } : { companyId: Number(company) }) : {}),
|
||||
});
|
||||
} catch (err) {
|
||||
setFormError(err instanceof Error ? err.message : "UsrSaveFailed");
|
||||
const rule = passwordRuleError(err, t);
|
||||
if (rule) setFieldErrors({ password: rule });
|
||||
else setFormError(err instanceof Error ? err.message : "UsrSaveFailed");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -161,7 +167,7 @@ export function UserForm({ initial, onSubmit, submitLabel, withPassword }: UserF
|
||||
id="user-name"
|
||||
required
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
onChange={(e) => { setName(e.target.value); clearError("name"); }}
|
||||
disabled={saving}
|
||||
aria-invalid={!!fieldErrors.name}
|
||||
/>
|
||||
@@ -188,7 +194,7 @@ export function UserForm({ initial, onSubmit, submitLabel, withPassword }: UserF
|
||||
id="user-username"
|
||||
required
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
onChange={(e) => { setUsername(e.target.value); clearError("username"); }}
|
||||
// The backend ignores username on update, so it is fixed once the user exists.
|
||||
disabled={saving || initial?.id != null}
|
||||
aria-invalid={!!fieldErrors.username}
|
||||
@@ -207,7 +213,7 @@ export function UserForm({ initial, onSubmit, submitLabel, withPassword }: UserF
|
||||
type="email"
|
||||
required
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
onChange={(e) => { setEmail(e.target.value); clearError("email"); }}
|
||||
disabled={saving}
|
||||
aria-invalid={!!fieldErrors.email}
|
||||
/>
|
||||
@@ -221,7 +227,7 @@ export function UserForm({ initial, onSubmit, submitLabel, withPassword }: UserF
|
||||
{showCompany && (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="user-company">{t("Company")}</Label>
|
||||
<Select value={company} onValueChange={(v) => setCompany(v)} disabled={saving}>
|
||||
<Select value={company} onValueChange={(v) => { setCompany(v); clearError("company"); }} disabled={saving}>
|
||||
<SelectTrigger id="user-company" aria-invalid={!!fieldErrors.company} className="w-full">
|
||||
<SelectValue placeholder={t("SelectCompany")} />
|
||||
</SelectTrigger>
|
||||
@@ -244,8 +250,8 @@ export function UserForm({ initial, onSubmit, submitLabel, withPassword }: UserF
|
||||
<PasswordFields
|
||||
password={password}
|
||||
confirmPassword={confirmPassword}
|
||||
onPassword={setPassword}
|
||||
onConfirmPassword={setConfirmPassword}
|
||||
onPassword={(v) => { setPassword(v); clearError("password"); }}
|
||||
onConfirmPassword={(v) => { setConfirmPassword(v); clearError("confirmPassword"); }}
|
||||
disabled={saving}
|
||||
passwordError={fieldErrors.password}
|
||||
confirmError={fieldErrors.confirmPassword}
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
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(), apiGet: vi.fn(), apiPost: vi.fn(), apiPut: vi.fn(), apiDelete: vi.fn(), useAdminAuth: vi.fn() }));
|
||||
vi.mock("@/app/lib/clientApi", async (importOriginal) => ({
|
||||
ApiError: (await importOriginal<typeof import("@/app/lib/clientApi")>()).ApiError,
|
||||
apiGet: mocks.apiGet,
|
||||
apiPost: mocks.apiPost,
|
||||
apiPut: mocks.apiPut,
|
||||
apiDelete: mocks.apiDelete,
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminInterests", async (importOriginal) => {
|
||||
const mod = await importOriginal<typeof import("@/app/lib/services/adminInterests")>();
|
||||
return { ...mod, listAdminInterests: mocks.list };
|
||||
});
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
|
||||
import InterestsPage from "./page";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
const ROWS = [
|
||||
{ id: 1, name: "Workshop", active: true, sortOrder: 1 },
|
||||
{ id: 2, name: "Webinar", active: false, sortOrder: 2 },
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.list.mockReset().mockResolvedValue(ROWS);
|
||||
mocks.apiPut.mockReset().mockResolvedValue({});
|
||||
mocks.apiPost.mockReset();
|
||||
mocks.apiDelete.mockReset().mockResolvedValue({});
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true, hasModule: () => true });
|
||||
});
|
||||
|
||||
const rowOf = async (name: string) => (await screen.findByText(name)).closest("tr")!;
|
||||
|
||||
describe("Interests delete and confirmations", () => {
|
||||
it("deletes after confirming, and the row disappears", async () => {
|
||||
render(<InterestsPage />);
|
||||
await userEvent.click(within(await rowOf("Workshop")).getByRole("button", { name: "Delete" }));
|
||||
expect(mocks.apiDelete).not.toHaveBeenCalled();
|
||||
mocks.list.mockResolvedValue([ROWS[1]]);
|
||||
await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Delete" }));
|
||||
await waitFor(() => expect(mocks.apiDelete).toHaveBeenCalledWith("/api/interests/1"));
|
||||
await waitFor(() => expect(screen.queryByText("Workshop")).toBeNull());
|
||||
});
|
||||
|
||||
it("a failed delete offers no Retry, only the message", async () => {
|
||||
mocks.apiDelete.mockRejectedValue(new Error("boom"));
|
||||
render(<InterestsPage />);
|
||||
await userEvent.click(within(await rowOf("Workshop")).getByRole("button", { name: "Delete" }));
|
||||
await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Delete" }));
|
||||
expect(await screen.findByText("Failed to delete interest.")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: /retry/i })).toBeNull();
|
||||
});
|
||||
|
||||
it("styles the row Delete as destructive-outline", async () => {
|
||||
render(<InterestsPage />);
|
||||
expect(within(await rowOf("Workshop")).getByRole("button", { name: "Delete" })).toHaveAttribute("data-variant", "destructive-outline");
|
||||
});
|
||||
|
||||
it("cancel closes the delete confirmation without deleting", async () => {
|
||||
render(<InterestsPage />);
|
||||
await userEvent.click(within(await rowOf("Workshop")).getByRole("button", { name: "Delete" }));
|
||||
await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Cancel" }));
|
||||
expect(screen.queryByRole("dialog")).toBeNull();
|
||||
expect(mocks.apiDelete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("hides Delete from staff who are not super admins", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper: false, hasModule: () => true });
|
||||
render(<InterestsPage />);
|
||||
await screen.findByText("Workshop");
|
||||
expect(screen.queryByRole("button", { name: "Delete" })).toBeNull();
|
||||
});
|
||||
|
||||
it("deactivate asks first, then saves active=false", async () => {
|
||||
render(<InterestsPage />);
|
||||
await userEvent.click(within(await rowOf("Workshop")).getByRole("button", { name: "Deactivate" }));
|
||||
expect(mocks.apiPut).not.toHaveBeenCalled();
|
||||
await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Deactivate" }));
|
||||
await waitFor(() => expect(mocks.apiPut).toHaveBeenCalledWith("/api/interests/1", { id: 1, active: false }));
|
||||
});
|
||||
|
||||
it("cancel closes the deactivate confirmation without saving", async () => {
|
||||
render(<InterestsPage />);
|
||||
await userEvent.click(within(await rowOf("Workshop")).getByRole("button", { name: "Deactivate" }));
|
||||
await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Cancel" }));
|
||||
expect(screen.queryByRole("dialog")).toBeNull();
|
||||
expect(mocks.apiPut).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("says a name belongs to a deleted interest", async () => {
|
||||
mocks.apiPost.mockRejectedValue(new ApiError("INTEREST_NAME_DELETED", 409, { code: "INTEREST_NAME_DELETED" }));
|
||||
render(<InterestsPage />);
|
||||
await userEvent.click(await screen.findByRole("button", { name: /add interest/i }));
|
||||
await userEvent.type(screen.getByLabelText(/^name/i), "Old");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByText("This name belongs to a deleted interest.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("Cancel in the add dialog closes it without saving", async () => {
|
||||
render(<InterestsPage />);
|
||||
await userEvent.click(await screen.findByRole("button", { name: /add interest/i }));
|
||||
await userEvent.type(screen.getByLabelText(/^name/i), "Draft");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Cancel" }));
|
||||
expect(screen.queryByLabelText(/^name/i)).toBeNull();
|
||||
expect(mocks.apiPost).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -111,6 +111,7 @@ describe("InterestsPage", () => {
|
||||
|
||||
const row = screen.getByText("Workshop").closest("tr")!;
|
||||
await userEvent.click(within(row).getByRole("button", { name: /Deactivate/i }));
|
||||
await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: /Deactivate/i }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mocks.apiPut).toHaveBeenCalledWith("/api/interests/1", expect.objectContaining({ active: false })),
|
||||
@@ -229,6 +230,7 @@ describe("InterestsPage", () => {
|
||||
|
||||
const row = screen.getByText("Workshop").closest("tr")!;
|
||||
await userEvent.click(within(row).getByRole("button", { name: /Deactivate/i }));
|
||||
await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: /Deactivate/i }));
|
||||
|
||||
expect(await screen.findByText("Failed to deactivate interest.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -7,13 +7,14 @@ 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 { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
||||
import { Badge } from "@/app/components/ui/badge";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { listAdminInterests, saveAdminInterest } from "@/app/lib/services/adminInterests";
|
||||
import { deleteAdminInterest, listAdminInterests, saveAdminInterest } from "@/app/lib/services/adminInterests";
|
||||
import type { AdminInterestEntity } from "@/app/lib/types";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
@@ -70,6 +71,8 @@ function InterestFormDialog({
|
||||
setFieldErrors({ name: t("IntDuplicateName") });
|
||||
} else if (code === "TOO_LONG") {
|
||||
setFieldErrors({ name: t("IntNameTooLong") });
|
||||
} else if (code === "INTEREST_NAME_DELETED") {
|
||||
setFieldErrors({ name: t("IntNameDeleted") });
|
||||
} else if (code === "REQUIRED_FIELD") {
|
||||
setFieldErrors({ name: t("IntNameRequired") });
|
||||
} else {
|
||||
@@ -125,6 +128,9 @@ function InterestFormDialog({
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button type="submit" disabled={saving}>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
@@ -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<AdminInterestEntity[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [actionError, setActionError] = useState<string | null>(null);
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const [dialog, setDialog] = useState<FormState | null>(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")}
|
||||
</Button>
|
||||
{row.original.active ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await saveAdminInterest({ id: row.original.id, active: false });
|
||||
refetch();
|
||||
} catch {
|
||||
setError("IntDeactivateFailed");
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button variant="outline" size="sm" onClick={() => setConfirm({ kind: "deactivate", item: row.original })}>
|
||||
{t("IntDeactivate")}
|
||||
</Button>
|
||||
) : (
|
||||
@@ -229,20 +227,39 @@ function InterestsPageContent() {
|
||||
await saveAdminInterest({ id: row.original.id, active: true });
|
||||
refetch();
|
||||
} catch {
|
||||
setError("IntActivateFailed");
|
||||
setActionError("IntActivateFailed");
|
||||
}
|
||||
}}
|
||||
>
|
||||
{t("IntActivate")}
|
||||
</Button>
|
||||
)}
|
||||
{isSuper === true && (
|
||||
<Button variant="destructive-outline" size="sm" onClick={() => setConfirm({ kind: "delete", item: row.original })}>
|
||||
{t("IntDelete")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
}]),
|
||||
],
|
||||
[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 (
|
||||
<>
|
||||
<PageHeader
|
||||
@@ -256,6 +273,8 @@ function InterestsPageContent() {
|
||||
/>
|
||||
|
||||
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
|
||||
{/* An action that failed: retrying the list would not help, so no Retry. */}
|
||||
{actionError && <ErrorState message={t(actionError)} className="mb-4" />}
|
||||
|
||||
<DataTable
|
||||
label={t("BO_INTERESTS")}
|
||||
@@ -270,6 +289,17 @@ function InterestsPageContent() {
|
||||
empty={<EmptyState title={t("IntNoInterests")} />}
|
||||
/>
|
||||
|
||||
{confirm && (
|
||||
<ConfirmDialog
|
||||
title={confirm.kind === "delete" ? t("IntDeleteTitle") : t("IntDeactivateTitle")}
|
||||
message={t(confirm.kind === "delete" ? "IntDeleteConfirm" : "IntDeactivateConfirm", { name: confirm.item.name ?? "" })}
|
||||
confirmLabel={confirm.kind === "delete" ? t("IntDelete") : t("IntDeactivate")}
|
||||
destructive={confirm.kind === "delete"}
|
||||
onConfirm={runConfirmed}
|
||||
onCancel={() => setConfirm(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{dialog && (
|
||||
<InterestFormDialog initial={dialog} onClose={() => setDialog(null)} onSaved={refetch} />
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
|
||||
vi.mock("@/app/lib/services/adminLeads", async (importActual) => ({
|
||||
...(await importActual<typeof import("@/app/lib/services/adminLeads")>()),
|
||||
listLeads: vi.fn().mockResolvedValue({ items: [], total: 0 }),
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ loading: false, hasModule: () => true }) }));
|
||||
vi.mock("@/app/lib/CompanyScope", () => ({
|
||||
useCompanyScope: () => ({ companyId: null, showCompanyColumn: true, codeOf: () => "INS" }),
|
||||
}));
|
||||
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
||||
|
||||
import LeadsPage from "./page";
|
||||
|
||||
describe("LeadsPage columns", () => {
|
||||
it("tells the tenant company from the lead's own company", async () => {
|
||||
render(<LeadsPage />);
|
||||
const headers = (await screen.findAllByRole("columnheader")).map((h) => h.textContent);
|
||||
expect(headers).toContain("Company");
|
||||
expect(headers).toContain("Lead's company");
|
||||
});
|
||||
});
|
||||
@@ -79,7 +79,7 @@ function LeadsPageContent() {
|
||||
...(showCompanyColumn ? [{ id: "company", cell: ({ row }) => codeOf(row.original.companyId ?? 0), header: t("Company"), enableSorting: false } as ColumnDef<LeadRow, unknown>] : []),
|
||||
{ accessorKey: "mobile", header: t("LeadMobile"), enableSorting: false },
|
||||
{ accessorKey: "email", header: t("Email"), enableSorting: false },
|
||||
{ accessorKey: "companyName", header: t("LeadCompany"), enableSorting: false },
|
||||
{ accessorKey: "companyName", header: t("LeadsLeadCompany"), enableSorting: false },
|
||||
{ accessorKey: "eventCount", header: t("LeadsEvents"), enableSorting: false },
|
||||
{ id: "lastEvent", header: t("LeadsLastEvent"), enableSorting: false, cell: ({ row }) => row.original.lastEvent?.name ?? "" },
|
||||
{ id: "latestSalesperson", header: t("LeadsLatestSalesperson"), enableSorting: false, cell: ({ row }) => row.original.latestSalesperson?.name ?? "" },
|
||||
|
||||
@@ -12,8 +12,32 @@ export interface SidebarLink {
|
||||
children: SidebarLink[];
|
||||
}
|
||||
|
||||
// ponytail: fixed list; a new admin module falls into the work section until added here.
|
||||
export const ADMIN_MODULES = ["BO_USERS", "BO_ROLES", "BO_EMAILS", "BO_LOGIN_SECURITY", "BO_AUDIT_LOG", "BO_COMPANIES"];
|
||||
// ponytail: fixed map; a new module lands in the trailing unlabelled section until added here.
|
||||
// `label` is an i18n key; the first section has none (Dashboard stands alone).
|
||||
export const SIDEBAR_SECTIONS: { label?: string; modules: string[] }[] = [
|
||||
{ modules: ["BO_DASHBOARD"] },
|
||||
{ label: "SidebarSectionEvents", modules: ["BO_EVENTS", "BO_EVENT_LEADS"] },
|
||||
{ label: "SidebarSectionLeads", modules: ["BO_LEADS", "BO_INTERESTS"] },
|
||||
{ label: "SidebarSectionAccess", modules: ["BO_USERS", "BO_ROLES", "BO_LOGIN_SECURITY"] },
|
||||
{ label: "SidebarSectionSystem", modules: ["BO_COMPANIES", "BO_EMAILS", "BO_AUDIT_LOG"] },
|
||||
];
|
||||
|
||||
// Icon overrides by module name, so a shared seed icon can differ in the sidebar.
|
||||
export const SIDEBAR_ICONS: Record<string, string> = { BO_LOGIN_SECURITY: "LockKeyhole" };
|
||||
|
||||
/** Splits links into the SIDEBAR_SECTIONS order; unknown links trail in an unlabelled section; empty sections drop. */
|
||||
export function groupSidebar(links: SidebarLink[]): { label?: string; links: SidebarLink[] }[] {
|
||||
const known = SIDEBAR_SECTIONS.flatMap((s) => s.modules);
|
||||
const withIcon = (l: SidebarLink) => ({ ...l, iconName: SIDEBAR_ICONS[l.name] ?? l.iconName });
|
||||
const sections = [
|
||||
...SIDEBAR_SECTIONS.map(({ label, modules }) => ({
|
||||
label,
|
||||
links: modules.flatMap((m) => links.filter((l) => l.name === m)).map(withIcon),
|
||||
})),
|
||||
{ label: undefined, links: links.filter((l) => !known.includes(l.name)).map(withIcon) },
|
||||
];
|
||||
return sections.filter((s) => s.links.length > 0);
|
||||
}
|
||||
|
||||
const byId = (nodes: AdminModule[] | undefined) => [...(nodes ?? [])].sort((a, b) => (a.id ?? 0) - (b.id ?? 0));
|
||||
|
||||
|
||||
@@ -86,12 +86,16 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
HeaderSwitchToDark: "Switch to dark theme",
|
||||
LocaleSwitcherChange: "Change language",
|
||||
SidebarMainNav: "Main",
|
||||
SidebarAdministration: "Administration",
|
||||
SidebarSectionEvents: "Events",
|
||||
SidebarSectionLeads: "Leads",
|
||||
SidebarSectionAccess: "Access",
|
||||
SidebarSectionSystem: "System",
|
||||
UiBreadcrumb: "breadcrumb",
|
||||
UiMore: "More",
|
||||
UiColumns: "Columns",
|
||||
UiVisibleColumns: "Visible columns",
|
||||
UiNoResults: "No results.",
|
||||
UiSortBy: "Sort by",
|
||||
UiRetry: "Retry",
|
||||
UiLoading: "Loading",
|
||||
NotAuthorizedTitle: "Not authorised",
|
||||
@@ -196,7 +200,22 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
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",
|
||||
@@ -294,6 +313,22 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
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",
|
||||
@@ -331,6 +366,7 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
LeadNew: "New",
|
||||
LeadExisting: "Existing",
|
||||
LeadCompany: "Company",
|
||||
LeadsLeadCompany: "Lead's company",
|
||||
LeadJobTitle: "Job title",
|
||||
LeadStatus: "Status",
|
||||
LeadNotes: "Notes",
|
||||
@@ -566,6 +602,7 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
GuestAddedCount: "Added {count}",
|
||||
GuestSendAll: "Send to all unsent",
|
||||
GuestSendResult: "Sent {sent}, skipped {skipped} with no email",
|
||||
GuestNoUnsent: "No unsent invitations",
|
||||
GuestSendFailed: "Could not send the invites.",
|
||||
GuestRegisteredRefused: "This guest has already registered and cannot be removed.",
|
||||
GuestRemoveFailed: "Could not remove the guest.",
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
import { callMobileApi } from "./mobileApi";
|
||||
|
||||
let fetchMock: ReturnType<typeof vi.fn>;
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -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<string, string | number | boolean> | 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<string, unknown>);
|
||||
const scalar = values.every(v => typeof v === "string" || typeof v === "number" || typeof v === "boolean");
|
||||
return scalar ? (details as Record<string, string | number | boolean>) : undefined;
|
||||
const o = parsed as Record<string, unknown>;
|
||||
const details = o.details;
|
||||
const base = details && typeof details === "object" && !Array.isArray(details) ? (details as Record<string, unknown>) : undefined;
|
||||
if (base && !Object.values(base).every(isScalar)) return undefined;
|
||||
const props: Record<string, unknown> = {};
|
||||
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<string, string | number | boolean>) : 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<string, unknown>;
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), apiDelete: vi.fn() }));
|
||||
vi.mock("@/app/lib/clientApi", () => mocks);
|
||||
|
||||
import { addGuests } from "./adminGuests";
|
||||
|
||||
describe("addGuests result", () => {
|
||||
it("turns the API's added guest list into a count", async () => {
|
||||
// The mobile-api returns the added guests themselves, not a number.
|
||||
mocks.apiPost.mockResolvedValue({ added: [{ name: "A" }, { name: "B" }], rejected: [] });
|
||||
expect(await addGuests("e1", [], true)).toEqual({ added: 2, rejected: [] });
|
||||
});
|
||||
});
|
||||
@@ -46,8 +46,11 @@ export interface Attendance {
|
||||
const base = (uuid: string) => `/api/events/${encodeURIComponent(uuid)}`;
|
||||
|
||||
export const listGuests = (uuid: string) => apiGet<EventGuest[]>(`${base(uuid)}/guests`);
|
||||
export const addGuests = (uuid: string, guests: GuestInput[], preview: boolean) =>
|
||||
apiPost<AddGuestsResult>(`${base(uuid)}/guests${preview ? "?preview=true" : ""}`, { guests });
|
||||
// The API lists the added guests; the screen only needs how many.
|
||||
export const addGuests = async (uuid: string, guests: GuestInput[], preview: boolean): Promise<AddGuestsResult> => {
|
||||
const res = await apiPost<{ added?: unknown[]; rejected: GuestRejection[] }>(`${base(uuid)}/guests${preview ? "?preview=true" : ""}`, { guests });
|
||||
return { added: res.added?.length ?? 0, rejected: res.rejected };
|
||||
};
|
||||
export const removeGuest = (uuid: string, id: number) => apiDelete<unknown>(`${base(uuid)}/guests/${id}`);
|
||||
export const sendInvites = (uuid: string, target: { guestIds: number[] } | { allUnsent: true }) =>
|
||||
apiPost<{ sent: number; skippedNoEmail: number }>(`${base(uuid)}/guests/send`, target);
|
||||
|
||||
@@ -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<AdminInterestEntity[]> {
|
||||
@@ -10,3 +10,5 @@ export async function saveAdminInterest(payload: AdminInterestEntity): Promise<A
|
||||
? apiPut<AdminInterestEntity>(`/api/interests/${payload.id}`, payload)
|
||||
: apiPost<AdminInterestEntity>("/api/interests", payload);
|
||||
}
|
||||
|
||||
export const deleteAdminInterest = (id: number) => apiDelete<unknown>(`/api/interests/${id}`);
|
||||
@@ -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<AdminRoleEntity[]> {
|
||||
@@ -14,3 +14,5 @@ export async function saveAdminRole(payload: AdminRoleEntity): Promise<AdminRole
|
||||
? apiPut<AdminRoleEntity>(`/api/roles/${payload.id}`, payload)
|
||||
: apiPost<AdminRoleEntity>("/api/roles", payload);
|
||||
}
|
||||
|
||||
export const deleteAdminRole = (id: number) => apiDelete<unknown>(`/api/roles/${id}`);
|
||||
@@ -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<typeof vi.fn>;
|
||||
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(<LoginPage />);
|
||||
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(<LoginPage />);
|
||||
submit("nobody");
|
||||
const unknown = (await screen.findByRole("alert")).textContent;
|
||||
unmount();
|
||||
render(<LoginPage />);
|
||||
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(<LoginPage />);
|
||||
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(<LoginPage />);
|
||||
submit("staff1", "ins");
|
||||
await waitFor(() => expect(screen.getByRole("alert")).toBeInTheDocument());
|
||||
expect(screen.queryByText(HINT)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -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<HTMLFormElement>) {
|
||||
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() {
|
||||
<p className="text-muted-foreground">{t("BackOfficeSubtitle")}</p>
|
||||
</div>
|
||||
|
||||
{error ? <ErrorState message={t(error)} /> : elsewhere && <ErrorState message={t("SignedInElsewhere")} />}
|
||||
{error ? <ErrorState message={t(error)} hint={companyHint ? t("LoginStaffCompanyHint") : undefined} /> : elsewhere && <ErrorState message={t("SignedInElsewhere")} />}
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-5" noValidate>
|
||||
<div className="space-y-1.5">
|
||||
|
||||
@@ -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(<HomePage />);
|
||||
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(<HomePage />);
|
||||
await screen.findByRole("group", { name: "Captures" });
|
||||
expect(screen.getByText("This period's captures, by their current stage.")).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -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<typeof import("@/app/lib/clientApi")>()).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<typeof vi.fn>;
|
||||
const post = apiPost as unknown as ReturnType<typeof vi.fn>;
|
||||
|
||||
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(<ResetPasswordPage />);
|
||||
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(<ResetPasswordPage />);
|
||||
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(<ResetPasswordPage />);
|
||||
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(<ResetPasswordPage />);
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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(<ResetPasswordPage />);
|
||||
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", () => {
|
||||
|
||||
@@ -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<string | null>(null);
|
||||
const [ruleError, setRuleError] = useState<string | null>(null);
|
||||
const [hintShown, setHintShown] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
|
||||
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"
|
||||
/>
|
||||
<p id="newPasswordRules" className="text-sm text-muted-foreground">{t("AdminPasswordHint")}</p>
|
||||
<PasswordRulesHint source="public" id="newPasswordRules" onShown={setHintShown} />
|
||||
{ruleError && <p id="newPasswordError" role="alert" className="text-sm text-destructive">{ruleError}</p>}
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="confirmPassword">{t("ResetConfirmPassword")}</Label>
|
||||
|
||||
@@ -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<typeof import("@/app/lib/clientApi")>()).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<typeof import("@/app/lib/services/adminRoles")>();
|
||||
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(<RolesPage />);
|
||||
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(<RolesPage />);
|
||||
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(<RolesPage />);
|
||||
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(<RolesPage />);
|
||||
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(<RolesPage />);
|
||||
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(<RolesPage />);
|
||||
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(<RolesPage />);
|
||||
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(<RolesPage />);
|
||||
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(<RolesPage />);
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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({
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button type="submit" disabled={saving}>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
@@ -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<AdminRoleEntity[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [actionError, setActionError] = useState<string | null>(null);
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
const [dialog, setDialog] = useState<FormState | null>(null);
|
||||
const [confirmDelete, setConfirmDelete] = useState<AdminRoleEntity | null>(null);
|
||||
|
||||
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
|
||||
|
||||
@@ -165,13 +176,34 @@ function RolesPageContent() {
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<a href={`/roles/${row.original.id}/access`}>{t("RolManageAccess")}</a>
|
||||
</Button>
|
||||
{isSuper === true && !PROTECTED_ROLES.includes(row.original.name) && (
|
||||
<Button variant="destructive-outline" size="sm" onClick={() => setConfirmDelete(row.original)}>
|
||||
{t("RolDelete")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
}]),
|
||||
],
|
||||
[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 (
|
||||
<>
|
||||
<PageHeader
|
||||
@@ -185,6 +217,8 @@ function RolesPageContent() {
|
||||
/>
|
||||
|
||||
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
|
||||
{/* An action that failed: retrying the list would not help, so no Retry. */}
|
||||
{actionError && <ErrorState message={t(actionError)} className="mb-4" />}
|
||||
|
||||
<DataTable
|
||||
label={t("BO_ROLES")}
|
||||
@@ -201,6 +235,17 @@ function RolesPageContent() {
|
||||
empty={<EmptyState title={t("RolNoRoles")} />}
|
||||
/>
|
||||
|
||||
{confirmDelete && (
|
||||
<ConfirmDialog
|
||||
title={t("RolDeleteTitle")}
|
||||
message={t("RolDeleteConfirm", { name: roleLabel(confirmDelete.name) })}
|
||||
confirmLabel={t("RolDelete")}
|
||||
destructive
|
||||
onConfirm={runDelete}
|
||||
onCancel={() => setConfirmDelete(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{dialog && (
|
||||
<RoleFormDialog initial={dialog} onClose={() => setDialog(null)} onSaved={refetch} />
|
||||
)}
|
||||
|
||||
@@ -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<HttpMethod, Pattern> publicPath(HttpMethod method, String regex) {
|
||||
return Map.entry(method, Pattern.compile(regex));
|
||||
|
||||
+74
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
@@ -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";
|
||||
|
||||
+3
@@ -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}";
|
||||
|
||||
|
||||
+31
@@ -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<Map<String, Object>> adminActive() {
|
||||
return rules.active();
|
||||
}
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/api/public/password-rules")
|
||||
public List<Map<String, Object>> publicActive() {
|
||||
return rules.publicActive();
|
||||
}
|
||||
}
|
||||
+5
-1
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
+9
@@ -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<Map<String, Object>> update(@PathVariable long id, @RequestBody AdminInterestRequest request) {
|
||||
return ResponseEntity.ok(adminInterestService.update(id, request));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_INTERESTS")
|
||||
@DeleteMapping("/interests/{id}")
|
||||
public ResponseEntity<Void> delete(@PathVariable long id) {
|
||||
adminInterestService.delete(id);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
+7
@@ -49,6 +49,13 @@ public class AdminRoleController {
|
||||
}
|
||||
@AppAuth
|
||||
@AdminModule("BO_ROLES")
|
||||
@DeleteMapping("/roles/{id}")
|
||||
public ResponseEntity<Void> delete(@PathVariable Long id) {
|
||||
adminRoleService.delete(id);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
@AppAuth
|
||||
@AdminModule("BO_ROLES")
|
||||
@GetMapping("/roles/{id}/modules")
|
||||
public ResponseEntity<List<AdminModuleGrant>> getModules(@PathVariable Long id) {
|
||||
return ResponseEntity.ok(adminAclService.getGrantTree(id));
|
||||
|
||||
+13
@@ -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<List> 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<Integer> ent = restTemplateUtil.postForEntity(
|
||||
|
||||
+1
-1
@@ -386,7 +386,7 @@ public class AdminEventLeadService {
|
||||
Map<Long, Map<String, Object>> out = new LinkedHashMap<>();
|
||||
if (rows != null) for (Map<String, Object> 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;
|
||||
}
|
||||
|
||||
+14
-2
@@ -32,7 +32,7 @@ public class AdminInterestService {
|
||||
|
||||
public List<Map<String, Object>> list() {
|
||||
caller();
|
||||
return load().stream().map(AdminInterestService::row).toList();
|
||||
return load().stream().filter(m -> m.get("deletedAt") == null).map(AdminInterestService::row).toList();
|
||||
}
|
||||
|
||||
public Map<String, Object> create(AdminInterestRequest r) {
|
||||
@@ -47,7 +47,7 @@ public class AdminInterestService {
|
||||
public Map<String, Object> update(long id, AdminInterestRequest r) {
|
||||
scope.requireSuper(caller());
|
||||
Map<String, Object> 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<String, Object> 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<Map<String, Object>> load() {
|
||||
List<Map<String, Object>> rows = restTemplateUtil.getForEntity(
|
||||
|
||||
+32
-1
@@ -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<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<List<Map<String, Object>>> MAP_LIST = new ParameterizedTypeReference<>() {};
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
private static final long SUPER_ADMIN_ROLE_ID = 1L;
|
||||
private static final List<String> HIDDEN = List.of("ROLE_MEMBER", "ROLE_ADMIN");
|
||||
private static final List<String> 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<String, Object> role) {
|
||||
return PROTECTED.contains(role.get("name"));
|
||||
}
|
||||
@@ -127,7 +153,12 @@ public class AdminRoleService {
|
||||
}
|
||||
|
||||
private Map<String, Object> save(Map<String, Object> role) {
|
||||
ResponseEntity<Map<String, Object>> ent = restTemplateUtil.postForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_ROLE_SAVE), MAP, role);
|
||||
ResponseEntity<Map<String, Object>> 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");
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
+33
@@ -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<List<Map<String, Object>>> RULES = new ParameterizedTypeReference<>() {};
|
||||
private static final int PUBLIC_LIMIT = 60;
|
||||
|
||||
private final RestTemplateCustomUtil rest;
|
||||
private final PublicRegistrationService limiter;
|
||||
|
||||
public List<Map<String, Object>> active() {
|
||||
List<Map<String, Object>> 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<Map<String, Object>> publicActive() {
|
||||
limiter.limit("pwr:" + PublicRegistrationService.ip(), PUBLIC_LIMIT, "Too many requests from this device. Try again later.");
|
||||
return active();
|
||||
}
|
||||
}
|
||||
+53
@@ -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();
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -45,7 +45,7 @@ class AdminInterestControllerTest {
|
||||
void everyHandlerIsAuthenticatedAndGuardedByBoInterests() {
|
||||
List<Method> 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");
|
||||
|
||||
+56
@@ -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<HttpReqRespUtils> 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);
|
||||
}
|
||||
}
|
||||
+138
@@ -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<HttpReqRespUtils> 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<String, Object> row(long id, String name, String deletedAt) {
|
||||
Map<String, Object> 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");
|
||||
}
|
||||
}
|
||||
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user