fix(admin-portal): match the screens to the Co-Lite backend after the browser check

- Login copy describes the event CRM instead of orders and payouts.
- Role dialog has no parent field; the role routes require a trimmed name and forward only {name}.
- New-user banner says a temporary password was emailed; TEMP_PASSWORD_NOT_SENT shows a message and a link back to users.
- Username is read-only when editing.
- Password hint and an 8-character minimum match the backend admin password rules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-11-26 22:16:02 +08:00
1 parent ad4713094a
commit 49966586ca
19 files changed
+165 -85

No files matched your search

@@ -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",
});
});
@@ -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<AdminRoleEntity>;
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<AdminRoleEntity>).name?.trim();
if (!name) {
return badRequest("Role name is required.");
}
const result = await callMobileApi<AdminRoleEntity>(`/api/admin/roles/${encodeURIComponent(id)}`, {
method: "PUT",
body,
body: { name },
token,
});
if (!result.ok) return errorResponse(result);
@@ -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",
});
});
});
+5 -4
View File
@@ -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<AdminRoleEntity>;
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<AdminRoleEntity>).name?.trim();
if (!name) {
return badRequest("Role name is required.");
}
const result = await callMobileApi<AdminRoleEntity>("/api/admin/roles", { method: "POST", body, token });
const result = await callMobileApi<AdminRoleEntity>("/api/admin/roles", { method: "POST", body: { name }, token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -18,6 +18,11 @@ async function fillAndSubmit(password: string, confirm: string) {
}
describe("ChangePasswordDialog", () => {
it("states the password rules", () => {
render(<ChangePasswordDialog userId={9} onClose={vi.fn()} />);
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(<ChangePasswordDialog userId={9} onClose={vi.fn()} />);
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(<ChangePasswordDialog userId={9} onClose={vi.fn()} />);
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();
});
@@ -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"
/>
<p id="new-password-rules" className="text-sm text-muted-foreground">{t("AdminPasswordHint")}</p>
</div>
<div className="space-y-1.5">
@@ -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(
<UserForm
initial={{ id: 9, name: "Jane", username: "jane.doe", email: "j@example.com", enabled: true, status: "Y", roles: [] }}
onSubmit={vi.fn()}
/>,
);
await waitForPickers();
expect(screen.getByLabelText("Username")).toBeDisabled();
unmount();
render(<UserForm onSubmit={vi.fn()} />);
await waitForPickers();
expect(screen.getByLabelText("Username")).toBeEnabled();
});
it("disables submit while the save is pending", async () => {
let resolveSubmit!: () => void;
const onSubmit = vi.fn(
@@ -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 && (
@@ -9,13 +9,13 @@
export const DEFAULT_MESSAGES: Record<string, string> = {
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<string, string> = {
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<string, string> = {
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",
+1 -1
View File
@@ -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
+9 -1
View File
@@ -108,11 +108,19 @@ describe("LoginPage", () => {
it("falls back to the built-in English defaults with no provider", () => {
render(<LoginPage />);
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(<LoginPage />);
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", () => {
+4 -4
View File
@@ -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
@@ -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(<ResetPasswordPage />);
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(<ResetPasswordPage />);
expect(screen.getByText("Choose a new password to continue.")).toBeInTheDocument();
@@ -66,7 +66,9 @@ export default function ResetPasswordPage() {
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
disabled={submitting}
aria-describedby="newPasswordRules"
/>
<p id="newPasswordRules" className="text-sm text-muted-foreground">{t("AdminPasswordHint")}</p>
</div>
<div className="space-y-1.5">
<Label htmlFor="confirmPassword">{t("ResetConfirmPassword")}</Label>
+17 -8
View File
@@ -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(<RolesPage />);
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(<RolesPage />);
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();
+6 -33
View File
@@ -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<HTMLFormElement>) {
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}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="role-parent">{t("RolParentRole")}</Label>
<Select value={form.parentId} onValueChange={(value) => setForm((f) => ({ ...f, parentId: value }))}>
<SelectTrigger id="role-parent" aria-label={t("RolParentRole")} className="h-9 w-full">
<SelectValue placeholder={t("RolSelectParent")} />
</SelectTrigger>
<SelectContent>
{roles
.filter((r) => r.id !== form.id)
.map((r) => (
<SelectItem key={r.id} value={String(r.id)}>
{roleLabel(r.name)}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<DialogFooter>
<Button type="submit" disabled={saving}>
{t("Save")}
@@ -177,13 +156,7 @@ function RolesPageContent() {
<Button
variant="outline"
size="sm"
onClick={() =>
setDialog({
id: row.original.id,
name: row.original.name,
parentId: String(row.original.parent?.id ?? ""),
})
}
onClick={() => setDialog({ id: row.original.id, name: row.original.name })}
>
{t("Edit")}
</Button>
@@ -227,7 +200,7 @@ function RolesPageContent() {
/>
{dialog && (
<RoleFormDialog roles={roles} initial={dialog} onClose={() => setDialog(null)} onSaved={refetch} />
<RoleFormDialog initial={dialog} onClose={() => setDialog(null)} onSaved={refetch} />
)}
</>
);
@@ -127,9 +127,11 @@ describe("EditUserPage", () => {
render(<EditUserPage />);
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 () => {
@@ -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<typeof import("@/app/lib/clientApi")>("@/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(<NewUserPage />);
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(<NewUserPage />);
+30 -5
View File
@@ -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 (
<>
<PageHeader title={t("UsrNewUser")} />
<ErrorState message={t("UsrCreatedNoEmail")} className="mb-4" />
<Link href="/users" className="text-primary underline-offset-4 hover:underline">
{t("UsrBackToUsers")}
</Link>
</>
);
}
return (
<>
<PageHeader title={t("UsrNewUser")} />