From 8ce9fcf4710acd2f087c9652f7593a1473b25cd5 Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 02:59:44 +0800 Subject: [PATCH] feat: portal password hints, company hint, interest and role delete, dashboard notes - Login: company-code hint after an invalid-credentials failure with an empty company. - Password forms show the active rules (label-first, count-safe) and tie hint and refusal to the input. - Interests and roles: soft delete with confirm dialogs; deactivate now confirms too. - Dashboard figure explanations. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../changes/polish-e2e-followups/tasks.md | 2 +- .../api/interests/[id]/route.delete.test.ts | 31 ++++++ .../app/api/interests/[id]/route.ts | 9 ++ .../app/api/password-rules/route.test.ts | 26 +++++ .../app/api/password-rules/route.ts | 12 +++ .../api/public/password-rules/route.test.ts | 25 +++++ .../app/api/public/password-rules/route.ts | 4 + .../app/api/roles/[id]/route.delete.test.ts | 31 ++++++ .../app/api/roles/[id]/route.ts | 9 ++ .../app/companies/page.cancel.test.tsx | 37 +++++++ solvway-admin-portal/app/companies/page.tsx | 6 ++ .../components/app/ChangePasswordDialog.tsx | 8 +- .../components/dashboard/LeadDashboard.tsx | 10 +- .../app/components/ui/confirm-dialog.tsx | 36 +++++++ .../app/components/ui/states.tsx | 8 +- .../app/components/users/PasswordFields.tsx | 9 +- .../users/PasswordRulesHint.test.tsx | 64 +++++++++++ .../components/users/PasswordRulesHint.tsx | 52 +++++++++ .../components/users/SetPasswordButton.tsx | 9 +- .../app/components/users/UserForm.tsx | 5 +- .../app/interests/page.delete.test.tsx | 101 ++++++++++++++++++ .../app/interests/page.test.tsx | 2 + solvway-admin-portal/app/interests/page.tsx | 56 +++++++--- .../app/lib/i18n/defaultMessages.ts | 33 +++++- .../lib/server/mobileApi.problemProps.test.ts | 33 ++++++ .../app/lib/server/mobileApi.ts | 20 ++-- .../app/lib/services/adminInterests.ts | 4 +- .../app/lib/services/adminRoles.ts | 4 +- .../app/login/page.companyHint.test.tsx | 65 +++++++++++ solvway-admin-portal/app/login/page.tsx | 6 +- .../app/page.dashboard.lines.test.tsx | 37 +++++++ .../app/reset-password/page.rules.test.tsx | 60 +++++++++++ .../app/reset-password/page.test.tsx | 6 +- .../app/reset-password/page.tsx | 13 ++- .../app/roles/page.delete.test.tsx | 97 +++++++++++++++++ solvway-admin-portal/app/roles/page.tsx | 49 ++++++++- 36 files changed, 934 insertions(+), 45 deletions(-) create mode 100644 solvway-admin-portal/app/api/interests/[id]/route.delete.test.ts create mode 100644 solvway-admin-portal/app/api/password-rules/route.test.ts create mode 100644 solvway-admin-portal/app/api/password-rules/route.ts create mode 100644 solvway-admin-portal/app/api/public/password-rules/route.test.ts create mode 100644 solvway-admin-portal/app/api/public/password-rules/route.ts create mode 100644 solvway-admin-portal/app/api/roles/[id]/route.delete.test.ts create mode 100644 solvway-admin-portal/app/companies/page.cancel.test.tsx create mode 100644 solvway-admin-portal/app/components/ui/confirm-dialog.tsx create mode 100644 solvway-admin-portal/app/components/users/PasswordRulesHint.test.tsx create mode 100644 solvway-admin-portal/app/components/users/PasswordRulesHint.tsx create mode 100644 solvway-admin-portal/app/interests/page.delete.test.tsx create mode 100644 solvway-admin-portal/app/lib/server/mobileApi.problemProps.test.ts create mode 100644 solvway-admin-portal/app/login/page.companyHint.test.tsx create mode 100644 solvway-admin-portal/app/page.dashboard.lines.test.tsx create mode 100644 solvway-admin-portal/app/reset-password/page.rules.test.tsx create mode 100644 solvway-admin-portal/app/roles/page.delete.test.tsx diff --git a/openspec/changes/polish-e2e-followups/tasks.md b/openspec/changes/polish-e2e-followups/tasks.md index 18acb3b..01c597a 100644 --- a/openspec/changes/polish-e2e-followups/tasks.md +++ b/openspec/changes/polish-e2e-followups/tasks.md @@ -24,7 +24,7 @@ Verify commands: - 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` -- [ ] 4. Portal behaviour: +- [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; diff --git a/solvway-admin-portal/app/api/interests/[id]/route.delete.test.ts b/solvway-admin-portal/app/api/interests/[id]/route.delete.test.ts new file mode 100644 index 0000000..c0cdde6 --- /dev/null +++ b/solvway-admin-portal/app/api/interests/[id]/route.delete.test.ts @@ -0,0 +1,31 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); +vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); +vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); + +import { DELETE } from "./route"; + +const call = () => DELETE(new Request("http://localhost/api/interests/7", { method: "DELETE" }) as never, { params: Promise.resolve({ id: "7" }) }); + +beforeEach(() => { + mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: undefined }); + mocks.getToken.mockReset().mockResolvedValue("tok"); +}); + +describe("DELETE /api/interests/[id]", () => { + it("is 401 without a session", async () => { + mocks.getToken.mockResolvedValue(null); + expect((await call()).status).toBe(401); + }); + + it("deletes upstream and answers ok", async () => { + expect((await call()).status).toBe(200); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/interests/7", { method: "DELETE", token: "tok" }); + }); + + it("passes the upstream refusal through", async () => { + mocks.callMobileApi.mockResolvedValue({ ok: false, error: "x", status: 404 }); + expect((await call()).status).toBe(404); + }); +}); diff --git a/solvway-admin-portal/app/api/interests/[id]/route.ts b/solvway-admin-portal/app/api/interests/[id]/route.ts index b06b8d7..5dd07ca 100644 --- a/solvway-admin-portal/app/api/interests/[id]/route.ts +++ b/solvway-admin-portal/app/api/interests/[id]/route.ts @@ -33,3 +33,12 @@ export async function PUT(req: NextRequest, { params }: Ctx) { if (!result.ok) return errorResponse(result); return NextResponse.json(result.data); } + +export async function DELETE(_req: NextRequest, { params }: Ctx) { + const token = await getToken(); + if (!token) return unauthorized(); + const { id } = await params; + const result = await callMobileApi(`/api/admin/interests/${encodeURIComponent(id)}`, { method: "DELETE", token }); + if (!result.ok) return errorResponse(result); + return NextResponse.json({ ok: true }); +} diff --git a/solvway-admin-portal/app/api/password-rules/route.test.ts b/solvway-admin-portal/app/api/password-rules/route.test.ts new file mode 100644 index 0000000..e60a865 --- /dev/null +++ b/solvway-admin-portal/app/api/password-rules/route.test.ts @@ -0,0 +1,26 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); +vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); +vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); + +import { GET } from "./route"; + +beforeEach(() => { + mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: [{ param: "NO_OTHER_LANGUAGE", value: null }] }); + mocks.getToken.mockReset().mockResolvedValue("tok"); +}); + +describe("GET /api/password-rules", () => { + it("is 401 without a session", async () => { + mocks.getToken.mockResolvedValue(null); + expect((await GET()).status).toBe(401); + expect(mocks.callMobileApi).not.toHaveBeenCalled(); + }); + + it("returns the active rules from the admin endpoint", async () => { + const res = await GET(); + expect(await res.json()).toEqual([{ param: "NO_OTHER_LANGUAGE", value: null }]); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/password-rules/active", { token: "tok" }); + }); +}); diff --git a/solvway-admin-portal/app/api/password-rules/route.ts b/solvway-admin-portal/app/api/password-rules/route.ts new file mode 100644 index 0000000..01bdca4 --- /dev/null +++ b/solvway-admin-portal/app/api/password-rules/route.ts @@ -0,0 +1,12 @@ +import { NextResponse } from "next/server"; +import { callMobileApi } from "@/app/lib/server/mobileApi"; +import { getToken } from "@/app/lib/server/session"; +import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; + +export async function GET() { + const token = await getToken(); + if (!token) return unauthorized(); + const result = await callMobileApi("/api/admin/password-rules/active", { token }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} diff --git a/solvway-admin-portal/app/api/public/password-rules/route.test.ts b/solvway-admin-portal/app/api/public/password-rules/route.test.ts new file mode 100644 index 0000000..25824fb --- /dev/null +++ b/solvway-admin-portal/app/api/public/password-rules/route.test.ts @@ -0,0 +1,25 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn() })); +vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); + +import { GET } from "./route"; + +type Req = Parameters[0]; +const req = (init: RequestInit = {}) => new Request("http://localhost/api/public/password-rules", init) as unknown as Req; + +beforeEach(() => mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: [{ param: "INPUT_LENGTH_MIN", value: 8 }] })); + +describe("/api/public/password-rules", () => { + it("forwards without a session, with only the last-hop visitor IP, and returns the rules", async () => { + const res = await GET(req({ headers: { "x-forwarded-for": "6.6.6.6, 203.0.113.7" } })); + expect(res.status).toBe(200); + expect(await res.json()).toEqual([{ param: "INPUT_LENGTH_MIN", value: 8 }]); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/public/password-rules", { headers: { "X-Forwarded-For": "203.0.113.7" } }); + }); + + it("passes upstream failures with their status", async () => { + mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Too many requests", status: 429 }); + expect((await GET(req())).status).toBe(429); + }); +}); diff --git a/solvway-admin-portal/app/api/public/password-rules/route.ts b/solvway-admin-portal/app/api/public/password-rules/route.ts new file mode 100644 index 0000000..704fa1b --- /dev/null +++ b/solvway-admin-portal/app/api/public/password-rules/route.ts @@ -0,0 +1,4 @@ +import type { NextRequest } from "next/server"; +import { forwardPublic } from "@/app/lib/server/publicProxy"; + +export const GET = (req: NextRequest) => forwardPublic(req, "/api/public/password-rules", "GET"); diff --git a/solvway-admin-portal/app/api/roles/[id]/route.delete.test.ts b/solvway-admin-portal/app/api/roles/[id]/route.delete.test.ts new file mode 100644 index 0000000..ac95889 --- /dev/null +++ b/solvway-admin-portal/app/api/roles/[id]/route.delete.test.ts @@ -0,0 +1,31 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); +vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); +vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); + +import { DELETE } from "./route"; + +const call = () => DELETE(new Request("http://localhost/api/roles/7", { method: "DELETE" }) as never, { params: Promise.resolve({ id: "7" }) }); + +beforeEach(() => { + mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: undefined }); + mocks.getToken.mockReset().mockResolvedValue("tok"); +}); + +describe("DELETE /api/roles/[id]", () => { + it("is 401 without a session", async () => { + mocks.getToken.mockResolvedValue(null); + expect((await call()).status).toBe(401); + }); + + it("deletes upstream and answers ok", async () => { + expect((await call()).status).toBe(200); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/roles/7", { method: "DELETE", token: "tok" }); + }); + + it("passes the upstream refusal through", async () => { + mocks.callMobileApi.mockResolvedValue({ ok: false, error: "x", status: 404 }); + expect((await call()).status).toBe(404); + }); +}); diff --git a/solvway-admin-portal/app/api/roles/[id]/route.ts b/solvway-admin-portal/app/api/roles/[id]/route.ts index 2a413d6..f239daf 100644 --- a/solvway-admin-portal/app/api/roles/[id]/route.ts +++ b/solvway-admin-portal/app/api/roles/[id]/route.ts @@ -33,3 +33,12 @@ export async function PUT(req: NextRequest, { params }: Ctx) { if (!result.ok) return errorResponse(result); return NextResponse.json(result.data); } + +export async function DELETE(_req: NextRequest, { params }: Ctx) { + const token = await getToken(); + if (!token) return unauthorized(); + const { id } = await params; + const result = await callMobileApi(`/api/admin/roles/${encodeURIComponent(id)}`, { method: "DELETE", token }); + if (!result.ok) return errorResponse(result); + return NextResponse.json({ ok: true }); +} diff --git a/solvway-admin-portal/app/companies/page.cancel.test.tsx b/solvway-admin-portal/app/companies/page.cancel.test.tsx new file mode 100644 index 0000000..25b28f3 --- /dev/null +++ b/solvway-admin-portal/app/companies/page.cancel.test.tsx @@ -0,0 +1,37 @@ +import { render, screen, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), getPrivacyNotice: vi.fn(), savePrivacyNotice: vi.fn() })); +vi.mock("@/app/lib/clientApi", async (importOriginal) => ({ + ApiError: (await importOriginal()).ApiError, + apiGet: mocks.apiGet, + apiPost: mocks.apiPost, +})); +vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ loading: false, isSuper: true }) })); +vi.mock("@/app/lib/services/adminRegistration", () => ({ + getPrivacyNotice: mocks.getPrivacyNotice, + savePrivacyNotice: mocks.savePrivacyNotice, +})); + +import CompaniesPage from "./page"; + +beforeEach(() => { + mocks.apiGet.mockReset().mockResolvedValue([{ id: 1, name: "Insight", code: "ins", status: "A" }]); + mocks.apiPost.mockReset(); + mocks.getPrivacyNotice.mockReset().mockResolvedValue(null); + mocks.savePrivacyNotice.mockReset(); +}); + +describe.each(["Edit", "Change code", "Privacy notice"])("Companies %s dialog", (action) => { + it("Cancel closes it without saving", async () => { + render(); + const row = (await screen.findByText("Insight")).closest("tr")!; + await userEvent.click(within(row).getByRole("button", { name: action })); + const dialog = await screen.findByRole("dialog"); + await userEvent.click(within(dialog).getByRole("button", { name: "Cancel" })); + expect(screen.queryByRole("dialog")).toBeNull(); + expect(mocks.apiPost).not.toHaveBeenCalled(); + expect(mocks.savePrivacyNotice).not.toHaveBeenCalled(); + }); +}); diff --git a/solvway-admin-portal/app/companies/page.tsx b/solvway-admin-portal/app/companies/page.tsx index 1cd3340..1daa15b 100644 --- a/solvway-admin-portal/app/companies/page.tsx +++ b/solvway-admin-portal/app/companies/page.tsx @@ -103,6 +103,9 @@ function CompanyDialog({ state, onClose, onSaved }: { state: DialogState; onClos )} + @@ -170,6 +173,9 @@ function PrivacyNoticeDialog({ company, onClose }: { company: AdminCompany; onCl

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

{t("DashFunnelNote")}

+
    {funnelRows.map(([key, label]) => { diff --git a/solvway-admin-portal/app/components/ui/confirm-dialog.tsx b/solvway-admin-portal/app/components/ui/confirm-dialog.tsx new file mode 100644 index 0000000..fa353d8 --- /dev/null +++ b/solvway-admin-portal/app/components/ui/confirm-dialog.tsx @@ -0,0 +1,36 @@ +"use client"; + +import { Button } from "@/app/components/ui/button"; +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog"; +import { useT } from "@/app/lib/i18n/MessagesProvider"; + +/** Cancel / confirm prompt; `onConfirm` is the caller's job to close it (it decides what stays open on failure). */ +export function ConfirmDialog(props: { + title: string; + message: string; + confirmLabel: string; + destructive?: boolean; + busy?: boolean; + onConfirm: () => void; + onCancel: () => void; +}) { + const t = useT(); + return ( + !open && props.onCancel()}> + + + {props.title} + {props.message} + + + + + + + + ); +} diff --git a/solvway-admin-portal/app/components/ui/states.tsx b/solvway-admin-portal/app/components/ui/states.tsx index 77de151..95c2546 100644 --- a/solvway-admin-portal/app/components/ui/states.tsx +++ b/solvway-admin-portal/app/components/ui/states.tsx @@ -37,10 +37,13 @@ export function EmptyState({ export function ErrorState({ message, + hint, onRetry, className, }: { message: string + /** A second, muted line under the message. */ + hint?: string onRetry?: () => void className?: string }) { @@ -61,7 +64,10 @@ export function ErrorState({ >
    {onRetry && ( @@ -137,12 +143,14 @@ function InterestFormDialog({ function InterestsPageContent() { const t = useT(); - const readOnly = useAdminAuth().isSuper === false; // super-admin-only writes; server returns 403 anyway + const { isSuper } = useAdminAuth(); + const readOnly = isSuper === false; // super-admin-only writes; server returns 403 anyway const [interests, setInterests] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [reloadKey, setReloadKey] = useState(0); const [dialog, setDialog] = useState(null); + const [confirm, setConfirm] = useState<{ kind: "delete" | "deactivate"; item: AdminInterestEntity } | null>(null); const refetch = useCallback(() => setReloadKey((k) => k + 1), []); @@ -206,18 +214,7 @@ function InterestsPageContent() { {t("Edit")} {row.original.active ? ( - ) : ( @@ -236,13 +233,31 @@ function InterestsPageContent() { {t("IntActivate")} )} + {isSuper === true && ( + + )}
), }]), ], - [t, refetch, readOnly], + [t, refetch, readOnly, isSuper], ); + async function runConfirmed() { + if (!confirm) return; + const { kind, item } = confirm; + setConfirm(null); + try { + if (kind === "delete") await deleteAdminInterest(item.id!); + else await saveAdminInterest({ id: item.id, active: false }); + refetch(); + } catch { + setError(kind === "delete" ? "IntDeleteFailed" : "IntDeactivateFailed"); + } + } + return ( <> } /> + {confirm && ( + setConfirm(null)} + /> + )} + {dialog && ( setDialog(null)} onSaved={refetch} /> )} diff --git a/solvway-admin-portal/app/lib/i18n/defaultMessages.ts b/solvway-admin-portal/app/lib/i18n/defaultMessages.ts index d9988b1..d45f7ff 100644 --- a/solvway-admin-portal/app/lib/i18n/defaultMessages.ts +++ b/solvway-admin-portal/app/lib/i18n/defaultMessages.ts @@ -199,7 +199,22 @@ export const DEFAULT_MESSAGES: Record = { UsrSetPasswordSubmit: "Set password", UsrSetPasswordFailed: "Failed to set the password.", UsrTempPasswordSet: "Temporary password set. The user must change it at next sign-in.", - AdminPasswordHint: "At least 8 characters, with at least one capital letter and one small letter.", + PwdHint_ALPHABET_LENGTH_MIN: "Letters: at least {n}", + PwdHint_ALPHABET_LENGTH_MAX: "Letters: at most {n}", + PwdHint_NUMERIC_LENGTH_MIN: "Digits: at least {n}", + PwdHint_NUMERIC_LENGTH_MAX: "Digits: at most {n}", + PwdHint_UPPERCASE_LENGTH_MIN: "Capital letters: at least {n}", + PwdHint_UPPERCASE_LENGTH_MAX: "Capital letters: at most {n}", + PwdHint_LOWERCASE_LENGTH_MIN: "Small letters: at least {n}", + PwdHint_LOWERCASE_LENGTH_MAX: "Small letters: at most {n}", + PwdHint_SYMBOLIC_LENGTH_MIN: "Symbols: at least {n}", + PwdHint_SYMBOLIC_LENGTH_MAX: "Symbols: at most {n}", + PwdHint_INPUT_LENGTH_MIN: "Length: at least {n}", + PwdHint_INPUT_LENGTH_MAX: "Length: at most {n}", + PwdHint_NO_OTHER_LANGUAGE: "English letters only", + PwdHint_SPACE_NOT_ALLOWED: "No spaces", + PwdRuleRefused: 'Password does not meet the rule "{rule}"', + LoginStaffCompanyHint: "Staff sign in with their company code.", UiDatePlaceholder: "DD/MM/YYYY", UiOpenCalendarFor: "Open calendar for {label}", UiOpenCalendar: "Open calendar", @@ -297,6 +312,22 @@ export const DEFAULT_MESSAGES: Record = { IntDeactivate: "Deactivate", IntActivateFailed: "Failed to activate interest.", IntDeactivateFailed: "Failed to deactivate interest.", + IntDelete: "Delete", + IntDeleteTitle: "Delete interest", + IntDeleteConfirm: "Delete \"{name}\"? It disappears from the list and can no longer be chosen.", + IntDeleteFailed: "Failed to delete interest.", + IntDeactivateTitle: "Deactivate interest", + IntDeactivateConfirm: "Deactivate \"{name}\"? It can no longer be chosen until activated again.", + IntNameDeleted: "This name belongs to a deleted interest.", + RolDelete: "Delete", + RolDeleteTitle: "Delete role", + RolDeleteConfirm: "Delete role \"{name}\"?", + RolDeleteFailed: "Failed to delete role.", + RolInUse: "Users holding this role: {n}. Remove it from them first.", + RolProtected: "This role is built in and cannot be deleted.", + RolNameDeleted: "This name belongs to a deleted role.", + DashWonInPeriodNote: "Leads won in this period, whenever they were captured.", + DashFunnelNote: "This period's captures, by their current stage.", // Event leads messages BO_EVENT_LEADS: "Event leads", LeadName: "Name", diff --git a/solvway-admin-portal/app/lib/server/mobileApi.problemProps.test.ts b/solvway-admin-portal/app/lib/server/mobileApi.problemProps.test.ts new file mode 100644 index 0000000..7d1dd2f --- /dev/null +++ b/solvway-admin-portal/app/lib/server/mobileApi.problemProps.test.ts @@ -0,0 +1,33 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { callMobileApi } from "./mobileApi"; + +let fetchMock: ReturnType; +const fail = (body: unknown) => + fetchMock.mockResolvedValue({ ok: false, status: 400, text: async () => JSON.stringify(body) } as Response); + +beforeEach(() => { + vi.stubEnv("MOBILE_API_BASE_URL", "https://mobile.example.test"); + vi.stubEnv("MOBILE_API_KEY", "k"); + fetchMock = vi.fn(); + vi.stubGlobal("fetch", fetchMock); +}); +afterEach(() => { + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); +}); + +describe("callMobileApi — ProblemDetail properties", () => { + it("surfaces param, value and users as details", async () => { + fail({ detail: "PASSWORD_RULE", code: "PASSWORD_RULE", param: "INPUT_LENGTH_MIN", value: 8 }); + expect(await callMobileApi("/x", { token: "t" })).toMatchObject({ code: "PASSWORD_RULE", details: { param: "INPUT_LENGTH_MIN", value: 8 } }); + fail({ detail: "ROLE_IN_USE", code: "ROLE_IN_USE", users: 3 }); + expect(await callMobileApi("/x", { token: "t" })).toMatchObject({ code: "ROLE_IN_USE", details: { users: 3 } }); + }); + + it("omits a null value (flag rules)", async () => { + fail({ detail: "PASSWORD_RULE", code: "PASSWORD_RULE", param: "SPACE_NOT_ALLOWED", value: null }); + const r = await callMobileApi("/x", { token: "t" }); + expect(r).toMatchObject({ details: { param: "SPACE_NOT_ALLOWED" } }); + expect((r as { details: object }).details).not.toHaveProperty("value"); + }); +}); diff --git a/solvway-admin-portal/app/lib/server/mobileApi.ts b/solvway-admin-portal/app/lib/server/mobileApi.ts index 0915463..ac67f59 100644 --- a/solvway-admin-portal/app/lib/server/mobileApi.ts +++ b/solvway-admin-portal/app/lib/server/mobileApi.ts @@ -29,16 +29,24 @@ function isExpiredSignal(status: number, raw: string): boolean { ); } -/** An upstream `details` object, kept only when it is a flat object of string/number/boolean values. */ +/** + * An upstream `details` object, kept only when it is a flat object of string/number/boolean values, + * plus the scalar problem properties the portal turns into messages (`param`, `value`, `users`). + */ function extractDetails(parsed: unknown): Record | undefined { if (!parsed || typeof parsed !== "object") return undefined; - const details = (parsed as { details?: unknown }).details; - if (!details || typeof details !== "object" || Array.isArray(details)) return undefined; - const values = Object.values(details as Record); - const scalar = values.every(v => typeof v === "string" || typeof v === "number" || typeof v === "boolean"); - return scalar ? (details as Record) : undefined; + const o = parsed as Record; + const details = o.details; + const base = details && typeof details === "object" && !Array.isArray(details) ? (details as Record) : undefined; + if (base && !Object.values(base).every(isScalar)) return undefined; + const props: Record = {}; + for (const k of ["param", "value", "users"]) if (isScalar(o[k])) props[k] = o[k]; + const merged = { ...props, ...base }; + return Object.keys(merged).length ? (merged as Record) : undefined; } +const isScalar = (v: unknown) => typeof v === "string" || typeof v === "number" || typeof v === "boolean"; + function extractError(parsed: unknown): string | undefined { if (parsed && typeof parsed === "object") { const o = parsed as Record; diff --git a/solvway-admin-portal/app/lib/services/adminInterests.ts b/solvway-admin-portal/app/lib/services/adminInterests.ts index 6dd0a1e..86d4ee0 100644 --- a/solvway-admin-portal/app/lib/services/adminInterests.ts +++ b/solvway-admin-portal/app/lib/services/adminInterests.ts @@ -1,4 +1,4 @@ -import { apiGet, apiPost, apiPut } from "@/app/lib/clientApi"; +import { apiGet, apiPost, apiPut, apiDelete } from "@/app/lib/clientApi"; import type { AdminInterestEntity } from "@/app/lib/types"; export async function listAdminInterests(): Promise { @@ -10,3 +10,5 @@ export async function saveAdminInterest(payload: AdminInterestEntity): Promise(`/api/interests/${payload.id}`, payload) : apiPost("/api/interests", payload); } + +export const deleteAdminInterest = (id: number) => apiDelete(`/api/interests/${id}`); diff --git a/solvway-admin-portal/app/lib/services/adminRoles.ts b/solvway-admin-portal/app/lib/services/adminRoles.ts index 3bbd0d7..87dfcee 100644 --- a/solvway-admin-portal/app/lib/services/adminRoles.ts +++ b/solvway-admin-portal/app/lib/services/adminRoles.ts @@ -1,4 +1,4 @@ -import { apiGet, apiPost, apiPut } from "@/app/lib/clientApi"; +import { apiGet, apiPost, apiPut, apiDelete } from "@/app/lib/clientApi"; import type { AdminRoleEntity } from "@/app/lib/types"; export async function listAdminRoles(): Promise { @@ -14,3 +14,5 @@ export async function saveAdminRole(payload: AdminRoleEntity): Promise(`/api/roles/${payload.id}`, payload) : apiPost("/api/roles", payload); } + +export const deleteAdminRole = (id: number) => apiDelete(`/api/roles/${id}`); diff --git a/solvway-admin-portal/app/login/page.companyHint.test.tsx b/solvway-admin-portal/app/login/page.companyHint.test.tsx new file mode 100644 index 0000000..bd57c50 --- /dev/null +++ b/solvway-admin-portal/app/login/page.companyHint.test.tsx @@ -0,0 +1,65 @@ +import { render, screen, waitFor, fireEvent } from "@testing-library/react"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }) })); +vi.mock("@/app/lib/clientApi", () => ({ + apiPost: vi.fn(), + ApiError: class ApiError extends Error { + constructor(m: string, public status = 0, public data?: unknown) { + super(m); + } + }, +})); +vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ refresh: vi.fn() }) })); + +import LoginPage from "./page"; +import { apiPost, ApiError } from "@/app/lib/clientApi"; + +const mockPost = apiPost as unknown as ReturnType; +const HINT = "Staff sign in with their company code."; + +function submit(username: string, company = "") { + fireEvent.change(screen.getByLabelText("Company"), { target: { value: company } }); + fireEvent.change(screen.getByLabelText("Username"), { target: { value: username } }); + fireEvent.change(screen.getByLabelText("Password"), { target: { value: "x" } }); + fireEvent.submit(screen.getByRole("button", { name: /log in/i })); +} + +beforeEach(() => { + mockPost.mockReset().mockRejectedValue(new ApiError("LoginInvalidCredentials", 401)); +}); + +describe("LoginPage company hint", () => { + it("adds the company-code hint to a failed sign-in with no company", async () => { + render(); + submit("staff1"); + const alert = await screen.findByRole("alert"); + expect(alert).toHaveTextContent("Invalid"); + expect(alert).toHaveTextContent(HINT); + }); + + it("shows the same text for an unknown username and a staff username", async () => { + const { unmount } = render(); + submit("nobody"); + const unknown = (await screen.findByRole("alert")).textContent; + unmount(); + render(); + submit("staff1"); + expect((await screen.findByRole("alert")).textContent).toBe(unknown); + }); + + it.each([0, 429, 500])("does not add the hint when the failure is HTTP %i, not bad credentials", async (status) => { + mockPost.mockRejectedValue(new ApiError("Something went wrong", status)); + render(); + submit("staff1"); + await waitFor(() => expect(screen.getByRole("alert")).toBeInTheDocument()); + expect(screen.queryByText(HINT)).toBeNull(); + }); + + it("does not add the hint when a company was typed", async () => { + render(); + submit("staff1", "ins"); + await waitFor(() => expect(screen.getByRole("alert")).toBeInTheDocument()); + expect(screen.queryByText(HINT)).toBeNull(); + }); +}); diff --git a/solvway-admin-portal/app/login/page.tsx b/solvway-admin-portal/app/login/page.tsx index 6ade404..a61c087 100644 --- a/solvway-admin-portal/app/login/page.tsx +++ b/solvway-admin-portal/app/login/page.tsx @@ -36,10 +36,12 @@ export default function LoginPage() { // Read after hydration (the server renders without it), so server and client markup agree. const elsewhere = useSyncExternalStore(noSubscription, () => signedInElsewhere(document.cookie), () => false); const [submitting, setSubmitting] = useState(false); + const [companyHint, setCompanyHint] = useState(false); async function handleSubmit(event: React.FormEvent) { event.preventDefault(); setError(null); + setCompanyHint(false); setSubmitting(true); try { const res = await apiPost<{ name: string; resetPasswordRequired: boolean }>("/api/auth/login", { @@ -60,6 +62,8 @@ export default function LoginPage() { router.refresh(); } catch (err) { const locked = err instanceof ApiError && (err.data as { code?: unknown } | undefined)?.code === "ACCOUNT_LOCKED"; + // From form state only, so an unknown username and a staff user without a company read the same. + setCompanyHint(err instanceof ApiError && err.status === 401 && !locked && !company.trim()); setError(locked ? "LoginAccountLocked" : err instanceof Error ? err.message : "LoginInvalidCredentials"); } finally { setSubmitting(false); @@ -73,7 +77,7 @@ export default function LoginPage() {

{t("BackOfficeSubtitle")}

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

{t("AdminPasswordHint")}

+ + {ruleError && }
diff --git a/solvway-admin-portal/app/roles/page.delete.test.tsx b/solvway-admin-portal/app/roles/page.delete.test.tsx new file mode 100644 index 0000000..810a132 --- /dev/null +++ b/solvway-admin-portal/app/roles/page.delete.test.tsx @@ -0,0 +1,97 @@ +import { render, screen, waitFor, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ list: vi.fn(), apiPost: vi.fn(), apiPut: vi.fn(), apiDelete: vi.fn(), useAdminAuth: vi.fn() })); +vi.mock("@/app/lib/clientApi", async (importOriginal) => ({ + ApiError: (await importOriginal()).ApiError, + apiGet: vi.fn(), + apiPost: mocks.apiPost, + apiPut: mocks.apiPut, + apiDelete: mocks.apiDelete, +})); +vi.mock("@/app/lib/services/adminRoles", async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, listAdminRoles: mocks.list }; +}); +vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth })); + +import RolesPage from "./page"; +import { ApiError } from "@/app/lib/clientApi"; + +const ROWS = [ + { id: 1, name: "ROLE_SUPER_ADMIN" }, + { id: 4, name: "ROLE_HQ", parent: { id: 1 } }, +]; + +beforeEach(() => { + mocks.list.mockReset().mockResolvedValue(ROWS); + mocks.apiPost.mockReset(); + mocks.apiPut.mockReset(); + mocks.apiDelete.mockReset().mockResolvedValue({}); + mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true, hasModule: () => true }); +}); + +const rowOf = async (code: string) => (await screen.findByText(code)).closest("tr")!; +const openDelete = async () => userEvent.click(within(await rowOf("ROLE_HQ")).getByRole("button", { name: "Delete" })); + +describe("Roles delete", () => { + it("deletes after confirming", async () => { + render(); + await openDelete(); + expect(mocks.apiDelete).not.toHaveBeenCalled(); + await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Delete" })); + await waitFor(() => expect(mocks.apiDelete).toHaveBeenCalledWith("/api/roles/4")); + }); + + it("cancel closes the confirmation without deleting", async () => { + render(); + await openDelete(); + await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Cancel" })); + expect(screen.queryByRole("dialog")).toBeNull(); + expect(mocks.apiDelete).not.toHaveBeenCalled(); + }); + + it("names how many users hold a role that is in use", async () => { + mocks.apiDelete.mockRejectedValue(new ApiError("ROLE_IN_USE", 409, { code: "ROLE_IN_USE", details: { users: 3 } })); + render(); + await openDelete(); + await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Delete" })); + expect(await screen.findByText("Users holding this role: 3. Remove it from them first.")).toBeInTheDocument(); + }); + + it("styles the row Delete as destructive-outline", async () => { + render(); + expect(within(await rowOf("ROLE_HQ")).getByRole("button", { name: "Delete" })).toHaveAttribute("data-variant", "destructive-outline"); + }); + + it("offers no Delete on a protected role, and none to non-super staff", async () => { + render(); + expect(within(await rowOf("ROLE_SUPER_ADMIN")).queryByRole("button", { name: "Delete" })).toBeNull(); + expect(within(await rowOf("ROLE_HQ")).getByRole("button", { name: "Delete" })).toBeInTheDocument(); + }); + + it("hides Delete from staff who are not super admins", async () => { + mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper: false, hasModule: () => true }); + render(); + await screen.findByText("ROLE_HQ"); + expect(screen.queryByRole("button", { name: "Delete" })).toBeNull(); + }); + + it("says a role name belongs to a deleted role", async () => { + mocks.apiPost.mockRejectedValue(new ApiError("ROLE_NAME_DELETED", 409, { error: "ROLE_NAME_DELETED", code: "ROLE_NAME_DELETED" })); + render(); + await userEvent.click(await screen.findByRole("button", { name: /add role/i })); + await userEvent.type(screen.getByLabelText(/role name/i), "ROLE_OLD"); + await userEvent.click(screen.getByRole("button", { name: "Save" })); + expect(await screen.findByText("This name belongs to a deleted role.")).toBeInTheDocument(); + }); + + it("Cancel in the add dialog closes it without saving", async () => { + render(); + await userEvent.click(await screen.findByRole("button", { name: /add role/i })); + await userEvent.click(screen.getByRole("button", { name: "Cancel" })); + expect(screen.queryByLabelText(/role name/i)).toBeNull(); + expect(mocks.apiPost).not.toHaveBeenCalled(); + }); +}); diff --git a/solvway-admin-portal/app/roles/page.tsx b/solvway-admin-portal/app/roles/page.tsx index ae7c3c5..9bb9444 100644 --- a/solvway-admin-portal/app/roles/page.tsx +++ b/solvway-admin-portal/app/roles/page.tsx @@ -7,6 +7,7 @@ import { useAdminAuth } from "@/app/lib/AdminAuthContext"; import { Button } from "@/app/components/ui/button"; import { Input } from "@/app/components/ui/input"; import { Label } from "@/app/components/ui/label"; +import { ConfirmDialog } from "@/app/components/ui/confirm-dialog"; import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog"; import { DataTable } from "@/app/components/ui/data-table"; import { sortRows } from "@/app/components/ui/sortable-head"; @@ -14,7 +15,7 @@ import { PageHeader } from "@/app/components/ui/page-header"; import { EmptyState, ErrorState } from "@/app/components/ui/states"; import { RequireModule } from "@/app/lib/RequireModule"; import { roleLabel } from "@/app/lib/roleLabel"; -import { listAdminRoles, saveAdminRole } from "@/app/lib/services/adminRoles"; +import { deleteAdminRole, listAdminRoles, saveAdminRole } from "@/app/lib/services/adminRoles"; import type { AdminRoleEntity } from "@/app/lib/types"; import { useT } from "@/app/lib/i18n/MessagesProvider"; @@ -23,6 +24,9 @@ interface FormState { name: string; } +// ponytail: mirrors the server list (ROLE_PROTECTED); a role flag from the API would replace it. +const PROTECTED_ROLES = ["ROLE_SUPER_ADMIN", "ROLE_ADMIN", "ROLE_MEMBER"]; + const EMPTY_FORM: FormState = { name: "" }; function RoleFormDialog({ @@ -52,7 +56,8 @@ function RoleFormDialog({ onSaved(); onClose(); } catch (err) { - setError(err instanceof Error ? err.message : "RolSaveFailed"); + const code = (err as { data?: { code?: string } }).data?.code; + setError(code === "ROLE_NAME_DELETED" ? "RolNameDeleted" : err instanceof Error ? err.message : "RolSaveFailed"); } finally { setSaving(false); } @@ -77,6 +82,9 @@ function RoleFormDialog({ />
+ @@ -89,13 +97,15 @@ function RoleFormDialog({ function RolesPageContent() { const t = useT(); - const readOnly = useAdminAuth().isSuper === false; // super-admin-only writes; server returns 403 anyway + const { isSuper } = useAdminAuth(); + const readOnly = isSuper === false; // super-admin-only writes; server returns 403 anyway const [roles, setRoles] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [reloadKey, setReloadKey] = useState(0); const [sorting, setSorting] = useState([]); const [dialog, setDialog] = useState(null); + const [confirmDelete, setConfirmDelete] = useState(null); const refetch = useCallback(() => setReloadKey((k) => k + 1), []); @@ -165,13 +175,33 @@ function RolesPageContent() {
+ {isSuper === true && !PROTECTED_ROLES.includes(row.original.name) && ( + + )}
), }]), ], - [parentLabel, t, readOnly], + [parentLabel, t, readOnly, isSuper], ); + async function runDelete() { + if (!confirmDelete) return; + const role = confirmDelete; + setConfirmDelete(null); + try { + await deleteAdminRole(role.id!); + refetch(); + } catch (err) { + const data = (err as { data?: { code?: string; details?: { users?: number } } }).data; + if (data?.code === "ROLE_IN_USE") setError(t("RolInUse", { n: data.details?.users ?? 0 })); + else if (data?.code === "ROLE_PROTECTED") setError("RolProtected"); + else setError("RolDeleteFailed"); + } + } + return ( <> } /> + {confirmDelete && ( + setConfirmDelete(null)} + /> + )} + {dialog && ( setDialog(null)} onSaved={refetch} /> )}