Compare commits
40
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 | ||
|
|
1f96548d92 | ||
|
|
1ebbffb808 | ||
|
|
a3944ea1f9 | ||
|
|
93f9e07a6c | ||
|
|
6fda854df0 | ||
|
|
1458ea4aab | ||
|
|
db9e218423 | ||
|
|
2c7729d139 | ||
|
|
282d2263f2 | ||
|
|
372cd7244e | ||
|
|
370c9f4ad0 | ||
|
|
ac69c34cf2 | ||
|
|
4a20e75f82 | ||
|
|
08617f87c0 | ||
|
|
5ac248cee7 | ||
|
|
d4ae94fcc9 | ||
|
|
a9e40280ee | ||
|
|
d3096cec59 | ||
|
|
9ce5d792f9 |
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,49 @@
|
||||
# Visual follow-up: visitor pages, My QR, login and shell fixes
|
||||
|
||||
Date: 2026-12-01. Follows `2026-12-01-visual-foundation-design.md` (merged), on the same tokens and DESIGN.md.
|
||||
|
||||
## Intent
|
||||
|
||||
Visitors judge INS and CV by the page they get when they scan a QR at the booth. Today that page is a plain stack of inputs with a long consent text and the company name only as small grey text. Staff see small leftovers in the shell from the first visual change. Finish the revamp before go-live (2027-01-15) so every screen a visitor or staff member sees matches the new look.
|
||||
|
||||
## Decisions
|
||||
|
||||
- **Neutral look (owner, 2026-12-01).** Visitor pages use Co-Lite's tokens with the company name prominent. No per-company logo or colour. Per-company branding is a later change if INS or CV ask for it.
|
||||
- **One way to build it (my call).** Restyle with the existing tokens and components. No new dependencies, no backend change, no copy change except the labels listed below.
|
||||
|
||||
## Scope
|
||||
|
||||
1. **Visitor pages `/r`, `/i`, `/c` (shared `RegistrationForm` and the check-in lookup)**
|
||||
- The page sits on the slate ground. The form is a white card (border, `shadow-card`), full width at 360 px and max-width `md` from `sm`.
|
||||
- Event header at the top of the card: company name as a small uppercase label in the accent colour, then the event name (h1), then dates and location on their own lines with calendar and map-pin icons. The pipe-separated line goes.
|
||||
- Fields keep their order and rules. Mobile gets the hint "Mobile or email is required" under the mobile field (new key in the default messages).
|
||||
- The privacy notice stays fully shown in both languages, as the spec requires. It becomes fine print: `text-xs`, muted foreground (contrast already tested ≥ 4.5), on a muted panel, with the language headings as small labels.
|
||||
- The consent row aligns the checkbox to the first line of text and gets normal line height.
|
||||
- The states (loading, inactive, too many, not yet, ended, thank you, welcome, checked in) render in the same card, with an icon (check, clock, alert) and a clear heading. The "register another person" button stays.
|
||||
- Footer: "Powered by Containerverse Sdn. Bhd." small and muted under the card, the same component as the admin shell.
|
||||
2. **My QR codes.** Each code is a card: event name as the card title, dates and location under it, the QR, then the buttons in one row that wraps on phones. "Switched off" stays as the warning badge in the card header.
|
||||
3. **Login and reset password.** They already use the new look. Remove the stale comments that describe the old brown and gold panel. Reset password gets the same two-column layout as login, so the two match.
|
||||
4. **Header label.** The trail no longer repeats the page title. On a top-level page (`/events`) it shows nothing. On a sub-page (`/events/new`, an event's page) it shows the parent as a link back ("Events").
|
||||
5. **Tables on phones.** When a table is wider than the screen, a soft fade on the right edge shows there is more to scroll. Pure CSS (background-attachment scroll shadows) on the shared table container, so every table gets it. The fade goes away at the end of the scroll.
|
||||
6. **Sidebar groups.** The flat list of 11 items gets one quiet divider with a small muted label "Administration" before Users, Roles, Emails, Login security, Audit log and Companies. Work items (Dashboard, Events, Event leads, Interests, Leads) stay above. The collapsed rail shows the divider without the label. The grouping is a fixed list of module names in the portal, since the menu tree from the server is flat.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Per-company logo or colour, or any change to Companies.
|
||||
- New fields, flows or copy on the visitor pages beyond the hint above.
|
||||
- Any change to how the visitor pages follow the light or dark theme. They keep today's behaviour.
|
||||
|
||||
## Anti-goals
|
||||
|
||||
- Hiding or shortening the privacy notice. It must stay readable in both languages.
|
||||
- Anything that slows the visitor form on a phone (no new fonts, images or libraries).
|
||||
|
||||
## Verification
|
||||
|
||||
- Vitest, typecheck and lint, with the exit-code check.
|
||||
- Playwright at 1280 and 360 px: `/r`, `/i` and `/c` in each state, My QR, login, reset password, `/events` and `/events/new` header, a wide table at 360 px, and the sidebar in full and rail mode.
|
||||
- The token and contrast tests stay green.
|
||||
|
||||
## Left to the builder
|
||||
|
||||
Icon choice within lucide, exact spacing, and the fade width.
|
||||
@@ -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,27 @@
|
||||
## Context
|
||||
|
||||
The product design is in `docs/superpowers/specs/2026-12-01-visual-followup-design.md`. It builds on the tokens, components and DESIGN.md from `add-visual-foundation`. The owner chose the neutral look.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:** a visitor-page card layout, My QR cards, reset password matching login, the header trail, the table scroll cue and the sidebar sections.
|
||||
|
||||
**Non-Goals:** per-company branding, backend changes, new dependencies, changing the theme behaviour of the visitor pages.
|
||||
|
||||
## Decisions
|
||||
|
||||
- **One shared visitor card.** Add a `VisitorCard` in `app/components/registration/` that renders the ground, the card, the event header and the footer. `/r`, `/i` and `/c` wrap every state in it. `RegistrationForm` drops its own header and takes the card's. The states render a small `VisitorState` (icon, heading, optional text, optional action) inside the card. Alternative rejected: styling each page separately, which would let the three pages drift.
|
||||
- **Fine-print notice.** Keep the `whitespace-pre-line` text and set it as `text-xs text-muted-foreground` on `bg-muted`. The muted foreground is already contrast-tested at ≥ 4.5 on card and muted.
|
||||
- **Scroll cue in CSS.** Use the background-attachment `local` versus `scroll` gradient technique on the `table-container` in `ui/table.tsx`, with colours from `--card`, as a utility in `globals.css`. It needs no JavaScript and no resize observers. Sticky header cells keep their opaque background.
|
||||
- **Trail.** In `Breadcrumbs`, return nothing when the pathname equals the leaf's own URL. Otherwise render the leaf as a link (the parent of the current sub-page), as it does now.
|
||||
- **Sidebar sections.** Keep a fixed `ADMIN_MODULES` list of module names (`BO_USERS`, `BO_ROLES`, `BO_EMAILS`, `BO_LOGIN_SECURITY`, `BO_AUDIT_LOG`, `BO_COMPANIES`; Companies is added by `useAclSidebar` for super admins, the rest come from the menu tree) in `aclSidebar.ts`. Split the top-level links into work and admin lists when rendering. The server menu tree is flat, so the grouping lives in the portal. A module not in the list stays with the work items.
|
||||
- **Reset password** reuses the login page's two-column frame. Extract it to a small `AuthFrame` only if both pages need the same markup; otherwise copy the wrapper classes.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- The fixed admin-module list goes stale when a new admin module is added. It then falls into the work section, which is visible and harmless. Mark it with a `ponytail:` comment.
|
||||
- The CSS scroll shadows need opaque table cells, or the fade draws under them. Row hover uses a token background, so check it at 360 px.
|
||||
|
||||
## Migration Plan
|
||||
|
||||
Portal deploy only. Roll back by redeploying the previous portal image.
|
||||
@@ -0,0 +1,29 @@
|
||||
## Why
|
||||
|
||||
Visitors judge INS and CV by the page they get when they scan a booth QR. Today that page is a plain stack of inputs with a long consent text, and the company name appears only as small grey text. Staff still see leftovers in the shell from `add-visual-foundation`: the header label repeats the page title, phone tables cut off with no scroll cue, and the sidebar is one flat list of 11 items. This change finishes the revamp before go-live.
|
||||
|
||||
## What Changes
|
||||
|
||||
- The visitor pages `/r`, `/i` and `/c` get a card layout with an event header (company label, event name, dates and location). The privacy notice becomes fine print and stays complete in both languages. The states get an icon and a heading. A "Mobile or email is required" hint is added.
|
||||
- My QR codes shows each code as a card.
|
||||
- Reset password matches the login layout. The stale login comments go.
|
||||
- The header trail stops repeating the page title. On a sub-page it shows the parent as a link back.
|
||||
- Wide tables show a fade on the edge that can still scroll.
|
||||
- The sidebar gets an "Administration" divider before the admin items.
|
||||
- The look is neutral: Co-Lite tokens, with no per-company logo or colour (owner decision, 2026-12-01).
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
None.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `admin-visual-design`: adds requirements for the visitor page look, the header trail, the table scroll cue and the sidebar sections.
|
||||
|
||||
## Impact
|
||||
|
||||
- Portal only (`solvway-admin-portal`): `RegistrationForm`, the `/r`, `/i` and `/c` pages, `my-qr`, `reset-password`, `login` (comments only), `Breadcrumbs`, the `ui/table` container, `Sidebar`, `globals.css`, and the i18n messages (one new key).
|
||||
- No backend, API, SQL or dependency change.
|
||||
- Product design: `docs/superpowers/specs/2026-12-01-visual-followup-design.md`.
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Visitor Page Look
|
||||
|
||||
The public visitor pages (registration, invitation and check-in) SHALL show their content in one card on the page ground. The card SHALL be headed by the company name as a small label, the event name as the main heading, and the event dates and location. The pages SHALL use only the portal's theme tokens and SHALL NOT show a per-company logo or colour. The privacy notice SHALL be shown in full in English and Bahasa Malaysia as smaller, muted text that keeps at least 4.5:1 contrast.
|
||||
|
||||
#### Scenario: Visitor opens a registration code
|
||||
|
||||
- **WHEN** a visitor opens the registration page of an INS event
|
||||
- **THEN** the card shows "INS" as a label above the event name, then the event dates and location
|
||||
- **AND** the full privacy notice appears in both languages above the consent box
|
||||
|
||||
#### Scenario: Visitor needs a contact
|
||||
|
||||
- **WHEN** a visitor sees the mobile field on the registration form
|
||||
- **THEN** a hint under it says that a mobile number or an email is required
|
||||
|
||||
#### Scenario: Visitor reaches an end state
|
||||
|
||||
- **WHEN** a visitor's registration is accepted, or the code is inactive, or check-in has not opened yet
|
||||
- **THEN** the same card shows an icon and a heading for that state
|
||||
|
||||
### Requirement: Header Trail Without Repeats
|
||||
|
||||
The admin header SHALL NOT repeat the page title. On a page reached directly from the sidebar it SHALL show no trail. On a page below one, it SHALL show the parent page as a link back.
|
||||
|
||||
#### Scenario: Top-level page
|
||||
|
||||
- **WHEN** an admin opens the Events list
|
||||
- **THEN** the header shows no trail text
|
||||
|
||||
#### Scenario: Sub-page
|
||||
|
||||
- **WHEN** an admin opens the new event page
|
||||
- **THEN** the header shows "Events" as a link to the Events list
|
||||
|
||||
### Requirement: Table Scroll Cue
|
||||
|
||||
A table wider than its container SHALL show a fade on each edge where more columns can be scrolled into view. The fade SHALL disappear at that end of the scroll. Where a data table pins its first column, the pinned column covers the left fade and SHALL instead show a divider on its right edge.
|
||||
|
||||
#### Scenario: Users list on a phone
|
||||
|
||||
- **WHEN** an admin opens the Users list at 360 px wide
|
||||
- **THEN** a fade shows on the right edge of the table
|
||||
- **AND** after scrolling to the last column the right fade is gone
|
||||
- **AND** the pinned username column shows a divider on its right edge
|
||||
|
||||
### 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.
|
||||
|
||||
#### 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
|
||||
|
||||
#### 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
|
||||
@@ -0,0 +1,57 @@
|
||||
# Tasks: refine-visitor-pages-and-shell
|
||||
|
||||
Design: `design.md` and `docs/superpowers/specs/2026-12-01-visual-followup-design.md`. Portal only. Every task is TDD, followed by the review gate. Tasks run serially in this order, because several of them touch `globals.css` and the i18n messages.
|
||||
|
||||
Verify for every task: `cd solvway-admin-portal && npx vitest run; echo VITEST=$? && npx tsc --noEmit && npm run lint`. Check the vitest exit code: an unhandled error fails the run even when every test passes.
|
||||
|
||||
## 1. Shell
|
||||
|
||||
- [x] 1.1 Header trail without repeats: `Breadcrumbs` shows nothing on a page whose URL is the matched leaf's own URL, and shows the leaf as a link on a sub-page.
|
||||
- Depends on: none
|
||||
- Scope: `solvway-admin-portal/app/components/app/Breadcrumbs*`
|
||||
- [x] 1.2 Sidebar sections: an `ADMIN_MODULES` list in `aclSidebar.ts`, the work and Administration split in `Sidebar` (full sidebar and drawer: divider and label; rail: divider only; no section when it has no items), and the "Administration" label in `defaultMessages.ts`.
|
||||
- Depends on: 1.1
|
||||
- Scope: `solvway-admin-portal/app/lib/aclSidebar*`, `solvway-admin-portal/app/components/app/Sidebar*`, `solvway-admin-portal/app/lib/i18n/defaultMessages.ts`
|
||||
- [x] 1.3 Table scroll cue: a scroll-shadow utility in `globals.css` applied to the `table-container`, with colours from tokens only (the design-tokens test stays green).
|
||||
- Depends on: 1.2
|
||||
- Scope: `solvway-admin-portal/app/components/ui/table*`, `solvway-admin-portal/app/globals.css`, `solvway-admin-portal/app/globals.test.ts`
|
||||
|
||||
## 2. Visitor pages
|
||||
|
||||
- [x] 2.1 `VisitorCard` (ground, card, event header with the company label, the dates and location with icons, footer) and `VisitorState` (icon, heading, text, action). `RegistrationForm` drops its header, adds the "Mobile or email is required" hint (new key in `defaultMessages.ts`), sets the notice as fine print, and aligns the consent row.
|
||||
- Depends on: 1.3
|
||||
- Scope: `solvway-admin-portal/app/components/registration/**` except `QrCodeItem*`, `solvway-admin-portal/app/lib/i18n/defaultMessages.ts`
|
||||
- [x] 2.2 `/r`, `/i` and `/c` render every state inside `VisitorCard`, with `VisitorState` for loading, inactive, error, too many, not yet, ended, thank you, welcome and checked in. Existing behaviour and text stay the same.
|
||||
- Depends on: 2.1
|
||||
- Scope: `solvway-admin-portal/app/r/**`, `solvway-admin-portal/app/i/**`, `solvway-admin-portal/app/c/**`
|
||||
|
||||
## 3. Staff screens
|
||||
|
||||
- [x] 3.1 My QR codes as cards: the event name as the title, dates and location, the switched-off badge in the card header, the QR and a wrapping button row.
|
||||
- Depends on: 2.2
|
||||
- Scope: `solvway-admin-portal/app/my-qr/**`, `solvway-admin-portal/app/components/registration/QrCodeItem*`
|
||||
- [x] 3.2 Reset password uses the login page's two-column frame. Remove the stale brown and gold comments in login.
|
||||
- Depends on: 3.1
|
||||
- Scope: `solvway-admin-portal/app/reset-password/**`, `solvway-admin-portal/app/login/**`
|
||||
|
||||
## 4. Release check
|
||||
|
||||
- [x] 4.1 Playwright at 1280 and 360 px:
|
||||
- `/r`, `/i` and `/c` in each reachable state;
|
||||
- My QR, using a throwaway staff user that is reverted afterwards;
|
||||
- login and reset password;
|
||||
- the `/events` and `/events/new` header;
|
||||
- the Users table at 360 px, before and after scrolling;
|
||||
- the sidebar, full and rail.
|
||||
|
||||
Run the full portal verify. Record the result here.
|
||||
- Depends on: 3.2
|
||||
- Done 2026-12-01 on the local stack (review server on port 3001), full portal verify green (vitest 1580 passed with exit 0, tsc 0, lint 0 errors).
|
||||
- Visitor pages at 360 and 1280 px: /r open form (company label, h1, dates, location, hint under mobile, fine-print notice in both languages before consent), the empty-submit errors shown on screen, an unknown code (no event details), /c lookup, /c not yet (heading balanced so the date stays whole), and /i already checked in. One h1 and one main in every state. Dark theme checked on /c. No registration was submitted (no records created).
|
||||
- Header: /events shows no trail, /events/new shows "Events" linking to /events.
|
||||
- Sidebar: Administration label and divider in the full sidebar, divider only in the rail.
|
||||
- Users table at 360 px: right fade at the start and gone at the end. The pinned first column hid the left fade, so it now carries a divider on its right edge (fix found in this check). Dark theme checked.
|
||||
- Reset password (throwaway CV staff user, reverted afterwards): same frame as login at 1280 and 360 px, and the policy error is shown.
|
||||
- My QR (same user, temporarily on the LC Live Check team, then removed and disabled): card layout at 360, 700, 1024 and 1280 px. At 1280 px a button overflowed the card, so the QR now stacks above the buttons (fix found in this check).
|
||||
|
||||
- After the whole-branch review: the giraffe-spot coat and 16px corners were removed from the signed-out frame (DESIGN.md forbids them); login checked again at 1280 and 360 px. DESIGN.md updated to the shipped look. Full verify: vitest 1585 passed (exit 0), tsc 0, lint 0 errors.
|
||||
@@ -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
|
||||
@@ -79,3 +79,93 @@ Every dropdown in the admin portal SHALL open a styled option menu that matches
|
||||
|
||||
- **WHEN** an admin focuses a dropdown and presses Enter or Space, then the arrow keys and Enter
|
||||
- **THEN** the menu opens, moves between options, and chooses one
|
||||
|
||||
### Requirement: Visitor Page Look
|
||||
|
||||
The public visitor pages (registration, invitation and check-in) SHALL show their content in one card on the page ground. The card SHALL be headed by the company name as a small label, the event name as the main heading, and the event dates and location. The pages SHALL use only the portal's theme tokens and SHALL NOT show a per-company logo or colour. The privacy notice SHALL be shown in full in English and Bahasa Malaysia as smaller, muted text that keeps at least 4.5:1 contrast.
|
||||
|
||||
#### Scenario: Visitor opens a registration code
|
||||
|
||||
- **WHEN** a visitor opens the registration page of an INS event
|
||||
- **THEN** the card shows "INS" as a label above the event name, then the event dates and location
|
||||
- **AND** the full privacy notice appears in both languages above the consent box
|
||||
|
||||
#### Scenario: Visitor needs a contact
|
||||
|
||||
- **WHEN** a visitor sees the mobile field on the registration form
|
||||
- **THEN** a hint under it says that a mobile number or an email is required
|
||||
|
||||
#### Scenario: Visitor reaches an end state
|
||||
|
||||
- **WHEN** a visitor's registration is accepted, or the code is inactive, or check-in has not opened yet
|
||||
- **THEN** the same card shows an icon and a heading for that state
|
||||
|
||||
### Requirement: Header Trail Without Repeats
|
||||
|
||||
The admin header SHALL NOT repeat the page title. On a page reached directly from the sidebar it SHALL show no trail. On a page below one, it SHALL show the parent page as a link back.
|
||||
|
||||
#### Scenario: Top-level page
|
||||
|
||||
- **WHEN** an admin opens the Events list
|
||||
- **THEN** the header shows no trail text
|
||||
|
||||
#### Scenario: Sub-page
|
||||
|
||||
- **WHEN** an admin opens the new event page
|
||||
- **THEN** the header shows "Events" as a link to the Events list
|
||||
|
||||
### Requirement: Table Scroll Cue
|
||||
|
||||
A table wider than its container SHALL show a fade on each edge where more columns can be scrolled into view. The fade SHALL disappear at that end of the scroll. Where a data table pins its first column, the pinned column covers the left fade and SHALL instead show a divider on its right edge.
|
||||
|
||||
#### Scenario: Users list on a phone
|
||||
|
||||
- **WHEN** an admin opens the Users list at 360 px wide
|
||||
- **THEN** a fade shows on the right edge of the table
|
||||
- **AND** after scrolling to the last column the right fade is gone
|
||||
- **AND** the pinned username column shows a divider on its right edge
|
||||
|
||||
### 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
|
||||
|
||||
### 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
|
||||
@@ -177,10 +177,16 @@ Slate neutrals with a single blue voice, plus muted semantic and chart tones tha
|
||||
|
||||
An app shell: a sticky 240px white sidebar (collapsible to a 76px icon rail on desktop, a left sheet below the lg breakpoint) beside a column holding a sticky 56px white header and the main area. The sidebar's top block is header-high so its bottom hairline continues the header's. Main content sits on the slate ground with 16px padding, centred up to 1600px.
|
||||
|
||||
Page anatomy: breadcrumb in the header, page header (title, optional meta line, actions right-aligned and wrapping), then filter row, then the content card. Rhythm is a 4px base: 8px between related controls, 16px between blocks and around the page, 24px inside cards. KPI tiles sit in one row of equal columns. Tables scroll horizontally inside their card with a soft shadow on whichever edge has more content. The page reserves the scrollbar gutter so overlays never shift the layout.
|
||||
Page anatomy: on a sub-page the header shows its parent page as a link back (a page reached from the sidebar shows none, since its title already names it), then the page header (title, optional meta line, actions right-aligned and wrapping), then filter row, then the content card. Rhythm is a 4px base: 8px between related controls, 16px between blocks and around the page, 24px inside cards. KPI tiles sit in one row of equal columns. Tables scroll horizontally inside their card with a 20px shadow at 18% ink on whichever edge has more content; it fades out at that end of the scroll. A data table's pinned first column covers the left shadow, so it carries a 1px hairline on its right edge instead. The page reserves the scrollbar gutter so overlays never shift the layout.
|
||||
|
||||
The footer credit "Powered by Containerverse Sdn. Bhd." sits at the foot of the sidebar on desktop and under the content on mobile, in 12px muted text.
|
||||
|
||||
**Public visitor pages** (`/r`, `/i`, `/c`) have no shell. One white card sits on the slate ground, full width with a 16px gutter on phones and at most 448px wide, with the footer credit under it. The card opens with the event header: the company name as a 12px semibold uppercase label in Action Blue, the event name as the 24px h1, then dates and location on their own muted lines with 16px icons. The privacy notice is fine print: 12px muted text on a slate-tint panel, both languages in full. Every end state (loading, thank you, welcome, not yet, inactive) is a centred 40px round icon (blue tint, or 10% red for errors) over a balanced semibold heading. The look is neutral: no company logo or colour.
|
||||
|
||||
**Signed-out pages** (login, forgot password, reset password) share one frame: from the lg breakpoint a blue-tint panel on the left with the "Back office" pill, a headline and three feature lines, and the form column on the ground at right; below lg the panel folds into a short band above the form.
|
||||
|
||||
**My QR codes** shows one card per code in a grid (one column on phones, two from 768px, three from 1280px): the event name as the card title, dates and location under it, the warning pill in the header when switched off, then the QR above its link and a wrapping row of outline buttons.
|
||||
|
||||
## Elevation & Depth
|
||||
|
||||
Flat surfaces separated by hairlines, with a whisper of shadow that only says "this lifts slightly". Cards carry the card shadow; controls carry a barely-there shadow; floating layers (menus, popovers, toasts, dialogs) step up. In dark mode the card shadow becomes a single dark drop and hairlines do the work.
|
||||
@@ -231,8 +237,8 @@ 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.
|
||||
- **Header:** white, bottom hairline, 56px; breadcrumb left; company picker (a styled select), locale switcher, theme toggle and user menu (blue avatar initial) right.
|
||||
- **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
|
||||
- Empty: centred muted icon, 14px muted message and a corrective action. Error: a 40% red-bordered panel on 5% red with an alert icon and an outline Retry. Loading: skeleton rows in a bordered surface.
|
||||
@@ -253,4 +259,4 @@ Quiet, compact, unmistakable.
|
||||
- **Don't** add a second typeface or a display face; Inter carries everything.
|
||||
- **Don't** use semantic or chart tones to mark something clickable.
|
||||
- **Don't** add shadows beyond the four steps, or let a shadow stand in for a hairline.
|
||||
- **Don't** apply this system to the booth (My QR), visitor pages (/r, /i, /c) or login screens piecemeal; they move onto it in their own follow-up change.
|
||||
- **Don't** brand the visitor pages per company (logo or colour) without an owner decision; they stay on the neutral Co-Lite tokens.
|
||||
@@ -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,89 @@
|
||||
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 { ApiError } from "@/app/lib/clientApi";
|
||||
import CheckinPage from "./page";
|
||||
|
||||
const open = {
|
||||
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: [],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.getCheckin.mockReset().mockResolvedValue(open);
|
||||
mocks.lookupCheckin.mockReset().mockResolvedValue({ result: "CHECKED_IN", firstName: "Aini" });
|
||||
mocks.registerWalkIn.mockReset().mockResolvedValue({});
|
||||
});
|
||||
|
||||
const h1s = () => screen.getAllByRole("heading", { level: 1 });
|
||||
|
||||
describe("/c visitor card", () => {
|
||||
it("lookup sits in the card under the event header with one h1", async () => {
|
||||
render(<CheckinPage />);
|
||||
await screen.findByLabelText("Mobile number or email");
|
||||
expect(screen.getByText("INS", { selector: "p" })).toBeTruthy();
|
||||
expect(h1s().map((h) => h.textContent)).toEqual(["Expo 2026"]);
|
||||
expect(screen.getByText("2026-12-01 - 2026-12-02")).toBeTruthy();
|
||||
expect(document.querySelectorAll("main").length).toBe(1);
|
||||
});
|
||||
|
||||
it("walk-in form shows the notice before consent under one h1", async () => {
|
||||
const user = userEvent.setup();
|
||||
mocks.lookupCheckin.mockResolvedValue({ result: "FORM" });
|
||||
render(<CheckinPage />);
|
||||
await user.type(await screen.findByLabelText("Mobile number or email"), "0123456789");
|
||||
await user.click(screen.getByRole("button", { name: "Check in" }));
|
||||
await screen.findByLabelText("Your name");
|
||||
const notice = screen.getByText("We keep your data safe.");
|
||||
expect(notice.compareDocumentPosition(screen.getByLabelText(/I agree to INS/)) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(h1s().map((h) => h.textContent)).toEqual(["Expo 2026"]);
|
||||
});
|
||||
|
||||
it("loading icon spins", () => {
|
||||
mocks.getCheckin.mockReturnValue(new Promise(() => {}));
|
||||
render(<CheckinPage />);
|
||||
expect(screen.getByRole("status").querySelector("svg")).toHaveClass("motion-safe:animate-spin");
|
||||
});
|
||||
|
||||
it("welcome shows an icon and heading under the event header", 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" }));
|
||||
const s = await screen.findByRole("status");
|
||||
expect(s.querySelector("svg")).toBeTruthy();
|
||||
expect(screen.getByRole("heading", { level: 2 }).textContent).toBe("Welcome, Aini. You're checked in.");
|
||||
expect(h1s().map((h) => h.textContent)).toEqual(["Expo 2026"]);
|
||||
});
|
||||
|
||||
it("not yet and ended have an icon and the heading as the only h1", async () => {
|
||||
mocks.getCheckin.mockResolvedValue({ state: "NOT_YET", startDate: "2026-12-01" });
|
||||
const { unmount } = render(<CheckinPage />);
|
||||
const s = await screen.findByRole("status");
|
||||
expect(s.querySelector("svg")).toBeTruthy();
|
||||
expect(h1s().map((h) => h.textContent)).toEqual(["Check-in opens on 2026-12-01."]);
|
||||
unmount();
|
||||
mocks.getCheckin.mockResolvedValue({ state: "ENDED", startDate: "2026-12-01" });
|
||||
render(<CheckinPage />);
|
||||
await screen.findByText("This event has ended.");
|
||||
expect(h1s().length).toBe(1);
|
||||
expect(document.querySelectorAll("main").length).toBe(1);
|
||||
});
|
||||
|
||||
it("inactive and load error are alerts with one h1 and no event details", async () => {
|
||||
mocks.getCheckin.mockRejectedValue(new ApiError("x", 404, { code: "CODE_INACTIVE" }));
|
||||
const { unmount } = render(<CheckinPage />);
|
||||
expect((await screen.findByRole("alert")).querySelector("svg")).toBeTruthy();
|
||||
expect(h1s().map((h) => h.textContent)).toEqual(["This code is no longer active."]);
|
||||
unmount();
|
||||
mocks.getCheckin.mockRejectedValue(new ApiError("x", 500, {}));
|
||||
render(<CheckinPage />);
|
||||
await screen.findByRole("alert");
|
||||
expect(h1s().length).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -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("");
|
||||
});
|
||||
});
|
||||
@@ -2,9 +2,11 @@
|
||||
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import { useParams } from "next/navigation";
|
||||
import { AlertCircle, CheckCircle2, Clock, Loader2 } from "lucide-react";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Input } from "@/app/components/ui/input";
|
||||
import { Label } from "@/app/components/ui/label";
|
||||
import { VisitorCard, VisitorState } from "@/app/components/registration/VisitorCard";
|
||||
import { RegistrationForm, apiData, failMessage } from "@/app/components/registration/RegistrationForm";
|
||||
import { getCheckin, lookupCheckin, registerWalkIn, type CheckinState } from "@/app/lib/services/publicInvite";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
@@ -39,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 {
|
||||
@@ -57,28 +62,31 @@ export default function CheckinPage() {
|
||||
}
|
||||
|
||||
const open = state?.state === "OPEN" ? state : null;
|
||||
const alone = (icon: typeof Clock, heading: string, role: "status" | "alert", tone?: "error", iconClassName?: string) => (
|
||||
<VisitorCard><VisitorState h1 icon={icon} heading={heading} role={role} tone={tone} iconClassName={iconClassName} /></VisitorCard>
|
||||
);
|
||||
if (phase === "loading") return alone(Loader2, t("UiLoading"), "status", undefined, "motion-safe:animate-spin");
|
||||
if (phase === "inactive") return alone(AlertCircle, t("RegInactive"), "alert");
|
||||
if (phase === "error" || !state) return alone(AlertCircle, error ?? t("RegLoadFailed"), "alert", "error");
|
||||
if (!open) return alone(Clock, state.state === "NOT_YET" ? t("ChkNotYet", { date: state.startDate }) : t("ChkEnded"), "status");
|
||||
|
||||
let body;
|
||||
if (phase === "loading") body = <p role="status">{t("UiLoading")}</p>;
|
||||
else if (phase === "inactive") body = <p role="alert">{t("RegInactive")}</p>;
|
||||
else if (phase === "error" || !state) body = <p role="alert" className="text-sm text-destructive">{error}</p>;
|
||||
else if (!open) body = <p role="status">{state.state === "NOT_YET" ? t("ChkNotYet", { date: state.startDate }) : t("ChkEnded")}</p>;
|
||||
else if (phase === "welcome") body = <p role="status" className="text-lg font-medium">{firstName ? t("InviteWelcome", { name: firstName }) : t("InviteWelcomeAnon")}</p>;
|
||||
else if (phase === "done") body = <p role="status" className="text-lg font-medium">{t("ChkDone", { event: open.eventName })}</p>;
|
||||
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>
|
||||
<h1 className="text-2xl font-semibold">{open.eventName}</h1>
|
||||
{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>
|
||||
);
|
||||
}
|
||||
|
||||
return <main className="mx-auto w-full max-w-md px-4 py-6">{body}</main>;
|
||||
return <VisitorCard event={open}>{body}</VisitorCard>;
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
"use client";
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { CalendarDays, ListChecks, UserPlus } from "lucide-react";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import PoweredBy from "@/app/components/app/PoweredBy";
|
||||
|
||||
/** What the back office is for, on the brand panel. */
|
||||
const PANEL_POINTS = [
|
||||
{ icon: CalendarDays, code: "BackOfficePanelEvents" },
|
||||
{ icon: UserPlus, code: "BackOfficePanelLeads" },
|
||||
{ icon: ListChecks, code: "BackOfficePanelFollowUps" },
|
||||
] as const;
|
||||
|
||||
// Two-column frame shared by the signed-out pages (login, forgot password, forced password
|
||||
// change): an accent panel on the left from lg, the page's own content on the right. Below lg
|
||||
// the panel folds into a compact brand row above the content.
|
||||
export default function AuthFrame({ children }: { children: ReactNode }) {
|
||||
const t = useT();
|
||||
return (
|
||||
<div className="grid min-h-svh bg-background lg:grid-cols-[minmax(0,5fr)_minmax(0,6fr)]">
|
||||
<aside className="relative isolate hidden flex-col justify-between gap-10 overflow-hidden bg-accent p-12 text-accent-foreground lg:flex">
|
||||
<div className="flex items-center gap-4">
|
||||
<span className="rounded-full bg-primary px-3 py-1 text-sm font-semibold text-primary-foreground dark:bg-accent-foreground dark:text-accent">
|
||||
{t("BackOfficeLabel")}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="max-w-md space-y-8">
|
||||
<p className="font-heading text-4xl leading-tight font-semibold tracking-tight text-balance">
|
||||
{t("BackOfficePanelTitle")}
|
||||
</p>
|
||||
<ul className="space-y-4">
|
||||
{PANEL_POINTS.map(({ icon: PointIcon, code }) => (
|
||||
<li key={code} className="flex items-center gap-3 text-base font-medium">
|
||||
<span className="flex size-10 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground dark:bg-accent-foreground dark:text-accent">
|
||||
<PointIcon aria-hidden="true" className="size-5" />
|
||||
</span>
|
||||
{t(code)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<span aria-hidden="true" />
|
||||
</aside>
|
||||
|
||||
<main className="flex flex-col items-center justify-center gap-8 p-6 sm:p-10">
|
||||
<div className="w-full max-w-sm space-y-8">
|
||||
{/* Below lg a short brand band stands in for the panel: same accent ground. */}
|
||||
<div className="relative isolate flex items-center gap-3 overflow-hidden rounded-lg bg-accent p-4 lg:hidden">
|
||||
<span className="rounded-full bg-primary px-3 py-1 text-xs font-semibold text-primary-foreground dark:bg-accent-foreground dark:text-accent">
|
||||
{t("BackOfficeLabel")}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{children}
|
||||
</div>
|
||||
<PoweredBy />
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,7 +4,8 @@ import type { SidebarLink } from "@/app/lib/aclSidebar";
|
||||
import { MessagesProvider } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
// fix-admin-shell-foundation: header breadcrumbs derived from the sidebar tree. Group names are
|
||||
// text; the module crumb is the current page on its own url and a link back to it on a sub-page.
|
||||
// text; on the module's own url there is no trail (refine-visitor-pages-and-shell), and on a
|
||||
// sub-page the module crumb is a link back to it.
|
||||
|
||||
const state = vi.hoisted(() => ({ links: [] as SidebarLink[], pathname: "/" }));
|
||||
|
||||
@@ -47,15 +48,14 @@ describe("Breadcrumbs", () => {
|
||||
expect(screen.queryByRole("link", { name: "Sales & Orders" })).toBeNull();
|
||||
});
|
||||
|
||||
it("marks the list page itself as the current page, not a link", () => {
|
||||
// The page title already names a list page, so its own trail is not repeated (refine-visitor-pages-and-shell).
|
||||
it("shows nothing on the list page itself", () => {
|
||||
state.links = LINKS;
|
||||
state.pathname = "/orders/web";
|
||||
|
||||
render(<Breadcrumbs />);
|
||||
const { container } = render(<Breadcrumbs />);
|
||||
|
||||
expect(screen.queryByRole("link", { name: "Sales Listing" })).toBeNull();
|
||||
expect(screen.getByText("Sales Listing")).toHaveAttribute("aria-current", "page");
|
||||
expect(screen.getByRole("navigation", { name: "breadcrumb" })).toHaveTextContent("Sales & Orders");
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
it("shows nothing on the dashboard", () => {
|
||||
@@ -78,7 +78,7 @@ describe("Breadcrumbs", () => {
|
||||
|
||||
it("uses the same translated labels as the sidebar", () => {
|
||||
state.links = [{ name: "BO_USERS", url: "", children: [{ name: "BO_MESSAGES", url: "/messages", children: [] }] }];
|
||||
state.pathname = "/messages";
|
||||
state.pathname = "/messages/7";
|
||||
|
||||
render(
|
||||
<MessagesProvider locale="zh_CN" messages={{ BO_MESSAGES: "消息" }}>
|
||||
@@ -86,7 +86,7 @@ describe("Breadcrumbs", () => {
|
||||
</MessagesProvider>,
|
||||
);
|
||||
|
||||
expect(screen.getByText("消息")).toHaveAttribute("aria-current", "page");
|
||||
expect(screen.getByRole("link", { name: "消息" })).toHaveAttribute("href", "/messages");
|
||||
expect(screen.getByRole("navigation", { name: "breadcrumb" })).toHaveTextContent("Users");
|
||||
});
|
||||
});
|
||||
@@ -97,11 +97,11 @@ describe("Breadcrumbs pick the most specific match", () => {
|
||||
{ name: "Event", url: "", children: [{ name: "Event POS", url: "/pos", children: [] }] },
|
||||
{ name: "Sales", url: "", children: [{ name: "Branch Counter", url: "/pos/counter", children: [] }] },
|
||||
];
|
||||
state.pathname = "/pos/counter";
|
||||
state.pathname = "/pos/counter/5";
|
||||
|
||||
render(<Breadcrumbs />);
|
||||
|
||||
expect(screen.getByText("Branch Counter")).toHaveAttribute("aria-current", "page");
|
||||
expect(screen.getByRole("link", { name: "Branch Counter" })).toHaveAttribute("href", "/pos/counter");
|
||||
expect(screen.getByRole("navigation", { name: "breadcrumb" })).not.toHaveTextContent("Event");
|
||||
});
|
||||
|
||||
@@ -115,3 +115,27 @@ describe("Breadcrumbs pick the most specific match", () => {
|
||||
expect(list.querySelectorAll("li li")).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Breadcrumbs trail without repeats", () => {
|
||||
const EVENT_LINKS: SidebarLink[] = [
|
||||
{ name: "Event", url: "", children: [{ name: "Events", url: "/events", children: [] }] },
|
||||
];
|
||||
|
||||
it("shows no trail on the Events list", () => {
|
||||
state.links = EVENT_LINKS;
|
||||
state.pathname = "/events";
|
||||
|
||||
const { container } = render(<Breadcrumbs />);
|
||||
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
it("shows Events as a link to the list on the new event page", () => {
|
||||
state.links = EVENT_LINKS;
|
||||
state.pathname = "/events/new";
|
||||
|
||||
render(<Breadcrumbs />);
|
||||
|
||||
expect(screen.getByRole("link", { name: "Events" })).toHaveAttribute("href", "/events");
|
||||
});
|
||||
});
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
BreadcrumbItem,
|
||||
BreadcrumbLink,
|
||||
BreadcrumbList,
|
||||
BreadcrumbPage,
|
||||
BreadcrumbSeparator,
|
||||
} from "@/app/components/ui/breadcrumb";
|
||||
|
||||
@@ -24,6 +23,7 @@ export default function Breadcrumbs() {
|
||||
if (!leaf || leaf.url === "/") return null;
|
||||
|
||||
const url = matchedUrl(leaf, pathname)!;
|
||||
if (pathname === url) return null;
|
||||
|
||||
return (
|
||||
<Breadcrumb className="hidden md:block">
|
||||
@@ -35,13 +35,9 @@ export default function Breadcrumbs() {
|
||||
</Fragment>
|
||||
))}
|
||||
<BreadcrumbItem>
|
||||
{pathname === url ? (
|
||||
<BreadcrumbPage>{t(leaf.name)}</BreadcrumbPage>
|
||||
) : (
|
||||
<BreadcrumbLink asChild>
|
||||
<Link href={url}>{t(leaf.name)}</Link>
|
||||
</BreadcrumbLink>
|
||||
)}
|
||||
<BreadcrumbLink asChild>
|
||||
<Link href={url}>{t(leaf.name)}</Link>
|
||||
</BreadcrumbLink>
|
||||
</BreadcrumbItem>
|
||||
</BreadcrumbList>
|
||||
</Breadcrumb>
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -2,10 +2,10 @@ 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 nav = vi.hoisted(() => ({ replace: vi.fn(), refresh: vi.fn() }));
|
||||
const nav = vi.hoisted(() => ({ replace: vi.fn(), refresh: vi.fn(), pathname: "/orders/web" }));
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({ replace: nav.replace, refresh: nav.refresh }),
|
||||
usePathname: () => "/orders/web",
|
||||
usePathname: () => nav.pathname,
|
||||
}));
|
||||
|
||||
// The mobile drawer (fix-admin-shell-foundation) renders the same aclMenu-derived tree as the sidebar.
|
||||
@@ -144,8 +144,19 @@ describe("Header mobile navigation", () => {
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
|
||||
});
|
||||
|
||||
it("shows breadcrumbs for the current page", () => {
|
||||
// On a list page the trail is empty: the page title already names it (refine-visitor-pages-and-shell).
|
||||
it("shows no breadcrumbs on a list page", () => {
|
||||
render(<Header />);
|
||||
expect(screen.getByRole("navigation", { name: "breadcrumb" })).toHaveTextContent("Sales Listing");
|
||||
expect(screen.queryByRole("navigation", { name: "breadcrumb" })).toBeNull();
|
||||
});
|
||||
|
||||
it("shows the list page as a link back on a sub-page", () => {
|
||||
nav.pathname = "/orders/web/1";
|
||||
try {
|
||||
render(<Header />);
|
||||
expect(screen.getByRole("link", { name: "Sales Listing" })).toHaveAttribute("href", "/orders/web");
|
||||
} finally {
|
||||
nav.pathname = "/orders/web";
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { render, screen, within } from "@testing-library/react";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import type { SidebarLink } from "@/app/lib/aclSidebar";
|
||||
|
||||
const state = vi.hoisted(() => ({ links: [] as SidebarLink[] }));
|
||||
|
||||
vi.mock("next/navigation", () => ({ usePathname: () => "/" }));
|
||||
vi.mock("@/app/lib/useAclSidebar", () => ({ useAclSidebar: () => state.links }));
|
||||
|
||||
import { SidebarNav } from "./Sidebar";
|
||||
|
||||
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 Dashboard, then Events, Leads, Access and System sections in order", () => {
|
||||
state.links = [...ALL].reverse();
|
||||
render(<SidebarNav />);
|
||||
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("shows only the sections the user has pages in", () => {
|
||||
state.links = names("BO_EVENTS", "BO_EVENT_LEADS");
|
||||
const { container } = render(<SidebarNav />);
|
||||
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("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 />);
|
||||
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 { 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,19 +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 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} />
|
||||
);
|
||||
|
||||
return (
|
||||
<nav aria-label={t("SidebarMainNav")} className="scrollable flex-1 overflow-x-hidden overflow-y-auto">
|
||||
<ul className={cn("space-y-1", collapsed ? "px-2 py-3" : "p-3")}>
|
||||
{links.map((link) =>
|
||||
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} />
|
||||
),
|
||||
)}
|
||||
</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"));
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Copy, Download, Maximize2, Share2 } from "lucide-react";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Dialog, DialogContent } from "@/app/components/ui/dialog";
|
||||
import { Switch } from "@/app/components/ui/switch";
|
||||
import { cn } from "@/app/lib/utils";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
const slug = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
|
||||
@@ -13,6 +14,7 @@ const slug = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(
|
||||
/** One registration code: QR, link, copy, PNG download and (when onToggle is given) an on/off switch. */
|
||||
export function QrCodeItem({
|
||||
label,
|
||||
className,
|
||||
eventName,
|
||||
fileLabel,
|
||||
token,
|
||||
@@ -21,7 +23,9 @@ export function QrCodeItem({
|
||||
prefix = "r",
|
||||
personal = false,
|
||||
}: {
|
||||
label: string;
|
||||
/** Heading above the link; omit when the surrounding card already names the event. */
|
||||
label?: string;
|
||||
className?: string;
|
||||
eventName: string;
|
||||
/** Member name for the download file name; omit for the event code. */
|
||||
fileLabel?: string;
|
||||
@@ -71,11 +75,11 @@ export function QrCodeItem({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3 rounded-lg border p-4 sm:flex-row sm:items-center">
|
||||
<div className={cn("flex flex-col gap-3 rounded-lg border p-4 sm:flex-row sm:items-center", className)}>
|
||||
<QRCodeSVG value={link} size={128} className="shrink-0" />
|
||||
<QRCodeCanvas ref={canvas} value={link} size={512} className="hidden" />
|
||||
<div className="min-w-0 flex-1 space-y-2">
|
||||
<p className="text-sm font-medium">{label}</p>
|
||||
{label && <p className="text-sm font-medium">{label}</p>}
|
||||
<p className="break-all text-xs text-muted-foreground">{link}</p>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button variant="outline" size="sm" onClick={copy}>
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { RegistrationForm } from "./RegistrationForm";
|
||||
|
||||
const info = {
|
||||
eventName: "Expo 2026", startDate: "2026-12-01", endDate: "2026-12-02", location: "KLCC", companyName: "INS",
|
||||
notice: { id: 1, textEn: "English text", textMs: "Teks Melayu" }, interests: [],
|
||||
};
|
||||
const props = { info, submit: async () => undefined, onDone: () => {}, onInactive: () => {} };
|
||||
const wrap = (ui: React.ReactElement) => render(ui);
|
||||
|
||||
describe("RegistrationForm look", () => {
|
||||
it("renders no heading of its own: the visitor card carries the event header", () => {
|
||||
wrap(<RegistrationForm {...props} />);
|
||||
expect(screen.queryByRole("heading", { level: 1 })).toBeNull();
|
||||
});
|
||||
it("links a contact hint to the mobile field", () => {
|
||||
wrap(<RegistrationForm {...props} />);
|
||||
const hint = screen.getByText("Mobile or email is required");
|
||||
expect(screen.getByLabelText("Mobile number").getAttribute("aria-describedby")).toBe(hint.id);
|
||||
});
|
||||
it("shows the notice as fine print in both languages", () => {
|
||||
wrap(<RegistrationForm {...props} />);
|
||||
expect(screen.getByText("English text").parentElement?.className).toContain("text-muted-foreground");
|
||||
expect(screen.getByText("Teks Melayu")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("sets the consent sentences in regular weight", () => {
|
||||
wrap(<RegistrationForm {...props} />);
|
||||
expect(screen.getByText(/I agree to INS/).closest("span[class*=space-y]")).toHaveClass("font-normal");
|
||||
});
|
||||
});
|
||||
@@ -13,6 +13,7 @@ const EMPTY: RegistrationBody = { name: "", mobile: "", email: "", companyName:
|
||||
// Fields the form renders; a server error for any other field goes to the form-level alert.
|
||||
const FIELDS = ["name", "mobile", "email", "companyName", "jobTitle", "consent"];
|
||||
const ROW = "flex min-h-11 w-full cursor-pointer items-center gap-3 rounded-md border p-3";
|
||||
const CONSENT_ROW = "flex min-h-11 w-full cursor-pointer items-start gap-3 rounded-md border p-3 leading-normal";
|
||||
const BOX = "size-6";
|
||||
|
||||
export function apiData(err: unknown): { status?: number; code?: string; error?: string; field?: string } {
|
||||
@@ -29,8 +30,6 @@ export function failMessage(t: (k: string) => string, err: unknown, tooMany = "R
|
||||
}
|
||||
|
||||
interface Props {
|
||||
/** Heading text; the event name when omitted. */
|
||||
title?: string;
|
||||
/** i18n key for the too-many message (default RegTooMany, the /r wording). */
|
||||
tooManyKey?: string;
|
||||
info: RegistrationInfo;
|
||||
@@ -43,8 +42,9 @@ interface Props {
|
||||
onInactive: () => void;
|
||||
}
|
||||
|
||||
// The visitor registration form shared by /r, /i and /c: event header, fields, bilingual privacy notice and consent.
|
||||
export function RegistrationForm({ title, tooManyKey, info, initial, submit, onDone, onInactive }: Props) {
|
||||
// The visitor registration form shared by /r, /i and /c: fields, bilingual privacy notice and consent.
|
||||
// The event header comes from the VisitorCard around it.
|
||||
export function RegistrationForm({ tooManyKey, info, initial, submit, onDone, onInactive }: Props) {
|
||||
const t = useT();
|
||||
const [form, setForm] = useState<RegistrationBody>({ ...EMPTY, ...initial });
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
@@ -82,25 +82,23 @@ export function RegistrationForm({ title, tooManyKey, info, initial, submit, onD
|
||||
}
|
||||
}
|
||||
|
||||
const field = (id: "name" | "mobile" | "email" | "companyName" | "jobTitle", label: string, type = "text") => (
|
||||
const field = (id: "name" | "mobile" | "email" | "companyName" | "jobTitle", label: string, type = "text", hint?: string) => {
|
||||
const describedBy = [hint && `reg-${id}-hint`, errors[id] && `reg-${id}-error`].filter(Boolean).join(" ") || undefined;
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor={`reg-${id}`}>{label}</Label>
|
||||
<Input id={`reg-${id}`} className="h-11" type={type} value={form[id]} onChange={(e) => set({ [id]: e.target.value })} disabled={saving} aria-invalid={!!errors[id]} aria-describedby={errors[id] ? `reg-${id}-error` : undefined} />
|
||||
<Input id={`reg-${id}`} className="h-11" type={type} value={form[id]} onChange={(e) => set({ [id]: e.target.value })} disabled={saving} aria-invalid={!!errors[id]} aria-describedby={describedBy} />
|
||||
{hint && <p id={`reg-${id}-hint`} className="text-xs text-muted-foreground">{hint}</p>}
|
||||
{errors[id] && <p id={`reg-${id}-error`} className="text-sm text-destructive">{errors[id]}</p>}
|
||||
</div>
|
||||
);
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={onSubmit} className="space-y-4" noValidate>
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold">{title ?? info.eventName}</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{info.companyName} | {info.startDate} - {info.endDate} | {info.location}
|
||||
</p>
|
||||
</div>
|
||||
{formError && <p role="alert" className="text-sm text-destructive">{formError}</p>}
|
||||
{field("name", t("RegName"))}
|
||||
{field("mobile", t("RegMobile"), "tel")}
|
||||
{field("mobile", t("RegMobile"), "tel", t("RegContactHint"))}
|
||||
{field("email", t("RegEmail"), "email")}
|
||||
{field("companyName", t("RegCompany"))}
|
||||
{field("jobTitle", t("RegJobTitle"))}
|
||||
@@ -120,15 +118,15 @@ export function RegistrationForm({ title, tooManyKey, info, initial, submit, onD
|
||||
))}
|
||||
</fieldset>
|
||||
)}
|
||||
<div className="space-y-2 rounded-md border p-3 text-sm">
|
||||
<h2 className="font-medium">{t("RegNoticeEn")}</h2>
|
||||
<div className="space-y-2 rounded-md bg-muted p-3 text-xs text-muted-foreground">
|
||||
<h2 className="font-semibold text-foreground">{t("RegNoticeEn")}</h2>
|
||||
<p className="whitespace-pre-line">{info.notice.textEn}</p>
|
||||
<h2 className="font-medium">{t("RegNoticeMs")}</h2>
|
||||
<h2 className="font-semibold text-foreground">{t("RegNoticeMs")}</h2>
|
||||
<p className="whitespace-pre-line">{info.notice.textMs}</p>
|
||||
</div>
|
||||
<Label htmlFor="reg-consent" className={ROW}>
|
||||
<Checkbox id="reg-consent" className={BOX} checked={form.consent} onCheckedChange={(on) => set({ consent: on === true })} aria-invalid={!!errors.consent} aria-describedby={errors.consent ? "reg-consent-error" : undefined} />
|
||||
<span>
|
||||
<Label htmlFor="reg-consent" className={CONSENT_ROW}>
|
||||
<Checkbox id="reg-consent" className={`${BOX} mt-0.5`} checked={form.consent} onCheckedChange={(on) => set({ consent: on === true })} aria-invalid={!!errors.consent} aria-describedby={errors.consent ? "reg-consent-error" : undefined} />
|
||||
<span className="space-y-1 font-normal">
|
||||
<span className="block">{t("RegConsentEn", { company: info.companyName })}</span>
|
||||
<span className="block">{t("RegConsentMs", { company: info.companyName })}</span>
|
||||
</span>
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { Inbox } from "lucide-react";
|
||||
import { VisitorCard, VisitorState } from "./VisitorCard";
|
||||
|
||||
const event = { companyName: "INS", eventName: "Expo 2026", startDate: "2026-12-01", endDate: "2026-12-02", location: "KLCC" };
|
||||
|
||||
describe("VisitorCard", () => {
|
||||
it("shows the event header in one card with one h1", () => {
|
||||
render(<VisitorCard event={event}><p>body</p></VisitorCard>);
|
||||
expect(screen.getByRole("main")).toBeTruthy();
|
||||
expect(screen.getByText("INS").className).toContain("uppercase");
|
||||
expect(screen.getByRole("heading", { level: 1 }).textContent).toBe("Expo 2026");
|
||||
expect(screen.getByText("2026-12-01 - 2026-12-02")).toBeTruthy();
|
||||
expect(screen.getByText("KLCC")).toBeTruthy();
|
||||
expect(screen.getByText("body")).toBeTruthy();
|
||||
expect(screen.getByText(/Powered by/)).toBeTruthy();
|
||||
});
|
||||
it("title overrides the h1", () => {
|
||||
render(<VisitorCard event={event} title="You're invited to Expo 2026" />);
|
||||
expect(screen.getByRole("heading", { level: 1 }).textContent).toBe("You're invited to Expo 2026");
|
||||
});
|
||||
it("renders without event data", () => {
|
||||
render(<VisitorCard><p>x</p></VisitorCard>);
|
||||
expect(screen.queryByRole("heading", { level: 1 })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("VisitorState", () => {
|
||||
it("renders heading, text, action and role", () => {
|
||||
render(<VisitorState icon={Inbox} heading="Gone" text="Not active" role="alert" tone="error" action={<button>Go</button>} />);
|
||||
expect(screen.getByRole("alert")).toBeTruthy();
|
||||
expect(screen.getByRole("heading", { level: 2 }).textContent).toBe("Gone");
|
||||
expect(screen.getByText("Not active")).toBeTruthy();
|
||||
expect(screen.getByRole("button", { name: "Go" })).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { CalendarDays, MapPin, type LucideIcon } from "lucide-react";
|
||||
import PoweredBy from "@/app/components/app/PoweredBy";
|
||||
import type { RegistrationInfo } from "@/app/lib/services/publicRegistration";
|
||||
|
||||
type EventHeader = Pick<RegistrationInfo, "companyName" | "eventName" | "startDate" | "endDate" | "location">;
|
||||
|
||||
// The public visitor page frame: one card on the page ground, event header first, PoweredBy under it.
|
||||
export function VisitorCard({ event, title, children }: { event?: EventHeader; title?: string; children?: ReactNode }) {
|
||||
return (
|
||||
<div className="flex min-h-svh flex-col items-center bg-background px-4 py-8">
|
||||
<main className="w-full max-w-md space-y-6 rounded-lg border bg-card p-6 shadow-card">
|
||||
{event && (
|
||||
<header className="space-y-2">
|
||||
<p className="text-xs font-semibold tracking-wide text-primary uppercase">{event.companyName}</p>
|
||||
<h1 className="text-2xl font-semibold">{title ?? event.eventName}</h1>
|
||||
<p className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<CalendarDays className="size-4 shrink-0" aria-hidden="true" />
|
||||
<span>{event.startDate} - {event.endDate}</span>
|
||||
</p>
|
||||
<p className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<MapPin className="size-4 shrink-0" aria-hidden="true" />
|
||||
<span>{event.location}</span>
|
||||
</p>
|
||||
</header>
|
||||
)}
|
||||
{children}
|
||||
</main>
|
||||
<div className="mt-4"><PoweredBy /></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface StateProps {
|
||||
icon: LucideIcon;
|
||||
heading: string;
|
||||
text?: string;
|
||||
action?: ReactNode;
|
||||
role?: "status" | "alert";
|
||||
tone?: "default" | "error";
|
||||
/** The heading is the page's h1: for states shown without the card's event header. */
|
||||
h1?: boolean;
|
||||
iconClassName?: string;
|
||||
}
|
||||
|
||||
// A message inside the card (thanks, inactive, closed). h2 under the event header's h1; h1 when the card has no event header.
|
||||
export function VisitorState({ icon: Icon, heading, text, action, role, tone = "default", h1, iconClassName }: StateProps) {
|
||||
const Heading = h1 ? "h1" : "h2";
|
||||
return (
|
||||
<div role={role} className="flex flex-col items-center gap-3 text-center">
|
||||
<span className={`flex size-12 items-center justify-center rounded-full ${tone === "error" ? "bg-destructive/10 text-destructive" : "bg-accent text-accent-foreground"}`}>
|
||||
<Icon className={`size-6 ${iconClassName ?? ""}`} aria-hidden="true" />
|
||||
</span>
|
||||
<Heading className="text-lg font-semibold text-balance">{heading}</Heading>
|
||||
{text && <p className="text-sm text-muted-foreground">{text}</p>}
|
||||
{action}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 }]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { DataTable } from "./data-table";
|
||||
|
||||
// refine-visitor-pages-and-shell: the pinned first column hides the left scroll cue, so it carries
|
||||
// a divider on its right edge that shows where scrolled columns slide under it.
|
||||
type Row = { id: string; name: string };
|
||||
const columns: ColumnDef<Row, unknown>[] = [{ accessorKey: "name", header: "Name" }];
|
||||
|
||||
describe("pinned first column", () => {
|
||||
it("draws a token-coloured divider on the right edge of the pinned head and body cells", () => {
|
||||
render(
|
||||
<DataTable<Row> label="t" columns={columns} data={[{ id: "1", name: "Alpha" }]} total={1} page={1} pageSize={20}
|
||||
onPageChange={() => {}} rowKey={r => r.id} />,
|
||||
);
|
||||
const divider = "shadow-[inset_-1px_0_0_var(--border)]";
|
||||
expect(screen.getByRole("columnheader", { name: "Name" })).toHaveClass(divider);
|
||||
expect(screen.getByText("Alpha").closest("td")).toHaveClass(divider);
|
||||
});
|
||||
});
|
||||
@@ -42,12 +42,20 @@ declare module '@tanstack/react-table' {
|
||||
|
||||
// The first column stays visible while a wide table scrolls sideways. Its cells need an opaque
|
||||
// background that follows the row's hover/focus/selected state, or scrolled cells show through.
|
||||
const PINNED_HEAD = 'sticky left-0 z-[1] bg-table-head'
|
||||
// The inset right divider stands in for the left scroll cue, which the opaque column covers.
|
||||
const PINNED_HEAD = 'sticky left-0 z-[1] bg-table-head shadow-[inset_-1px_0_0_var(--border)]'
|
||||
// Clicks on these inside a row act on the control, not the row.
|
||||
const ROW_CONTROLS = 'a, button, input, select, textarea, label, [role="checkbox"]'
|
||||
|
||||
const PINNED_CELL =
|
||||
'sticky left-0 z-[1] bg-card group-hover:bg-muted group-focus-visible:bg-muted group-aria-selected:bg-accent'
|
||||
'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
|
||||
@@ -127,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 (
|
||||
@@ -158,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) => {
|
||||
@@ -191,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">
|
||||
@@ -213,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',
|
||||
)}
|
||||
@@ -243,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">
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
// refine-visitor-pages-and-shell: wide tables show a visible fade on an edge that can still scroll.
|
||||
// The old 10px shadow at 12% was too faint to notice at 360px.
|
||||
describe("table scroll cue", () => {
|
||||
const css = readFileSync(join(__dirname, "../../globals.css"), "utf8");
|
||||
const rule = css.match(/\[data-slot="table-container"\]\s*\{([\s\S]*?)\n\}/)?.[1] ?? "";
|
||||
|
||||
it("uses local covers over scroll shadows", () => {
|
||||
expect(rule.match(/ local/g)).toHaveLength(2);
|
||||
expect(rule.match(/ scroll/g)).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("draws a shadow wide and strong enough to see, from theme tokens only", () => {
|
||||
const shadow = [...rule.matchAll(/var\(--foreground\) (\d+)%[^/]*\/ (\d+)px/g)];
|
||||
expect(shadow).toHaveLength(2);
|
||||
for (const [, pct, px] of shadow) {
|
||||
expect(Number(pct)).toBeGreaterThanOrEqual(18);
|
||||
expect(Number(px)).toBeGreaterThanOrEqual(16);
|
||||
}
|
||||
expect(rule).not.toMatch(/#[0-9a-f]{3,8}\b|rgb\(|hsl\(/i);
|
||||
});
|
||||
|
||||
it("makes each cover wider than its shadow, so the fade is gone at that end", () => {
|
||||
const covers = [...rule.matchAll(/var\(--card\)[^/]*\/ (\d+)px/g)].map((m) => Number(m[1]));
|
||||
const shadows = [...rule.matchAll(/var\(--foreground\)[^/]*\/ (\d+)px/g)].map((m) => Number(m[1]));
|
||||
expect(covers).toHaveLength(2);
|
||||
expect(Math.min(...covers)).toBeGreaterThan(Math.max(...shadows));
|
||||
});
|
||||
});
|
||||
@@ -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,16 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
|
||||
vi.mock("@/app/lib/clientApi", () => ({ apiPost: vi.fn() }));
|
||||
|
||||
import ForgotPasswordPage from "./page";
|
||||
|
||||
// Every signed-out page shares the login frame (DESIGN.md, Layout).
|
||||
describe("ForgotPasswordPage frame", () => {
|
||||
it("uses the login two-column frame with its title as the page heading", () => {
|
||||
render(<ForgotPasswordPage />);
|
||||
expect(screen.getByText("Everything behind Co-Lite, in one place.")).toBeInTheDocument();
|
||||
expect(screen.getAllByRole("link", { name: "Containerverse Sdn. Bhd." })).toHaveLength(1);
|
||||
expect(screen.getByRole("heading", { level: 1 }).textContent).toBe("Forgot password");
|
||||
});
|
||||
});
|
||||
@@ -4,13 +4,12 @@ import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/app/components/ui/card";
|
||||
import { Input } from "@/app/components/ui/input";
|
||||
import { Label } from "@/app/components/ui/label";
|
||||
import { ErrorState } from "@/app/components/ui/states";
|
||||
import { apiPost } from "@/app/lib/clientApi";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import PoweredBy from "@/app/components/app/PoweredBy";
|
||||
import AuthFrame from "@/app/components/app/AuthFrame";
|
||||
|
||||
// Public "email me a temporary password" form. Whatever happens (match, no match, server or network
|
||||
// failure) the visitor sees the same message, so the page never reveals whether an account exists.
|
||||
@@ -41,49 +40,44 @@ export default function ForgotPasswordPage() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-svh flex-col items-center justify-center gap-4 bg-background p-4">
|
||||
<Card className="w-full max-w-sm">
|
||||
<CardHeader className="gap-2">
|
||||
<CardTitle className="text-lg">{t("ForgotTitle")}</CardTitle>
|
||||
<CardDescription>{t("ForgotIntro")}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{sent ? (
|
||||
<p role="status" className="text-sm">{t("ForgotSent")}</p>
|
||||
) : (
|
||||
<>
|
||||
{required && <ErrorState message={t("ForgotRequired")} />}
|
||||
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="company">{t("Company")}</Label>
|
||||
<Input id="company" autoComplete="organization" placeholder={t("CompanyBlankForSuper")} value={company}
|
||||
onChange={(e) => setCompany(e.target.value)} disabled={submitting} />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="username">{t("Username")}</Label>
|
||||
<Input id="username" autoComplete="username" required value={username}
|
||||
onChange={(e) => setUsername(e.target.value)} disabled={submitting} />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="email">{t("Email")}</Label>
|
||||
<Input id="email" type="email" autoComplete="email" required value={email}
|
||||
onChange={(e) => setEmail(e.target.value)} disabled={submitting} />
|
||||
</div>
|
||||
<Button type="submit" className="w-full" disabled={submitting}>
|
||||
{submitting && <Loader2 aria-hidden="true" className="size-4 animate-spin" />}
|
||||
{t("ForgotSubmit")}
|
||||
</Button>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
<Link href="/login" className="block text-sm text-muted-foreground underline-offset-4 hover:underline">
|
||||
{t("ForgotBack")}
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div className="text-center">
|
||||
<PoweredBy />
|
||||
<AuthFrame>
|
||||
<div className="space-y-2">
|
||||
<h1 className="font-heading text-3xl font-semibold tracking-tight">{t("ForgotTitle")}</h1>
|
||||
<p className="text-muted-foreground">{t("ForgotIntro")}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-5">
|
||||
{sent ? (
|
||||
<p role="status" className="text-sm">{t("ForgotSent")}</p>
|
||||
) : (
|
||||
<>
|
||||
{required && <ErrorState message={t("ForgotRequired")} />}
|
||||
<form onSubmit={handleSubmit} className="space-y-5" noValidate>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="company">{t("Company")}</Label>
|
||||
<Input id="company" autoComplete="organization" placeholder={t("CompanyBlankForSuper")} value={company}
|
||||
onChange={(e) => setCompany(e.target.value)} disabled={submitting} className="h-11 bg-card" />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="username">{t("Username")}</Label>
|
||||
<Input id="username" autoComplete="username" required value={username}
|
||||
onChange={(e) => setUsername(e.target.value)} disabled={submitting} className="h-11 bg-card" />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="email">{t("Email")}</Label>
|
||||
<Input id="email" type="email" autoComplete="email" required value={email}
|
||||
onChange={(e) => setEmail(e.target.value)} disabled={submitting} className="h-11 bg-card" />
|
||||
</div>
|
||||
<Button type="submit" className="h-11 w-full text-base shadow-md" disabled={submitting}>
|
||||
{submitting && <Loader2 aria-hidden="true" className="size-4 animate-spin" />}
|
||||
{t("ForgotSubmit")}
|
||||
</Button>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
<Link href="/login" className="block text-sm text-muted-foreground underline-offset-4 hover:underline">
|
||||
{t("ForgotBack")}
|
||||
</Link>
|
||||
</div>
|
||||
</AuthFrame>
|
||||
);
|
||||
}
|
||||
@@ -75,11 +75,6 @@
|
||||
--table-head: #F1F5F9;
|
||||
--table-head-foreground: #475569;
|
||||
|
||||
/* Giraffe-spot brand pattern (same artwork as the customer portal's --giraffe-motif): a seamless
|
||||
tile of coat patches, shape only — used as a mask by .giraffe-spots below. */
|
||||
--giraffe-tile: 180px;
|
||||
--giraffe-motif: url('data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="180" height="180" viewBox="0 0 180 180"%3E%3Cpath d="M9.1 -0.2Q15.0 -5.6 23.9 -5.3L37.9 -4.9Q46.8 -4.6 50.4 -1.0L56.1 4.7Q59.7 8.4 56.0 18.6L50.2 34.8Q46.6 45.0 37.4 47.5L23.1 51.3Q13.9 53.7 8.9 47.6L0.9 38.0Q-4.1 31.9 -4.7 26.9L-5.6 18.9Q-6.2 13.8 -0.2 8.4ZM9.1 179.8Q15.0 174.4 23.9 174.7L37.9 175.1Q46.8 175.4 50.4 179.0L56.1 184.7Q59.7 188.4 56.0 198.6L50.2 214.8Q46.6 225.0 37.4 227.5L23.1 231.3Q13.9 233.7 8.9 227.6L0.9 218.0Q-4.1 211.9 -4.7 206.9L-5.6 198.9Q-6.2 193.8 -0.2 188.4ZM230.2 34.8Q226.6 45.0 217.4 47.5L203.1 51.3Q193.9 53.7 188.9 47.6L180.9 38.0Q175.9 31.9 175.3 26.9L174.4 18.9Q173.8 13.8 179.8 8.4L189.1 -0.2Q195.0 -5.6 203.9 -5.3L217.9 -4.9Q226.8 -4.6 230.4 -1.0L236.1 4.7Q239.7 8.4 236.0 18.6ZM230.2 214.8Q226.6 225.0 217.4 227.5L203.1 231.3Q193.9 233.7 188.9 227.6L180.9 218.0Q175.9 211.9 175.3 206.9L174.4 198.9Q173.8 193.8 179.8 188.4L189.1 179.8Q195.0 174.4 203.9 174.7L217.9 175.1Q226.8 175.4 230.4 179.0L236.1 184.7Q239.7 188.4 236.0 198.6ZM12.7 70.7Q15.2 58.5 24.3 56.1L38.6 52.3Q47.8 49.9 55.8 57.4L68.3 69.3Q76.4 76.9 70.4 86.7L61.1 102.2Q55.1 112.1 41.5 109.3L20.1 104.8Q6.4 101.9 8.9 89.8ZM49.1 156.8Q45.9 170.4 37.5 170.1L24.4 169.7Q16.0 169.5 11.5 152.7L4.4 126.3Q-0.2 109.5 1.0 108.7L2.9 107.4Q4.0 106.5 18.2 109.5L40.5 114.2Q54.7 117.1 55.4 118.5L56.5 120.6Q57.2 121.9 54.0 135.5ZM229.1 156.8Q225.9 170.4 217.5 170.1L204.4 169.7Q196.0 169.5 191.5 152.7L184.4 126.3Q179.8 109.5 181.0 108.7L182.9 107.4Q184.0 106.5 198.2 109.5L220.5 114.2Q234.7 117.1 235.4 118.5L236.5 120.6Q237.2 121.9 234.0 135.5ZM59.5 54.1Q51.4 46.4 55.0 36.3L60.7 20.3Q64.4 10.2 74.6 9.7L90.7 9.0Q101.0 8.6 103.9 24.4L108.5 49.3Q111.4 65.2 111.2 65.8L110.9 66.8Q110.6 67.4 102.2 69.2L88.8 72.0Q80.3 73.7 72.2 66.1ZM78.1 126.0Q61.6 119.6 61.0 118.3L59.9 116.3Q59.2 115.0 65.4 104.8L75.0 88.8Q81.1 78.7 89.6 76.9L103.0 74.1Q111.5 72.4 119.4 83.5L131.8 100.9Q139.6 112.1 134.2 120.5L125.7 133.8Q120.3 142.3 103.9 135.9ZM74.3 4.7Q63.6 5.2 60.0 1.5L54.3 -4.2Q50.6 -7.9 53.7 -21.1L58.6 -41.8Q61.6 -55.0 77.6 -48.8L102.8 -39.1Q118.8 -32.9 118.7 -27.7L118.6 -19.5Q118.6 -14.2 113.9 -9.3L106.6 -1.4Q101.9 3.5 91.2 4.0ZM74.3 184.7Q63.6 185.2 60.0 181.5L54.3 175.8Q50.6 172.1 53.7 158.9L58.6 138.2Q61.6 125.0 77.6 131.2L102.8 140.9Q118.8 147.1 118.7 152.3L118.6 160.5Q118.6 165.8 113.9 170.7L106.6 178.6Q101.9 183.5 91.2 184.0ZM155.6 7.5Q168.9 14.4 169.4 19.2L170.3 26.8Q170.8 31.6 155.4 40.0L131.2 53.1Q115.8 61.5 113.0 46.2L108.5 22.1Q105.7 6.8 110.2 2.0L117.1 -5.4Q121.6 -10.1 134.8 -3.3ZM155.6 187.5Q168.9 194.4 169.4 199.2L170.3 206.8Q170.8 211.6 155.4 220.0L131.2 233.1Q115.8 241.5 113.0 226.2L108.5 202.1Q105.7 186.8 110.2 182.0L117.1 174.6Q121.6 169.9 134.8 176.7ZM-56.7 80.4Q-64.7 69.2 -64.5 68.6L-64.2 67.7Q-64.0 67.1 -48.1 58.4L-23.0 44.8Q-7.1 36.1 -2.2 42.0L5.4 51.3Q10.3 57.2 7.8 69.8L3.8 89.7Q1.2 102.4 -0.2 103.4L-2.5 105.0Q-3.9 106.0 -13.0 107.0L-27.1 108.4Q-36.2 109.3 -44.1 98.1ZM123.3 80.4Q115.3 69.2 115.5 68.6L115.8 67.7Q116.0 67.1 131.9 58.4L157.0 44.8Q172.9 36.1 177.8 42.0L185.4 51.3Q190.3 57.2 187.8 69.8L183.8 89.7Q181.2 102.4 179.8 103.4L177.5 105.0Q176.1 106.0 167.0 107.0L152.9 108.4Q143.8 109.3 135.9 98.1ZM-13.6 -68.0Q-4.9 -68.9 -0.4 -52.1L6.7 -25.7Q11.2 -8.9 5.5 -3.7L-3.5 4.5Q-9.2 9.8 -22.4 2.9L-43.2 -7.9Q-56.4 -14.7 -56.4 -20.1L-56.2 -28.5Q-56.2 -33.9 -50.5 -42.8L-41.6 -56.8Q-35.9 -65.7 -27.2 -66.6ZM-13.6 112.0Q-4.9 111.1 -0.4 127.9L6.7 154.3Q11.2 171.1 5.5 176.3L-3.5 184.5Q-9.2 189.8 -22.4 182.9L-43.2 172.1Q-56.4 165.3 -56.4 159.9L-56.2 151.5Q-56.2 146.1 -50.5 137.2L-41.6 123.2Q-35.9 114.3 -27.2 113.4ZM166.4 -68.0Q175.1 -68.9 179.6 -52.1L186.7 -25.7Q191.2 -8.9 185.5 -3.7L176.5 4.5Q170.8 9.8 157.6 2.9L136.8 -7.9Q123.6 -14.7 123.6 -20.1L123.8 -28.5Q123.8 -33.9 129.5 -42.8L138.4 -56.8Q144.1 -65.7 152.8 -66.6ZM166.4 112.0Q175.1 111.1 179.6 127.9L186.7 154.3Q191.2 171.1 185.5 176.3L176.5 184.5Q170.8 189.8 157.6 182.9L136.8 172.1Q123.6 165.3 123.6 159.9L123.8 151.5Q123.8 146.1 129.5 137.2L138.4 123.2Q144.1 114.3 152.8 113.4Z"/%3E%3C/svg%3E');
|
||||
|
||||
--sidebar: #FFFFFF;
|
||||
--sidebar-foreground: #0F172A;
|
||||
--sidebar-primary: #2563EB;
|
||||
@@ -190,16 +185,6 @@ h4 {
|
||||
}
|
||||
|
||||
/* every figure, ID and percentage
|
||||
aligns on tabular numerals. */
|
||||
/* The giraffe-spot pattern as a field: the element's background is the patch colour, masked to the
|
||||
coat shape, so whatever is behind shows through the gaps. Recolour with --giraffe-patch, rescale
|
||||
with --giraffe-size. Decorative only; under text only as a faint wash whose contrast is checked. */
|
||||
.giraffe-spots {
|
||||
background-color: var(--giraffe-patch, var(--accent));
|
||||
-webkit-mask-image: var(--giraffe-motif);
|
||||
mask-image: var(--giraffe-motif);
|
||||
-webkit-mask-size: var(--giraffe-size, var(--giraffe-tile)) var(--giraffe-size, var(--giraffe-tile));
|
||||
mask-size: var(--giraffe-size, var(--giraffe-tile)) var(--giraffe-size, var(--giraffe-tile));
|
||||
}
|
||||
|
||||
.tabular {
|
||||
@@ -248,13 +233,15 @@ h4 {
|
||||
}
|
||||
}
|
||||
|
||||
/* Scroll-edge cue: a soft shadow on a side only while more content is scrollable there. */
|
||||
/* Scroll-edge cue: a shadow on a side only while more content is scrollable there. The covers
|
||||
(local) scroll with the content and hide the shadows (scroll) at each end. Covers assume a card
|
||||
backdrop; on the page ground they read as a faint lighter strip. */
|
||||
[data-slot="table-container"] {
|
||||
background:
|
||||
linear-gradient(to right, var(--card) 30%, transparent) left center / 24px 100% no-repeat local,
|
||||
linear-gradient(to left, var(--card) 30%, transparent) right center / 24px 100% no-repeat local,
|
||||
linear-gradient(to right, color-mix(in srgb, var(--foreground) 12%, transparent), transparent) left center / 10px 100% no-repeat scroll,
|
||||
linear-gradient(to left, color-mix(in srgb, var(--foreground) 12%, transparent), transparent) right center / 10px 100% no-repeat scroll;
|
||||
linear-gradient(to right, var(--card) 40%, transparent) left center / 40px 100% no-repeat local,
|
||||
linear-gradient(to left, var(--card) 40%, transparent) right center / 40px 100% no-repeat local,
|
||||
linear-gradient(to right, color-mix(in srgb, var(--foreground) 18%, transparent), transparent) left center / 20px 100% no-repeat scroll,
|
||||
linear-gradient(to left, color-mix(in srgb, var(--foreground) 18%, transparent), transparent) right center / 20px 100% no-repeat scroll;
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
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(() => ({ getInvite: vi.fn(), submitInvite: vi.fn(), inviteCheckin: vi.fn() }));
|
||||
vi.mock("@/app/lib/services/publicInvite", () => mocks);
|
||||
vi.mock("next/navigation", () => ({ useParams: () => ({ token: "inv1" }) }));
|
||||
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import InvitePage from "./page";
|
||||
|
||||
const info = {
|
||||
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: [],
|
||||
guest: { name: "Aini Binti", mobile: "", email: "aini@b.co", companyName: "Acme" }, state: "OPEN",
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.getInvite.mockReset().mockResolvedValue(info);
|
||||
mocks.submitInvite.mockReset().mockResolvedValue({});
|
||||
mocks.inviteCheckin.mockReset().mockResolvedValue({ firstName: "Aini" });
|
||||
});
|
||||
|
||||
const h1s = () => screen.getAllByRole("heading", { level: 1 });
|
||||
|
||||
describe("/i visitor card", () => {
|
||||
it("form shows the invited title as the only h1 with the event header and notice before consent", async () => {
|
||||
render(<InvitePage />);
|
||||
await screen.findByLabelText("Your name");
|
||||
expect(h1s().map((h) => h.textContent)).toEqual(["You're invited to Expo 2026"]);
|
||||
expect(screen.getByText("INS", { selector: "p" })).toBeTruthy();
|
||||
expect(screen.getByText("2026-12-01 - 2026-12-02")).toBeTruthy();
|
||||
expect(screen.getByText("KLCC")).toBeTruthy();
|
||||
const notice = screen.getByText("We keep your data safe.");
|
||||
expect(notice.compareDocumentPosition(screen.getByLabelText(/I agree to INS/)) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(document.querySelectorAll("main").length).toBe(1);
|
||||
});
|
||||
|
||||
it("thank you shows an icon and heading under one h1", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<InvitePage />);
|
||||
await user.click(await screen.findByRole("button", { name: "Register" }));
|
||||
const s = await screen.findByRole("status");
|
||||
expect(s.querySelector("svg")).toBeTruthy();
|
||||
expect(screen.getByRole("heading", { level: 2 }).textContent).toContain("Thank you");
|
||||
expect(h1s().length).toBe(1);
|
||||
});
|
||||
|
||||
it("loading icon spins", () => {
|
||||
mocks.getInvite.mockReturnValue(new Promise(() => {}));
|
||||
render(<InvitePage />);
|
||||
expect(screen.getByRole("status").querySelector("svg")).toHaveClass("motion-safe:animate-spin");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["REGISTERED", "You're already registered for Expo 2026."],
|
||||
["CHECKED_IN", "You're already checked in to Expo 2026."],
|
||||
])("%s invite shows an icon and heading under one h1", async (state, heading) => {
|
||||
mocks.getInvite.mockResolvedValue({ ...info, state });
|
||||
render(<InvitePage />);
|
||||
const s = await screen.findByRole("status");
|
||||
expect(s.querySelector("svg")).toBeTruthy();
|
||||
expect(screen.getByRole("heading", { level: 2 }).textContent).toBe(heading);
|
||||
expect(h1s().map((h) => h.textContent)).toEqual(["Expo 2026"]);
|
||||
});
|
||||
|
||||
it("check-in day offers the button and welcomes with an icon under one h1", async () => {
|
||||
const user = userEvent.setup();
|
||||
mocks.getInvite.mockResolvedValue({ ...info, state: "CHECKIN" });
|
||||
render(<InvitePage />);
|
||||
await user.click(await screen.findByRole("button", { name: "Check in" }));
|
||||
const s = await screen.findByRole("status");
|
||||
expect(s.querySelector("svg")).toBeTruthy();
|
||||
expect(screen.getByRole("heading", { level: 2 }).textContent).toBe("Welcome, Aini. You're checked in.");
|
||||
expect(h1s().map((h) => h.textContent)).toEqual(["Expo 2026"]);
|
||||
});
|
||||
|
||||
it("inactive and error have an alert icon, one h1 and no event details", async () => {
|
||||
mocks.getInvite.mockRejectedValue(new ApiError("x", 404, { code: "INVITE_INACTIVE" }));
|
||||
const { unmount } = render(<InvitePage />);
|
||||
expect((await screen.findByRole("alert")).querySelector("svg")).toBeTruthy();
|
||||
expect(h1s().map((h) => h.textContent)).toEqual(["This invitation is no longer active."]);
|
||||
expect(screen.queryByText("Expo 2026")).toBeNull();
|
||||
unmount();
|
||||
mocks.getInvite.mockRejectedValue(new ApiError("x", 500, {}));
|
||||
render(<InvitePage />);
|
||||
await screen.findByRole("alert");
|
||||
expect(h1s().length).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -33,7 +33,10 @@ describe("/i/[token] invite page", () => {
|
||||
expect((screen.getByLabelText("Company") as HTMLInputElement).value).toBe("Acme");
|
||||
expect(screen.getByText("Data anda selamat.")).toBeTruthy();
|
||||
expect(screen.getByRole("heading", { level: 1 }).textContent).toBe("You're invited to Expo 2026");
|
||||
expect(screen.getByText(/INS \| 2026-12-01 - 2026-12-02 \| KLCC/)).toBeTruthy();
|
||||
// refine-visitor-pages-and-shell: the card header shows company, dates and location on their own lines.
|
||||
expect(screen.getByText("INS")).toBeTruthy();
|
||||
expect(screen.getByText("2026-12-01 - 2026-12-02")).toBeTruthy();
|
||||
expect(screen.getByText("KLCC")).toBeTruthy();
|
||||
expect(screen.getByLabelText(/I agree to INS using my details/).getAttribute("aria-checked")).toBe("false");
|
||||
expect(mocks.getInvite).toHaveBeenCalledWith("inv1");
|
||||
});
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useParams } from "next/navigation";
|
||||
import { AlertCircle, CheckCircle2, Loader2 } from "lucide-react";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { VisitorCard, VisitorState } from "@/app/components/registration/VisitorCard";
|
||||
import { RegistrationForm, apiData, failMessage } from "@/app/components/registration/RegistrationForm";
|
||||
import { getInvite, inviteCheckin, submitInvite, type InviteInfo } from "@/app/lib/services/publicInvite";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
@@ -46,18 +48,19 @@ export default function InvitePage() {
|
||||
}
|
||||
|
||||
const event = info?.eventName ?? "";
|
||||
const done = (text: string) => <VisitorState icon={CheckCircle2} heading={text} role="status" />;
|
||||
if (phase === "loading") return <VisitorCard><VisitorState h1 icon={Loader2} iconClassName="motion-safe:animate-spin" heading={t("UiLoading")} role="status" /></VisitorCard>;
|
||||
if (phase === "inactive") return <VisitorCard><VisitorState h1 icon={AlertCircle} heading={t("InviteInactive")} role="alert" /></VisitorCard>;
|
||||
if (phase === "error" || !info) return <VisitorCard><VisitorState h1 icon={AlertCircle} heading={error ?? t("RegLoadFailed")} role="alert" tone="error" /></VisitorCard>;
|
||||
|
||||
let body;
|
||||
if (phase === "loading") body = <p role="status">{t("UiLoading")}</p>;
|
||||
else if (phase === "inactive") body = <p role="alert">{t("InviteInactive")}</p>;
|
||||
else if (phase === "error" || !info) body = <p role="alert" className="text-sm text-destructive">{error}</p>;
|
||||
else if (welcome !== null) body = <p role="status" className="text-lg font-medium">{welcome ? t("InviteWelcome", { name: welcome }) : t("InviteWelcomeAnon")}</p>;
|
||||
else if (info.state === "CHECKED_IN") body = <p role="status" className="text-lg font-medium">{t("InviteCheckedIn", { event })}</p>;
|
||||
else if (thanks) body = <p role="status" className="text-lg font-medium">{t("RegThanks", { event })}</p>;
|
||||
else if (info.state === "REGISTERED") body = <p role="status" className="text-lg font-medium">{t("InviteRegistered", { event })}</p>;
|
||||
if (welcome !== null) body = done(welcome ? t("InviteWelcome", { name: welcome }) : t("InviteWelcomeAnon"));
|
||||
else if (info.state === "CHECKED_IN") body = done(t("InviteCheckedIn", { event }));
|
||||
else if (thanks) body = done(t("RegThanks", { event }));
|
||||
else if (info.state === "REGISTERED") body = done(t("InviteRegistered", { event }));
|
||||
else if (info.state === "CHECKIN") {
|
||||
body = (
|
||||
<div className="space-y-4">
|
||||
<h1 className="text-2xl font-semibold">{event}</h1>
|
||||
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
|
||||
<Button className="h-11 w-full" onClick={checkIn}>{t("InviteCheckin")}</Button>
|
||||
</div>
|
||||
@@ -66,7 +69,6 @@ export default function InvitePage() {
|
||||
body = (
|
||||
<RegistrationForm
|
||||
info={info}
|
||||
title={t("InviteTitle", { event })}
|
||||
tooManyKey="InviteTooMany"
|
||||
initial={{ name: info.guest.name ?? "", mobile: info.guest.mobile ?? "", email: info.guest.email ?? "", companyName: info.guest.companyName ?? "" }}
|
||||
submit={(b) => submitInvite(token, b)}
|
||||
@@ -76,5 +78,5 @@ export default function InvitePage() {
|
||||
);
|
||||
}
|
||||
|
||||
return <main className="mx-auto w-full max-w-md px-4 py-6">{body}</main>;
|
||||
return <VisitorCard event={info} title={info.state === "OPEN" && welcome === null && !thanks ? t("InviteTitle", { event }) : undefined}>{body}</VisitorCard>;
|
||||
}
|
||||
@@ -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,6 +12,33 @@ export interface SidebarLink {
|
||||
children: SidebarLink[];
|
||||
}
|
||||
|
||||
// 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,11 +86,16 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
HeaderSwitchToDark: "Switch to dark theme",
|
||||
LocaleSwitcherChange: "Change language",
|
||||
SidebarMainNav: "Main",
|
||||
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",
|
||||
@@ -195,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",
|
||||
@@ -293,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",
|
||||
@@ -330,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",
|
||||
@@ -478,6 +515,7 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
RegName: "Your name",
|
||||
RegMobile: "Mobile number",
|
||||
RegEmail: "Email",
|
||||
RegContactHint: "Mobile or email is required",
|
||||
RegCompany: "Company",
|
||||
RegJobTitle: "Job title",
|
||||
RegInterests: "Interests (optional)",
|
||||
@@ -564,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();
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useSyncExternalStore } from "react";
|
||||
import { CalendarDays, Eye, EyeOff, ListChecks, Loader2, UserPlus } from "lucide-react";
|
||||
import { Eye, EyeOff, Loader2 } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
@@ -11,20 +11,13 @@ import { ErrorState } from "@/app/components/ui/states";
|
||||
import { ApiError, apiPost } from "@/app/lib/clientApi";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import PoweredBy from "@/app/components/app/PoweredBy";
|
||||
import AuthFrame from "@/app/components/app/AuthFrame";
|
||||
import { signedInElsewhere } from "@/app/lib/signedInElsewhere";
|
||||
import { safeReturnTo } from "@/app/lib/returnTo";
|
||||
|
||||
/** The marker is read once per render; nothing in the page changes it. */
|
||||
const noSubscription = () => () => {};
|
||||
|
||||
/** What the back office is for, on the brand panel. */
|
||||
const PANEL_POINTS = [
|
||||
{ icon: CalendarDays, code: "BackOfficePanelEvents" },
|
||||
{ icon: UserPlus, code: "BackOfficePanelLeads" },
|
||||
{ icon: ListChecks, code: "BackOfficePanelFollowUps" },
|
||||
] as const;
|
||||
|
||||
// Ported from src/legacy-pages/login/LoginPage.tsx. The hardcoded
|
||||
// services/auth.ts credential check and localStorage session are gone (spec:
|
||||
// "The hardcoded SPA auth is gone"); submit now calls the same-origin
|
||||
@@ -43,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", {
|
||||
@@ -67,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);
|
||||
@@ -74,127 +71,80 @@ export default function LoginPage() {
|
||||
}
|
||||
|
||||
return (
|
||||
// Brand split (feedback 2026-10-23, "make it impactful"): a brand-gold panel with the brown giraffe
|
||||
// coat and the logo on the left from lg, the form on the cream page on the right. Below lg the
|
||||
// panel folds into a compact brand row above the form.
|
||||
<div className="grid min-h-svh bg-background lg:grid-cols-[minmax(0,5fr)_minmax(0,6fr)]">
|
||||
<aside className="relative isolate hidden flex-col justify-between gap-10 overflow-hidden bg-accent p-12 text-accent-foreground lg:flex">
|
||||
{/* Gold ground, brown coat at 14% (owner request: lighter, colours reversed). Dark text still
|
||||
clears AA on a patch: --accent-foreground ≈ 7.0:1 (8.4:1 on plain gold). In dark mode
|
||||
--primary turns light gold, so the coat and the chips switch to --accent-foreground, which
|
||||
stays dark brown; the logo inverts to white on its dark plate. */}
|
||||
<span aria-hidden="true" className="giraffe-spots absolute inset-0 -z-10 opacity-[0.14] [--giraffe-patch:var(--primary)] dark:[--giraffe-patch:var(--accent-foreground)]" />
|
||||
<div className="flex items-center gap-4">
|
||||
<span className="rounded-full bg-primary px-3 py-1 text-sm font-semibold text-primary-foreground dark:bg-accent-foreground dark:text-accent">
|
||||
{t("BackOfficeLabel")}
|
||||
</span>
|
||||
<AuthFrame>
|
||||
<div className="space-y-2">
|
||||
<h1 className="font-heading text-3xl font-semibold tracking-tight">{t("BackOfficeTitle")}</h1>
|
||||
<p className="text-muted-foreground">{t("BackOfficeSubtitle")}</p>
|
||||
</div>
|
||||
|
||||
{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">
|
||||
<Label htmlFor="company">{t("Company")}</Label>
|
||||
<Input
|
||||
id="company"
|
||||
type="text"
|
||||
autoComplete="organization"
|
||||
placeholder={t("CompanyBlankForSuper")}
|
||||
value={company}
|
||||
onChange={(e) => setCompany(e.target.value)}
|
||||
disabled={submitting}
|
||||
className="h-11 bg-card"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="max-w-md space-y-8">
|
||||
<p className="font-heading text-4xl leading-tight font-semibold tracking-tight text-balance">
|
||||
{t("BackOfficePanelTitle")}
|
||||
</p>
|
||||
<ul className="space-y-4">
|
||||
{PANEL_POINTS.map(({ icon: PointIcon, code }) => (
|
||||
<li key={code} className="flex items-center gap-3 text-base font-medium">
|
||||
<span className="flex size-10 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground dark:bg-accent-foreground dark:text-accent">
|
||||
<PointIcon aria-hidden="true" className="size-5" />
|
||||
</span>
|
||||
{t(code)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="username">{t("Username")}</Label>
|
||||
<Input
|
||||
id="username"
|
||||
type="text"
|
||||
autoComplete="username"
|
||||
required
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
disabled={submitting}
|
||||
className="h-11 bg-card"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<span aria-hidden="true" />
|
||||
</aside>
|
||||
|
||||
<main className="flex flex-col items-center justify-center gap-8 p-6 sm:p-10">
|
||||
<div className="w-full max-w-sm space-y-8">
|
||||
{/* Below lg a short brand band stands in for the panel: same brown, coat and logo. */}
|
||||
<div className="relative isolate flex items-center gap-3 overflow-hidden rounded-2xl bg-accent p-4 lg:hidden">
|
||||
<span aria-hidden="true" className="giraffe-spots absolute inset-0 -z-10 opacity-[0.14] [--giraffe-patch:var(--primary)] dark:[--giraffe-patch:var(--accent-foreground)]" />
|
||||
<span className="rounded-full bg-primary px-3 py-1 text-xs font-semibold text-primary-foreground dark:bg-accent-foreground dark:text-accent">
|
||||
{t("BackOfficeLabel")}
|
||||
</span>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="password">{t("Password")}</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="password"
|
||||
type={showPassword ? "text" : "password"}
|
||||
autoComplete="current-password"
|
||||
required
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
disabled={submitting}
|
||||
className="h-11 bg-card pr-11"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword((v) => !v)}
|
||||
aria-label={showPassword ? t("LoginHidePassword") : t("LoginShowPassword")}
|
||||
className="absolute top-1/2 right-1 flex size-9 -translate-y-1/2 cursor-pointer items-center justify-center rounded-full text-muted-foreground transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
|
||||
>
|
||||
{showPassword ? (
|
||||
<EyeOff aria-hidden="true" className="size-4" />
|
||||
) : (
|
||||
<Eye aria-hidden="true" className="size-4" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<h1 className="font-heading text-3xl font-semibold tracking-tight">{t("BackOfficeTitle")}</h1>
|
||||
<p className="text-muted-foreground">{t("BackOfficeSubtitle")}</p>
|
||||
</div>
|
||||
|
||||
{error ? <ErrorState message={t(error)} /> : elsewhere && <ErrorState message={t("SignedInElsewhere")} />}
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-5" noValidate>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="company">{t("Company")}</Label>
|
||||
<Input
|
||||
id="company"
|
||||
type="text"
|
||||
autoComplete="organization"
|
||||
placeholder={t("CompanyBlankForSuper")}
|
||||
value={company}
|
||||
onChange={(e) => setCompany(e.target.value)}
|
||||
disabled={submitting}
|
||||
className="h-11 bg-card"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="username">{t("Username")}</Label>
|
||||
<Input
|
||||
id="username"
|
||||
type="text"
|
||||
autoComplete="username"
|
||||
required
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
disabled={submitting}
|
||||
className="h-11 bg-card"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="password">{t("Password")}</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="password"
|
||||
type={showPassword ? "text" : "password"}
|
||||
autoComplete="current-password"
|
||||
required
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
disabled={submitting}
|
||||
className="h-11 bg-card pr-11"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword((v) => !v)}
|
||||
aria-label={showPassword ? t("LoginHidePassword") : t("LoginShowPassword")}
|
||||
className="absolute top-1/2 right-1 flex size-9 -translate-y-1/2 cursor-pointer items-center justify-center rounded-full text-muted-foreground transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
|
||||
>
|
||||
{showPassword ? (
|
||||
<EyeOff aria-hidden="true" className="size-4" />
|
||||
) : (
|
||||
<Eye aria-hidden="true" className="size-4" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Link href="/forgot-password" className="block text-sm text-muted-foreground underline-offset-4 hover:underline">
|
||||
{t("ForgotLink")}
|
||||
</Link>
|
||||
|
||||
<Button type="submit" className="h-11 w-full text-base shadow-md" disabled={submitting}>
|
||||
{submitting && <Loader2 aria-hidden="true" className="size-4 animate-spin" />}
|
||||
{t("LogIn")}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
<PoweredBy />
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<Link href="/forgot-password" className="block text-sm text-muted-foreground underline-offset-4 hover:underline">
|
||||
{t("ForgotLink")}
|
||||
</Link>
|
||||
|
||||
<Button type="submit" className="h-11 w-full text-base shadow-md" disabled={submitting}>
|
||||
{submitting && <Loader2 aria-hidden="true" className="size-4 animate-spin" />}
|
||||
{t("LogIn")}
|
||||
</Button>
|
||||
</form>
|
||||
</AuthFrame>
|
||||
);
|
||||
}
|
||||
Loaded 100 of 151 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user