From c8ffc6aede13331999969ac284d8d7f53dbda07e Mon Sep 17 00:00:00 2001 From: ngqile Date: Mon, 30 Nov 2026 21:19:22 +0800 Subject: [PATCH] feat(portal): company picker, Company column, company fields and super-admin-only screens Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- solvway-admin-portal/app/api/events/route.ts | 2 + .../api/events/salesperson-options/route.ts | 5 +- .../[[...path]]/route.companyId.test.ts | 20 +++ .../api/login-security/[[...path]]/route.ts | 2 +- solvway-admin-portal/app/api/users/route.ts | 2 + solvway-admin-portal/app/audit-log/page.tsx | 11 +- .../app/companyScope.capture.test.tsx | 70 ++++++++ .../app/companyScope.forms.test.tsx | 164 ++++++++++++++++++ .../app/companyScope.lists.test.tsx | 119 +++++++++++++ .../app/companyScope.readonly.test.tsx | 92 ++++++++++ .../app/companyScope.review.test.tsx | 99 +++++++++++ .../app/components/app/AppShell.tsx | 3 + .../app/components/app/CompanyPicker.tsx | 26 +++ .../app/components/app/Header.logout.test.tsx | 22 +++ .../app/components/app/Header.tsx | 4 + .../app/components/events/EventForm.tsx | 43 ++++- .../app/components/users/UserForm.tsx | 37 +++- solvway-admin-portal/app/emails/page.tsx | 10 +- .../app/event-leads/[eventUuid]/new/page.tsx | 23 ++- .../app/event-leads/[eventUuid]/page.tsx | 15 +- solvway-admin-portal/app/event-leads/page.tsx | 6 +- solvway-admin-portal/app/events/page.tsx | 11 +- solvway-admin-portal/app/interests/page.tsx | 14 +- solvway-admin-portal/app/leads/page.tsx | 13 +- .../app/lib/CompanyScope.stored.test.tsx | 29 ++++ .../app/lib/CompanyScope.test.tsx | 71 ++++++++ solvway-admin-portal/app/lib/CompanyScope.tsx | 93 ++++++++++ .../app/lib/hooks/useResetPageOnCompany.ts | 14 ++ .../app/lib/i18n/defaultMessages.ts | 4 + .../app/lib/services/adminEmails.ts | 3 + .../app/lib/services/adminEventLeads.ts | 12 +- .../app/lib/services/adminEvents.ts | 6 +- .../app/lib/services/adminLeads.ts | 11 +- .../app/lib/services/adminUsers.ts | 3 + .../app/lib/services/auditLog.ts | 2 + .../app/lib/services/companyScope.test.ts | 76 ++++++++ .../app/lib/services/loginSecurity.ts | 10 +- solvway-admin-portal/app/lib/types.ts | 13 ++ .../app/login-security/page.tsx | 36 ++-- .../roles/[id]/access/page.readonly.test.tsx | 32 ++++ .../app/roles/[id]/access/page.tsx | 10 +- solvway-admin-portal/app/roles/page.tsx | 14 +- solvway-admin-portal/app/users/page.tsx | 11 +- 43 files changed, 1189 insertions(+), 74 deletions(-) create mode 100644 solvway-admin-portal/app/api/login-security/[[...path]]/route.companyId.test.ts create mode 100644 solvway-admin-portal/app/companyScope.capture.test.tsx create mode 100644 solvway-admin-portal/app/companyScope.forms.test.tsx create mode 100644 solvway-admin-portal/app/companyScope.lists.test.tsx create mode 100644 solvway-admin-portal/app/companyScope.readonly.test.tsx create mode 100644 solvway-admin-portal/app/companyScope.review.test.tsx create mode 100644 solvway-admin-portal/app/components/app/CompanyPicker.tsx create mode 100644 solvway-admin-portal/app/components/app/Header.logout.test.tsx create mode 100644 solvway-admin-portal/app/lib/CompanyScope.stored.test.tsx create mode 100644 solvway-admin-portal/app/lib/CompanyScope.test.tsx create mode 100644 solvway-admin-portal/app/lib/CompanyScope.tsx create mode 100644 solvway-admin-portal/app/lib/hooks/useResetPageOnCompany.ts create mode 100644 solvway-admin-portal/app/lib/services/companyScope.test.ts create mode 100644 solvway-admin-portal/app/roles/[id]/access/page.readonly.test.tsx diff --git a/solvway-admin-portal/app/api/events/route.ts b/solvway-admin-portal/app/api/events/route.ts index dae3a6a..5146cf9 100644 --- a/solvway-admin-portal/app/api/events/route.ts +++ b/solvway-admin-portal/app/api/events/route.ts @@ -16,6 +16,8 @@ export async function GET(req: NextRequest) { if (enabled !== "Y" && enabled !== "N") return badRequest("enabled must be Y or N."); qs.set("enabled", enabled); } + const companyId = params.get("companyId"); + if (companyId && /^\d+$/.test(companyId)) qs.set("companyId", companyId); qs.set("page", params.get("page") ?? "0"); qs.set("size", params.get("size") ?? "20"); const sortBy = params.get("sortBy"); diff --git a/solvway-admin-portal/app/api/events/salesperson-options/route.ts b/solvway-admin-portal/app/api/events/salesperson-options/route.ts index 97ce01c..4e127a6 100644 --- a/solvway-admin-portal/app/api/events/salesperson-options/route.ts +++ b/solvway-admin-portal/app/api/events/salesperson-options/route.ts @@ -7,7 +7,10 @@ export async function GET(req: NextRequest) { const token = await getToken(); if (!token) return unauthorized(); - const result = await callMobileApi>("/api/admin/events/salesperson-options", { token }); + const companyId = new URL(req.url).searchParams.get("companyId"); + const qs = new URLSearchParams(); + if (companyId && /^\d+$/.test(companyId)) qs.set("companyId", companyId); + const result = await callMobileApi>(`/api/admin/events/salesperson-options${qs.size ? `?${qs}` : ""}`, { token }); if (!result.ok) return errorResponse(result); return NextResponse.json(result.data); } diff --git a/solvway-admin-portal/app/api/login-security/[[...path]]/route.companyId.test.ts b/solvway-admin-portal/app/api/login-security/[[...path]]/route.companyId.test.ts new file mode 100644 index 0000000..6e9e996 --- /dev/null +++ b/solvway-admin-portal/app/api/login-security/[[...path]]/route.companyId.test.ts @@ -0,0 +1,20 @@ +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"; + +beforeEach(() => { + mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: {} }); + mocks.getToken.mockReset().mockResolvedValue("jwt"); +}); + +describe("/api/login-security unlock", () => { + it("POST forwards the companyId query to the upstream URL", async () => { + const req = new Request("http://localhost/api/login-security/locked/a/unlock?companyId=2", { method: "POST", body: "{}", headers: { "Content-Type": "application/json" } }); + await POST(req as unknown as Parameters[0], { params: Promise.resolve({ path: ["locked", "a", "unlock"] }) }); + expect(mocks.callMobileApi.mock.calls[0][0]).toBe("/api/admin/login-security/locked/a/unlock?companyId=2"); + }); +}); diff --git a/solvway-admin-portal/app/api/login-security/[[...path]]/route.ts b/solvway-admin-portal/app/api/login-security/[[...path]]/route.ts index 0d121fa..0578741 100644 --- a/solvway-admin-portal/app/api/login-security/[[...path]]/route.ts +++ b/solvway-admin-portal/app/api/login-security/[[...path]]/route.ts @@ -11,7 +11,7 @@ async function forward(method: "GET" | "POST" | "PUT", req: NextRequest, { param if (!token) return unauthorized(); const { path = [] } = await params; if (path.some((s) => s === "." || s === "..")) return badRequest("Invalid path."); - const target = `/api/admin/login-security${path.map(encodeURIComponent).map((s) => `/${s}`).join("")}${method === "GET" ? new URL(req.url).search : ""}`; + const target = `/api/admin/login-security${path.map(encodeURIComponent).map((s) => `/${s}`).join("")}${new URL(req.url).search}`; let body: unknown; if (method !== "GET") { const text = await req.text(); diff --git a/solvway-admin-portal/app/api/users/route.ts b/solvway-admin-portal/app/api/users/route.ts index 5d66c83..2c93d78 100644 --- a/solvway-admin-portal/app/api/users/route.ts +++ b/solvway-admin-portal/app/api/users/route.ts @@ -19,6 +19,8 @@ export async function GET(req: NextRequest) { if (enabled !== "true" && enabled !== "false") return badRequest("enabled must be true or false."); qs.set("enabled", enabled); } + const companyId = params.get("companyId"); + if (companyId && /^\d+$/.test(companyId)) qs.set("companyId", companyId); qs.set("page", params.get("page") ?? "0"); qs.set("size", params.get("size") ?? "20"); const sortBy = params.get("sortBy"); diff --git a/solvway-admin-portal/app/audit-log/page.tsx b/solvway-admin-portal/app/audit-log/page.tsx index 8cd9839..afb0b44 100644 --- a/solvway-admin-portal/app/audit-log/page.tsx +++ b/solvway-admin-portal/app/audit-log/page.tsx @@ -11,10 +11,12 @@ import { PageHeader } from "@/app/components/ui/page-header"; import { EmptyState, ErrorState } from "@/app/components/ui/states"; import { RequireModule } from "@/app/lib/RequireModule"; import { useListFilters } from "@/app/lib/hooks/useListFilters"; +import { useResetPageOnCompany } from "@/app/lib/hooks/useResetPageOnCompany"; import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize"; import { ROUTE_MODULES } from "@/app/lib/routeModules"; import { formatEmailDate as formatDate } from "@/app/lib/services/adminEmails"; import { searchAuditLog, type AuditEvent } from "@/app/lib/services/auditLog"; +import { useCompanyScope } from "@/app/lib/CompanyScope"; import { useT } from "@/app/lib/i18n/MessagesProvider"; const DEFAULTS = { actor: "", module: "", action: "", outcome: "", from: "", to: "" }; @@ -23,8 +25,10 @@ const MODULES = [...Object.values(ROUTE_MODULES).filter((m) => m !== "BO_AUDIT_L function AuditLogContent() { const t = useT(); + const { companyId, showCompanyColumn, codeOf } = useCompanyScope(); const { tableRef, pageSize } = useFitPageSize(); const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS); + useResetPageOnCompany(setPage); const [data, setData] = useState<{ items: AuditEvent[]; total: number }>({ items: [], total: 0 }); const [loading, setLoading] = useState(true); const [failed, setFailed] = useState(false); @@ -37,18 +41,19 @@ function AuditLogContent() { // eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error before the filter/page/reloadKey-triggered fetch below, which is the actual synchronization. setLoading(true); setFailed(false); - searchAuditLog({ ...filters, page, pageSize }) + searchAuditLog({ ...filters, page, pageSize, companyId }) .then((result) => { if (!cancelled) setData(result); }) .catch(() => { if (!cancelled) setFailed(true); }) .finally(() => { if (!cancelled) setLoading(false); }); return () => { cancelled = true; }; - }, [filters, page, reloadKey, pageSize]); + }, [filters, page, reloadKey, pageSize, companyId]); const moduleOptions = useMemo(() => MODULES.map((m) => ({ value: m, label: t(m) })), [t]); const outcomeOptions = useMemo(() => [{ value: "SUCCESS", label: t("AuditSuccess") }, { value: "FAILURE", label: t("AuditFailure") }], [t]); const cut = (text: string | null | undefined, max = "max-w-40") => {text}; const columns = useMemo[]>( () => [ + ...(showCompanyColumn ? [{ id: "company", accessorFn: (r: AuditEvent) => codeOf(r.companyId ?? 0), header: t("Company"), enableSorting: false } as ColumnDef] : []), { id: "time", header: t("LsTime"), enableSorting: false, cell: ({ row }) => {formatDate(row.original.occurredAt)} }, { id: "actor", header: t("AuditWho"), enableSorting: false, cell: ({ row }) => cut(row.original.actor, "max-w-32") }, { id: "module", header: t("AuditModule"), enableSorting: false, cell: ({ row }) => (row.original.module ? t(row.original.module) : "—") }, @@ -73,7 +78,7 @@ function AuditLogContent() { }, { accessorKey: "clientIp", header: t("LsIp"), enableSorting: false }, ], - [t], + [t, showCompanyColumn, codeOf], ); return ( diff --git a/solvway-admin-portal/app/companyScope.capture.test.tsx b/solvway-admin-portal/app/companyScope.capture.test.tsx new file mode 100644 index 0000000..c43876a --- /dev/null +++ b/solvway-admin-portal/app/companyScope.capture.test.tsx @@ -0,0 +1,70 @@ +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(() => ({ + matchLead: vi.fn(), + listEventSalespeople: vi.fn(), + listEventLeadEvents: vi.fn(), + listEventLeadInterests: vi.fn(), + useAdminAuth: vi.fn(), + useCompanyScope: vi.fn(), +})); +vi.mock("@/app/lib/services/adminEventLeads", async (importActual) => ({ + ...(await importActual()), + matchLead: mocks.matchLead, + listEventSalespeople: mocks.listEventSalespeople, + listEventLeadEvents: mocks.listEventLeadEvents, + listEventLeadInterests: mocks.listEventLeadInterests, +})); +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, + useParams: () => ({ eventUuid: "evt-1" }), +})); + +import { memoryRouter } from "@/test/memoryRouter"; +import NewEventLeadPage from "./event-leads/[eventUuid]/new/page"; + +const COMPANIES = [ + { id: 1, name: "Ins Co", code: "INS", status: "A" }, + { id: 2, name: "CV Co", code: "CV", status: "A" }, +]; +const scope = (companyId?: number) => ({ companyId, companies: COMPANIES, showCompanyColumn: false, codeOf: () => "", setCompanyId: vi.fn() }); + +beforeEach(() => { + memoryRouter.reset("/event-leads/evt-1/new"); + mocks.matchLead.mockReset().mockResolvedValue({ mobile: "+65911", email: "a@b.com", candidates: [] }); + mocks.listEventSalespeople.mockReset().mockResolvedValue([]); + mocks.listEventLeadEvents.mockReset().mockResolvedValue([{ uuid: "evt-1", name: "Expo", companyId: 2 }]); + mocks.listEventLeadInterests.mockReset().mockResolvedValue([]); + mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true, hasModule: () => true }); + mocks.useCompanyScope.mockReset().mockReturnValue(scope(2)); +}); + +describe("event-lead capture company", () => { + it("shows no Company picker to a super admin and sends the event's own company with the lead match", async () => { + mocks.useCompanyScope.mockReturnValue(scope()); + const user = userEvent.setup(); + render(); + expect(screen.queryByRole("combobox", { name: "Company" })).not.toBeInTheDocument(); + await waitFor(() => expect(screen.getByRole("button", { name: "Next" })).toBeEnabled()); + await user.type(screen.getByLabelText("Mobile"), "91111111"); + await user.type(screen.getByLabelText("Email"), "a@b.com"); + await user.click(screen.getByRole("button", { name: "Next" })); + await waitFor(() => expect(mocks.matchLead).toHaveBeenCalledWith("evt-1", expect.objectContaining({ email: "a@b.com" }), 2)); + }); + + it("does not show Company to staff and sends no companyId", async () => { + mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper: false, hasModule: () => true }); + mocks.useCompanyScope.mockReturnValue(scope()); + const user = userEvent.setup(); + render(); + expect(screen.queryByRole("combobox", { name: "Company" })).not.toBeInTheDocument(); + await user.type(screen.getByLabelText("Mobile"), "91111111"); + await user.click(screen.getByRole("button", { name: "Next" })); + await waitFor(() => expect(mocks.matchLead).toHaveBeenCalled()); + expect(mocks.matchLead.mock.calls[0]).toHaveLength(2); + }); +}); diff --git a/solvway-admin-portal/app/companyScope.forms.test.tsx b/solvway-admin-portal/app/companyScope.forms.test.tsx new file mode 100644 index 0000000..fc5f1b2 --- /dev/null +++ b/solvway-admin-portal/app/companyScope.forms.test.tsx @@ -0,0 +1,164 @@ +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(() => ({ + listAdminRoles: vi.fn(), + listSalespersonOptions: vi.fn(), + useAdminAuth: vi.fn(), + useCompanyScope: vi.fn(), +})); +vi.mock("@/app/lib/services/adminRoles", () => ({ listAdminRoles: mocks.listAdminRoles })); +vi.mock("@/app/lib/services/adminEvents", () => ({ listSalespersonOptions: mocks.listSalespersonOptions })); +vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth })); +vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope })); + +import { UserForm } from "@/app/components/users/UserForm"; +import { EventForm } from "@/app/components/events/EventForm"; +import { pickDate } from "@/test/pickDate"; +import { ApiError } from "@/app/lib/clientApi"; + +const COMPANIES = [ + { id: 1, name: "Ins Co", code: "INS", status: "A" }, + { id: 2, name: "CV Co", code: "CV", status: "A" }, +]; +const scope = (companyId?: number) => ({ companyId, companies: COMPANIES, showCompanyColumn: false, codeOf: () => "", setCompanyId: vi.fn() }); +const ROLES = [ + { id: 1, name: "ROLE_SUPER_ADMIN", level: 1, parent: { id: 0 } }, + { id: 2, name: "ROLE_HQ", level: 1, parent: { id: 0 } }, +]; + +beforeEach(() => { + mocks.listAdminRoles.mockReset().mockResolvedValue(ROLES); + mocks.listSalespersonOptions.mockReset().mockResolvedValue([{ id: 1, name: "Alice", username: "alice" }]); + mocks.useAdminAuth.mockReset().mockReturnValue({ id: 9, isSuper: true }); + mocks.useCompanyScope.mockReset().mockReturnValue(scope(2)); +}); + +async function fillUser(user: ReturnType) { + await screen.findByLabelText("HQ"); + await user.type(screen.getByLabelText("Name"), "Jane"); + await user.type(screen.getByLabelText("Surname"), "Doe"); + await user.type(screen.getByLabelText("Username"), "jane"); + await user.type(screen.getByLabelText("Email"), "jane@x.test"); +} + +describe("UserForm company", () => { + it("shows Company to a super admin, defaulted to the picker, and sends it", async () => { + const onSubmit = vi.fn().mockResolvedValue(undefined); + const user = userEvent.setup(); + render(); + const company = await screen.findByRole("combobox", { name: "Company" }); + expect(company).toHaveValue("2"); + await fillUser(user); + await user.click(screen.getByLabelText("HQ")); + await user.click(screen.getByRole("button", { name: /create|save/i })); + await waitFor(() => expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ companyId: 2 }))); + }); + + it("offers Super admin (no company), which sends superAdmin and requires role 1", async () => { + const onSubmit = vi.fn().mockResolvedValue(undefined); + const user = userEvent.setup(); + render(); + await user.selectOptions(await screen.findByRole("combobox", { name: "Company" }), "super"); + await fillUser(user); + await user.click(screen.getByLabelText("HQ")); + await user.click(screen.getByRole("button", { name: /create|save/i })); + expect(onSubmit).not.toHaveBeenCalled(); + await user.click(screen.getByLabelText("Super admin")); + await user.click(screen.getByRole("button", { name: /create|save/i })); + await waitFor(() => expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ superAdmin: true }))); + expect(onSubmit.mock.calls[0][0]).not.toHaveProperty("companyId", expect.anything()); + }); + + it("requires a company when none is chosen", async () => { + mocks.useCompanyScope.mockReturnValue(scope()); + const onSubmit = vi.fn(); + const user = userEvent.setup(); + render(); + await fillUser(user); + await user.click(screen.getByLabelText("HQ")); + await user.click(screen.getByRole("button", { name: /create|save/i })); + expect(onSubmit).not.toHaveBeenCalled(); + expect(await screen.findByText("Choose a company.")).toBeInTheDocument(); + }); + + it("does not show Company to staff or send it", async () => { + mocks.useAdminAuth.mockReturnValue({ id: 9, isSuper: false }); + const onSubmit = vi.fn().mockResolvedValue(undefined); + const user = userEvent.setup(); + render(); + await fillUser(user); + expect(screen.queryByRole("combobox", { name: "Company" })).not.toBeInTheDocument(); + await user.click(screen.getByLabelText("HQ")); + await user.click(screen.getByRole("button", { name: /create|save/i })); + await waitFor(() => expect(onSubmit).toHaveBeenCalled()); + expect(onSubmit.mock.calls[0][0]).not.toHaveProperty("companyId"); + expect(onSubmit.mock.calls[0][0]).not.toHaveProperty("superAdmin"); + }); + + it("shows the server's COMPANY_REQUIRED message", async () => { + const onSubmit = vi.fn().mockRejectedValue(new ApiError("Choose a company.", 400, { code: "COMPANY_REQUIRED" })); + const user = userEvent.setup(); + render(); + await fillUser(user); + await user.click(screen.getByLabelText("HQ")); + await user.click(screen.getByRole("button", { name: /create|save/i })); + expect(await screen.findByText("Choose a company.")).toBeInTheDocument(); + }); +}); + +describe("EventForm company", () => { + it("shows Company to a super admin, defaulted to the picker, and sends it on create", async () => { + const onSubmit = vi.fn().mockResolvedValue(undefined); + const user = userEvent.setup(); + render(); + expect(await screen.findByRole("combobox", { name: "Company" })).toHaveValue("2"); + await user.type(screen.getByLabelText("Name"), "Expo"); + await user.type(screen.getByLabelText("Location"), "KL"); + pickDate("Start date", "2026-12-01"); + pickDate("End date", "2026-12-02"); + await user.click(screen.getByRole("button", { name: /create|save/i })); + await waitFor(() => expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ companyId: 2 }))); + }); + + it("does not show Company to staff", async () => { + mocks.useAdminAuth.mockReturnValue({ id: 9, isSuper: false }); + render(); + await waitFor(() => expect(mocks.listSalespersonOptions).toHaveBeenCalled()); + expect(screen.queryByRole("combobox", { name: "Company" })).not.toBeInTheDocument(); + }); + + it("asks for salesperson options with the company chosen, and with the event's own company on edit", async () => { + const user = userEvent.setup(); + const { unmount } = render(); + await waitFor(() => expect(mocks.listSalespersonOptions).toHaveBeenLastCalledWith(2)); + await user.selectOptions(screen.getByRole("combobox", { name: "Company" }), "1"); + await waitFor(() => expect(mocks.listSalespersonOptions).toHaveBeenLastCalledWith(1)); + unmount(); + mocks.useCompanyScope.mockReturnValue(scope(1)); + render( + , + ); + await waitFor(() => expect(mocks.listSalespersonOptions).toHaveBeenLastCalledWith(2)); + }); +}); + +describe("EventForm company required", () => { + it("refuses a super-admin create with no company chosen", async () => { + mocks.useCompanyScope.mockReturnValue(scope()); + const onSubmit = vi.fn(); + const user = userEvent.setup(); + render(); + await user.type(await screen.findByLabelText("Name"), "Expo"); + await user.type(screen.getByLabelText("Location"), "KL"); + pickDate("Start date", "2026-12-01"); + pickDate("End date", "2026-12-02"); + await user.click(screen.getByRole("button", { name: /create|save/i })); + expect(onSubmit).not.toHaveBeenCalled(); + expect(await screen.findByText("Choose a company.")).toBeInTheDocument(); + }); +}); diff --git a/solvway-admin-portal/app/companyScope.lists.test.tsx b/solvway-admin-portal/app/companyScope.lists.test.tsx new file mode 100644 index 0000000..df0e74f --- /dev/null +++ b/solvway-admin-portal/app/companyScope.lists.test.tsx @@ -0,0 +1,119 @@ +import { render, screen, waitFor, within } from "@testing-library/react"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ + listAdminUsers: vi.fn(), + listAdminEvents: vi.fn(), + listEmails: vi.fn(), + searchAuditLog: vi.fn(), + listLeads: vi.fn(), + useAdminAuth: vi.fn(), + useCompanyScope: vi.fn(), +})); +vi.mock("@/app/lib/services/adminUsers", async (i) => ({ ...(await i()), listAdminUsers: mocks.listAdminUsers })); +vi.mock("@/app/lib/services/adminEvents", async (i) => ({ ...(await i()), listAdminEvents: mocks.listAdminEvents })); +vi.mock("@/app/lib/services/adminEmails", async (i) => ({ ...(await i()), listEmails: mocks.listEmails })); +vi.mock("@/app/lib/services/auditLog", async (i) => ({ ...(await i()), searchAuditLog: mocks.searchAuditLog })); +vi.mock("@/app/lib/services/adminLeads", async (i) => ({ ...(await i()), listLeads: mocks.listLeads })); +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 { memoryRouter } from "@/test/memoryRouter"; +import UsersPage from "./users/page"; +import EventsPage from "./events/page"; +import EmailsPage from "./emails/page"; +import AuditLogPage from "./audit-log/page"; +import LeadsPage from "./leads/page"; + +const CODES: Record = { 1: "INS", 2: "CV" }; +const scope = (companyId?: number, isShown = companyId === undefined) => ({ + companyId, + companies: [], + showCompanyColumn: isShown, + codeOf: (id?: number) => (id ? CODES[id] ?? "" : ""), + setCompanyId: vi.fn(), +}); +const headers = async () => within(await screen.findByRole("table")).getAllByRole("columnheader").map((h) => h.textContent); + +const PAGES = [ + { + name: "users", + Page: UsersPage, + list: mocks.listAdminUsers, + row: { id: 5, username: "jane", name: "Jane", email: "j@x.test", enabled: true, status: "A", roles: [], companyId: 2, companyCode: "CV", loginName: "jane@cv" }, + }, + { + name: "events", + Page: EventsPage, + list: mocks.listAdminEvents, + row: { uuid: "e1", name: "Expo", location: "KL", startDate: "2026-12-01", endDate: "2026-12-02", enabled: true, companyId: 2 }, + }, + { + name: "emails", + Page: EmailsPage, + list: mocks.listEmails, + row: { id: 9, datetime: "2026-11-30T11:44:26", recipients: ["a@x.test"], subject: "Hello", status: "Y", companyId: 2 }, + }, + { + name: "audit log", + Page: AuditLogPage, + list: mocks.searchAuditLog, + row: { id: 2, companyId: 2, occurredAt: "2026-11-30T15:52:00", actor: "sales1", module: "BO_USERS", action: "USER_UPDATE", httpMethod: "PUT", pathTemplate: "/x", targetId: "4", outcome: "SUCCESS", httpStatus: 200, clientIp: "10.0.0.5", changes: null }, + }, +]; + +beforeEach(() => { + memoryRouter.reset("/x"); + for (const p of [...PAGES.map((x) => x.list), mocks.listLeads]) p.mockReset(); + for (const p of PAGES) p.list.mockResolvedValue({ items: [p.row], total: 1 }); + mocks.listLeads.mockResolvedValue({ items: [], total: 0 }); + mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true, hasModule: () => true }); + mocks.useCompanyScope.mockReset().mockReturnValue(scope()); +}); + +describe.each(PAGES)("$name list company scope", ({ Page, list, row }) => { + it("shows the Company column with the code for a super admin on All companies, and sends no companyId", async () => { + render(); + expect(await headers()).toContain("Company"); + expect(await screen.findByText("CV")).toBeInTheDocument(); + expect(list.mock.calls.at(-1)?.[0]).not.toHaveProperty("companyId", expect.anything()); + expect(row).toBeTruthy(); + }); + + it("hides the Company column and sends the picked companyId when one company is chosen", async () => { + mocks.useCompanyScope.mockReturnValue(scope(2)); + render(); + expect(await headers()).not.toContain("Company"); + await waitFor(() => expect(list).toHaveBeenLastCalledWith(expect.objectContaining({ companyId: 2 }))); + }); + + it("hides the Company column for staff and never sends companyId", async () => { + mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper: false, hasModule: () => true }); + mocks.useCompanyScope.mockReturnValue(scope(undefined, false)); + render(); + expect(await headers()).not.toContain("Company"); + expect(list.mock.calls.every((c) => (c[0] as { companyId?: number }).companyId === undefined)).toBe(true); + }); +}); + +describe("users list names", () => { + it("shows the local username, not the login name with @code", async () => { + render(); + expect(await screen.findByText("jane")).toBeInTheDocument(); + expect(screen.queryByText("jane@cv")).not.toBeInTheDocument(); + }); +}); + +describe("leads list company scope", () => { + it("adds a tenant Company column only on All companies, and sends the picked companyId", async () => { + const count = async () => (await headers()).filter((h) => h === "Company").length; + const { unmount } = render(); + const withAll = await count(); + unmount(); + mocks.useCompanyScope.mockReturnValue(scope(2)); + render(); + expect(withAll).toBe((await count()) + 1); + await waitFor(() => expect(mocks.listLeads).toHaveBeenLastCalledWith(expect.objectContaining({ companyId: 2 }))); + }); +}); diff --git a/solvway-admin-portal/app/companyScope.readonly.test.tsx b/solvway-admin-portal/app/companyScope.readonly.test.tsx new file mode 100644 index 0000000..2e89c89 --- /dev/null +++ b/solvway-admin-portal/app/companyScope.readonly.test.tsx @@ -0,0 +1,92 @@ +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(() => ({ + listAdminRoles: vi.fn(), + listInterests: vi.fn(), + apiGet: vi.fn(), + useAdminAuth: vi.fn(), +})); +vi.mock("@/app/lib/clientApi", async (i) => ({ ...(await i()), apiGet: mocks.apiGet, apiPost: vi.fn(), apiPut: vi.fn() })); +vi.mock("@/app/lib/services/adminRoles", async (i) => ({ ...(await i()), listAdminRoles: mocks.listAdminRoles })); +vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth })); +vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock); + +import { memoryRouter } from "@/test/memoryRouter"; +import RolesPage from "./roles/page"; +import InterestsPage from "./interests/page"; +import LoginSecurityPage from "./login-security/page"; + +const as = (isSuper: boolean) => mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper, hasModule: () => true }); + +beforeEach(() => { + memoryRouter.reset("/x"); + mocks.listAdminRoles.mockReset().mockResolvedValue([{ id: 4, name: "ROLE_HQ", parent: { id: 1 } }]); + mocks.apiGet.mockReset().mockImplementation(async (path: string) => { + if (path.includes("/interests")) return [{ id: 3, name: "Product A", active: true }]; + if (path.includes("/config")) return { enabled: true, maxAttempts: 5, period: 15, unit: "M" }; + if (path.includes("/password-rules")) return []; + return []; + }); + mocks.useAdminAuth.mockReset(); +}); + +describe("Roles read-only for staff", () => { + it("hides Add role, Edit and Manage access for staff", async () => { + as(false); + render(); + await screen.findByText("ROLE_HQ"); + expect(screen.queryByRole("button", { name: /add role/i })).not.toBeInTheDocument(); + expect(screen.queryByRole("button", { name: /^edit/i })).not.toBeInTheDocument(); + expect(screen.queryByRole("link", { name: /manage access/i })).not.toBeInTheDocument(); + }); + + it("keeps them for a super admin", async () => { + as(true); + render(); + await screen.findByText("ROLE_HQ"); + expect(screen.getByRole("button", { name: /add role/i })).toBeInTheDocument(); + }); +}); + +describe("Interests read-only for staff", () => { + it("hides Add interest and row actions for staff", async () => { + as(false); + render(); + await screen.findByText("Product A"); + expect(screen.queryByRole("button", { name: /add interest/i })).not.toBeInTheDocument(); + expect(screen.queryByRole("button", { name: /^edit/i })).not.toBeInTheDocument(); + expect(screen.queryByRole("button", { name: /deactivate/i })).not.toBeInTheDocument(); + }); + + it("keeps Add interest for a super admin", async () => { + as(true); + render(); + await screen.findByText("Product A"); + expect(screen.getByRole("button", { name: /add interest/i })).toBeInTheDocument(); + }); +}); + +describe("Login security Settings read-only for staff", () => { + async function openSettings() { + const user = userEvent.setup(); + render(); + await user.click(await screen.findByRole("tab", { name: /settings/i })); + return user; + } + + it("hides the Save buttons for staff", async () => { + as(false); + await openSettings(); + await waitFor(() => expect(mocks.apiGet).toHaveBeenCalledWith(expect.stringContaining("/config"))); + expect(screen.queryByRole("button", { name: /save lockout settings/i })).not.toBeInTheDocument(); + expect(screen.queryByRole("button", { name: /save password rules/i })).not.toBeInTheDocument(); + }); + + it("shows the Save buttons to a super admin", async () => { + as(true); + await openSettings(); + expect(await screen.findByRole("button", { name: /save lockout settings/i })).toBeInTheDocument(); + }); +}); diff --git a/solvway-admin-portal/app/companyScope.review.test.tsx b/solvway-admin-portal/app/companyScope.review.test.tsx new file mode 100644 index 0000000..d6d44dc --- /dev/null +++ b/solvway-admin-portal/app/companyScope.review.test.tsx @@ -0,0 +1,99 @@ +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(() => ({ + listAdminUsers: vi.fn(), + listAdminEvents: vi.fn(), + listEmails: vi.fn(), + searchAuditLog: vi.fn(), + listLeads: vi.fn(), + listAudit: vi.fn(), + listLocked: vi.fn(), + getConfig: vi.fn(), + getPasswordRules: vi.fn(), + useAdminAuth: vi.fn(), + useCompanyScope: vi.fn(), +})); +vi.mock("@/app/lib/services/adminUsers", async (i) => ({ ...(await i()), listAdminUsers: mocks.listAdminUsers })); +vi.mock("@/app/lib/services/adminEvents", async (i) => ({ ...(await i()), listAdminEvents: mocks.listAdminEvents })); +vi.mock("@/app/lib/services/adminEmails", async (i) => ({ ...(await i()), listEmails: mocks.listEmails })); +vi.mock("@/app/lib/services/auditLog", async (i) => ({ ...(await i()), searchAuditLog: mocks.searchAuditLog })); +vi.mock("@/app/lib/services/adminLeads", async (i) => ({ ...(await i()), listLeads: mocks.listLeads })); +vi.mock("@/app/lib/services/loginSecurity", async (i) => ({ + ...(await i()), + listAudit: mocks.listAudit, + listLocked: mocks.listLocked, + getConfig: mocks.getConfig, + getPasswordRules: mocks.getPasswordRules, +})); +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 { memoryRouter } from "@/test/memoryRouter"; +import UsersPage from "./users/page"; +import EventsPage from "./events/page"; +import EmailsPage from "./emails/page"; +import AuditLogPage from "./audit-log/page"; +import LeadsPage from "./leads/page"; +import LoginSecurityPage from "./login-security/page"; + +const scope = (companyId?: number) => ({ companyId, companies: [], showCompanyColumn: companyId === undefined, codeOf: () => "CV", setCompanyId: vi.fn() }); +const EMPTY = { items: [], total: 0 }; + +beforeEach(() => { + memoryRouter.reset("/x", "page=3"); + for (const m of [mocks.listAdminUsers, mocks.listAdminEvents, mocks.listEmails, mocks.searchAuditLog, mocks.listLeads, mocks.listAudit]) m.mockReset().mockResolvedValue(EMPTY); + mocks.listLocked.mockReset().mockResolvedValue([{ username: "jane", failures: 5, lastFailure: "2026-11-30T10:00:00", lockedUntil: "2026-11-30T11:00:00" }]); + mocks.getConfig.mockReset().mockResolvedValue({ enabled: true, maxAttempts: 5, period: 15, unit: "M" }); + mocks.getPasswordRules.mockReset().mockResolvedValue([{ id: 1, param: "MIN_LENGTH", status: "Y", value: "8" }]); + mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true, hasModule: () => true }); + mocks.useCompanyScope.mockReset().mockReturnValue(scope(1)); +}); + +describe.each([ + ["users", UsersPage, mocks.listAdminUsers], + ["events", EventsPage, mocks.listAdminEvents], + ["emails", EmailsPage, mocks.listEmails], + ["audit log", AuditLogPage, mocks.searchAuditLog], + ["leads", LeadsPage, mocks.listLeads], +])("%s picker change resets paging", (_name, Page, list) => { + it("returns to the first page when the company changes, not on first render", async () => { + const { rerender } = render(); + await waitFor(() => expect(list).toHaveBeenCalled()); + expect(memoryRouter.getSearch().get("page")).toBe("3"); + mocks.useCompanyScope.mockReturnValue(scope(2)); + rerender(); + await waitFor(() => expect(memoryRouter.getSearch().get("page")).toBeNull()); + }); +}); + +describe("login security", () => { + it("history returns to the first page when the company changes", async () => { + const { rerender } = render(); + await waitFor(() => expect(mocks.listAudit).toHaveBeenCalled()); + expect(memoryRouter.getSearch().get("page")).toBe("3"); + mocks.useCompanyScope.mockReturnValue(scope(2)); + rerender(); + await waitFor(() => expect(memoryRouter.getSearch().get("page")).toBeNull()); + }); + + it("Locked tab has no Company column on All companies", async () => { + mocks.useCompanyScope.mockReturnValue(scope()); + const user = userEvent.setup(); + render(); + await user.click(screen.getByRole("tab", { name: "Locked" })); + await screen.findByText("jane"); + expect(screen.queryByRole("columnheader", { name: "Company" })).not.toBeInTheDocument(); + }); + + it("disables the settings inputs for a non-super user", async () => { + mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper: false, hasModule: () => true }); + const user = userEvent.setup(); + render(); + await user.click(screen.getByRole("tab", { name: "Settings" })); + expect(await screen.findByLabelText(/max/i)).toBeDisabled(); + expect(screen.getByRole("switch", { name: /min/i })).toBeDisabled(); + }); +}); diff --git a/solvway-admin-portal/app/components/app/AppShell.tsx b/solvway-admin-portal/app/components/app/AppShell.tsx index ad71f96..971dd2f 100644 --- a/solvway-admin-portal/app/components/app/AppShell.tsx +++ b/solvway-admin-portal/app/components/app/AppShell.tsx @@ -4,6 +4,7 @@ import { useEffect } from "react"; import { usePathname, useRouter } from "next/navigation"; import { useAdminAuth } from "@/app/lib/AdminAuthContext"; import { isPublicPath } from "@/app/lib/routeGuard"; +import { CompanyScopeProvider } from "@/app/lib/CompanyScope"; import Header from "./Header"; import Sidebar from "./Sidebar"; import PoweredBy from "./PoweredBy"; @@ -45,6 +46,7 @@ export default function AppShell({ children }: { children: React.ReactNode }) { } return ( +
@@ -63,5 +65,6 @@ export default function AppShell({ children }: { children: React.ReactNode }) {
+
); } diff --git a/solvway-admin-portal/app/components/app/CompanyPicker.tsx b/solvway-admin-portal/app/components/app/CompanyPicker.tsx new file mode 100644 index 0000000..96ac7a5 --- /dev/null +++ b/solvway-admin-portal/app/components/app/CompanyPicker.tsx @@ -0,0 +1,26 @@ +"use client"; + +import { useAdminAuth } from "@/app/lib/AdminAuthContext"; +import { useCompanyScope } from "@/app/lib/CompanyScope"; +import { useT } from "@/app/lib/i18n/MessagesProvider"; + +// Header company filter; super admins only (staff are always scoped by the server). +export default function CompanyPicker() { + const { isSuper } = useAdminAuth(); + const { companyId, setCompanyId, companies } = useCompanyScope(); + const t = useT(); + if (!isSuper) return null; + return ( + + ); +} diff --git a/solvway-admin-portal/app/components/app/Header.logout.test.tsx b/solvway-admin-portal/app/components/app/Header.logout.test.tsx new file mode 100644 index 0000000..3d21562 --- /dev/null +++ b/solvway-admin-portal/app/components/app/Header.logout.test.tsx @@ -0,0 +1,22 @@ +import { render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +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: () => [] })); +vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ name: "Admin User", companyCode: null, hasModule: () => false }) })); +vi.mock("@/app/lib/theme", () => ({ useTheme: () => ({ theme: "light", toggleTheme: vi.fn() }) })); + +import Header from "./Header"; + +describe("Header logout", () => { + it("clears the stored company choice", async () => { + sessionStorage.setItem("company-scope", "2"); + vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(null, { status: 204 }))); + const user = userEvent.setup(); + render(
); + await user.click(screen.getByRole("button", { name: /admin user/i })); + await user.click(await screen.findByText(/logout/i)); + await waitFor(() => expect(sessionStorage.getItem("company-scope")).toBeNull()); + }); +}); diff --git a/solvway-admin-portal/app/components/app/Header.tsx b/solvway-admin-portal/app/components/app/Header.tsx index 830be14..fc5bfa0 100644 --- a/solvway-admin-portal/app/components/app/Header.tsx +++ b/solvway-admin-portal/app/components/app/Header.tsx @@ -19,6 +19,8 @@ import { import { Sheet, SheetContent, SheetTitle } from "@/app/components/ui/sheet"; import Breadcrumbs from "./Breadcrumbs"; import { BrandLink, SidebarNav } from "./Sidebar"; +import CompanyPicker from "./CompanyPicker"; +import { clearStoredCompany } from "@/app/lib/CompanyScope"; import LocaleSwitcher from "./LocaleSwitcher"; import ChangePasswordDialog from "./ChangePasswordDialog"; @@ -41,6 +43,7 @@ export default function Header() { // app/api/auth/logout/route.ts), so the browser always ends up signed out // locally even if this request itself fails. try { + clearStoredCompany(); await fetch("/api/auth/logout", { method: "POST" }); } catch { // Network failure: still sign out locally below. @@ -73,6 +76,7 @@ export default function Header() {
+ + )} diff --git a/solvway-admin-portal/app/event-leads/[eventUuid]/page.tsx b/solvway-admin-portal/app/event-leads/[eventUuid]/page.tsx index a2396fd..821a2c0 100644 --- a/solvway-admin-portal/app/event-leads/[eventUuid]/page.tsx +++ b/solvway-admin-portal/app/event-leads/[eventUuid]/page.tsx @@ -18,6 +18,7 @@ import { useListFilters } from "@/app/lib/hooks/useListFilters"; import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize"; import { exportEventLeads, listEventLeads, listEventSalespeople, listEventLeadInterests, listEventLeadEvents } from "@/app/lib/services/adminEventLeads"; import type { EventLeadRow, InterestOption, SalespersonOption } from "@/app/lib/types"; +import { useCompanyScope } from "@/app/lib/CompanyScope"; import { useT } from "@/app/lib/i18n/MessagesProvider"; import { formatDmy } from "@/app/lib/date-input"; @@ -30,6 +31,7 @@ const STATUS_BADGE = { OPEN: "neutral", CONTACTED: "neutral", QUALIFIED: "contra function EventLeadsDetailPageContent() { const t = useT(); + const { companyId, showCompanyColumn, codeOf } = useCompanyScope(); const { hasModule } = useAdminAuth(); const { eventUuid } = useParams<{ eventUuid: string }>(); const { tableRef, pageSize } = useFitPageSize(); @@ -46,7 +48,7 @@ function EventLeadsDetailPageContent() { // Load event name from the events list useEffect(() => { let cancelled = false; - listEventLeadEvents() + (companyId ? listEventLeadEvents(companyId) : listEventLeadEvents()) .then((events) => { if (!cancelled) { const found = events.find((e) => e.uuid === eventUuid); @@ -55,7 +57,7 @@ function EventLeadsDetailPageContent() { }) .catch(() => { if (!cancelled) setEventName(null); }); return () => { cancelled = true; }; - }, [eventUuid]); + }, [eventUuid, companyId]); const [exporting, setExporting] = useState(false); const [exportError, setExportError] = useState(null); @@ -63,7 +65,7 @@ function EventLeadsDetailPageContent() { const runExport = () => { setExporting(true); setExportError(null); - exportEventLeads(eventUuid, filters) + (companyId ? exportEventLeads(eventUuid, filters, companyId) : exportEventLeads(eventUuid, filters)) .catch((err: unknown) => { const tooLarge = err instanceof ApiError && (err.data as { code?: string } | undefined)?.code === "EXPORT_TOO_LARGE"; setExportError(tooLarge ? t("LeadsExportTooLarge") : err instanceof Error ? err.message : t("LeadListLoadFailed")); @@ -96,7 +98,7 @@ function EventLeadsDetailPageContent() { setLoading(true); setError(null); setExportError(null); - listEventLeads(eventUuid, { page, pageSize, ...filters }) + listEventLeads(eventUuid, { page, pageSize, ...filters, companyId }) .then((result) => { if (!cancelled) setData(result); }) @@ -107,7 +109,7 @@ function EventLeadsDetailPageContent() { if (!cancelled) setLoading(false); }); return () => { cancelled = true; }; - }, [eventUuid, filters, page, pageSize, reloadKey]); + }, [eventUuid, filters, page, pageSize, reloadKey, companyId]); const salespersonOptions = useMemo( () => salespeople.map((o) => ({ value: String(o.id), label: o.name })), @@ -136,6 +138,7 @@ function EventLeadsDetailPageContent() { const columns = useMemo[]>( () => [ + ...(showCompanyColumn ? [{ id: "company", accessorFn: (r: EventLeadRow) => codeOf(r.companyId ?? 0), header: t("Company"), enableSorting: false } as ColumnDef] : []), { accessorKey: "name", header: t("LeadName"), @@ -206,7 +209,7 @@ function EventLeadsDetailPageContent() { cell: ({ row }) => {row.original.nextFollowUpDate ? formatDmy(row.original.nextFollowUpDate) : "—"}, }, ], - [t], + [t, showCompanyColumn, codeOf], ); return ( diff --git a/solvway-admin-portal/app/event-leads/page.tsx b/solvway-admin-portal/app/event-leads/page.tsx index fbe2b14..417d123 100644 --- a/solvway-admin-portal/app/event-leads/page.tsx +++ b/solvway-admin-portal/app/event-leads/page.tsx @@ -8,6 +8,7 @@ import { RequireModule } from "@/app/lib/RequireModule"; import { PageHeader } from "@/app/components/ui/page-header"; import { listEventLeadEvents } from "@/app/lib/services/adminEventLeads"; import type { EventLeadEvent } from "@/app/lib/types"; +import { useCompanyScope } from "@/app/lib/CompanyScope"; import { useT } from "@/app/lib/i18n/MessagesProvider"; import { formatDmy } from "@/app/lib/date-input"; @@ -18,6 +19,7 @@ const isoToday = () => { function EventLeadsPageContent() { const t = useT(); + const { companyId } = useCompanyScope(); const [events, setEvents] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); @@ -28,7 +30,7 @@ function EventLeadsPageContent() { // eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error before the triggered fetch below, which is the actual synchronization. setLoading(true); setError(null); - listEventLeadEvents() + (companyId ? listEventLeadEvents(companyId) : listEventLeadEvents()) .then((data) => { if (!cancelled) setEvents(data); }) @@ -39,7 +41,7 @@ function EventLeadsPageContent() { if (!cancelled) setLoading(false); }); return () => { cancelled = true; }; - }, [reloadKey]); + }, [reloadKey, companyId]); const today = isoToday(); const sorted = events diff --git a/solvway-admin-portal/app/events/page.tsx b/solvway-admin-portal/app/events/page.tsx index ced7390..26a1fe2 100644 --- a/solvway-admin-portal/app/events/page.tsx +++ b/solvway-admin-portal/app/events/page.tsx @@ -14,10 +14,12 @@ import { RowActions } from "@/app/components/ui/row-actions"; import { EmptyState, ErrorState } from "@/app/components/ui/states"; import { RequireModule } from "@/app/lib/RequireModule"; import { useListFilters } from "@/app/lib/hooks/useListFilters"; +import { useResetPageOnCompany } from "@/app/lib/hooks/useResetPageOnCompany"; import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize"; import { listAdminEvents } from "@/app/lib/services/adminEvents"; import type { AdminEvent } from "@/app/lib/types"; import { useTableSort } from "@/app/lib/hooks/useTableSort"; +import { useCompanyScope } from "@/app/lib/CompanyScope"; import { useT } from "@/app/lib/i18n/MessagesProvider"; import { formatDmy } from "@/app/lib/date-input"; @@ -27,9 +29,11 @@ export const EVENT_STATUS_FILTER_OPTIONS = [{ value: "Y", label: "Enabled" }, { function EventsPageContent() { const t = useT(); + const { companyId, showCompanyColumn, codeOf } = useCompanyScope(); const router = useRouter(); const { tableRef, pageSize } = useFitPageSize(); const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS); + useResetPageOnCompany(setPage); const { sorting, onSortingChange, sortBy, sortDir } = useTableSort(); const [data, setData] = useState<{ items: AdminEvent[]; total: number }>({ items: [], total: 0 }); const [loading, setLoading] = useState(true); @@ -44,7 +48,7 @@ function EventsPageContent() { // eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error before the filter/page/reloadKey-triggered fetch below, which is the actual synchronization. setLoading(true); setError(null); - listAdminEvents({ q: filters.q || undefined, enabled: filters.enabled || undefined, page, pageSize, sortBy, sortDir }) + listAdminEvents({ q: filters.q || undefined, enabled: filters.enabled || undefined, page, pageSize, sortBy, sortDir, companyId }) .then((result) => { if (!cancelled) setData(result); }) @@ -57,7 +61,7 @@ function EventsPageContent() { return () => { cancelled = true; }; - }, [filters, page, reloadKey, pageSize, sortBy, sortDir]); + }, [filters, page, reloadKey, pageSize, sortBy, sortDir, companyId]); const statusOptions = useMemo( () => EVENT_STATUS_FILTER_OPTIONS.map((o) => ({ value: o.value, label: t(o.label) })), @@ -75,6 +79,7 @@ function EventsPageContent() { ), }, + ...(showCompanyColumn ? [{ id: "company", accessorFn: (e: AdminEvent) => codeOf(e.companyId ?? 0), header: t("Company"), enableSorting: false } as ColumnDef] : []), { accessorKey: "location", header: t("Location"), enableSorting: false }, { accessorKey: "startDate", @@ -118,7 +123,7 @@ function EventsPageContent() { ), }, ], - [t, router], + [t, router, showCompanyColumn, codeOf], ); return ( diff --git a/solvway-admin-portal/app/interests/page.tsx b/solvway-admin-portal/app/interests/page.tsx index 7949586..14c8a59 100644 --- a/solvway-admin-portal/app/interests/page.tsx +++ b/solvway-admin-portal/app/interests/page.tsx @@ -3,6 +3,7 @@ import { useCallback, useEffect, useMemo, useState, type FormEvent } from "react"; import { Plus } from "lucide-react"; import type { ColumnDef } from "@tanstack/react-table"; +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"; @@ -136,6 +137,7 @@ function InterestFormDialog({ function InterestsPageContent() { const t = useT(); + const readOnly = useAdminAuth().isSuper === false; // super-admin-only writes; server returns 403 anyway const [interests, setInterests] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); @@ -185,10 +187,10 @@ function InterestsPageContent() { ), }, - { + ...(readOnly ? [] : [{ id: "actions", header: t("CatActions"), - cell: ({ row }) => ( + cell: ({ row }: { row: { original: AdminInterestEntity } }) => (
- } + )} /> {error && } diff --git a/solvway-admin-portal/app/leads/page.tsx b/solvway-admin-portal/app/leads/page.tsx index 828a866..d0f60e4 100644 --- a/solvway-admin-portal/app/leads/page.tsx +++ b/solvway-admin-portal/app/leads/page.tsx @@ -13,7 +13,9 @@ import { RequireModule } from "@/app/lib/RequireModule"; import { useAdminAuth } from "@/app/lib/AdminAuthContext"; import { ApiError } from "@/app/lib/clientApi"; import { useListFilters } from "@/app/lib/hooks/useListFilters"; +import { useResetPageOnCompany } from "@/app/lib/hooks/useResetPageOnCompany"; import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize"; +import { useCompanyScope } from "@/app/lib/CompanyScope"; import { exportLeads, listLeads } from "@/app/lib/services/adminLeads"; import type { LeadRow } from "@/app/lib/types"; import { useT } from "@/app/lib/i18n/MessagesProvider"; @@ -22,9 +24,11 @@ const DEFAULTS = { q: "" }; function LeadsPageContent() { const t = useT(); + const { companyId, showCompanyColumn, codeOf } = useCompanyScope(); const { hasModule } = useAdminAuth(); const { tableRef, pageSize } = useFitPageSize(); const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS); + useResetPageOnCompany(setPage); const [data, setData] = useState<{ items: LeadRow[]; total: number }>({ items: [], total: 0 }); const [loading, setLoading] = useState(true); const [failed, setFailed] = useState(false); @@ -36,7 +40,7 @@ function LeadsPageContent() { const runExport = () => { setExporting(true); setExportError(null); - exportLeads({ q: filters.q || undefined }) + exportLeads({ q: filters.q || undefined, companyId }) .catch((err: unknown) => { const tooLarge = err instanceof ApiError && (err.data as { code?: string } | undefined)?.code === "EXPORT_TOO_LARGE"; setExportError(tooLarge ? t("LeadsExportTooLarge") : err instanceof Error ? err.message : t("LeadListLoadFailed")); @@ -53,12 +57,12 @@ function LeadsPageContent() { setLoading(true); setFailed(false); setExportError(null); - listLeads({ q: filters.q || undefined, page, pageSize }) + listLeads({ q: filters.q || undefined, page, pageSize, companyId }) .then((result) => { if (!cancelled) setData(result); }) .catch(() => { if (!cancelled) setFailed(true); }) .finally(() => { if (!cancelled) setLoading(false); }); return () => { cancelled = true; }; - }, [filters, page, reloadKey, pageSize]); + }, [filters, page, reloadKey, pageSize, companyId]); const columns = useMemo[]>( () => [ @@ -72,6 +76,7 @@ function LeadsPageContent() { ), }, + ...(showCompanyColumn ? [{ id: "company", accessorFn: (r: LeadRow) => codeOf(r.companyId ?? 0), header: t("Company"), enableSorting: false } as ColumnDef] : []), { accessorKey: "mobile", header: t("LeadMobile"), enableSorting: false }, { accessorKey: "email", header: t("Email"), enableSorting: false }, { accessorKey: "companyName", header: t("LeadCompany"), enableSorting: false }, @@ -79,7 +84,7 @@ function LeadsPageContent() { { id: "lastEvent", header: t("LeadsLastEvent"), enableSorting: false, cell: ({ row }) => row.original.lastEvent?.name ?? "" }, { id: "latestSalesperson", header: t("LeadsLatestSalesperson"), enableSorting: false, cell: ({ row }) => row.original.latestSalesperson?.name ?? "" }, ], - [t], + [t, showCompanyColumn, codeOf], ); return ( diff --git a/solvway-admin-portal/app/lib/CompanyScope.stored.test.tsx b/solvway-admin-portal/app/lib/CompanyScope.stored.test.tsx new file mode 100644 index 0000000..f2e90ac --- /dev/null +++ b/solvway-admin-portal/app/lib/CompanyScope.stored.test.tsx @@ -0,0 +1,29 @@ +import { render, screen, waitFor } from "@testing-library/react"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ useAdminAuth: vi.fn(), listAdminCompanies: vi.fn() })); +vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth })); +vi.mock("@/app/lib/services/adminCompanies", () => ({ listAdminCompanies: mocks.listAdminCompanies })); + +import { CompanyScopeProvider, useCompanyScope } from "./CompanyScope"; + +function Probe() { + const s = useCompanyScope(); + return

{String(s.companyId)}

; +} + +beforeEach(() => { + sessionStorage.clear(); + mocks.useAdminAuth.mockReset().mockReturnValue({ isSuper: true }); + mocks.listAdminCompanies.mockReset().mockResolvedValue([{ id: 1, name: "Ins Co", code: "INS", status: "A" }]); +}); + +describe("stored company choice", () => { + it("falls back to All companies when the stored id is not in the companies list", async () => { + sessionStorage.setItem("company-scope", "99"); + render(); + await waitFor(() => expect(mocks.listAdminCompanies).toHaveBeenCalled()); + await waitFor(() => expect(screen.getByTestId("probe")).toHaveTextContent("undefined")); + expect(sessionStorage.getItem("company-scope")).toBeNull(); + }); +}); diff --git a/solvway-admin-portal/app/lib/CompanyScope.test.tsx b/solvway-admin-portal/app/lib/CompanyScope.test.tsx new file mode 100644 index 0000000..2e83735 --- /dev/null +++ b/solvway-admin-portal/app/lib/CompanyScope.test.tsx @@ -0,0 +1,71 @@ +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(() => ({ useAdminAuth: vi.fn(), listAdminCompanies: vi.fn() })); +vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth })); +vi.mock("@/app/lib/services/adminCompanies", () => ({ listAdminCompanies: mocks.listAdminCompanies })); + +import { CompanyScopeProvider, useCompanyScope } from "./CompanyScope"; +import CompanyPicker from "@/app/components/app/CompanyPicker"; + +const COMPANIES = [ + { id: 1, name: "Ins Co", code: "INS", status: "A" }, + { id: 2, name: "CV Co", code: "CV", status: "A" }, +]; + +function Probe() { + const s = useCompanyScope(); + return

{String(s.companyId)}|{String(s.showCompanyColumn)}|{s.codeOf(2)}

; +} +const renderScope = () => + render( + + + + , + ); + +beforeEach(() => { + sessionStorage.clear(); + mocks.listAdminCompanies.mockReset().mockResolvedValue(COMPANIES); + mocks.useAdminAuth.mockReset().mockReturnValue({ isSuper: true }); +}); + +describe("CompanyPicker", () => { + it("is shown to a super admin with All companies plus each company", async () => { + renderScope(); + const picker = await screen.findByRole("combobox", { name: "Company" }); + await waitFor(() => expect(picker.querySelectorAll("option")).toHaveLength(3)); + expect([...picker.querySelectorAll("option")].map((o) => o.textContent)).toEqual(["All companies", "INS", "CV"]); + expect(screen.getByTestId("probe")).toHaveTextContent("undefined|true|CV"); + }); + + it("is not shown to staff, who never load companies or get a companyId", async () => { + mocks.useAdminAuth.mockReturnValue({ isSuper: false }); + sessionStorage.setItem("company-scope", "2"); + renderScope(); + expect(screen.queryByRole("combobox", { name: "Company" })).not.toBeInTheDocument(); + expect(mocks.listAdminCompanies).not.toHaveBeenCalled(); + expect(screen.getByTestId("probe")).toHaveTextContent("undefined|false|"); + }); + + it("feeds the chosen company into the scope and keeps it for the tab; All companies clears it", async () => { + const user = userEvent.setup(); + renderScope(); + const picker = await screen.findByRole("combobox", { name: "Company" }); + await waitFor(() => expect(picker.querySelectorAll("option")).toHaveLength(3)); + await user.selectOptions(picker, "2"); + expect(screen.getByTestId("probe")).toHaveTextContent("2|false|CV"); + expect(sessionStorage.getItem("company-scope")).toBe("2"); + await user.selectOptions(picker, ""); + expect(screen.getByTestId("probe")).toHaveTextContent("undefined|true|CV"); + expect(sessionStorage.getItem("company-scope")).toBeNull(); + }); + + it("restores the choice from sessionStorage", async () => { + sessionStorage.setItem("company-scope", "1"); + renderScope(); + await waitFor(() => expect(screen.getByTestId("probe")).toHaveTextContent("1|false|CV")); + }); +}); diff --git a/solvway-admin-portal/app/lib/CompanyScope.tsx b/solvway-admin-portal/app/lib/CompanyScope.tsx new file mode 100644 index 0000000..08e1493 --- /dev/null +++ b/solvway-admin-portal/app/lib/CompanyScope.tsx @@ -0,0 +1,93 @@ +"use client"; + +import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from "react"; +import { useAdminAuth } from "@/app/lib/AdminAuthContext"; +import { listAdminCompanies } from "@/app/lib/services/adminCompanies"; +import type { AdminCompany } from "@/app/lib/types"; + +// A super admin's company picker choice, kept per tab. Staff get no scope at all: +// companyId stays undefined for them, so they never send the query param. +const KEY = "company-scope"; + +interface CompanyScope { + /** The picked company; undefined for "All companies" and for staff. */ + companyId: number | undefined; + setCompanyId: (id: number | undefined) => void; + companies: AdminCompany[]; + /** True for a super admin looking at All companies: lists then show a Company column. */ + showCompanyColumn: boolean; + /** Company code for a row's companyId ("" when unknown). */ + codeOf: (id?: number | null) => string; +} + +const Ctx = createContext({ + companyId: undefined, + setCompanyId: () => {}, + companies: [], + showCompanyColumn: false, + codeOf: () => "", +}); + +export const useCompanyScope = () => useContext(Ctx); + +function readStored(): number | undefined { + try { + const n = Number(sessionStorage.getItem(KEY)); + return n > 0 ? n : undefined; + } catch { + return undefined; + } +} + +export function clearStoredCompany() { + try { + sessionStorage.removeItem(KEY); + } catch { + // Storage blocked: nothing was stored. + } +} + +export function CompanyScopeProvider({ children }: { children: ReactNode }) { + const { isSuper } = useAdminAuth(); + const [picked, setPicked] = useState(readStored); + const [companies, setCompanies] = useState([]); + + useEffect(() => { + if (!isSuper) return; + let live = true; + listAdminCompanies() + .then((c) => { + if (!live) return; + setCompanies(c); + // A stored choice that is no longer a company (removed, or another login's) means All companies. + const stored = readStored(); + if (stored !== undefined && !c.some((x) => x.id === stored)) { + clearStoredCompany(); + setPicked(undefined); + } + }) + .catch(() => {}); + return () => { live = false; }; + }, [isSuper]); + + const value = useMemo(() => { + const companyId = isSuper ? picked : undefined; + return { + companyId, + setCompanyId: (id) => { + setPicked(id); + try { + if (id === undefined) clearStoredCompany(); + else sessionStorage.setItem(KEY, String(id)); + } catch { + // Storage blocked: the choice just lasts until reload. + } + }, + companies, + showCompanyColumn: !!isSuper && companyId === undefined, + codeOf: (id) => companies.find((c) => c.id === id)?.code ?? "", + }; + }, [isSuper, picked, companies]); + + return {children}; +} diff --git a/solvway-admin-portal/app/lib/hooks/useResetPageOnCompany.ts b/solvway-admin-portal/app/lib/hooks/useResetPageOnCompany.ts new file mode 100644 index 0000000..012f2f9 --- /dev/null +++ b/solvway-admin-portal/app/lib/hooks/useResetPageOnCompany.ts @@ -0,0 +1,14 @@ +"use client"; +import { useEffect, useRef } from "react"; +import { useCompanyScope } from "@/app/lib/CompanyScope"; + +/** A different company is a different list: go back to page 1 when the picker changes (not on first render). */ +export function useResetPageOnCompany(setPage: (p: number) => void) { + const { companyId } = useCompanyScope(); + const last = useRef(companyId); + useEffect(() => { + if (last.current === companyId) return; + last.current = companyId; + setPage(1); + }, [companyId, setPage]); +} diff --git a/solvway-admin-portal/app/lib/i18n/defaultMessages.ts b/solvway-admin-portal/app/lib/i18n/defaultMessages.ts index 887c949..29dc2d6 100644 --- a/solvway-admin-portal/app/lib/i18n/defaultMessages.ts +++ b/solvway-admin-portal/app/lib/i18n/defaultMessages.ts @@ -17,6 +17,10 @@ export const DEFAULT_MESSAGES: Record = { BackOfficePanelLeads: "Leads captured at every event", BackOfficePanelFollowUps: "Follow-ups for your sales team", Company: "Company", + AllCompanies: "All companies", + CompanySuperAdmin: "Super admin (no company)", + ChooseCompany: "Choose a company.", + SuperAdminNeedsRole: "A super admin must have the Super admin role.", CompanyBlankForSuper: "Leave blank for super admin", BO_COMPANIES: "Companies", CompAdd: "Add company", diff --git a/solvway-admin-portal/app/lib/services/adminEmails.ts b/solvway-admin-portal/app/lib/services/adminEmails.ts index a80c0aa..c2248fe 100644 --- a/solvway-admin-portal/app/lib/services/adminEmails.ts +++ b/solvway-admin-portal/app/lib/services/adminEmails.ts @@ -9,6 +9,7 @@ export interface EmailRow { subject: string; /** P pending, N failed, Y success. */ status: string; + companyId?: number; } export interface EmailDetail extends Omit { @@ -26,11 +27,13 @@ export interface EmailListParams { /** 1-based. */ page: number; pageSize: number; + companyId?: number; } export async function listEmails(params: EmailListParams): Promise<{ items: EmailRow[]; total: number }> { const qs = new URLSearchParams(); for (const key of ["recipient", "subject", "from", "to"] as const) if (params[key]) qs.set(key, params[key]); + if (params.companyId) qs.set("companyId", String(params.companyId)); qs.set("page", String(Math.max(0, params.page - 1))); qs.set("size", String(params.pageSize)); const raw = await apiGet<{ content?: EmailRow[]; totalElements?: number } | null>(`/api/emails?${qs}`); diff --git a/solvway-admin-portal/app/lib/services/adminEventLeads.ts b/solvway-admin-portal/app/lib/services/adminEventLeads.ts index b805246..edd5138 100644 --- a/solvway-admin-portal/app/lib/services/adminEventLeads.ts +++ b/solvway-admin-portal/app/lib/services/adminEventLeads.ts @@ -18,9 +18,11 @@ export interface EventLeadListParams extends EventLeadFilters { /** 1-based. */ page: number; pageSize: number; + companyId?: number; } -export const listEventLeadEvents = () => apiGet(`${BASE}/events`); +export const listEventLeadEvents = (companyId?: number) => + apiGet(`${BASE}/events${companyId ? `?companyId=${companyId}` : ""}`); export const listEventLeadInterests = () => apiGet(`${BASE}/interest-options`); export const listEventSalespeople = (eventUuid: string) => apiGet(`${BASE}/${eventUuid}/salesperson-options`); @@ -28,6 +30,7 @@ export const listEventSalespeople = (eventUuid: string) => export async function listEventLeads(eventUuid: string, params: EventLeadListParams): Promise<{ items: EventLeadRow[]; total: number }> { const qs = new URLSearchParams(); for (const key of FILTERS) if (params[key]) qs.set(key, params[key]); + if (params.companyId) qs.set("companyId", String(params.companyId)); qs.set("page", String(Math.max(0, params.page - 1))); qs.set("size", String(params.pageSize)); const raw = await apiGet<{ content?: EventLeadRow[]; totalElements?: number } | null>(`${BASE}/${eventUuid}/leads?${qs}`); @@ -35,8 +38,8 @@ export async function listEventLeads(eventUuid: string, params: EventLeadListPar return { items, total: typeof raw?.totalElements === "number" ? raw.totalElements : items.length }; } -export const matchLead = (eventUuid: string, contact: { mobile: string | null; email: string | null }) => - apiPost(`${BASE}/${eventUuid}/match`, contact); +export const matchLead = (eventUuid: string, contact: { mobile: string | null; email: string | null }, companyId?: number) => + apiPost(`${BASE}/${eventUuid}/match`, companyId ? { ...contact, companyId } : contact); export const captureEventLead = (eventUuid: string, payload: EventLeadCapturePayload) => apiPost(`${BASE}/${eventUuid}`, payload); export const getEventLead = (eventUuid: string, eventLeadUuid: string) => @@ -44,8 +47,9 @@ export const getEventLead = (eventUuid: string, eventLeadUuid: string) => export const updateEventLead = (eventUuid: string, eventLeadUuid: string, payload: EventLeadUpdatePayload) => apiPut(`${BASE}/${eventUuid}/leads/${eventLeadUuid}`, payload); -export function exportEventLeads(eventUuid: string, filters: EventLeadFilters) { +export function exportEventLeads(eventUuid: string, filters: EventLeadFilters, companyId?: number) { const qs = new URLSearchParams(); for (const key of FILTERS) if (filters[key]) qs.set(key, filters[key]); + if (companyId) qs.set("companyId", String(companyId)); return apiDownload(`${BASE}/${eventUuid}/export${qs.size ? `?${qs}` : ""}`, "event-leads.xlsx"); } diff --git a/solvway-admin-portal/app/lib/services/adminEvents.ts b/solvway-admin-portal/app/lib/services/adminEvents.ts index d8afeb5..db4ebb3 100644 --- a/solvway-admin-portal/app/lib/services/adminEvents.ts +++ b/solvway-admin-portal/app/lib/services/adminEvents.ts @@ -8,6 +8,7 @@ export interface AdminEventListParams { pageSize: number; sortBy?: string; sortDir?: "asc" | "desc"; + companyId?: number; } export interface AdminEventListResult { @@ -27,6 +28,7 @@ export async function listAdminEvents(params: AdminEventListParams): Promise("/api/events", payload); } -export async function listSalespersonOptions(): Promise { - return apiGet("/api/events/salesperson-options"); +export async function listSalespersonOptions(companyId?: number): Promise { + return apiGet(`/api/events/salesperson-options${companyId ? `?companyId=${companyId}` : ""}`); } diff --git a/solvway-admin-portal/app/lib/services/adminLeads.ts b/solvway-admin-portal/app/lib/services/adminLeads.ts index 20d23a8..5425de4 100644 --- a/solvway-admin-portal/app/lib/services/adminLeads.ts +++ b/solvway-admin-portal/app/lib/services/adminLeads.ts @@ -3,9 +3,10 @@ import type { LeadDetail, LeadRow, LeadUpdatePayload } from "@/app/lib/types"; const BASE = "/api/leads"; -export async function listLeads(params: { q?: string; /** 1-based. */ page: number; pageSize: number }): Promise<{ items: LeadRow[]; total: number }> { +export async function listLeads(params: { q?: string; /** 1-based. */ page: number; pageSize: number; companyId?: number }): Promise<{ items: LeadRow[]; total: number }> { const qs = new URLSearchParams(); if (params.q) qs.set("q", params.q); + if (params.companyId) qs.set("companyId", String(params.companyId)); qs.set("page", String(Math.max(0, params.page - 1))); qs.set("size", String(params.pageSize)); const raw = await apiGet<{ content?: LeadRow[]; totalElements?: number } | null>(`${BASE}?${qs}`); @@ -16,5 +17,9 @@ export async function listLeads(params: { q?: string; /** 1-based. */ page: numb export const getLead = (uuid: string) => apiGet(`${BASE}/${uuid}`); export const updateLead = (uuid: string, payload: LeadUpdatePayload) => apiPut(`${BASE}/${uuid}`, payload); -export const exportLeads = (params: { q?: string }) => - apiDownload(`${BASE}/export${params.q ? `?${new URLSearchParams({ q: params.q })}` : ""}`, "leads.xlsx"); +export function exportLeads(params: { q?: string; companyId?: number }) { + const qs = new URLSearchParams(); + if (params.q) qs.set("q", params.q); + if (params.companyId) qs.set("companyId", String(params.companyId)); + return apiDownload(`${BASE}/export${qs.size ? `?${qs}` : ""}`, "leads.xlsx"); +} diff --git a/solvway-admin-portal/app/lib/services/adminUsers.ts b/solvway-admin-portal/app/lib/services/adminUsers.ts index 55ab153..3846191 100644 --- a/solvway-admin-portal/app/lib/services/adminUsers.ts +++ b/solvway-admin-portal/app/lib/services/adminUsers.ts @@ -15,6 +15,8 @@ export interface AdminUserListParams { /** Server-side sort: attribute name + direction; sent only when present. */ sortBy?: string; sortDir?: "asc" | "desc"; + /** Super admin's company choice; omitted for All companies. */ + companyId?: number; } export interface AdminUserListResult { @@ -45,6 +47,7 @@ export async function listAdminUsers(params: AdminUserListParams): Promise { const qs = new URLSearchParams(); for (const key of ["actor", "module", "action", "outcome", "from", "to"] as const) if (params[key]) qs.set(key, params[key]); + if (params.companyId) qs.set("companyId", String(params.companyId)); qs.set("page", String(Math.max(0, params.page - 1))); qs.set("size", String(params.pageSize)); const raw = await apiGet<{ content?: AuditEvent[]; totalElements?: number } | null>(`${BASE}?${qs}`); diff --git a/solvway-admin-portal/app/lib/services/companyScope.test.ts b/solvway-admin-portal/app/lib/services/companyScope.test.ts new file mode 100644 index 0000000..c0e87e3 --- /dev/null +++ b/solvway-admin-portal/app/lib/services/companyScope.test.ts @@ -0,0 +1,76 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), apiPut: vi.fn(), apiDownload: vi.fn() })); +vi.mock("@/app/lib/clientApi", () => mocks); + +import { listAdminUsers } from "./adminUsers"; +import { listAdminEvents, listSalespersonOptions } from "./adminEvents"; +import { exportLeads, listLeads } from "./adminLeads"; +import { exportEventLeads, listEventLeadEvents, listEventLeads, matchLead } from "./adminEventLeads"; +import { listEmails } from "./adminEmails"; +import { searchAuditLog } from "./auditLog"; +import { listAudit, listLocked, unlock } from "./loginSecurity"; + +const url = (m: { mock: { calls: unknown[][] } }) => String(m.mock.calls.at(-1)?.[0]); + +beforeEach(() => { + for (const m of Object.values(mocks)) m.mockReset().mockResolvedValue({ content: [], totalElements: 0, items: [], total: 0 }); +}); + +describe("companyId on list and export queries", () => { + it("adds it to the users list only when set", async () => { + await listAdminUsers({ page: 1, pageSize: 20, companyId: 2 }); + expect(url(mocks.apiGet)).toContain("companyId=2"); + await listAdminUsers({ page: 1, pageSize: 20 }); + expect(url(mocks.apiGet)).not.toContain("companyId"); + }); + + it("adds it to events list and salesperson options", async () => { + await listAdminEvents({ page: 1, pageSize: 20, companyId: 2 }); + expect(url(mocks.apiGet)).toContain("companyId=2"); + await listSalespersonOptions(3); + expect(mocks.apiGet).toHaveBeenLastCalledWith("/api/events/salesperson-options?companyId=3"); + await listSalespersonOptions(); + expect(mocks.apiGet).toHaveBeenLastCalledWith("/api/events/salesperson-options"); + }); + + it("adds it to leads list and export", async () => { + await listLeads({ page: 1, pageSize: 20, companyId: 2 }); + expect(url(mocks.apiGet)).toContain("companyId=2"); + await exportLeads({ q: "x", companyId: 2 }); + expect(url(mocks.apiDownload)).toContain("companyId=2"); + await exportLeads({}); + expect(url(mocks.apiDownload)).not.toContain("companyId"); + }); + + it("adds it to event-lead events, leads and export", async () => { + await listEventLeadEvents(2); + expect(url(mocks.apiGet)).toContain("companyId=2"); + await listEventLeadEvents(); + expect(url(mocks.apiGet)).not.toContain("companyId"); + await listEventLeads("e1", { page: 1, pageSize: 20, companyId: 2 }); + expect(url(mocks.apiGet)).toContain("companyId=2"); + await exportEventLeads("e1", {}, 2); + expect(url(mocks.apiDownload)).toContain("companyId=2"); + }); + + it("adds it to emails, audit log, login history, locked list and unlock", async () => { + await listEmails({ page: 1, pageSize: 20, companyId: 2 }); + expect(url(mocks.apiGet)).toContain("companyId=2"); + await searchAuditLog({ page: 1, pageSize: 20, companyId: 2 }); + expect(url(mocks.apiGet)).toContain("companyId=2"); + await listAudit({ page: 1, pageSize: 20, companyId: 2 }); + expect(url(mocks.apiGet)).toContain("companyId=2"); + await listLocked(2); + expect(url(mocks.apiGet)).toContain("companyId=2"); + await unlock("jane", 2); + expect(url(mocks.apiPost)).toContain("companyId=2"); + }); + + it("puts companyId in the lead match body only when given", async () => { + await matchLead("e1", { mobile: "1", email: null }, 2); + expect(mocks.apiPost).toHaveBeenLastCalledWith(expect.any(String), { mobile: "1", email: null, companyId: 2 }); + await matchLead("e1", { mobile: "1", email: null }); + expect(mocks.apiPost.mock.calls.at(-1)?.[1]).toEqual({ mobile: "1", email: null }); + }); +}); diff --git a/solvway-admin-portal/app/lib/services/loginSecurity.ts b/solvway-admin-portal/app/lib/services/loginSecurity.ts index f2dda3c..4d4a55d 100644 --- a/solvway-admin-portal/app/lib/services/loginSecurity.ts +++ b/solvway-admin-portal/app/lib/services/loginSecurity.ts @@ -12,6 +12,7 @@ export interface AuditRow { ipAddress: string | null; userAgent: string | null; message: string | null; + companyId?: number; } export interface AuditParams { @@ -23,6 +24,7 @@ export interface AuditParams { /** 1-based. */ page: number; pageSize: number; + companyId?: number; } export interface LockedAccount { @@ -30,6 +32,7 @@ export interface LockedAccount { failures: number; lastFailure: string | null; lockedUntil: string | null; + companyId?: number; } export interface LockoutConfig { @@ -53,6 +56,7 @@ const BASE = "/api/login-security"; export async function listAudit(params: AuditParams): Promise<{ items: AuditRow[]; total: number }> { const qs = new URLSearchParams(); for (const key of ["username", "event", "from", "to"] as const) if (params[key]) qs.set(key, params[key]); + if (params.companyId) qs.set("companyId", String(params.companyId)); qs.set("page", String(Math.max(0, params.page - 1))); qs.set("size", String(params.pageSize)); const raw = await apiGet<{ content?: AuditRow[]; totalElements?: number } | null>(`${BASE}/audit?${qs}`); @@ -60,8 +64,10 @@ export async function listAudit(params: AuditParams): Promise<{ items: AuditRow[ return { items, total: typeof raw?.totalElements === "number" ? raw.totalElements : items.length }; } -export const listLocked = () => apiGet(`${BASE}/locked`); -export const unlock = (username: string) => apiPost(`${BASE}/locked/${encodeURIComponent(username)}/unlock`); +const scoped = (companyId?: number) => (companyId ? `?companyId=${companyId}` : ""); +export const listLocked = (companyId?: number) => apiGet(`${BASE}/locked${scoped(companyId)}`); +export const unlock = (username: string, companyId?: number) => + apiPost(`${BASE}/locked/${encodeURIComponent(username)}/unlock${scoped(companyId)}`); export const getConfig = () => apiGet(`${BASE}/config`); export const saveConfig = (cfg: LockoutConfig) => apiPut(`${BASE}/config`, cfg); export const getPasswordRules = () => apiGet(`${BASE}/password-rules`); diff --git a/solvway-admin-portal/app/lib/types.ts b/solvway-admin-portal/app/lib/types.ts index 00d2ab2..3959cb0 100644 --- a/solvway-admin-portal/app/lib/types.ts +++ b/solvway-admin-portal/app/lib/types.ts @@ -120,6 +120,13 @@ export interface AdminUser { enabled: boolean; status?: "Y" | "N" | "P"; roles: AdminRole[]; + /** Set by the server on rows; sent on create by super admins. */ + companyId?: number; + companyCode?: string; + /** Full "local@code"; `username` is the local part. */ + loginName?: string; + /** Create only: a super admin with no company. */ + superAdmin?: boolean; } /** One flat row of the ACL grant matrix for a role (GET/PUT @@ -142,6 +149,7 @@ export interface AdminEvent { endDate: string; enabled: boolean; team?: AdminEventMember[]; + companyId?: number; } export interface AdminEventMember { @@ -159,6 +167,7 @@ export interface AdminEventPayload { endDate: string; enabled?: boolean; salespersonIds: number[]; + companyId?: number; } /** A salesperson row from the salesperson-options endpoint. */ @@ -188,6 +197,7 @@ export interface EventLeadEvent { location: string | null; startDate: string | null; endDate: string | null; + companyId?: number; } export interface InterestOption { @@ -230,6 +240,7 @@ export interface EventLeadRow { nextFollowUpDate: string | null; notes: string | null; capturedAt: string; + companyId?: number; } export interface EventLeadUpdatePayload { @@ -249,6 +260,7 @@ export interface EventLeadCapturePayload extends EventLeadUpdatePayload { email?: string | null; companyName?: string | null; jobTitle?: string | null; + companyId?: number; } /** Lead records (`/api/admin/leads`). */ @@ -258,6 +270,7 @@ export interface LeadRow { mobile: string | null; email: string | null; companyName: string | null; + companyId?: number; jobTitle: string | null; eventCount: number; lastEvent: { uuid: string; name: string | null } | null; diff --git a/solvway-admin-portal/app/login-security/page.tsx b/solvway-admin-portal/app/login-security/page.tsx index b2516ac..9a08e49 100644 --- a/solvway-admin-portal/app/login-security/page.tsx +++ b/solvway-admin-portal/app/login-security/page.tsx @@ -1,5 +1,7 @@ "use client"; +import { useCompanyScope } from "@/app/lib/CompanyScope"; +import { useAdminAuth } from "@/app/lib/AdminAuthContext"; import { useCallback, useEffect, useMemo, useState } from "react"; import type { ColumnDef } from "@tanstack/react-table"; import { Button } from "@/app/components/ui/button"; @@ -17,6 +19,7 @@ import { PageHeader } from "@/app/components/ui/page-header"; import { EmptyState, ErrorState } from "@/app/components/ui/states"; import { RequireModule } from "@/app/lib/RequireModule"; import { useListFilters } from "@/app/lib/hooks/useListFilters"; +import { useResetPageOnCompany } from "@/app/lib/hooks/useResetPageOnCompany"; import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize"; import { formatEmailDate as formatDate } from "@/app/lib/services/adminEmails"; import { @@ -31,8 +34,10 @@ const errMessage = (err: unknown, fallback: string) => (err instanceof Error ? e function HistoryTab() { const t = useT(); + const { companyId, showCompanyColumn, codeOf } = useCompanyScope(); const { tableRef, pageSize } = useFitPageSize(); const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS); + useResetPageOnCompany(setPage); const [data, setData] = useState<{ items: AuditRow[]; total: number }>({ items: [], total: 0 }); const [loading, setLoading] = useState(true); const [failed, setFailed] = useState(false); @@ -52,17 +57,19 @@ function HistoryTab() { to: filters.to || undefined, page, pageSize, + companyId, }) .then((result) => { if (!cancelled) setData(result); }) .catch(() => { if (!cancelled) setFailed(true); }) .finally(() => { if (!cancelled) setLoading(false); }); return () => { cancelled = true; }; - }, [filters, page, reloadKey, pageSize]); + }, [filters, page, reloadKey, pageSize, companyId]); const eventOptions = useMemo(() => LOGIN_EVENTS.map((e) => ({ value: e, label: t(LOGIN_EVENT_KEYS[e]) })), [t]); const columns = useMemo[]>( () => [ { id: "datetime", header: t("LsTime"), enableSorting: false, cell: ({ row }) => formatDate(row.original.datetime) }, + ...(showCompanyColumn ? [{ id: "company", accessorFn: (r: AuditRow) => codeOf(r.companyId ?? 0), header: t("Company"), enableSorting: false } as ColumnDef] : []), { accessorKey: "username", header: t("Username"), enableSorting: false }, { id: "event", header: t("LsEvent"), enableSorting: false, cell: ({ row }) => t(LOGIN_EVENT_KEYS[row.original.event] ?? row.original.event) }, { accessorKey: "ipAddress", header: t("LsIp"), enableSorting: false }, @@ -74,7 +81,7 @@ function HistoryTab() { }, { accessorKey: "message", header: t("LsNote"), enableSorting: false }, ], - [t], + [t, showCompanyColumn, codeOf], ); return ( @@ -113,6 +120,7 @@ function HistoryTab() { function LockedTab() { const t = useT(); + const { companyId } = useCompanyScope(); const [rows, setRows] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); @@ -125,18 +133,18 @@ function LockedTab() { let cancelled = false; // eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading ahead of the reloadKey-triggered fetch below. setLoading(true); - listLocked() + (companyId ? listLocked(companyId) : listLocked()) .then((result) => { if (!cancelled) { setRows(result); setError(null); } }) .catch((err: unknown) => { if (!cancelled) setError(errMessage(err, "LsLockedLoadFailed")); }) .finally(() => { if (!cancelled) setLoading(false); }); return () => { cancelled = true; }; - }, [reloadKey]); + }, [reloadKey, companyId]); async function confirmUnlock() { if (!target) return; setBusy(true); try { - await unlock(target); + await (companyId ? unlock(target, companyId) : unlock(target)); setError(null); refetch(); } catch (err) { @@ -208,6 +216,7 @@ function NoticeLine({ notice }: { notice: Notice }) { function LockoutForm() { const t = useT(); + const readOnly = useAdminAuth().isSuper === false; // super-admin-only writes; server returns 403 anyway const [cfg, setCfg] = useState(null); const [saving, setSaving] = useState(false); const [notice, setNotice] = useState(null); @@ -241,21 +250,21 @@ function LockoutForm() {

{t("LsLockoutTitle")}

- setCfg({ ...cfg, enabled })} /> + setCfg({ ...cfg, enabled })} />
- setCfg({ ...cfg, maxAttempts: num(e.target.value) })} /> + setCfg({ ...cfg, maxAttempts: num(e.target.value) })} />
- setCfg({ ...cfg, period: num(e.target.value) })} /> + setCfg({ ...cfg, period: num(e.target.value) })} />
- setCfg({ ...cfg, unit: unit as LockoutConfig["unit"] })}> {LOCKOUT_UNITS.map((u) => {t(`LsUnit${u}`)})} @@ -264,7 +273,7 @@ function LockoutForm() {
- + {!readOnly && }
@@ -275,6 +284,7 @@ type RuleEdit = { status: "Y" | "N"; value: string | null }; function PasswordRulesForm() { const t = useT(); + const readOnly = useAdminAuth().isSuper === false; // super-admin-only writes; server returns 403 anyway const [rules, setRules] = useState(null); const [edits, setEdits] = useState>({}); const [saving, setSaving] = useState(false); @@ -329,11 +339,11 @@ function PasswordRulesForm() { {label} - edit(r.id, { status: on ? "Y" : "N" })} /> + edit(r.id, { status: on ? "Y" : "N" })} /> {!FLAG_RULE_PARAMS.includes(r.param) && ( - edit(r.id, { value: ev.target.value })} /> + edit(r.id, { value: ev.target.value })} /> )} @@ -342,7 +352,7 @@ function PasswordRulesForm() {
- + {!readOnly && }
diff --git a/solvway-admin-portal/app/roles/[id]/access/page.readonly.test.tsx b/solvway-admin-portal/app/roles/[id]/access/page.readonly.test.tsx new file mode 100644 index 0000000..b88e4c0 --- /dev/null +++ b/solvway-admin-portal/app/roles/[id]/access/page.readonly.test.tsx @@ -0,0 +1,32 @@ +import { render, screen, waitFor } from "@testing-library/react"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ getRoleGrantTree: vi.fn(), updateRoleGrantTree: vi.fn(), useAdminAuth: vi.fn(), getAdminRole: vi.fn() })); +vi.mock("@/app/lib/services/adminAcl", () => mocks); +vi.mock("@/app/lib/services/adminRoles", () => ({ getAdminRole: mocks.getAdminRole })); +vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth })); +vi.mock("next/navigation", () => ({ useParams: () => ({ id: "4" }) })); + +import RoleAccessPage from "./page"; + +beforeEach(() => { + mocks.getRoleGrantTree.mockReset().mockResolvedValue([ + { id: 1, name: "BO_ROOT", parentId: null, granted: true }, + { id: 2, name: "BO_USERS", parentId: 1, granted: false }, + ]); + mocks.getAdminRole.mockReset().mockResolvedValue({ id: 4, name: "Test Role", parent: { id: 1 } }); +}); + +describe("RoleAccessPage for staff", () => { + it("hides Save for a non-super user and shows it for a super admin", async () => { + mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper: false, hasModule: () => true, roles: [{ name: "ROLE_HQ" }] }); + const { unmount } = render(); + await waitFor(() => expect(screen.getByLabelText("Users")).toBeInTheDocument()); + expect(screen.queryByRole("button", { name: /save/i })).not.toBeInTheDocument(); + unmount(); + mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper: true, hasModule: () => true, roles: [{ name: "ROLE_HQ" }] }); + render(); + await waitFor(() => expect(screen.getByLabelText("Users")).toBeInTheDocument()); + expect(screen.getByRole("button", { name: /save/i })).toBeInTheDocument(); + }); +}); diff --git a/solvway-admin-portal/app/roles/[id]/access/page.tsx b/solvway-admin-portal/app/roles/[id]/access/page.tsx index ab69bdf..6bb5598 100644 --- a/solvway-admin-portal/app/roles/[id]/access/page.tsx +++ b/solvway-admin-portal/app/roles/[id]/access/page.tsx @@ -77,7 +77,7 @@ function GrantTreeNode({ function RoleAccessPageContent() { const { id } = useParams<{ id: string }>(); const roleId = Number(id); - const { roles: myRoles } = useAdminAuth(); + const { roles: myRoles, isSuper } = useAdminAuth(); const t = useT(); const [rows, setRows] = useState([]); @@ -226,9 +226,11 @@ function RoleAccessPageContent() { - + {isSuper !== false && ( + + )}
{confirming && ( diff --git a/solvway-admin-portal/app/roles/page.tsx b/solvway-admin-portal/app/roles/page.tsx index 4a2c1c1..ae7c3c5 100644 --- a/solvway-admin-portal/app/roles/page.tsx +++ b/solvway-admin-portal/app/roles/page.tsx @@ -3,6 +3,7 @@ import { useCallback, useEffect, useMemo, useState, type FormEvent } from "react"; import { Plus } from "lucide-react"; import type { ColumnDef, SortingState } from "@tanstack/react-table"; +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"; @@ -88,6 +89,7 @@ function RoleFormDialog({ function RolesPageContent() { const t = useT(); + const readOnly = useAdminAuth().isSuper === false; // super-admin-only writes; server returns 403 anyway const [roles, setRoles] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); @@ -148,10 +150,10 @@ function RolesPageContent() { header: t("ModulesParent"), cell: ({ row }) => parentLabel(row.original), }, - { + ...(readOnly ? [] : [{ id: "actions", header: t("CatActions"), - cell: ({ row }) => ( + cell: ({ row }: { row: { original: AdminRoleEntity } }) => (
), - }, + }]), ], - [parentLabel, t], + [parentLabel, t, readOnly], ); return ( <> setDialog(EMPTY_FORM)}>