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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
1 parent
5e68478670
commit
8ce9fcf471
36 files changed
+934
-45
No files matched your search
@@ -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;
|
||||
|
||||
@@ -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,37 @@
|
||||
import { render, screen, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), getPrivacyNotice: vi.fn(), savePrivacyNotice: vi.fn() }));
|
||||
vi.mock("@/app/lib/clientApi", async (importOriginal) => ({
|
||||
ApiError: (await importOriginal<typeof import("@/app/lib/clientApi")>()).ApiError,
|
||||
apiGet: mocks.apiGet,
|
||||
apiPost: mocks.apiPost,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ loading: false, isSuper: true }) }));
|
||||
vi.mock("@/app/lib/services/adminRegistration", () => ({
|
||||
getPrivacyNotice: mocks.getPrivacyNotice,
|
||||
savePrivacyNotice: mocks.savePrivacyNotice,
|
||||
}));
|
||||
|
||||
import CompaniesPage from "./page";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.apiGet.mockReset().mockResolvedValue([{ id: 1, name: "Insight", code: "ins", status: "A" }]);
|
||||
mocks.apiPost.mockReset();
|
||||
mocks.getPrivacyNotice.mockReset().mockResolvedValue(null);
|
||||
mocks.savePrivacyNotice.mockReset();
|
||||
});
|
||||
|
||||
describe.each(["Edit", "Change code", "Privacy notice"])("Companies %s dialog", (action) => {
|
||||
it("Cancel closes it without saving", async () => {
|
||||
render(<CompaniesPage />);
|
||||
const row = (await screen.findByText("Insight")).closest("tr")!;
|
||||
await userEvent.click(within(row).getByRole("button", { name: action }));
|
||||
const dialog = await screen.findByRole("dialog");
|
||||
await userEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
|
||||
expect(screen.queryByRole("dialog")).toBeNull();
|
||||
expect(mocks.apiPost).not.toHaveBeenCalled();
|
||||
expect(mocks.savePrivacyNotice).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -103,6 +103,9 @@ function CompanyDialog({ state, onClose, onSaved }: { state: DialogState; onClos
|
||||
</>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button type="submit" disabled={saving}>
|
||||
{mode === "code" ? t("CompConfirm") : t("Save")}
|
||||
</Button>
|
||||
@@ -170,6 +173,9 @@ function PrivacyNoticeDialog({ company, onClose }: { company: AdminCompany; onCl
|
||||
</p>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button type="submit" disabled={saving}>
|
||||
{t("PrivSave")}
|
||||
</Button>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "
|
||||
import { Input } from "@/app/components/ui/input";
|
||||
import { Label } from "@/app/components/ui/label";
|
||||
import { PasswordFields } from "@/app/components/users/PasswordFields";
|
||||
import { passwordRuleError } from "@/app/components/users/PasswordRulesHint";
|
||||
import { changeOwnPassword } from "@/app/lib/services/adminUsers";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
@@ -17,6 +18,7 @@ export default function ChangePasswordDialog({ onClose, onDone }: { onClose: ()
|
||||
const [confirmPassword, setConfirmPassword] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [ruleError, setRuleError] = useState<string | undefined>();
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
@@ -24,12 +26,15 @@ export default function ChangePasswordDialog({ onClose, onDone }: { onClose: ()
|
||||
if (password !== confirmPassword) return setError("UsrPasswordMismatch");
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
setRuleError(undefined);
|
||||
try {
|
||||
await changeOwnPassword(current, password, confirmPassword);
|
||||
onClose();
|
||||
onDone();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "PwdChangeRequired");
|
||||
const rule = passwordRuleError(err, t);
|
||||
if (rule) setRuleError(rule);
|
||||
else setError(err instanceof Error ? err.message : "PwdChangeRequired");
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
@@ -59,6 +64,7 @@ export default function ChangePasswordDialog({ onClose, onDone }: { onClose: ()
|
||||
onPassword={setPassword}
|
||||
onConfirmPassword={setConfirmPassword}
|
||||
disabled={saving}
|
||||
passwordError={ruleError}
|
||||
/>
|
||||
{error && (
|
||||
<div role="alert" className="rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">
|
||||
|
||||
@@ -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,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>
|
||||
);
|
||||
}
|
||||
@@ -37,10 +37,13 @@ export function EmptyState({
|
||||
|
||||
export function ErrorState({
|
||||
message,
|
||||
hint,
|
||||
onRetry,
|
||||
className,
|
||||
}: {
|
||||
message: string
|
||||
/** A second, muted line under the message. */
|
||||
hint?: string
|
||||
onRetry?: () => void
|
||||
className?: string
|
||||
}) {
|
||||
@@ -61,7 +64,10 @@ export function ErrorState({
|
||||
>
|
||||
<div className="flex items-start gap-2">
|
||||
<AlertCircle aria-hidden="true" className="mt-0.5 size-4 shrink-0 text-destructive" />
|
||||
<p className="text-sm text-foreground">{message}</p>
|
||||
<div>
|
||||
<p className="text-sm text-foreground">{message}</p>
|
||||
{hint && <p className="text-sm text-muted-foreground">{hint}</p>}
|
||||
</div>
|
||||
</div>
|
||||
{onRetry && (
|
||||
<Button variant="outline" size="sm" onClick={onRetry} className="h-9">
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Input } from "@/app/components/ui/input";
|
||||
import { Label } from "@/app/components/ui/label";
|
||||
import { PasswordRulesHint } from "./PasswordRulesHint";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
/** Password + confirmation inputs shared by the create form and "Set temporary password". */
|
||||
@@ -17,6 +19,7 @@ export function PasswordFields(props: {
|
||||
passwordLabel?: string;
|
||||
}) {
|
||||
const t = useT();
|
||||
const [hintShown, setHintShown] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<div className="space-y-1.5">
|
||||
@@ -29,10 +32,10 @@ export function PasswordFields(props: {
|
||||
onChange={(e) => props.onPassword(e.target.value)}
|
||||
disabled={props.disabled}
|
||||
aria-invalid={!!props.passwordError}
|
||||
aria-describedby="user-password-hint"
|
||||
aria-describedby={[hintShown && "user-password-hint", props.passwordError && "user-password-error"].filter(Boolean).join(" ") || undefined}
|
||||
/>
|
||||
<p id="user-password-hint" className="text-sm text-muted-foreground">{t("AdminPasswordHint")}</p>
|
||||
{props.passwordError && <p role="alert" className="text-sm text-destructive">{props.passwordError}</p>}
|
||||
<PasswordRulesHint source="admin" id="user-password-hint" onShown={setHintShown} />
|
||||
{props.passwordError && <p id="user-password-error" role="alert" className="text-sm text-destructive">{props.passwordError}</p>}
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="user-confirm-password">{t("UsrConfirmPassword")}</Label>
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), changeOwnPassword: vi.fn() }));
|
||||
vi.mock("@/app/lib/clientApi", async (importOriginal) => ({
|
||||
ApiError: (await importOriginal<typeof import("@/app/lib/clientApi")>()).ApiError,
|
||||
apiGet: mocks.apiGet,
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminUsers", () => ({ changeOwnPassword: mocks.changeOwnPassword }));
|
||||
|
||||
import { PasswordRulesHint } from "./PasswordRulesHint";
|
||||
import ChangePasswordDialog from "@/app/components/app/ChangePasswordDialog";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
const RULES = [
|
||||
{ param: "INPUT_LENGTH_MIN", value: 8 },
|
||||
{ param: "UPPERCASE_LENGTH_MIN", value: 1 },
|
||||
{ param: "SPACE_NOT_ALLOWED", value: null },
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.apiGet.mockReset().mockResolvedValue(RULES);
|
||||
mocks.changeOwnPassword.mockReset();
|
||||
});
|
||||
|
||||
describe("PasswordRulesHint", () => {
|
||||
it("lists only the switched-on rules, with their numbers", async () => {
|
||||
render(<PasswordRulesHint source="admin" />);
|
||||
expect(await screen.findByText("Length: at least 8")).toBeInTheDocument();
|
||||
expect(screen.getByText("Capital letters: at least 1")).toBeInTheDocument();
|
||||
expect(screen.getByText("No spaces")).toBeInTheDocument();
|
||||
expect(screen.getAllByRole("listitem")).toHaveLength(3);
|
||||
expect(screen.queryByText(/symbol/i)).toBeNull();
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/password-rules");
|
||||
});
|
||||
|
||||
it("reads the public route on the signed-out page", async () => {
|
||||
render(<PasswordRulesHint source="public" />);
|
||||
await screen.findByText("No spaces");
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/public/password-rules");
|
||||
});
|
||||
|
||||
it("shows nothing when the rules fail to load", async () => {
|
||||
mocks.apiGet.mockRejectedValue(new Error("down"));
|
||||
const { container } = render(<PasswordRulesHint source="admin" />);
|
||||
await waitFor(() => expect(mocks.apiGet).toHaveBeenCalled());
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
});
|
||||
});
|
||||
|
||||
describe("PASSWORD_RULE refusal", () => {
|
||||
it("names the broken rule at the password field of the change-password dialog", async () => {
|
||||
mocks.changeOwnPassword.mockRejectedValue(
|
||||
new ApiError("PASSWORD_RULE", 400, { error: "PASSWORD_RULE", code: "PASSWORD_RULE", details: { param: "UPPERCASE_LENGTH_MIN", value: 1 } }),
|
||||
);
|
||||
render(<ChangePasswordDialog onClose={() => {}} onDone={() => {}} />);
|
||||
await userEvent.type(screen.getByLabelText("Current password"), "old");
|
||||
await userEvent.type(screen.getByLabelText("New password"), "abcdefgh");
|
||||
await userEvent.type(screen.getByLabelText("Confirm password"), "abcdefgh");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Change password" }));
|
||||
expect(await screen.findByText('Password does not meet the rule "Capital letters: at least 1"')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { ApiError, apiGet } from "@/app/lib/clientApi";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
type Rule = { param: string; value: number | null };
|
||||
type Translate = ReturnType<typeof useT>;
|
||||
|
||||
const sentence = (t: Translate, param: string, value: unknown) => t(`PwdHint_${param}`, { n: value == null ? "" : String(value) });
|
||||
|
||||
/**
|
||||
* The refusal text when the API answered 400 PASSWORD_RULE, else null.
|
||||
* ponytail: relies on the BFF forwarding `param`/`value` in details (mobileApi.extractDetails).
|
||||
*/
|
||||
export function passwordRuleError(err: unknown, t: Translate): string | null {
|
||||
const data = err instanceof ApiError ? (err.data as { code?: string; details?: { param?: string; value?: unknown } } | undefined) : undefined;
|
||||
if (data?.code !== "PASSWORD_RULE" || !data.details?.param) return null;
|
||||
return t("PwdRuleRefused", { rule: sentence(t, data.details.param, data.details.value) });
|
||||
}
|
||||
|
||||
/** The switched-on password rules as a short list; shows nothing while loading or if they cannot be loaded. */
|
||||
export function PasswordRulesHint({ source, id, onShown }: { source: "admin" | "public"; id?: string; onShown?: (shown: boolean) => void }) {
|
||||
const t = useT();
|
||||
const [rules, setRules] = useState<Rule[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const loaded = await apiGet<Rule[]>(source === "admin" ? "/api/password-rules" : "/api/public/password-rules");
|
||||
if (!cancelled && Array.isArray(loaded)) setRules(loaded);
|
||||
} catch {
|
||||
// no banner: the hint is optional, a refusal still names the rule
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [source]);
|
||||
|
||||
useEffect(() => onShown?.(rules.length > 0), [rules.length, onShown]);
|
||||
|
||||
if (!rules.length) return null;
|
||||
return (
|
||||
<ul id={id} className="list-disc pl-5 text-sm text-muted-foreground">
|
||||
{rules.map((r) => (
|
||||
<li key={r.param}>{sentence(t, r.param, r.value)}</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "
|
||||
import { setAdminUserPassword } from "@/app/lib/services/adminUsers";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { PasswordFields } from "./PasswordFields";
|
||||
import { passwordRuleError } from "./PasswordRulesHint";
|
||||
|
||||
/** "Set temporary password" on the user edit page: the admin types it; the user must change it at next sign-in. */
|
||||
export function SetPasswordButton({ userId, onDone }: { userId: number; onDone: () => void }) {
|
||||
@@ -15,6 +16,7 @@ export function SetPasswordButton({ userId, onDone }: { userId: number; onDone:
|
||||
const [confirmPassword, setConfirmPassword] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [ruleError, setRuleError] = useState<string | undefined>();
|
||||
|
||||
function close() {
|
||||
// The password lives only in this state; clear it whenever the dialog closes.
|
||||
@@ -22,6 +24,7 @@ export function SetPasswordButton({ userId, onDone }: { userId: number; onDone:
|
||||
setPassword("");
|
||||
setConfirmPassword("");
|
||||
setError(null);
|
||||
setRuleError(undefined);
|
||||
}
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
@@ -30,12 +33,15 @@ export function SetPasswordButton({ userId, onDone }: { userId: number; onDone:
|
||||
if (password !== confirmPassword) return setError("UsrPasswordMismatch");
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
setRuleError(undefined);
|
||||
try {
|
||||
await setAdminUserPassword(userId, password, confirmPassword);
|
||||
close();
|
||||
onDone();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "UsrSetPasswordFailed");
|
||||
const rule = passwordRuleError(err, t);
|
||||
if (rule) setRuleError(rule);
|
||||
else setError(err instanceof Error ? err.message : "UsrSetPasswordFailed");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -60,6 +66,7 @@ export function SetPasswordButton({ userId, onDone }: { userId: number; onDone:
|
||||
onPassword={setPassword}
|
||||
onConfirmPassword={setConfirmPassword}
|
||||
disabled={saving}
|
||||
passwordError={ruleError}
|
||||
/>
|
||||
{error && (
|
||||
<div role="alert" className="rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">
|
||||
|
||||
@@ -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
|
||||
@@ -147,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);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
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("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,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<AdminInterestEntity[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = 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 +214,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>
|
||||
) : (
|
||||
@@ -236,13 +233,31 @@ function InterestsPageContent() {
|
||||
{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);
|
||||
try {
|
||||
if (kind === "delete") await deleteAdminInterest(item.id!);
|
||||
else await saveAdminInterest({ id: item.id, active: false });
|
||||
refetch();
|
||||
} catch {
|
||||
setError(kind === "delete" ? "IntDeleteFailed" : "IntDeactivateFailed");
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
@@ -270,6 +285,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} />
|
||||
)}
|
||||
|
||||
@@ -199,7 +199,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",
|
||||
@@ -297,6 +312,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",
|
||||
|
||||
@@ -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>;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { apiGet, apiPost, apiPut } from "@/app/lib/clientApi";
|
||||
import { apiGet, apiPost, apiPut, apiDelete } from "@/app/lib/clientApi";
|
||||
import type { AdminInterestEntity } from "@/app/lib/types";
|
||||
|
||||
export async function listAdminInterests(): Promise<AdminInterestEntity[]> {
|
||||
@@ -10,3 +10,5 @@ export async function saveAdminInterest(payload: AdminInterestEntity): Promise<A
|
||||
? apiPut<AdminInterestEntity>(`/api/interests/${payload.id}`, payload)
|
||||
: apiPost<AdminInterestEntity>("/api/interests", payload);
|
||||
}
|
||||
|
||||
export const deleteAdminInterest = (id: number) => apiDelete<unknown>(`/api/interests/${id}`);
|
||||
@@ -1,4 +1,4 @@
|
||||
import { apiGet, apiPost, apiPut } from "@/app/lib/clientApi";
|
||||
import { apiGet, apiPost, apiPut, apiDelete } from "@/app/lib/clientApi";
|
||||
import type { AdminRoleEntity } from "@/app/lib/types";
|
||||
|
||||
export async function listAdminRoles(): Promise<AdminRoleEntity[]> {
|
||||
@@ -14,3 +14,5 @@ export async function saveAdminRole(payload: AdminRoleEntity): Promise<AdminRole
|
||||
? apiPut<AdminRoleEntity>(`/api/roles/${payload.id}`, payload)
|
||||
: apiPost<AdminRoleEntity>("/api/roles", payload);
|
||||
}
|
||||
|
||||
export const deleteAdminRole = (id: number) => apiDelete<unknown>(`/api/roles/${id}`);
|
||||
@@ -0,0 +1,65 @@
|
||||
import { render, screen, waitFor, fireEvent } from "@testing-library/react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }) }));
|
||||
vi.mock("@/app/lib/clientApi", () => ({
|
||||
apiPost: vi.fn(),
|
||||
ApiError: class ApiError extends Error {
|
||||
constructor(m: string, public status = 0, public data?: unknown) {
|
||||
super(m);
|
||||
}
|
||||
},
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ refresh: vi.fn() }) }));
|
||||
|
||||
import LoginPage from "./page";
|
||||
import { apiPost, ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
const mockPost = apiPost as unknown as ReturnType<typeof vi.fn>;
|
||||
const HINT = "Staff sign in with their company code.";
|
||||
|
||||
function submit(username: string, company = "") {
|
||||
fireEvent.change(screen.getByLabelText("Company"), { target: { value: company } });
|
||||
fireEvent.change(screen.getByLabelText("Username"), { target: { value: username } });
|
||||
fireEvent.change(screen.getByLabelText("Password"), { target: { value: "x" } });
|
||||
fireEvent.submit(screen.getByRole("button", { name: /log in/i }));
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockPost.mockReset().mockRejectedValue(new ApiError("LoginInvalidCredentials", 401));
|
||||
});
|
||||
|
||||
describe("LoginPage company hint", () => {
|
||||
it("adds the company-code hint to a failed sign-in with no company", async () => {
|
||||
render(<LoginPage />);
|
||||
submit("staff1");
|
||||
const alert = await screen.findByRole("alert");
|
||||
expect(alert).toHaveTextContent("Invalid");
|
||||
expect(alert).toHaveTextContent(HINT);
|
||||
});
|
||||
|
||||
it("shows the same text for an unknown username and a staff username", async () => {
|
||||
const { unmount } = render(<LoginPage />);
|
||||
submit("nobody");
|
||||
const unknown = (await screen.findByRole("alert")).textContent;
|
||||
unmount();
|
||||
render(<LoginPage />);
|
||||
submit("staff1");
|
||||
expect((await screen.findByRole("alert")).textContent).toBe(unknown);
|
||||
});
|
||||
|
||||
it.each([0, 429, 500])("does not add the hint when the failure is HTTP %i, not bad credentials", async (status) => {
|
||||
mockPost.mockRejectedValue(new ApiError("Something went wrong", status));
|
||||
render(<LoginPage />);
|
||||
submit("staff1");
|
||||
await waitFor(() => expect(screen.getByRole("alert")).toBeInTheDocument());
|
||||
expect(screen.queryByText(HINT)).toBeNull();
|
||||
});
|
||||
|
||||
it("does not add the hint when a company was typed", async () => {
|
||||
render(<LoginPage />);
|
||||
submit("staff1", "ins");
|
||||
await waitFor(() => expect(screen.getByRole("alert")).toBeInTheDocument());
|
||||
expect(screen.queryByText(HINT)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -36,10 +36,12 @@ export default function LoginPage() {
|
||||
// Read after hydration (the server renders without it), so server and client markup agree.
|
||||
const elsewhere = useSyncExternalStore(noSubscription, () => signedInElsewhere(document.cookie), () => false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [companyHint, setCompanyHint] = useState(false);
|
||||
|
||||
async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
setCompanyHint(false);
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const res = await apiPost<{ name: string; resetPasswordRequired: boolean }>("/api/auth/login", {
|
||||
@@ -60,6 +62,8 @@ export default function LoginPage() {
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
const locked = err instanceof ApiError && (err.data as { code?: unknown } | undefined)?.code === "ACCOUNT_LOCKED";
|
||||
// From form state only, so an unknown username and a staff user without a company read the same.
|
||||
setCompanyHint(err instanceof ApiError && err.status === 401 && !locked && !company.trim());
|
||||
setError(locked ? "LoginAccountLocked" : err instanceof Error ? err.message : "LoginInvalidCredentials");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
@@ -73,7 +77,7 @@ export default function LoginPage() {
|
||||
<p className="text-muted-foreground">{t("BackOfficeSubtitle")}</p>
|
||||
</div>
|
||||
|
||||
{error ? <ErrorState message={t(error)} /> : elsewhere && <ErrorState message={t("SignedInElsewhere")} />}
|
||||
{error ? <ErrorState message={t(error)} hint={companyHint ? t("LoginStaffCompanyHint") : undefined} /> : elsewhere && <ErrorState message={t("SignedInElsewhere")} />}
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-5" noValidate>
|
||||
<div className="space-y-1.5">
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { render, screen, within } from "@testing-library/react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ getLeadDashboard: vi.fn(), useAdminAuth: vi.fn(), useCompanyScope: vi.fn() }));
|
||||
vi.mock("@/app/lib/services/adminDashboard", () => ({ getLeadDashboard: mocks.getLeadDashboard }));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope }));
|
||||
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
||||
|
||||
import HomePage from "./page";
|
||||
|
||||
const DATA = {
|
||||
from: "2026-12-01", to: "2026-12-01", bucket: "DAY",
|
||||
captures: 40, newLeads: 25, wonInPeriod: 8, medianDaysToWin: 4.5, overdueFollowUps: 3,
|
||||
funnel: { OPEN: 11, CONTACTED: 12, QUALIFIED: 13, WON: 8, LOST: 6 },
|
||||
trend: [], events: [], salespeople: [], interests: [],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.getLeadDashboard.mockReset().mockResolvedValue(DATA);
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ name: "Alice", loading: false, isSuper: false, hasModule: (m: string) => m === "BO_DASHBOARD" });
|
||||
mocks.useCompanyScope.mockReset().mockReturnValue({ companyId: undefined, companies: [], showCompanyColumn: false, codeOf: () => "", setCompanyId: vi.fn() });
|
||||
});
|
||||
|
||||
describe("dashboard explanation lines", () => {
|
||||
it("explains Won in period as visible text inside its tile", async () => {
|
||||
render(<HomePage />);
|
||||
const tile = within(await screen.findByRole("group", { name: "Won in period" }));
|
||||
expect(tile.getByText("Leads won in this period, whenever they were captured.")).toBeVisible();
|
||||
});
|
||||
|
||||
it("explains the funnel as visible text", async () => {
|
||||
render(<HomePage />);
|
||||
await screen.findByRole("group", { name: "Captures" });
|
||||
expect(screen.getByText("This period's captures, by their current stage.")).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,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<typeof import("@/app/lib/clientApi")>()).ApiError,
|
||||
apiGet: vi.fn(),
|
||||
apiPost: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ refresh: vi.fn() }) }));
|
||||
|
||||
import ResetPasswordPage from "./page";
|
||||
import { apiGet, apiPost, ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
const get = apiGet as unknown as ReturnType<typeof vi.fn>;
|
||||
const post = apiPost as unknown as ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
get.mockReset().mockResolvedValue([{ param: "INPUT_LENGTH_MIN", value: 10 }, { param: "SPACE_NOT_ALLOWED", value: null }]);
|
||||
post.mockReset();
|
||||
});
|
||||
|
||||
describe("ResetPasswordPage rules", () => {
|
||||
it("lists the switched-on rules from the public route", async () => {
|
||||
render(<ResetPasswordPage />);
|
||||
expect(await screen.findByText("Length: at least 10")).toBeInTheDocument();
|
||||
expect(screen.getByText("No spaces")).toBeInTheDocument();
|
||||
expect(get).toHaveBeenCalledWith("/api/public/password-rules");
|
||||
});
|
||||
|
||||
it("ties the hint and the refusal to the password input with aria-describedby", async () => {
|
||||
post.mockRejectedValue(new ApiError("PASSWORD_RULE", 400, { code: "PASSWORD_RULE", details: { param: "INPUT_LENGTH_MIN", value: 10 } }));
|
||||
render(<ResetPasswordPage />);
|
||||
await screen.findByText("No spaces");
|
||||
const input = screen.getByLabelText("New password");
|
||||
expect(input.getAttribute("aria-describedby")).toBe("newPasswordRules");
|
||||
fireEvent.change(input, { target: { value: "Short1" } });
|
||||
fireEvent.change(screen.getByLabelText("Confirm new password"), { target: { value: "Short1" } });
|
||||
fireEvent.submit(screen.getByRole("button", { name: /set password/i }));
|
||||
const alert = await screen.findByRole("alert");
|
||||
expect(input.getAttribute("aria-describedby")).toBe(`newPasswordRules ${alert.id}`);
|
||||
});
|
||||
|
||||
it("sets no aria-describedby when the rules cannot be loaded", async () => {
|
||||
get.mockRejectedValue(new Error("down"));
|
||||
render(<ResetPasswordPage />);
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
expect(screen.getByLabelText("New password")).not.toHaveAttribute("aria-describedby");
|
||||
});
|
||||
|
||||
it("names the refused rule at the password field", async () => {
|
||||
post.mockRejectedValue(new ApiError("PASSWORD_RULE", 400, { code: "PASSWORD_RULE", details: { param: "INPUT_LENGTH_MIN", value: 10 } }));
|
||||
render(<ResetPasswordPage />);
|
||||
fireEvent.change(screen.getByLabelText("New password"), { target: { value: "Short1" } });
|
||||
fireEvent.change(screen.getByLabelText("Confirm new password"), { target: { value: "Short1" } });
|
||||
fireEvent.submit(screen.getByRole("button", { name: /set password/i }));
|
||||
const alert = await screen.findByRole("alert");
|
||||
expect(within(alert).getByText('Password does not meet the rule "Length: at least 10"')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@ const nav = vi.hoisted(() => ({ push: vi.fn() }));
|
||||
vi.mock("next/navigation", () => ({ useRouter: () => ({ push: nav.push }) }));
|
||||
vi.mock("@/app/lib/clientApi", () => ({
|
||||
apiPost: vi.fn(),
|
||||
apiGet: vi.fn().mockResolvedValue([{ param: "INPUT_LENGTH_MIN", value: 8 }, { param: "UPPERCASE_LENGTH_MIN", value: 1 }]),
|
||||
ApiError: class ApiError extends Error {},
|
||||
}));
|
||||
const refresh = vi.fn();
|
||||
@@ -35,9 +36,10 @@ describe("ResetPasswordPage (first sign-in)", () => {
|
||||
expect(screen.getByLabelText("Confirm new password")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("states the password rules under the new password field", () => {
|
||||
it("states the password rules under the new password field", async () => {
|
||||
render(<ResetPasswordPage />);
|
||||
expect(screen.getByText("At least 8 characters, with at least one capital letter and one small letter.")).toBeInTheDocument();
|
||||
expect(await screen.findByText("Length: at least 8")).toBeInTheDocument();
|
||||
expect(screen.getByText("Capital letters: at least 1")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the choose-a-new-password intro, not the temporary-password one", () => {
|
||||
|
||||
@@ -10,6 +10,7 @@ import { ErrorState } from "@/app/components/ui/states";
|
||||
import { apiPost } from "@/app/lib/clientApi";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { PasswordRulesHint, passwordRuleError } from "@/app/components/users/PasswordRulesHint";
|
||||
import AuthFrame from "@/app/components/app/AuthFrame";
|
||||
|
||||
// First sign-in: login answered resetPasswordRequired (the account is still on the temporary
|
||||
@@ -21,11 +22,14 @@ export default function ResetPasswordPage() {
|
||||
const [newPassword, setNewPassword] = useState("");
|
||||
const [confirmPassword, setConfirmPassword] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [ruleError, setRuleError] = useState<string | null>(null);
|
||||
const [hintShown, setHintShown] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
setRuleError(null);
|
||||
if (!newPassword || !confirmPassword) {
|
||||
setError("ResetAllRequired");
|
||||
return;
|
||||
@@ -40,7 +44,9 @@ export default function ResetPasswordPage() {
|
||||
await refresh();
|
||||
router.push("/");
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "ResetFailed");
|
||||
const rule = passwordRuleError(err, t);
|
||||
if (rule) setRuleError(rule);
|
||||
else setError(err instanceof Error ? err.message : "ResetFailed");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
@@ -63,10 +69,11 @@ export default function ResetPasswordPage() {
|
||||
value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.target.value)}
|
||||
disabled={submitting}
|
||||
aria-describedby="newPasswordRules"
|
||||
aria-describedby={[hintShown && "newPasswordRules", ruleError && "newPasswordError"].filter(Boolean).join(" ") || undefined}
|
||||
className="h-11 bg-card"
|
||||
/>
|
||||
<p id="newPasswordRules" className="text-sm text-muted-foreground">{t("AdminPasswordHint")}</p>
|
||||
<PasswordRulesHint source="public" id="newPasswordRules" onShown={setHintShown} />
|
||||
{ruleError && <p id="newPasswordError" role="alert" className="text-sm text-destructive">{ruleError}</p>}
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="confirmPassword">{t("ResetConfirmPassword")}</Label>
|
||||
|
||||
@@ -0,0 +1,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<typeof import("@/app/lib/clientApi")>()).ApiError,
|
||||
apiGet: vi.fn(),
|
||||
apiPost: mocks.apiPost,
|
||||
apiPut: mocks.apiPut,
|
||||
apiDelete: mocks.apiDelete,
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminRoles", async (importOriginal) => {
|
||||
const mod = await importOriginal<typeof import("@/app/lib/services/adminRoles")>();
|
||||
return { ...mod, listAdminRoles: mocks.list };
|
||||
});
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
|
||||
import RolesPage from "./page";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
const ROWS = [
|
||||
{ id: 1, name: "ROLE_SUPER_ADMIN" },
|
||||
{ id: 4, name: "ROLE_HQ", parent: { id: 1 } },
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.list.mockReset().mockResolvedValue(ROWS);
|
||||
mocks.apiPost.mockReset();
|
||||
mocks.apiPut.mockReset();
|
||||
mocks.apiDelete.mockReset().mockResolvedValue({});
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true, hasModule: () => true });
|
||||
});
|
||||
|
||||
const rowOf = async (code: string) => (await screen.findByText(code)).closest("tr")!;
|
||||
const openDelete = async () => userEvent.click(within(await rowOf("ROLE_HQ")).getByRole("button", { name: "Delete" }));
|
||||
|
||||
describe("Roles delete", () => {
|
||||
it("deletes after confirming", async () => {
|
||||
render(<RolesPage />);
|
||||
await openDelete();
|
||||
expect(mocks.apiDelete).not.toHaveBeenCalled();
|
||||
await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Delete" }));
|
||||
await waitFor(() => expect(mocks.apiDelete).toHaveBeenCalledWith("/api/roles/4"));
|
||||
});
|
||||
|
||||
it("cancel closes the confirmation without deleting", async () => {
|
||||
render(<RolesPage />);
|
||||
await openDelete();
|
||||
await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Cancel" }));
|
||||
expect(screen.queryByRole("dialog")).toBeNull();
|
||||
expect(mocks.apiDelete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("names how many users hold a role that is in use", async () => {
|
||||
mocks.apiDelete.mockRejectedValue(new ApiError("ROLE_IN_USE", 409, { code: "ROLE_IN_USE", details: { users: 3 } }));
|
||||
render(<RolesPage />);
|
||||
await openDelete();
|
||||
await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Delete" }));
|
||||
expect(await screen.findByText("Users holding this role: 3. Remove it from them first.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("styles the row Delete as destructive-outline", async () => {
|
||||
render(<RolesPage />);
|
||||
expect(within(await rowOf("ROLE_HQ")).getByRole("button", { name: "Delete" })).toHaveAttribute("data-variant", "destructive-outline");
|
||||
});
|
||||
|
||||
it("offers no Delete on a protected role, and none to non-super staff", async () => {
|
||||
render(<RolesPage />);
|
||||
expect(within(await rowOf("ROLE_SUPER_ADMIN")).queryByRole("button", { name: "Delete" })).toBeNull();
|
||||
expect(within(await rowOf("ROLE_HQ")).getByRole("button", { name: "Delete" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("hides Delete from staff who are not super admins", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper: false, hasModule: () => true });
|
||||
render(<RolesPage />);
|
||||
await screen.findByText("ROLE_HQ");
|
||||
expect(screen.queryByRole("button", { name: "Delete" })).toBeNull();
|
||||
});
|
||||
|
||||
it("says a role name belongs to a deleted role", async () => {
|
||||
mocks.apiPost.mockRejectedValue(new ApiError("ROLE_NAME_DELETED", 409, { error: "ROLE_NAME_DELETED", code: "ROLE_NAME_DELETED" }));
|
||||
render(<RolesPage />);
|
||||
await userEvent.click(await screen.findByRole("button", { name: /add role/i }));
|
||||
await userEvent.type(screen.getByLabelText(/role name/i), "ROLE_OLD");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByText("This name belongs to a deleted role.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("Cancel in the add dialog closes it without saving", async () => {
|
||||
render(<RolesPage />);
|
||||
await userEvent.click(await screen.findByRole("button", { name: /add role/i }));
|
||||
await userEvent.click(screen.getByRole("button", { name: "Cancel" }));
|
||||
expect(screen.queryByLabelText(/role name/i)).toBeNull();
|
||||
expect(mocks.apiPost).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Input } from "@/app/components/ui/input";
|
||||
import { Label } from "@/app/components/ui/label";
|
||||
import { ConfirmDialog } from "@/app/components/ui/confirm-dialog";
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog";
|
||||
import { DataTable } from "@/app/components/ui/data-table";
|
||||
import { sortRows } from "@/app/components/ui/sortable-head";
|
||||
@@ -14,7 +15,7 @@ import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { roleLabel } from "@/app/lib/roleLabel";
|
||||
import { listAdminRoles, saveAdminRole } from "@/app/lib/services/adminRoles";
|
||||
import { deleteAdminRole, listAdminRoles, saveAdminRole } from "@/app/lib/services/adminRoles";
|
||||
import type { AdminRoleEntity } from "@/app/lib/types";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
@@ -23,6 +24,9 @@ interface FormState {
|
||||
name: string;
|
||||
}
|
||||
|
||||
// ponytail: mirrors the server list (ROLE_PROTECTED); a role flag from the API would replace it.
|
||||
const PROTECTED_ROLES = ["ROLE_SUPER_ADMIN", "ROLE_ADMIN", "ROLE_MEMBER"];
|
||||
|
||||
const EMPTY_FORM: FormState = { name: "" };
|
||||
|
||||
function RoleFormDialog({
|
||||
@@ -52,7 +56,8 @@ function RoleFormDialog({
|
||||
onSaved();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "RolSaveFailed");
|
||||
const code = (err as { data?: { code?: string } }).data?.code;
|
||||
setError(code === "ROLE_NAME_DELETED" ? "RolNameDeleted" : err instanceof Error ? err.message : "RolSaveFailed");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -77,6 +82,9 @@ function RoleFormDialog({
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button type="submit" disabled={saving}>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
@@ -89,13 +97,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<AdminRoleEntity[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
const [dialog, setDialog] = useState<FormState | null>(null);
|
||||
const [confirmDelete, setConfirmDelete] = useState<AdminRoleEntity | null>(null);
|
||||
|
||||
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
|
||||
|
||||
@@ -165,13 +175,33 @@ function RolesPageContent() {
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<a href={`/roles/${row.original.id}/access`}>{t("RolManageAccess")}</a>
|
||||
</Button>
|
||||
{isSuper === true && !PROTECTED_ROLES.includes(row.original.name) && (
|
||||
<Button variant="destructive-outline" size="sm" onClick={() => setConfirmDelete(row.original)}>
|
||||
{t("RolDelete")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
}]),
|
||||
],
|
||||
[parentLabel, t, readOnly],
|
||||
[parentLabel, t, readOnly, isSuper],
|
||||
);
|
||||
|
||||
async function runDelete() {
|
||||
if (!confirmDelete) return;
|
||||
const role = confirmDelete;
|
||||
setConfirmDelete(null);
|
||||
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 (
|
||||
<>
|
||||
<PageHeader
|
||||
@@ -201,6 +231,17 @@ function RolesPageContent() {
|
||||
empty={<EmptyState title={t("RolNoRoles")} />}
|
||||
/>
|
||||
|
||||
{confirmDelete && (
|
||||
<ConfirmDialog
|
||||
title={t("RolDeleteTitle")}
|
||||
message={t("RolDeleteConfirm", { name: roleLabel(confirmDelete.name) })}
|
||||
confirmLabel={t("RolDelete")}
|
||||
destructive
|
||||
onConfirm={runDelete}
|
||||
onCancel={() => setConfirmDelete(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{dialog && (
|
||||
<RoleFormDialog initial={dialog} onClose={() => setDialog(null)} onSaved={refetch} />
|
||||
)}
|
||||
|
||||
Reference in new issue
Block a user