feat(portal): company sign-in, session company and Companies screen

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-30 19:48:30 +08:00
1 parent de007b5328
commit 5526294e69
26 files changed
+807 -11

No files matched your search

@@ -0,0 +1,15 @@
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 { POST } from "./route";
beforeEach(() => mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: {} }));
describe("POST /api/auth/forgot-password company", () => {
it("forwards a trimmed company", async () => {
await POST(new Request("http://localhost/x", { method: "POST", body: JSON.stringify({ company: " ins ", username: "john", email: "j@x.com" }) }) as never);
expect(mocks.callMobileApi.mock.calls[0][1].body).toEqual({ company: "ins", username: "john", email: "j@x.com" });
});
});
@@ -5,11 +5,15 @@ import { callMobileApi } from "@/app/lib/server/mobileApi";
// the answer must not reveal whether the account exists, so upstream errors are never forwarded.
// Same-origin and body-size checks are enforced for every /api write by middleware.
export async function POST(req: NextRequest) {
const body = (await req.json().catch(() => ({}))) as { username?: unknown; email?: unknown };
const body = (await req.json().catch(() => ({}))) as { company?: unknown; username?: unknown; email?: unknown };
const username = typeof body.username === "string" ? body.username.trim() : "";
const email = typeof body.email === "string" ? body.email.trim() : "";
const company = typeof body.company === "string" ? body.company.trim() : "";
if (username && email) {
await callMobileApi("/api/admin/auth/forgot-password", { method: "POST", body: { username, email } });
await callMobileApi("/api/admin/auth/forgot-password", {
method: "POST",
body: { ...(company && { company }), username, email },
});
}
return NextResponse.json({ ok: true });
}
@@ -0,0 +1,24 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), setSession: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ setSession: mocks.setSession }));
import { POST } from "./route";
const req = (body: unknown) =>
new Request("http://localhost/api/auth/login", { method: "POST", body: JSON.stringify(body) }) as unknown as Parameters<typeof POST>[0];
beforeEach(() => {
mocks.callMobileApi.mockReset().mockResolvedValue({
ok: true,
data: { token: "t", name: "N", roles: [], aclMenu: {}, resetPasswordRequired: "false" },
});
});
describe("POST /api/auth/login company", () => {
it("forwards a trimmed company", async () => {
await POST(req({ company: " ins ", username: "john", password: "pw" }));
expect(mocks.callMobileApi.mock.calls[0][1].body).toEqual({ company: "ins", username: "john", password: "pw" });
});
});
@@ -14,7 +14,7 @@ import type { AdminLoginResponse } from "@/app/lib/types";
// echoed back here, keeping this handler's response minimal.
export async function POST(req: NextRequest) {
const body = await req.json().catch(() => ({}));
const { username, password } = body as { username?: string; password?: string };
const { company, username, password } = body as { company?: string; username?: string; password?: string };
const identifier = (username ?? "").trim();
if (!identifier || !password) {
@@ -23,7 +23,8 @@ export async function POST(req: NextRequest) {
const result = await callMobileApi<AdminLoginResponse>("/api/admin/auth/login", {
method: "POST",
body: { username: identifier, password },
// A blank company is a super-admin login: omit the key rather than send "".
body: { ...(company?.trim() && { company: company.trim() }), username: identifier, password },
// Real-client context for the login_audit trail (X-Client-Ip / X-Client-User-Agent).
headers: clientContextHeaders(req),
});
@@ -0,0 +1,21 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: vi.fn().mockResolvedValue("jwt") }));
vi.mock("@/app/lib/server/sessionRefresh", () => ({ maybeRefreshSession: vi.fn() }));
import { GET } from "./route";
beforeEach(() => mocks.callMobileApi.mockReset());
describe("GET /api/auth/session company", () => {
it("passes companyId, companyCode and isSuper through", async () => {
mocks.callMobileApi.mockResolvedValue({
ok: true,
data: { id: 1, username: "john@ins", name: "J", roles: [], aclMenu: {}, companyId: 7, companyCode: "ins", isSuper: false },
});
const res = await GET(new Request("http://localhost/api/auth/session") as never);
expect(await res.json()).toMatchObject({ companyId: 7, companyCode: "ins", isSuper: false });
});
});
@@ -25,6 +25,9 @@ export async function GET(req: NextRequest) {
const result = await callMobileApi<AdminMeResponse>("/api/admin/me", { token });
if (!result.ok) return errorResponse(result);
const { id, username, name, roles, aclMenu, branch } = result.data;
return NextResponse.json({ id, username, name, roles, aclMenu, branch: branch ?? null });
const { id, username, name, roles, aclMenu, branch, companyId, companyCode, isSuper } = result.data;
return NextResponse.json({
id, username, name, roles, aclMenu, branch: branch ?? null,
companyId, companyCode, isSuper,
});
}
@@ -0,0 +1,32 @@
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 { POST } from "./route";
const call = (body: unknown) =>
POST(new Request("http://localhost/x", { method: "POST", body: JSON.stringify(body) }) as never, { params: Promise.resolve({ id: "7" }) });
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset().mockResolvedValue("jwt");
});
describe("POST /api/companies/[id]/code", () => {
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
expect((await call({ code: "new" })).status).toBe(401);
});
it("forwards the code to /api/admin/companies/{id}/code", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 7, code: "new" } });
await call({ code: "new" });
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/companies/7/code", {
method: "POST",
body: { code: "new" },
token: "jwt",
});
});
});
@@ -0,0 +1,19 @@
import { NextResponse, type NextRequest } 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";
import type { AdminCompany } from "@/app/lib/types";
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const token = await getToken();
if (!token) return unauthorized();
const { id } = await params;
const { code } = (await req.json().catch(() => ({}))) as { code?: string };
const result = await callMobileApi<AdminCompany>(`/api/admin/companies/${encodeURIComponent(id)}/code`, {
method: "POST",
body: { code },
token,
});
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -0,0 +1,46 @@
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, POST } from "./route";
const post = (body: unknown) =>
new Request("http://localhost/api/companies", { method: "POST", body: JSON.stringify(body) }) as unknown as Parameters<typeof POST>[0];
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset().mockResolvedValue("jwt");
});
describe("/api/companies", () => {
it("GET returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
expect((await GET()).status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("GET forwards to /api/admin/companies", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: [] });
await GET();
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/companies", { token: "jwt" });
});
it("POST forwards id, name, code and status", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 1 } });
await POST(post({ id: 1, name: "Ins", code: "ins", status: "A", extra: "x" }));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/companies", {
method: "POST",
body: { id: 1, name: "Ins", code: "ins", status: "A" },
token: "jwt",
});
});
it("POST relays a 409 from the API", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 409, error: "Code already used" });
const res = await POST(post({ name: "Ins", code: "ins", status: "A" }));
expect(res.status).toBe(409);
expect((await res.json()).error).toBe("Code already used");
});
});
@@ -0,0 +1,27 @@
import { NextResponse, type NextRequest } 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";
import type { AdminCompany } from "@/app/lib/types";
// Super admin only; the mobile-api answers 403 for anyone else, and validation (400) and duplicate codes (409) too.
export async function GET() {
const token = await getToken();
if (!token) return unauthorized();
const result = await callMobileApi<AdminCompany[]>("/api/admin/companies", { token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
export async function POST(req: NextRequest) {
const token = await getToken();
if (!token) return unauthorized();
const { id, name, code, status } = (await req.json().catch(() => ({}))) as Partial<AdminCompany>;
const result = await callMobileApi<AdminCompany>("/api/admin/companies", {
method: "POST",
body: { id, name, code, status },
token,
});
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -0,0 +1,38 @@
import { render, screen } 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(), 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,
}));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
import CompaniesPage from "./page";
beforeEach(() => {
mocks.apiGet.mockReset().mockResolvedValue([{ id: 1, name: "Insight", code: "ins", status: "A" }]);
mocks.apiPost.mockReset();
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true });
});
describe("CompaniesPage fixes", () => {
it("does not post a code change when the new code equals the current code", async () => {
render(<CompaniesPage />);
await userEvent.click(await screen.findByRole("button", { name: "Change code" }));
const input = screen.getByLabelText("New code");
await userEvent.clear(input);
await userEvent.type(input, " INS ");
await userEvent.click(screen.getByRole("button", { name: "Confirm" }));
expect(mocks.apiPost).not.toHaveBeenCalled();
expect(screen.getByRole("alert")).toBeInTheDocument();
});
it("shows the API error text of a failed load directly", async () => {
mocks.apiGet.mockRejectedValue(new Error("Forbidden for you"));
render(<CompaniesPage />);
expect(await screen.findByText("Forbidden for you")).toBeInTheDocument();
});
});
@@ -0,0 +1,96 @@
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(() => ({ apiGet: vi.fn(), apiPost: 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,
}));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
import CompaniesPage from "./page";
import { ApiError } from "@/app/lib/clientApi";
const ROWS = [
{ id: 1, name: "Insight", code: "ins", status: "A" },
{ id: 2, name: "Clever", code: "cv", status: "I" },
];
beforeEach(() => {
mocks.apiGet.mockReset().mockResolvedValue(ROWS);
mocks.apiPost.mockReset();
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true });
});
describe("CompaniesPage", () => {
it("lists name, code and status", async () => {
render(<CompaniesPage />);
const row = (await screen.findByText("Insight")).closest("tr")!;
expect(within(row).getByText("ins")).toBeInTheDocument();
expect(within(row).getByText("Active")).toBeInTheDocument();
expect(within(screen.getByText("Clever").closest("tr")!).getByText("Inactive")).toBeInTheDocument();
expect(mocks.apiGet).toHaveBeenCalledWith("/api/companies");
});
it("creates a company with name, code and status", async () => {
mocks.apiPost.mockResolvedValue({ id: 3 });
render(<CompaniesPage />);
await userEvent.click(await screen.findByRole("button", { name: /add company/i }));
await userEvent.type(screen.getByLabelText("Name"), " Acme ");
await userEvent.type(screen.getByLabelText("Code"), "acme");
await userEvent.click(screen.getByRole("button", { name: /save/i }));
await waitFor(() =>
expect(mocks.apiPost).toHaveBeenCalledWith("/api/companies", { name: "Acme", code: "acme", status: "A" }),
);
});
it("edits name and status only, with no code field", async () => {
mocks.apiPost.mockResolvedValue({ id: 1 });
render(<CompaniesPage />);
const row = (await screen.findByText("Insight")).closest("tr")!;
await userEvent.click(within(row).getByRole("button", { name: "Edit" }));
expect(screen.queryByLabelText("Code")).toBeNull();
const name = screen.getByLabelText("Name");
await userEvent.clear(name);
await userEvent.type(name, "Insight Ltd");
await userEvent.click(screen.getByRole("button", { name: /save/i }));
await waitFor(() =>
expect(mocks.apiPost).toHaveBeenCalledWith("/api/companies", { id: 1, name: "Insight Ltd", status: "A" }),
);
});
it("shows an API 409 message on the form", async () => {
mocks.apiPost.mockRejectedValue(new ApiError("Code already used", 409));
render(<CompaniesPage />);
await userEvent.click(await screen.findByRole("button", { name: /add company/i }));
await userEvent.type(screen.getByLabelText("Name"), "Acme");
await userEvent.type(screen.getByLabelText("Code"), "ins");
await userEvent.click(screen.getByRole("button", { name: /save/i }));
expect(await screen.findByText("Code already used")).toBeInTheDocument();
});
it("warns before a code change, then posts the new code", async () => {
mocks.apiPost.mockResolvedValue({ id: 1, code: "new" });
render(<CompaniesPage />);
const row = (await screen.findByText("Insight")).closest("tr")!;
await userEvent.click(within(row).getByRole("button", { name: /change code/i }));
expect(
screen.getByText("Changing the code changes every staff login name of this company and signs them out."),
).toBeInTheDocument();
expect(mocks.apiPost).not.toHaveBeenCalled();
const code = screen.getByLabelText("New code");
await userEvent.clear(code);
await userEvent.type(code, "new");
await userEvent.click(screen.getByRole("button", { name: /confirm/i }));
await waitFor(() => expect(mocks.apiPost).toHaveBeenCalledWith("/api/companies/1/code", { code: "new" }));
});
it("is refused for non-super users", () => {
mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper: false });
render(<CompaniesPage />);
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
expect(mocks.apiGet).not.toHaveBeenCalled();
});
});
+213
View File
@@ -0,0 +1,213 @@
"use client";
import { useCallback, useEffect, useMemo, useState, type FormEvent } from "react";
import { Plus } from "lucide-react";
import type { ColumnDef } 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 { 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 { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { NotAuthorized } from "@/app/lib/RequireModule";
import { changeAdminCompanyCode, listAdminCompanies, saveAdminCompany } from "@/app/lib/services/adminCompanies";
import type { AdminCompany } from "@/app/lib/types";
import { useT } from "@/app/lib/i18n/MessagesProvider";
type Mode = "form" | "code";
type DialogState = { mode: Mode; company: AdminCompany };
const NEW_COMPANY: AdminCompany = { name: "", code: "", status: "A" };
// ponytail: the API message is shown as returned (not translated); add codes to the API if that matters.
function CompanyDialog({ state, onClose, onSaved }: { state: DialogState; onClose: () => void; onSaved: () => void }) {
const t = useT();
const { mode, company } = state;
const [form, setForm] = useState<AdminCompany>(company);
const [newCode, setNewCode] = useState(company.code);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (mode === "form" && !form.name.trim()) return setError(t("CompNameRequired"));
if ((mode === "code" ? newCode : form.code).trim() === "" && (mode === "code" || !form.id)) {
return setError(t("CompCodeRequired"));
}
if (mode === "code" && newCode.trim().toLowerCase() === company.code.toLowerCase()) {
return setError(t("CompCodeUnchanged"));
}
setError(null);
setSaving(true);
try {
if (mode === "code") await changeAdminCompanyCode(company.id!, newCode.trim());
else if (form.id) await saveAdminCompany({ id: form.id, name: form.name.trim(), status: form.status });
else await saveAdminCompany({ name: form.name.trim(), code: form.code.trim(), status: form.status });
onSaved();
onClose();
} catch (err) {
setError(err instanceof Error && err.message ? err.message : t("CompSaveFailed"));
} finally {
setSaving(false);
}
}
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>{mode === "code" ? t("CompChangeCode") : form.id ? t("CompEdit") : t("CompAdd")}</DialogTitle>
</DialogHeader>
{error && (
<div className="text-sm text-destructive" role="alert">
{error}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
{mode === "code" ? (
<>
<p className="text-sm">{t("CompChangeCodeWarning")}</p>
<div className="space-y-1.5">
<Label htmlFor="company-new-code">{t("CompNewCode")}</Label>
<Input id="company-new-code" value={newCode} onChange={(e) => setNewCode(e.target.value)} disabled={saving} />
</div>
</>
) : (
<>
<div className="space-y-1.5">
<Label htmlFor="company-name">{t("Name")}</Label>
<Input id="company-name" value={form.name} onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))} disabled={saving} />
</div>
{!form.id && (
<div className="space-y-1.5">
<Label htmlFor="company-code">{t("Code")}</Label>
<Input id="company-code" value={form.code} onChange={(e) => setForm((f) => ({ ...f, code: e.target.value }))} disabled={saving} />
</div>
)}
<div className="space-y-1.5">
<Label htmlFor="company-status">{t("Status")}</Label>
<select
id="company-status"
value={form.status}
onChange={(e) => setForm((f) => ({ ...f, status: e.target.value as AdminCompany["status"] }))}
disabled={saving}
className="h-9 w-full rounded-md border border-input bg-transparent px-3 text-sm"
>
<option value="A">{t("CompActive")}</option>
<option value="I">{t("CompInactive")}</option>
</select>
</div>
</>
)}
<DialogFooter>
<Button type="submit" disabled={saving}>
{mode === "code" ? t("CompConfirm") : t("Save")}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
function CompaniesPageContent() {
const t = useT();
const [companies, setCompanies] = useState<AdminCompany[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [reloadKey, setReloadKey] = useState(0);
const [dialog, setDialog] = useState<DialogState | null>(null);
const [page, setPage] = useState(1);
const { tableRef, pageSize } = useFitPageSize();
const size = pageSize ?? MIN_PAGE_SIZE;
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
useEffect(() => {
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets ahead of the reloadKey-triggered fetch below.
setLoading(true);
setError(null);
listAdminCompanies()
.then((result) => !cancelled && setCompanies(result))
.catch((err: unknown) => !cancelled && setError(err instanceof Error && err.message ? err.message : t("CompLoadFailed")))
.finally(() => !cancelled && setLoading(false));
return () => {
cancelled = true;
};
}, [reloadKey, t]);
const columns = useMemo<ColumnDef<AdminCompany, unknown>[]>(
() => [
{ accessorKey: "name", header: t("Name") },
{ accessorKey: "code", header: t("Code") },
{
accessorKey: "status",
header: t("Status"),
cell: ({ row }) => (
<Badge variant={row.original.status === "A" ? "positive" : "neutral"}>
{row.original.status === "A" ? t("CompActive") : t("CompInactive")}
</Badge>
),
},
{
id: "actions",
header: t("CatActions"),
cell: ({ row }) => (
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={() => setDialog({ mode: "form", company: row.original })}>
{t("Edit")}
</Button>
<Button variant="outline" size="sm" onClick={() => setDialog({ mode: "code", company: row.original })}>
{t("CompChangeCode")}
</Button>
</div>
),
},
],
[t],
);
return (
<>
<PageHeader
title={t("BO_COMPANIES")}
actions={
<Button onClick={() => setDialog({ mode: "form", company: NEW_COMPANY })}>
<Plus aria-hidden="true" className="size-4" />
{t("CompAdd")}
</Button>
}
/>
{error && <ErrorState message={error} onRetry={refetch} className="mb-4" />}
<DataTable
label={t("BO_COMPANIES")}
columns={columns}
data={companies.slice((page - 1) * size, page * size)}
total={companies.length}
page={page}
pageSize={size}
onPageChange={setPage}
tableRef={tableRef}
isLoading={loading}
rowKey={(r) => String(r.id)}
empty={<EmptyState title={t("CompNone")} />}
/>
{dialog && <CompanyDialog state={dialog} onClose={() => setDialog(null)} onSaved={refetch} />}
</>
);
}
// Gated by isSuper (UX only; the API refuses everyone else), not by a module.
export default function CompaniesPage() {
const { isSuper, loading } = useAdminAuth();
if (loading) return null;
return isSuper ? <CompaniesPageContent /> : <NotAuthorized />;
}
@@ -0,0 +1,25 @@
import { render, screen } from "@testing-library/react";
import { describe, it, expect, vi } from "vitest";
vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }), usePathname: () => "/" }));
vi.mock("@/app/lib/useAclSidebar", () => ({ useAclSidebar: () => [] }));
const auth = vi.hoisted(() => ({ companyCode: "ins" as string | null }));
vi.mock("@/app/lib/AdminAuthContext", () => ({
useAdminAuth: () => ({ name: "Admin User", companyCode: auth.companyCode, hasModule: () => false }),
}));
vi.mock("@/app/lib/theme", () => ({ useTheme: () => ({ theme: "light", toggleTheme: vi.fn() }) }));
import Header from "./Header";
describe("Header company code", () => {
it("shows the company code next to the name", () => {
render(<Header />);
expect(screen.getByTestId("company-code")).toHaveTextContent("ins");
});
it("shows nothing for a super admin", () => {
auth.companyCode = null;
render(<Header />);
expect(screen.queryByTestId("company-code")).toBeNull();
});
});
@@ -27,7 +27,7 @@ import ChangePasswordDialog from "./ChangePasswordDialog";
// same-origin /api/auth/logout route handler — never the mobile-api directly
// (spec: "The Admin Portal Is A Next.js Backend-For-Frontend").
export default function Header() {
const { name } = useAdminAuth();
const { name, companyCode } = useAdminAuth();
const { theme, toggleTheme } = useTheme();
const t = useT();
const router = useRouter();
@@ -96,6 +96,7 @@ export default function Header() {
<AvatarFallback className="bg-primary text-xs text-primary-foreground">{initial}</AvatarFallback>
</Avatar>
<span className="hidden sm:inline">{name}</span>
{companyCode && <span data-testid="company-code" className="hidden text-xs text-muted-foreground sm:inline">{companyCode}</span>}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
@@ -0,0 +1,37 @@
import { render, screen, waitFor, fireEvent } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("@/app/lib/clientApi", () => ({ apiPost: vi.fn() }));
import ForgotPasswordPage from "./page";
import { apiPost } from "@/app/lib/clientApi";
const mockPost = apiPost as unknown as ReturnType<typeof vi.fn>;
beforeEach(() => {
mockPost.mockReset().mockResolvedValue({ ok: true });
});
function fill(company: string) {
if (company) fireEvent.change(screen.getByLabelText("Company"), { target: { value: company } });
fireEvent.change(screen.getByLabelText("Username"), { target: { value: "john" } });
fireEvent.change(screen.getByLabelText("Email"), { target: { value: "john@x.com" } });
fireEvent.submit(screen.getByRole("button", { name: /temporary password/i }));
}
describe("ForgotPasswordPage company field", () => {
it("sends company, username and email", async () => {
render(<ForgotPasswordPage />);
fill(" ins ");
await waitFor(() =>
expect(mockPost).toHaveBeenCalledWith("/api/auth/forgot-password", { company: "ins", username: "john", email: "john@x.com" }),
);
});
it("allows a blank company", async () => {
render(<ForgotPasswordPage />);
fill("");
await waitFor(() => expect(mockPost).toHaveBeenCalled());
expect(mockPost.mock.calls[0][1].company ?? "").toBe("");
});
});
@@ -16,6 +16,7 @@ import PoweredBy from "@/app/components/app/PoweredBy";
// failure) the visitor sees the same message, so the page never reveals whether an account exists.
export default function ForgotPasswordPage() {
const t = useT();
const [company, setCompany] = useState("");
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [required, setRequired] = useState(false);
@@ -31,7 +32,7 @@ export default function ForgotPasswordPage() {
setRequired(false);
setSubmitting(true);
try {
await apiPost("/api/auth/forgot-password", { username: username.trim(), email: email.trim() });
await apiPost("/api/auth/forgot-password", { company: company.trim() || undefined, username: username.trim(), email: email.trim() });
} catch {
// Deliberately ignored: a failure must look the same as success.
}
@@ -53,6 +54,11 @@ export default function ForgotPasswordPage() {
<>
{required && <ErrorState message={t("ForgotRequired")} />}
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
<div className="space-y-1.5">
<Label htmlFor="company">{t("Company")}</Label>
<Input id="company" autoComplete="organization" placeholder={t("CompanyBlankForSuper")} value={company}
onChange={(e) => setCompany(e.target.value)} disabled={submitting} />
</div>
<div className="space-y-1.5">
<Label htmlFor="username">{t("Username")}</Label>
<Input id="username" autoComplete="username" required value={username}
@@ -0,0 +1,34 @@
import { render, screen, waitFor } from "@testing-library/react";
import { describe, it, expect, vi, afterEach } from "vitest";
import { AdminAuthProvider, useAdminAuth } from "./AdminAuthContext";
function Probe() {
const { companyId, companyCode, isSuper, loading } = useAdminAuth();
return <div data-testid="p">{loading ? "loading" : `${companyId}|${companyCode}|${isSuper}`}</div>;
}
function stub(body: unknown, ok = true) {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok, status: ok ? 200 : 401, json: async () => body }));
}
afterEach(() => vi.unstubAllGlobals());
describe("AdminAuthContext company", () => {
it("holds the company and isSuper from the session", async () => {
stub({ name: "J", roles: [], aclMenu: null, companyId: 7, companyCode: "ins", isSuper: false });
render(<AdminAuthProvider><Probe /></AdminAuthProvider>);
await waitFor(() => expect(screen.getByTestId("p")).toHaveTextContent("7|ins|false"));
});
it("holds isSuper for a super admin with no company", async () => {
stub({ name: "R", roles: [], aclMenu: null, companyId: null, companyCode: null, isSuper: true });
render(<AdminAuthProvider><Probe /></AdminAuthProvider>);
await waitFor(() => expect(screen.getByTestId("p")).toHaveTextContent("null|null|true"));
});
it("clears them when the session fails", async () => {
stub({}, false);
render(<AdminAuthProvider><Probe /></AdminAuthProvider>);
await waitFor(() => expect(screen.getByTestId("p")).toHaveTextContent("null|null|false"));
});
});
@@ -20,6 +20,10 @@ interface AdminAuthCtx {
/** The signed-in admin's assigned branch (add-branch-counter-sale). Null when unassigned —
* the Branch Counter POS page must show an empty state and suppress Place-sale. */
branch: AdminBranchRef | null;
/** The signed-in admin's company; null for a super admin. */
companyId: number | null;
companyCode: string | null;
isSuper: boolean;
loading: boolean;
refresh: () => Promise<void>;
/** Matches over roles[].name, e.g. hasRole("ROLE_ADMIN"). */
@@ -37,6 +41,9 @@ const AdminAuthContext = createContext<AdminAuthCtx>({
roles: [],
aclMenu: null,
branch: null,
companyId: null,
companyCode: null,
isSuper: false,
loading: true,
refresh: async () => {},
hasRole: () => false,
@@ -64,6 +71,9 @@ export function AdminAuthProvider({ children }: { children: ReactNode }) {
const [aclMenu, setAclMenu] = useState<AdminModule | null>(null);
const [grantedMenu, setGrantedMenu] = useState<AdminModule | null>(null);
const [branch, setBranch] = useState<AdminBranchRef | null>(null);
const [companyId, setCompanyId] = useState<number | null>(null);
const [companyCode, setCompanyCode] = useState<string | null>(null);
const [isSuper, setIsSuper] = useState(false);
const [loading, setLoading] = useState(true);
const load = useCallback(async () => {
@@ -79,6 +89,9 @@ export function AdminAuthProvider({ children }: { children: ReactNode }) {
setAclMenu(null);
setGrantedMenu(null);
setBranch(null);
setCompanyId(null);
setCompanyCode(null);
setIsSuper(false);
return;
}
const data = (await res.json()) as {
@@ -88,6 +101,9 @@ export function AdminAuthProvider({ children }: { children: ReactNode }) {
roles: AdminRole[];
aclMenu: AdminModule;
branch?: AdminBranchRef | null;
companyId?: number | null;
companyCode?: string | null;
isSuper?: boolean;
};
setId(data.id ?? null);
setUsername(data.username ?? null);
@@ -96,6 +112,9 @@ export function AdminAuthProvider({ children }: { children: ReactNode }) {
setAclMenu(data.aclMenu ?? null);
setGrantedMenu(data.aclMenu ?? null);
setBranch(data.branch ?? null);
setCompanyId(data.companyId ?? null);
setCompanyCode(data.companyCode ?? null);
setIsSuper(data.isSuper === true);
} catch {
setId(null);
setUsername(null);
@@ -104,6 +123,9 @@ export function AdminAuthProvider({ children }: { children: ReactNode }) {
setAclMenu(null);
setGrantedMenu(null);
setBranch(null);
setCompanyId(null);
setCompanyCode(null);
setIsSuper(false);
} finally {
setLoading(false);
}
@@ -130,7 +152,7 @@ export function AdminAuthProvider({ children }: { children: ReactNode }) {
return (
<AdminAuthContext.Provider
value={{ id, username, name, roles, aclMenu, branch, loading, refresh: load, hasRole, hasModule, hasGrantedModule }}
value={{ id, username, name, roles, aclMenu, branch, companyId, companyCode, isSuper, loading, refresh: load, hasRole, hasModule, hasGrantedModule }}
>
{children}
</AdminAuthContext.Provider>
@@ -16,6 +16,23 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
BackOfficePanelEvents: "Events and attendees",
BackOfficePanelLeads: "Leads captured at every event",
BackOfficePanelFollowUps: "Follow-ups for your sales team",
Company: "Company",
CompanyBlankForSuper: "Leave blank for super admin",
BO_COMPANIES: "Companies",
CompAdd: "Add company",
CompEdit: "Edit company",
CompNewCode: "New code",
CompChangeCode: "Change code",
CompChangeCodeWarning: "Changing the code changes every staff login name of this company and signs them out.",
CompConfirm: "Confirm",
CompActive: "Active",
CompInactive: "Inactive",
CompNone: "No companies found",
CompLoadFailed: "Failed to load companies",
CompSaveFailed: "Failed to save company.",
CompNameRequired: "Name is required.",
CompCodeUnchanged: "The new code is the same as the current code.",
CompCodeRequired: "Code is required.",
Username: "Username",
Password: "Password",
LogIn: "Log in",
@@ -0,0 +1,10 @@
import { apiGet, apiPost } from "@/app/lib/clientApi";
import type { AdminCompany } from "@/app/lib/types";
export const listAdminCompanies = () => apiGet<AdminCompany[]>("/api/companies");
/** Create when `id` is absent; otherwise edit name and status. */
export const saveAdminCompany = (company: Partial<AdminCompany>) => apiPost<AdminCompany>("/api/companies", company);
export const changeAdminCompanyCode = (id: number, code: string) =>
apiPost<AdminCompany>(`/api/companies/${id}/code`, { code });
+17
View File
@@ -60,6 +60,9 @@ export interface AdminLoginResponse {
aclMenu: AdminModule;
/** The mobile-api serializes this as the string "true"/"false", not a boolean. */
resetPasswordRequired: string;
companyId?: number | null;
companyCode?: string | null;
isSuper?: boolean;
}
/**
@@ -82,6 +85,9 @@ export interface AdminMeResponse {
roles: AdminRole[];
aclMenu: AdminModule;
branch?: AdminBranchRef | null;
companyId?: number | null;
companyCode?: string | null;
isSuper?: boolean;
}
/** Session payload returned by GET /api/auth/session after hydration. */
@@ -90,6 +96,17 @@ export interface AdminSession {
roles: AdminRole[];
aclMenu: AdminModule;
branch?: AdminBranchRef | null;
companyId?: number | null;
companyCode?: string | null;
isSuper?: boolean;
}
/** A company, as served by /api/admin/companies; status is "A" (active) or "I" (inactive). */
export interface AdminCompany {
id?: number;
name: string;
code: string;
status: "A" | "I";
}
/** Mirrors solvway-mobile-api's com.solvway.mobile.api.model.AdminUser. Deliberately has no
@@ -0,0 +1,27 @@
import { render, screen } from "@testing-library/react";
import { describe, it, expect, vi } from "vitest";
const mocks = vi.hoisted(() => ({ isSuper: false }));
vi.mock("@/app/lib/AdminAuthContext", () => ({
useAdminAuth: () => ({ aclMenu: { name: "root", type: "R", children: [{ name: "BO_DASHBOARD", type: "M", url: "/" }] }, isSuper: mocks.isSuper }),
}));
import { useAclSidebar } from "./useAclSidebar";
function Probe() {
return <div data-testid="n">{useAclSidebar().map((l) => `${l.name}:${l.url}`).join(",")}</div>;
}
describe("useAclSidebar Companies link", () => {
it("is added for super admins", () => {
mocks.isSuper = true;
render(<Probe />);
expect(screen.getByTestId("n")).toHaveTextContent("BO_DASHBOARD:/,BO_COMPANIES:/companies");
});
it("is absent for everyone else", () => {
mocks.isSuper = false;
render(<Probe />);
expect(screen.getByTestId("n").textContent).toBe("BO_DASHBOARD:/");
});
});
@@ -11,6 +11,13 @@ import { sidebarFromAclMenu, type SidebarLink } from "@/app/lib/aclSidebar";
* Order and grouping follow the aclMenu tree (siblings by module id);
*/
export function useAclSidebar(): SidebarLink[] {
const { aclMenu } = useAdminAuth();
return useMemo(() => sidebarFromAclMenu(aclMenu), [aclMenu]);
const { aclMenu, isSuper } = useAdminAuth();
// Companies is gated by isSuper, not by a module, so it is not in the aclMenu tree.
return useMemo(
() => [
...sidebarFromAclMenu(aclMenu),
...(isSuper ? [{ name: "BO_COMPANIES", url: "/companies", iconName: "Store", children: [] }] : []),
],
[aclMenu, isSuper],
);
}
@@ -0,0 +1,38 @@
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 {} }));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ refresh: vi.fn().mockResolvedValue(undefined) }) }));
import LoginPage from "./page";
import { apiPost } from "@/app/lib/clientApi";
const mockPost = apiPost as unknown as ReturnType<typeof vi.fn>;
beforeEach(() => {
mockPost.mockReset().mockResolvedValue({ name: "A", resetPasswordRequired: false });
});
describe("LoginPage company field", () => {
it("sends the company with the username and password", async () => {
render(<LoginPage />);
fireEvent.change(screen.getByLabelText("Company"), { target: { value: " ins " } });
fireEvent.change(screen.getByLabelText("Username"), { target: { value: "john" } });
fireEvent.change(screen.getByLabelText("Password"), { target: { value: "secret" } });
fireEvent.submit(screen.getByRole("button", { name: /log in/i }));
await waitFor(() =>
expect(mockPost).toHaveBeenCalledWith("/api/auth/login", { company: "ins", username: "john", password: "secret" }),
);
});
it("allows a blank company (super admin)", async () => {
render(<LoginPage />);
fireEvent.change(screen.getByLabelText("Username"), { target: { value: "root" } });
fireEvent.change(screen.getByLabelText("Password"), { target: { value: "secret" } });
fireEvent.submit(screen.getByRole("button", { name: /log in/i }));
await waitFor(() => expect(mockPost).toHaveBeenCalled());
expect(mockPost.mock.calls[0][1]).toMatchObject({ username: "root", password: "secret" });
expect(mockPost.mock.calls[0][1].company ?? "").toBe("");
});
});
+16
View File
@@ -34,6 +34,7 @@ export default function LoginPage() {
const router = useRouter();
const { refresh } = useAdminAuth();
const t = useT();
const [company, setCompany] = useState("");
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [showPassword, setShowPassword] = useState(false);
@@ -49,6 +50,7 @@ export default function LoginPage() {
setSubmitting(true);
try {
const res = await apiPost<{ name: string; resetPasswordRequired: boolean }>("/api/auth/login", {
company: company.trim() || undefined,
username,
password,
});
@@ -125,6 +127,20 @@ export default function LoginPage() {
{error ? <ErrorState message={t(error)} /> : elsewhere && <ErrorState message={t("SignedInElsewhere")} />}
<form onSubmit={handleSubmit} className="space-y-5" noValidate>
<div className="space-y-1.5">
<Label htmlFor="company">{t("Company")}</Label>
<Input
id="company"
type="text"
autoComplete="organization"
placeholder={t("CompanyBlankForSuper")}
value={company}
onChange={(e) => setCompany(e.target.value)}
disabled={submitting}
className="h-11 bg-card"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="username">{t("Username")}</Label>
<Input