diff --git a/solvway-admin-portal/app/api/roles/[id]/route.test.ts b/solvway-admin-portal/app/api/roles/[id]/route.test.ts index ec5324a..d6e4adc 100644 --- a/solvway-admin-portal/app/api/roles/[id]/route.test.ts +++ b/solvway-admin-portal/app/api/roles/[id]/route.test.ts @@ -40,11 +40,12 @@ describe("GET /api/roles/[id]", () => { }); describe("PUT /api/roles/[id]", () => { - it("requires name and parent.id, then forwards a valid body to PUT /api/admin/roles/{id}", async () => { + it("requires a name, then forwards only the name to PUT /api/admin/roles/{id}", async () => { mocks.getToken.mockResolvedValue("jwt-abc"); - const invalid = await PUT(putReq({ name: "ROLE_NEW" }), ctx("4")); + const invalid = await PUT(putReq({}), ctx("4")); expect(invalid.status).toBe(400); + expect((await PUT(putReq({ name: " " }), ctx("4"))).status).toBe(400); expect(mocks.callMobileApi).not.toHaveBeenCalled(); const body = { id: 4, name: "ROLE_NEW", parent: { id: 1 } }; @@ -52,7 +53,7 @@ describe("PUT /api/roles/[id]", () => { await PUT(putReq(body), ctx("4")); expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/roles/4", { method: "PUT", - body, + body: { name: "ROLE_NEW" }, token: "jwt-abc", }); }); diff --git a/solvway-admin-portal/app/api/roles/[id]/route.ts b/solvway-admin-portal/app/api/roles/[id]/route.ts index 1c92568..2a413d6 100644 --- a/solvway-admin-portal/app/api/roles/[id]/route.ts +++ b/solvway-admin-portal/app/api/roles/[id]/route.ts @@ -20,13 +20,14 @@ export async function PUT(req: NextRequest, { params }: Ctx) { if (!token) return unauthorized(); const { id } = await params; const body = await req.json().catch(() => ({})); - const { name, parent } = body as Partial; - if (!name || !parent?.id) { - return badRequest("name and parent.id are required."); + // The backend takes only {name}; new roles are always filed under the super admin. + const name = (body as Partial).name?.trim(); + if (!name) { + return badRequest("Role name is required."); } const result = await callMobileApi(`/api/admin/roles/${encodeURIComponent(id)}`, { method: "PUT", - body, + body: { name }, token, }); if (!result.ok) return errorResponse(result); diff --git a/solvway-admin-portal/app/api/roles/route.test.ts b/solvway-admin-portal/app/api/roles/route.test.ts index ffaa223..90cfd39 100644 --- a/solvway-admin-portal/app/api/roles/route.test.ts +++ b/solvway-admin-portal/app/api/roles/route.test.ts @@ -31,18 +31,22 @@ describe("GET /api/roles", () => { }); describe("POST /api/roles", () => { - it("requires name and parent.id", async () => { + it("requires a name (no parent needed)", async () => { mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await POST(postReq({ name: "ROLE_NEW" })); + const res = await POST(postReq({})); expect(res.status).toBe(400); + expect((await POST(postReq({ name: " " }))).status).toBe(400); expect(mocks.callMobileApi).not.toHaveBeenCalled(); }); - it("forwards a valid body to POST /api/admin/roles", async () => { + it("forwards only the name to POST /api/admin/roles", async () => { mocks.getToken.mockResolvedValue("jwt-abc"); - const body = { name: "ROLE_NEW", parent: { id: 4 } }; - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 200, ...body } }); - await POST(postReq(body)); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/roles", { method: "POST", body, token: "jwt-abc" }); + mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 200, name: "ROLE_NEW" } }); + await POST(postReq({ name: "ROLE_NEW", parent: { id: 4 } })); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/roles", { + method: "POST", + body: { name: "ROLE_NEW" }, + token: "jwt-abc", + }); }); }); diff --git a/solvway-admin-portal/app/api/roles/route.ts b/solvway-admin-portal/app/api/roles/route.ts index 27afcbf..5fd85b1 100644 --- a/solvway-admin-portal/app/api/roles/route.ts +++ b/solvway-admin-portal/app/api/roles/route.ts @@ -16,11 +16,12 @@ export async function POST(req: NextRequest) { const token = await getToken(); if (!token) return unauthorized(); const body = await req.json().catch(() => ({})); - const { name, parent } = body as Partial; - if (!name || !parent?.id) { - return badRequest("name and parent.id are required."); + // The backend takes only {name}; new roles are always filed under the super admin. + const name = (body as Partial).name?.trim(); + if (!name) { + return badRequest("Role name is required."); } - const result = await callMobileApi("/api/admin/roles", { method: "POST", body, token }); + const result = await callMobileApi("/api/admin/roles", { method: "POST", body: { name }, token }); if (!result.ok) return errorResponse(result); return NextResponse.json(result.data); } diff --git a/solvway-admin-portal/app/components/users/ChangePasswordDialog.test.tsx b/solvway-admin-portal/app/components/users/ChangePasswordDialog.test.tsx index 7a19b3b..9ab6bea 100644 --- a/solvway-admin-portal/app/components/users/ChangePasswordDialog.test.tsx +++ b/solvway-admin-portal/app/components/users/ChangePasswordDialog.test.tsx @@ -18,6 +18,11 @@ async function fillAndSubmit(password: string, confirm: string) { } describe("ChangePasswordDialog", () => { + it("states the password rules", () => { + render(); + expect(screen.getByText("At least 8 characters, with at least one capital letter and one small letter.")).toBeInTheDocument(); + }); + it("blocks submit when the fields are empty", async () => { render(); await userEvent.click(screen.getByRole("button", { name: "Change password" })); @@ -28,9 +33,10 @@ describe("ChangePasswordDialog", () => { it("blocks submit when the password is too short", async () => { render(); - await fillAndSubmit("abc", "abc"); + // 7 characters: the backend admin rule needs at least 8. + await fillAndSubmit("Abcdefg", "Abcdefg"); - expect(await screen.findByText(/at least 6 characters/i)).toBeInTheDocument(); + expect(await screen.findByText(/must be at least 8 characters/i)).toBeInTheDocument(); expect(mocks.changeAdminUserPassword).not.toHaveBeenCalled(); }); diff --git a/solvway-admin-portal/app/components/users/ChangePasswordDialog.tsx b/solvway-admin-portal/app/components/users/ChangePasswordDialog.tsx index 075630a..4f1497c 100644 --- a/solvway-admin-portal/app/components/users/ChangePasswordDialog.tsx +++ b/solvway-admin-portal/app/components/users/ChangePasswordDialog.tsx @@ -10,7 +10,7 @@ import { ErrorState } from "@/app/components/ui/states"; import { useT } from "@/app/lib/i18n/MessagesProvider"; import { changeAdminUserPassword } from "@/app/lib/services/adminUsers"; -const MIN_LENGTH = 6; +const MIN_LENGTH = 8; // services-system ADMIN_PWD_FORMAT minimum export function ChangePasswordDialog({ userId, @@ -89,7 +89,9 @@ export function ChangePasswordDialog({ value={password} onChange={(e) => setPassword(e.target.value)} disabled={saving} + aria-describedby="new-password-rules" /> +

{t("AdminPasswordHint")}

diff --git a/solvway-admin-portal/app/components/users/UserForm.test.tsx b/solvway-admin-portal/app/components/users/UserForm.test.tsx index 0ffaba1..7689c3b 100644 --- a/solvway-admin-portal/app/components/users/UserForm.test.tsx +++ b/solvway-admin-portal/app/components/users/UserForm.test.tsx @@ -165,6 +165,21 @@ describe("UserForm", () => { expect(screen.getByLabelText("Enabled")).not.toBeChecked(); }); + it("makes the username read-only when editing, editable when creating", async () => { + const { unmount } = render( + , + ); + await waitForPickers(); + expect(screen.getByLabelText("Username")).toBeDisabled(); + unmount(); + render(); + await waitForPickers(); + expect(screen.getByLabelText("Username")).toBeEnabled(); + }); + it("disables submit while the save is pending", async () => { let resolveSubmit!: () => void; const onSubmit = vi.fn( diff --git a/solvway-admin-portal/app/components/users/UserForm.tsx b/solvway-admin-portal/app/components/users/UserForm.tsx index 09b57b9..2741677 100644 --- a/solvway-admin-portal/app/components/users/UserForm.tsx +++ b/solvway-admin-portal/app/components/users/UserForm.tsx @@ -169,7 +169,8 @@ export function UserForm({ initial, onSubmit, submitLabel }: UserFormProps) { required value={username} onChange={(e) => setUsername(e.target.value)} - disabled={saving} + // The backend ignores username on update, so it is fixed once the user exists. + disabled={saving || initial?.id != null} aria-invalid={!!fieldErrors.username} /> {fieldErrors.username && ( diff --git a/solvway-admin-portal/app/lib/i18n/defaultMessages.ts b/solvway-admin-portal/app/lib/i18n/defaultMessages.ts index f035fe5..af986d2 100644 --- a/solvway-admin-portal/app/lib/i18n/defaultMessages.ts +++ b/solvway-admin-portal/app/lib/i18n/defaultMessages.ts @@ -9,13 +9,13 @@ export const DEFAULT_MESSAGES: Record = { BackOfficeTitle: "Co-Lite", BackOfficeMetaTitle: "Co-Lite :: BackOffice", - BackOfficeSubtitle: "Sign in to manage members, reports and payouts.", + BackOfficeSubtitle: "Sign in to manage events, leads and your team.", SignedInElsewhere: "You were signed out because your account signed in somewhere else.", BackOfficeLabel: "Back office", BackOfficePanelTitle: "Everything behind Co-Lite, in one place.", - BackOfficePanelOrders: "Orders, deliveries and refunds", - BackOfficePanelMembers: "Members, ranks and payouts", - BackOfficePanelCatalogue: "Products, stock and promotions", + BackOfficePanelEvents: "Events and attendees", + BackOfficePanelLeads: "Leads captured at every event", + BackOfficePanelFollowUps: "Follow-ups for your sales team", Username: "Username", Password: "Password", LogIn: "Log in", @@ -132,7 +132,10 @@ export const DEFAULT_MESSAGES: Record = { UsrDisabledHint: "Disabled users cannot sign in.", UsrOwnAccountHint: "You can't deactivate your own account", UsrNameRequired: "Name is required.", - UsrCreatedBanner: "User created. Set a password via Change password, or send a password reset email.", + UsrCreatedBanner: "User created. A temporary password has been emailed to them; they will be asked to set their own at first sign-in.", + UsrCreatedNoEmail: "User created, but the temporary password email could not be sent. Open the user from the users list and use Send password reset to try again.", + UsrBackToUsers: "Back to users", + AdminPasswordHint: "At least 8 characters, with at least one capital letter and one small letter.", UsrLoadFailed: "Failed to load user", UsrSaved: "User saved.", UsrResetSent: "Password reset email sent to {email}.", @@ -164,13 +167,11 @@ export const DEFAULT_MESSAGES: Record = { RolConfirmChanges: "Confirm access changes", RolGrantList: "Grant: {list}.", RolRevokeList: "Revoke: {list}.", - RolParentRequired: "Parent role is required.", + RolNameRequired: "Role name is required.", RolSaveFailed: "Failed to save role", RolEditRole: "Edit role", RolAddRole: "Add role", RolRoleName: "Role name", - RolParentRole: "Parent role", - RolSelectParent: "Select a parent role", RolLoadFailed: "Failed to load roles", RolColRole: "Role", RolManageAccess: "Manage access", diff --git a/solvway-admin-portal/app/lib/types.ts b/solvway-admin-portal/app/lib/types.ts index 413ea52..8db74ac 100644 --- a/solvway-admin-portal/app/lib/types.ts +++ b/solvway-admin-portal/app/lib/types.ts @@ -35,7 +35,7 @@ export interface AdminRoleEntity { id?: number; name: string; level?: number; - parent: { id: number }; + parent?: { id: number } | null; } // Mirrors com.solvway.core.model.Module (solvway-core-libs): the aclMenu tree diff --git a/solvway-admin-portal/app/login/page.test.tsx b/solvway-admin-portal/app/login/page.test.tsx index a071552..ef7475b 100644 --- a/solvway-admin-portal/app/login/page.test.tsx +++ b/solvway-admin-portal/app/login/page.test.tsx @@ -108,11 +108,19 @@ describe("LoginPage", () => { it("falls back to the built-in English defaults with no provider", () => { render(); expect(screen.getByText("Co-Lite")).toBeInTheDocument(); - expect(screen.getByText("Sign in to manage members, reports and payouts.")).toBeInTheDocument(); + expect(screen.getByText("Sign in to manage events, leads and your team.")).toBeInTheDocument(); expect(screen.getByLabelText("Username")).toBeInTheDocument(); expect(screen.getByLabelText("Password")).toBeInTheDocument(); expect(screen.getByRole("button", { name: "Log in" })).toBeInTheDocument(); }); + + it("describes the event CRM on the brand panel", () => { + render(); + for (const text of ["Events and attendees", "Leads captured at every event", "Follow-ups for your sales team"]) { + expect(screen.getByText(text)).toBeInTheDocument(); + } + expect(screen.queryByText(/payouts|deliveries|promotions/i)).not.toBeInTheDocument(); + }); }); describe("Forgot password link", () => { diff --git a/solvway-admin-portal/app/login/page.tsx b/solvway-admin-portal/app/login/page.tsx index e6127f8..9c4e864 100644 --- a/solvway-admin-portal/app/login/page.tsx +++ b/solvway-admin-portal/app/login/page.tsx @@ -1,7 +1,7 @@ "use client"; import { useState, useSyncExternalStore } from "react"; -import { Eye, EyeOff, Loader2, Package, Truck, Users } from "lucide-react"; +import { CalendarDays, Eye, EyeOff, ListChecks, Loader2, UserPlus } from "lucide-react"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { Button } from "@/app/components/ui/button"; @@ -20,9 +20,9 @@ const noSubscription = () => () => {}; /** What the back office is for, on the brand panel. */ const PANEL_POINTS = [ - { icon: Truck, code: "BackOfficePanelOrders" }, - { icon: Users, code: "BackOfficePanelMembers" }, - { icon: Package, code: "BackOfficePanelCatalogue" }, + { icon: CalendarDays, code: "BackOfficePanelEvents" }, + { icon: UserPlus, code: "BackOfficePanelLeads" }, + { icon: ListChecks, code: "BackOfficePanelFollowUps" }, ] as const; // Ported from src/legacy-pages/login/LoginPage.tsx. The hardcoded diff --git a/solvway-admin-portal/app/reset-password/page.test.tsx b/solvway-admin-portal/app/reset-password/page.test.tsx index b4ddec6..232d1a0 100644 --- a/solvway-admin-portal/app/reset-password/page.test.tsx +++ b/solvway-admin-portal/app/reset-password/page.test.tsx @@ -35,6 +35,11 @@ describe("ResetPasswordPage (first sign-in)", () => { expect(screen.getByLabelText("Confirm new password")).toBeInTheDocument(); }); + it("states the password rules under the new password field", () => { + render(); + expect(screen.getByText("At least 8 characters, with at least one capital letter and one small letter.")).toBeInTheDocument(); + }); + it("shows the choose-a-new-password intro, not the temporary-password one", () => { const { container } = render(); expect(screen.getByText("Choose a new password to continue.")).toBeInTheDocument(); diff --git a/solvway-admin-portal/app/reset-password/page.tsx b/solvway-admin-portal/app/reset-password/page.tsx index 682cce1..74a4999 100644 --- a/solvway-admin-portal/app/reset-password/page.tsx +++ b/solvway-admin-portal/app/reset-password/page.tsx @@ -66,7 +66,9 @@ export default function ResetPasswordPage() { value={newPassword} onChange={(e) => setNewPassword(e.target.value)} disabled={submitting} + aria-describedby="newPasswordRules" /> +

{t("AdminPasswordHint")}

diff --git a/solvway-admin-portal/app/roles/page.test.tsx b/solvway-admin-portal/app/roles/page.test.tsx index ebd844c..747f24d 100644 --- a/solvway-admin-portal/app/roles/page.test.tsx +++ b/solvway-admin-portal/app/roles/page.test.tsx @@ -52,16 +52,29 @@ describe("RolesPage", () => { expect(screen.getByRole("heading", { level: 1, name: "Roles" })).toBeInTheDocument(); }); - it("requires a parent to be chosen before submitting the add-role form", async () => { + it("has no parent field and posts only the name on create", async () => { + mocks.listAdminRoles.mockResolvedValue([{ id: 4, name: "ROLE_HQ" }]); + mocks.apiPost.mockResolvedValue({ id: 5, name: "ROLE_NEW" }); + render(); + await waitFor(() => expect(screen.getByText("ROLE_HQ")).toBeInTheDocument()); + + await userEvent.click(screen.getByRole("button", { name: /add role/i })); + expect(screen.queryByLabelText(/parent/i)).not.toBeInTheDocument(); + await userEvent.type(screen.getByLabelText(/role name/i), "ROLE_NEW"); + await userEvent.click(screen.getByRole("button", { name: /save/i })); + + await waitFor(() => expect(mocks.apiPost).toHaveBeenCalledWith("/api/roles", { name: "ROLE_NEW" })); + }); + + it("requires a role name before submitting", async () => { mocks.listAdminRoles.mockResolvedValue([{ id: 4, name: "ROLE_HQ" }]); render(); await waitFor(() => expect(screen.getByText("ROLE_HQ")).toBeInTheDocument()); await userEvent.click(screen.getByRole("button", { name: /add role/i })); - await userEvent.type(screen.getByLabelText(/role name/i), "ROLE_NEW"); await userEvent.click(screen.getByRole("button", { name: /save/i })); - expect(screen.getByText(/parent role is required/i)).toBeInTheDocument(); + expect(screen.getByText("Role name is required.")).toBeInTheDocument(); expect(mocks.apiPost).not.toHaveBeenCalled(); }); @@ -89,7 +102,7 @@ describe("RolesPage", () => { await waitFor(() => expect(mocks.apiPut).toHaveBeenCalledWith( "/api/roles/200", - expect.objectContaining({ id: 200, name: "ROLE_NEW_EDIT" }), + { id: 200, name: "ROLE_NEW_EDIT" }, ), ); }); @@ -102,8 +115,6 @@ describe("RolesPage", () => { await userEvent.click(screen.getByRole("button", { name: /add role/i })); await userEvent.type(screen.getByLabelText(/role name/i), "ROLE_NEW"); - await userEvent.click(screen.getByLabelText(/parent/i)); - await userEvent.click(await screen.findByRole("option", { name: "HQ" })); await userEvent.click(screen.getByRole("button", { name: /save/i })); expect(await screen.findByText(/could not be saved/i)).toBeInTheDocument(); @@ -119,8 +130,6 @@ describe("RolesPage", () => { await userEvent.click(screen.getByRole("button", { name: /add role/i })); await userEvent.type(screen.getByLabelText(/role name/i), "ROLE_HQ"); - await userEvent.click(screen.getByLabelText(/parent/i)); - await userEvent.click(await screen.findByRole("option", { name: "HQ" })); await userEvent.click(screen.getByRole("button", { name: /save/i })); expect(await screen.findByText(message)).toBeInTheDocument(); diff --git a/solvway-admin-portal/app/roles/page.tsx b/solvway-admin-portal/app/roles/page.tsx index 82f07af..4a2c1c1 100644 --- a/solvway-admin-portal/app/roles/page.tsx +++ b/solvway-admin-portal/app/roles/page.tsx @@ -6,7 +6,6 @@ import type { ColumnDef, SortingState } from "@tanstack/react-table"; import { Button } from "@/app/components/ui/button"; import { Input } from "@/app/components/ui/input"; import { Label } from "@/app/components/ui/label"; -import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select"; 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"; @@ -21,18 +20,15 @@ import { useT } from "@/app/lib/i18n/MessagesProvider"; interface FormState { id?: number; name: string; - parentId: string; } -const EMPTY_FORM: FormState = { name: "", parentId: "" }; +const EMPTY_FORM: FormState = { name: "" }; function RoleFormDialog({ - roles, initial, onClose, onSaved, }: { - roles: AdminRoleEntity[]; initial: FormState; onClose: () => void; onSaved: () => void; @@ -44,14 +40,14 @@ function RoleFormDialog({ async function handleSubmit(event: FormEvent) { event.preventDefault(); - if (!form.parentId) { - setError("RolParentRequired"); + if (!form.name.trim()) { + setError("RolNameRequired"); return; } setSaving(true); setError(null); try { - await saveAdminRole({ id: form.id, name: form.name.trim(), parent: { id: Number(form.parentId) } }); + await saveAdminRole({ id: form.id, name: form.name.trim() }); onSaved(); onClose(); } catch (err) { @@ -79,23 +75,6 @@ function RoleFormDialog({ disabled={saving} />
-
- - -
@@ -227,7 +200,7 @@ function RolesPageContent() { /> {dialog && ( - setDialog(null)} onSaved={refetch} /> + setDialog(null)} onSaved={refetch} /> )} ); diff --git a/solvway-admin-portal/app/users/[id]/page.test.tsx b/solvway-admin-portal/app/users/[id]/page.test.tsx index cd26fd3..5e3c82e 100644 --- a/solvway-admin-portal/app/users/[id]/page.test.tsx +++ b/solvway-admin-portal/app/users/[id]/page.test.tsx @@ -127,9 +127,11 @@ describe("EditUserPage", () => { render(); await waitFor(() => expect(screen.getByLabelText("Name")).toHaveValue("Jane")); - expect(screen.getByRole("alert").textContent ?? screen.getByText(/set a password/i).textContent).toMatch( - /set a password/i, - ); + expect( + screen.getByText( + "User created. A temporary password has been emailed to them; they will be asked to set their own at first sign-in.", + ), + ).toBeInTheDocument(); }); it("opens the change password dialog and calls changeAdminUserPassword", async () => { diff --git a/solvway-admin-portal/app/users/new/page.test.tsx b/solvway-admin-portal/app/users/new/page.test.tsx index 370df59..6120bb4 100644 --- a/solvway-admin-portal/app/users/new/page.test.tsx +++ b/solvway-admin-portal/app/users/new/page.test.tsx @@ -59,6 +59,30 @@ describe("NewUserPage", () => { await waitFor(() => expect(mocks.push).toHaveBeenCalledWith("/users/42?created=1")); }); + it("when the temp-password email fails, says so with a link to the users list instead of redirecting", async () => { + const { ApiError } = await vi.importActual("@/app/lib/clientApi"); + mocks.saveAdminUser.mockRejectedValue( + new ApiError("User created but the temporary password email was not sent; retry the password reset", 400, { + code: "TEMP_PASSWORD_NOT_SENT", + }), + ); + render(); + await waitFor(() => expect(screen.getByLabelText("Name")).toBeInTheDocument()); + await userEvent.type(screen.getByLabelText("Name"), "Jane"); + await userEvent.type(screen.getByLabelText("Username"), "jane.doe"); + await userEvent.type(screen.getByLabelText("Email"), "jane@example.com"); + await userEvent.click(screen.getByRole("button", { name: /create user/i })); + + expect( + await screen.findByText( + "User created, but the temporary password email could not be sent. Open the user from the users list and use Send password reset to try again.", + ), + ).toBeInTheDocument(); + expect(screen.getByRole("link", { name: "Back to users" })).toHaveAttribute("href", "/users"); + expect(mocks.push).not.toHaveBeenCalled(); + expect(screen.queryByRole("button", { name: /create user/i })).not.toBeInTheDocument(); + }); + it("renders NotAuthorized when the Users module is absent from aclMenu", () => { mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false }); render(); diff --git a/solvway-admin-portal/app/users/new/page.tsx b/solvway-admin-portal/app/users/new/page.tsx index 7a6c844..2739ffd 100644 --- a/solvway-admin-portal/app/users/new/page.tsx +++ b/solvway-admin-portal/app/users/new/page.tsx @@ -1,6 +1,10 @@ "use client"; +import { useState } from "react"; +import Link from "next/link"; import { useRouter } from "next/navigation"; +import { ApiError } from "@/app/lib/clientApi"; +import { ErrorState } from "@/app/components/ui/states"; import { RequireModule } from "@/app/lib/RequireModule"; import { PageHeader } from "@/app/components/ui/page-header"; import { UserForm } from "@/app/components/users/UserForm"; @@ -12,20 +16,41 @@ import { useT } from "@/app/lib/i18n/MessagesProvider"; // AdminUserService.create never accepts a client-supplied password (see // AdminUser.java's Javadoc), so this form has no password field. Once the // mobile-api returns the created user's id, we redirect to its edit page, -// which surfaces a banner (via the `created=1` query param) prompting the -// caller to set a password through Change password or Send password reset. +// which surfaces a banner (via the `created=1` query param). The backend emails a temporary password +// on create; if that email fails the user exists but the error body carries no id, so we stay here. function NewUserPageContent() { const t = useT(); const router = useRouter(); + const [emailFailed, setEmailFailed] = useState(false); async function handleSubmit(payload: AdminUser) { - const created = await saveAdminUser(payload); - if (created.id != null) { - router.push(`/users/${created.id}?created=1`); + try { + const created = await saveAdminUser(payload); + if (created.id != null) { + router.push(`/users/${created.id}?created=1`); + } + } catch (err) { + if (err instanceof ApiError && (err.data as { code?: string } | undefined)?.code === "TEMP_PASSWORD_NOT_SENT") { + setEmailFailed(true); + return; + } + throw err; } } + if (emailFailed) { + return ( + <> + + + + {t("UsrBackToUsers")} + + + ); + } + return ( <>