feat(portal): company picker, Company column, company fields and super-admin-only screens
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
1 parent
57e187a992
commit
c8ffc6aede
43 files changed
+1189
-74
No files matched your search
@@ -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");
|
||||
|
||||
@@ -7,7 +7,10 @@ export async function GET(req: NextRequest) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
|
||||
const result = await callMobileApi<Record<string, unknown>>("/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<Record<string, unknown>>(`/api/admin/events/salesperson-options${qs.size ? `?${qs}` : ""}`, { token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -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<typeof POST>[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");
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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") => <span className={`block truncate ${max}`} title={text ?? undefined}>{text}</span>;
|
||||
const columns = useMemo<ColumnDef<AuditEvent, unknown>[]>(
|
||||
() => [
|
||||
...(showCompanyColumn ? [{ id: "company", accessorFn: (r: AuditEvent) => codeOf(r.companyId ?? 0), header: t("Company"), enableSorting: false } as ColumnDef<AuditEvent, unknown>] : []),
|
||||
{ id: "time", header: t("LsTime"), enableSorting: false, cell: ({ row }) => <span className="whitespace-nowrap">{formatDate(row.original.occurredAt)}</span> },
|
||||
{ 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 (
|
||||
|
||||
@@ -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<typeof import("@/app/lib/services/adminEventLeads")>()),
|
||||
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(<NewEventLeadPage />);
|
||||
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(<NewEventLeadPage />);
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -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<typeof userEvent.setup>) {
|
||||
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(<UserForm onSubmit={onSubmit} />);
|
||||
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(<UserForm onSubmit={onSubmit} />);
|
||||
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(<UserForm onSubmit={onSubmit} />);
|
||||
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(<UserForm onSubmit={onSubmit} />);
|
||||
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(<UserForm onSubmit={onSubmit} />);
|
||||
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(<EventForm onSubmit={onSubmit} />);
|
||||
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(<EventForm onSubmit={vi.fn()} />);
|
||||
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(<EventForm onSubmit={vi.fn()} />);
|
||||
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(
|
||||
<EventForm
|
||||
initial={{ uuid: "e1", name: "Expo", location: "KL", startDate: "2026-12-01", endDate: "2026-12-02", enabled: true, companyId: 2, salespersons: [] } as never}
|
||||
onSubmit={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
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(<EventForm onSubmit={onSubmit} />);
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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<object>()), listAdminUsers: mocks.listAdminUsers }));
|
||||
vi.mock("@/app/lib/services/adminEvents", async (i) => ({ ...(await i<object>()), listAdminEvents: mocks.listAdminEvents }));
|
||||
vi.mock("@/app/lib/services/adminEmails", async (i) => ({ ...(await i<object>()), listEmails: mocks.listEmails }));
|
||||
vi.mock("@/app/lib/services/auditLog", async (i) => ({ ...(await i<object>()), searchAuditLog: mocks.searchAuditLog }));
|
||||
vi.mock("@/app/lib/services/adminLeads", async (i) => ({ ...(await i<object>()), 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<number, string> = { 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(<Page />);
|
||||
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(<Page />);
|
||||
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(<Page />);
|
||||
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(<UsersPage />);
|
||||
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(<LeadsPage />);
|
||||
const withAll = await count();
|
||||
unmount();
|
||||
mocks.useCompanyScope.mockReturnValue(scope(2));
|
||||
render(<LeadsPage />);
|
||||
expect(withAll).toBe((await count()) + 1);
|
||||
await waitFor(() => expect(mocks.listLeads).toHaveBeenLastCalledWith(expect.objectContaining({ companyId: 2 })));
|
||||
});
|
||||
});
|
||||
@@ -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<object>()), apiGet: mocks.apiGet, apiPost: vi.fn(), apiPut: vi.fn() }));
|
||||
vi.mock("@/app/lib/services/adminRoles", async (i) => ({ ...(await i<object>()), 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(<RolesPage />);
|
||||
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(<RolesPage />);
|
||||
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(<InterestsPage />);
|
||||
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(<InterestsPage />);
|
||||
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(<LoginSecurityPage />);
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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<object>()), listAdminUsers: mocks.listAdminUsers }));
|
||||
vi.mock("@/app/lib/services/adminEvents", async (i) => ({ ...(await i<object>()), listAdminEvents: mocks.listAdminEvents }));
|
||||
vi.mock("@/app/lib/services/adminEmails", async (i) => ({ ...(await i<object>()), listEmails: mocks.listEmails }));
|
||||
vi.mock("@/app/lib/services/auditLog", async (i) => ({ ...(await i<object>()), searchAuditLog: mocks.searchAuditLog }));
|
||||
vi.mock("@/app/lib/services/adminLeads", async (i) => ({ ...(await i<object>()), listLeads: mocks.listLeads }));
|
||||
vi.mock("@/app/lib/services/loginSecurity", async (i) => ({
|
||||
...(await i<object>()),
|
||||
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(<Page />);
|
||||
await waitFor(() => expect(list).toHaveBeenCalled());
|
||||
expect(memoryRouter.getSearch().get("page")).toBe("3");
|
||||
mocks.useCompanyScope.mockReturnValue(scope(2));
|
||||
rerender(<Page />);
|
||||
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(<LoginSecurityPage />);
|
||||
await waitFor(() => expect(mocks.listAudit).toHaveBeenCalled());
|
||||
expect(memoryRouter.getSearch().get("page")).toBe("3");
|
||||
mocks.useCompanyScope.mockReturnValue(scope(2));
|
||||
rerender(<LoginSecurityPage />);
|
||||
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(<LoginSecurityPage />);
|
||||
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(<LoginSecurityPage />);
|
||||
await user.click(screen.getByRole("tab", { name: "Settings" }));
|
||||
expect(await screen.findByLabelText(/max/i)).toBeDisabled();
|
||||
expect(screen.getByRole("switch", { name: /min/i })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -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 (
|
||||
<CompanyScopeProvider>
|
||||
<div className="flex min-h-svh bg-background">
|
||||
<SessionKeepAlive />
|
||||
<Sidebar />
|
||||
@@ -63,5 +65,6 @@ export default function AppShell({ children }: { children: React.ReactNode }) {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CompanyScopeProvider>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<select
|
||||
aria-label={t("Company")}
|
||||
value={companyId ?? ""}
|
||||
onChange={(e) => setCompanyId(e.target.value ? Number(e.target.value) : undefined)}
|
||||
className="h-9 rounded-md border bg-background px-2 text-sm"
|
||||
>
|
||||
<option value="">{t("AllCompanies")}</option>
|
||||
{companies.map((c) => (
|
||||
<option key={c.id} value={c.id}>{c.code}</option>
|
||||
))}
|
||||
</select>
|
||||
);
|
||||
}
|
||||
@@ -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(<Header />);
|
||||
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());
|
||||
});
|
||||
});
|
||||
@@ -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() {
|
||||
</Sheet>
|
||||
<Breadcrumbs />
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<CompanyPicker />
|
||||
<LocaleSwitcher />
|
||||
|
||||
<Button
|
||||
|
||||
@@ -8,6 +8,8 @@ import { Label } from "@/app/components/ui/label";
|
||||
import { Switch } from "@/app/components/ui/switch";
|
||||
import { DatePicker } from "@/app/components/ui/date-picker";
|
||||
import { ErrorState } from "@/app/components/ui/states";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { listSalespersonOptions } from "@/app/lib/services/adminEvents";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import type { AdminEvent, AdminEventPayload, SalespersonOption } from "@/app/lib/types";
|
||||
@@ -31,10 +33,16 @@ const REQUIRED_MESSAGE: Record<string, string> = {
|
||||
endDate: "EvtEndRequired",
|
||||
};
|
||||
/** Fields the form can show an API error under; anything else goes to the top of the form. */
|
||||
const FIELD_ERROR_SLOTS = ["name", "location", "startDate", "endDate", "salespersonIds"];
|
||||
const FIELD_ERROR_SLOTS = ["company", "name", "location", "startDate", "endDate", "salespersonIds"];
|
||||
|
||||
export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
|
||||
const t = useT();
|
||||
const { isSuper } = useAdminAuth();
|
||||
const scope = useCompanyScope();
|
||||
// Super admins choose the company on create; on edit it is the event's own (it cannot move).
|
||||
const showCompany = isSuper === true && !initial;
|
||||
const [companyChoice, setCompanyChoice] = useState(scope.companyId ? String(scope.companyId) : "");
|
||||
const optionsCompanyId = isSuper === true ? (initial ? initial.companyId : Number(companyChoice) || undefined) : undefined;
|
||||
|
||||
const [name, setName] = useState(initial?.name ?? "");
|
||||
const [location, setLocation] = useState(initial?.location ?? "");
|
||||
@@ -55,7 +63,7 @@ export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- loading/picker reset is the actual synchronization; initial is in the deps below.
|
||||
setLoadingPickers(true);
|
||||
setPickersError(null);
|
||||
listSalespersonOptions()
|
||||
(optionsCompanyId ? listSalespersonOptions(optionsCompanyId) : listSalespersonOptions())
|
||||
.then((opts) => {
|
||||
if (cancelled) return;
|
||||
const activeOpts = opts.map((o) => ({ ...o, active: true } as SalespersonOptionExtended));
|
||||
@@ -86,7 +94,7 @@ export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [initial]);
|
||||
}, [initial, optionsCompanyId]);
|
||||
|
||||
// Build the set of initially selected team member IDs.
|
||||
// Members from initial.team that are also in the active options → checked.
|
||||
@@ -118,6 +126,7 @@ export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
|
||||
if (!endDate) errors.endDate = t("EvtEndRequired");
|
||||
if (endDate && startDate && endDate < startDate) errors.endDate = t("EvtEndBeforeStart");
|
||||
if (trimmedName.length > 100) errors.name = t("EvtNameTooLong");
|
||||
if (showCompany && !companyChoice) errors.company = t("ChooseCompany");
|
||||
if (trimmedLocation.length > 200) errors.location = t("EvtLocationTooLong");
|
||||
|
||||
setFieldErrors(errors);
|
||||
@@ -133,6 +142,7 @@ export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
|
||||
endDate,
|
||||
salespersonIds: Array.from(selectedIds).filter((id): id is number => id != null),
|
||||
};
|
||||
if (showCompany) payload.companyId = Number(companyChoice);
|
||||
// `enabled` is only sent on edit (when initial exists).
|
||||
if (initial) {
|
||||
payload.enabled = enabled;
|
||||
@@ -166,6 +176,33 @@ export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
|
||||
{formError && <ErrorState message={t(formError)} />}
|
||||
{pickersError && <ErrorState message={t(pickersError)} />}
|
||||
|
||||
{showCompany && (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="evt-company">{t("Company")}</Label>
|
||||
<select
|
||||
id="evt-company"
|
||||
value={companyChoice}
|
||||
onChange={(e) => {
|
||||
setCompanyChoice(e.target.value);
|
||||
setSelectedIds(new Set()); // the team is company-specific
|
||||
}}
|
||||
disabled={saving}
|
||||
aria-invalid={!!fieldErrors.company}
|
||||
className="h-9 w-full rounded-md border bg-background px-2 text-sm"
|
||||
>
|
||||
<option value="" />
|
||||
{scope.companies.map((c) => (
|
||||
<option key={c.id} value={c.id}>{c.code}</option>
|
||||
))}
|
||||
</select>
|
||||
{fieldErrors.company && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{fieldErrors.company}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="evt-name">{t("Name")}</Label>
|
||||
<Input
|
||||
|
||||
@@ -13,6 +13,7 @@ import { roleLabel } from "@/app/lib/roleLabel";
|
||||
import { Skeleton } from "@/app/components/ui/skeleton";
|
||||
import { listAdminRoles } from "@/app/lib/services/adminRoles";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import type { AdminUser } from "@/app/lib/types";
|
||||
import { PasswordFields } from "./PasswordFields";
|
||||
@@ -31,7 +32,7 @@ interface RoleOption {
|
||||
}
|
||||
|
||||
/** On create the payload also carries the admin-typed first password and its confirmation. */
|
||||
export type UserFormPayload = AdminUser & { password?: string; confirmPassword?: string };
|
||||
export type UserFormPayload = AdminUser & { password?: string; confirmPassword?: string; companyId?: number; superAdmin?: boolean };
|
||||
|
||||
export interface UserFormProps {
|
||||
initial?: AdminUser;
|
||||
@@ -43,7 +44,11 @@ export interface UserFormProps {
|
||||
|
||||
export function UserForm({ initial, onSubmit, submitLabel, withPassword }: UserFormProps) {
|
||||
const t = useT();
|
||||
const { id: myId } = useAdminAuth();
|
||||
const { id: myId, isSuper } = useAdminAuth();
|
||||
const scope = useCompanyScope();
|
||||
// Super admins pick the new user's company on create; "super" makes another company-less super admin.
|
||||
const showCompany = isSuper === true && initial?.id == null;
|
||||
const [company, setCompany] = useState(scope.companyId ? String(scope.companyId) : "");
|
||||
// The server refuses SELF_DEACTIVATION; this keeps the switch from offering it.
|
||||
const isOwnAccount = initial?.id != null && initial.id === myId;
|
||||
const [name, setName] = useState(initial?.name ?? "");
|
||||
@@ -114,6 +119,8 @@ export function UserForm({ initial, onSubmit, submitLabel, withPassword }: UserF
|
||||
if (!username.trim()) errors.username = t("UsrUsernameRequired");
|
||||
if (!email.trim()) errors.email = t("UsrEmailRequired");
|
||||
else if (!EMAIL_RE.test(email.trim())) errors.email = t("UsrEmailInvalid");
|
||||
if (showCompany && !company) errors.company = t("ChooseCompany");
|
||||
else if (showCompany && company === "super" && !selectedRoleIds.has(1)) errors.company = t("SuperAdminNeedsRole");
|
||||
if (withPassword && !password) errors.password = t("UsrPasswordRequired");
|
||||
else if (withPassword && password !== confirmPassword) errors.confirmPassword = t("UsrPasswordMismatch");
|
||||
setFieldErrors(errors);
|
||||
@@ -133,6 +140,7 @@ export function UserForm({ initial, onSubmit, submitLabel, withPassword }: UserF
|
||||
status: enabled ? "Y" : "N",
|
||||
roles: selectedRoles.map((r) => ({ id: r.id, name: r.name })),
|
||||
...(withPassword ? { password, confirmPassword } : {}),
|
||||
...(showCompany ? (company === "super" ? { superAdmin: true } : { companyId: Number(company) }) : {}),
|
||||
});
|
||||
} catch (err) {
|
||||
setFormError(err instanceof Error ? err.message : "UsrSaveFailed");
|
||||
@@ -209,6 +217,31 @@ export function UserForm({ initial, onSubmit, submitLabel, withPassword }: UserF
|
||||
)}
|
||||
</div>
|
||||
|
||||
{showCompany && (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="user-company">{t("Company")}</Label>
|
||||
<select
|
||||
id="user-company"
|
||||
value={company}
|
||||
onChange={(e) => setCompany(e.target.value)}
|
||||
disabled={saving}
|
||||
aria-invalid={!!fieldErrors.company}
|
||||
className="h-9 w-full rounded-md border bg-background px-2 text-sm"
|
||||
>
|
||||
<option value="" />
|
||||
{scope.companies.map((c) => (
|
||||
<option key={c.id} value={c.id}>{c.code}</option>
|
||||
))}
|
||||
<option value="super">{t("CompanySuperAdmin")}</option>
|
||||
</select>
|
||||
{fieldErrors.company && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{fieldErrors.company}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{withPassword && (
|
||||
<PasswordFields
|
||||
password={password}
|
||||
|
||||
@@ -10,7 +10,9 @@ 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 { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { EMAIL_STATUS_KEYS, formatEmailDate, listEmails, type EmailRow } from "@/app/lib/services/adminEmails";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
@@ -20,8 +22,10 @@ const DEFAULTS = { recipient: "", subject: "", from: "", to: "" };
|
||||
|
||||
function EmailsPageContent() {
|
||||
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: EmailRow[]; total: number }>({ items: [], total: 0 });
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [failed, setFailed] = useState(false);
|
||||
@@ -41,12 +45,13 @@ function EmailsPageContent() {
|
||||
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 columns = useMemo<ColumnDef<EmailRow, unknown>[]>(
|
||||
() => [
|
||||
@@ -62,9 +67,10 @@ function EmailsPageContent() {
|
||||
},
|
||||
{ id: "recipients", header: t("EmlRecipient"), enableSorting: false, cell: ({ row }) => row.original.recipients.join(", ") },
|
||||
{ id: "datetime", header: t("EmlDate"), enableSorting: false, cell: ({ row }) => formatEmailDate(row.original.datetime) },
|
||||
...(showCompanyColumn ? [{ id: "company", accessorFn: (r: EmailRow) => codeOf(r.companyId ?? 0), header: t("Company"), enableSorting: false } as ColumnDef<EmailRow, unknown>] : []),
|
||||
{ id: "status", header: t("Status"), enableSorting: false, cell: ({ row }) => t(EMAIL_STATUS_KEYS[row.original.status] ?? row.original.status) },
|
||||
],
|
||||
[t],
|
||||
[t, showCompanyColumn, codeOf],
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -12,7 +12,7 @@ import { ErrorState } from "@/app/components/ui/states";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { captureEventLead, listEventLeadInterests, listEventSalespeople, matchLead } from "@/app/lib/services/adminEventLeads";
|
||||
import { captureEventLead, listEventLeadEvents, listEventLeadInterests, listEventSalespeople, matchLead } from "@/app/lib/services/adminEventLeads";
|
||||
import type { InterestOption, LeadCandidate, LeadMatchResult, LeadStatus, LeadTemperature, SalespersonOption } from "@/app/lib/types";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
@@ -66,7 +66,11 @@ function readError(err: unknown, t: (k: string) => string, fallbackKey: string,
|
||||
function NewEventLead() {
|
||||
const t = useT();
|
||||
const router = useRouter();
|
||||
const { id: myId } = useAdminAuth();
|
||||
const { id: myId, isSuper } = useAdminAuth();
|
||||
// A super admin's lead belongs to the event's own company; staff are scoped by the server.
|
||||
const needsCompany = isSuper === true;
|
||||
const [eventCompanyId, setEventCompanyId] = useState<number | undefined>();
|
||||
const companyId = needsCompany ? eventCompanyId : undefined;
|
||||
const { eventUuid } = useParams<{ eventUuid: string }>();
|
||||
const [step, setStep] = useState<Step>("match");
|
||||
const [candidates, setCandidates] = useState<LeadCandidate[] | null>(null);
|
||||
@@ -103,6 +107,15 @@ function NewEventLead() {
|
||||
return () => { cancelled = true; };
|
||||
}, [eventUuid, t, myId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!needsCompany) return;
|
||||
let cancelled = false;
|
||||
listEventLeadEvents()
|
||||
.then((events) => { if (!cancelled) setEventCompanyId(events.find((e) => e.uuid === eventUuid)?.companyId ?? undefined); })
|
||||
.catch(() => { if (!cancelled) setOptionsError(t("LeadOptionsLoadFailed")); });
|
||||
return () => { cancelled = true; };
|
||||
}, [needsCompany, eventUuid, t]);
|
||||
|
||||
const fieldProps = (f: string) => ({
|
||||
id: `lead-${f}`,
|
||||
"aria-invalid": fieldErrors[f] ? (true as const) : undefined,
|
||||
@@ -122,7 +135,8 @@ function NewEventLead() {
|
||||
setFormError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
const result = await matchLead(eventUuid, { mobile: mobile.trim() || null, email: email.trim() || null });
|
||||
const body = { mobile: mobile.trim() || null, email: email.trim() || null };
|
||||
const result = await (companyId ? matchLead(eventUuid, body, companyId) : matchLead(eventUuid, body));
|
||||
setMatch(result);
|
||||
if (result.candidates.length === 0) startDetails(result, null);
|
||||
else setCandidates(result.candidates);
|
||||
@@ -168,6 +182,7 @@ function NewEventLead() {
|
||||
interestIds,
|
||||
nextFollowUpDate: nextFollowUpDate || null,
|
||||
notes: notes.trim() || null,
|
||||
...(companyId ? { companyId } : {}),
|
||||
});
|
||||
router.push(`/event-leads/${eventUuid}`);
|
||||
} catch (err) {
|
||||
@@ -204,7 +219,7 @@ function NewEventLead() {
|
||||
<form onSubmit={onMatch} className="space-y-4" noValidate>
|
||||
{textInput("mobile", t("LeadMobile"), mobile, setMobile, { type: "tel", inputMode: "tel", autoComplete: "tel" })}
|
||||
{textInput("email", t("Email"), email, setEmail, { type: "email", autoComplete: "email" })}
|
||||
<Button type="submit" className={`${TALL} w-full sm:w-auto`} disabled={busy}>{t("LeadNext")}</Button>
|
||||
<Button type="submit" className={`${TALL} w-full sm:w-auto`} disabled={busy || (needsCompany && !companyId)}>{t("LeadNext")}</Button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
|
||||
@@ -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<string | null>(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<ColumnDef<EventLeadRow, unknown>[]>(
|
||||
() => [
|
||||
...(showCompanyColumn ? [{ id: "company", accessorFn: (r: EventLeadRow) => codeOf(r.companyId ?? 0), header: t("Company"), enableSorting: false } as ColumnDef<EventLeadRow, unknown>] : []),
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: t("LeadName"),
|
||||
@@ -206,7 +209,7 @@ function EventLeadsDetailPageContent() {
|
||||
cell: ({ row }) => <span>{row.original.nextFollowUpDate ? formatDmy(row.original.nextFollowUpDate) : "—"}</span>,
|
||||
},
|
||||
],
|
||||
[t],
|
||||
[t, showCompanyColumn, codeOf],
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -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<EventLeadEvent[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(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
|
||||
|
||||
@@ -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() {
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
...(showCompanyColumn ? [{ id: "company", accessorFn: (e: AdminEvent) => codeOf(e.companyId ?? 0), header: t("Company"), enableSorting: false } as ColumnDef<AdminEvent, unknown>] : []),
|
||||
{ accessorKey: "location", header: t("Location"), enableSorting: false },
|
||||
{
|
||||
accessorKey: "startDate",
|
||||
@@ -118,7 +123,7 @@ function EventsPageContent() {
|
||||
),
|
||||
},
|
||||
],
|
||||
[t, router],
|
||||
[t, router, showCompanyColumn, codeOf],
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -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<AdminInterestEntity[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -185,10 +187,10 @@ function InterestsPageContent() {
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
...(readOnly ? [] : [{
|
||||
id: "actions",
|
||||
header: t("CatActions"),
|
||||
cell: ({ row }) => (
|
||||
cell: ({ row }: { row: { original: AdminInterestEntity } }) => (
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
@@ -236,21 +238,21 @@ function InterestsPageContent() {
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
}]),
|
||||
],
|
||||
[t, refetch],
|
||||
[t, refetch, readOnly],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={t("BO_INTERESTS")}
|
||||
actions={
|
||||
actions={readOnly ? undefined : (
|
||||
<Button onClick={() => setDialog(EMPTY_FORM)}>
|
||||
<Plus aria-hidden="true" className="size-4" />
|
||||
{t("IntAddInterest")}
|
||||
</Button>
|
||||
}
|
||||
)}
|
||||
/>
|
||||
|
||||
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
|
||||
|
||||
@@ -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<ColumnDef<LeadRow, unknown>[]>(
|
||||
() => [
|
||||
@@ -72,6 +76,7 @@ function LeadsPageContent() {
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
...(showCompanyColumn ? [{ id: "company", accessorFn: (r: LeadRow) => codeOf(r.companyId ?? 0), header: t("Company"), enableSorting: false } as ColumnDef<LeadRow, unknown>] : []),
|
||||
{ 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 (
|
||||
|
||||
@@ -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 <p data-testid="probe">{String(s.companyId)}</p>;
|
||||
}
|
||||
|
||||
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(<CompanyScopeProvider><Probe /></CompanyScopeProvider>);
|
||||
await waitFor(() => expect(mocks.listAdminCompanies).toHaveBeenCalled());
|
||||
await waitFor(() => expect(screen.getByTestId("probe")).toHaveTextContent("undefined"));
|
||||
expect(sessionStorage.getItem("company-scope")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -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 <p data-testid="probe">{String(s.companyId)}|{String(s.showCompanyColumn)}|{s.codeOf(2)}</p>;
|
||||
}
|
||||
const renderScope = () =>
|
||||
render(
|
||||
<CompanyScopeProvider>
|
||||
<CompanyPicker />
|
||||
<Probe />
|
||||
</CompanyScopeProvider>,
|
||||
);
|
||||
|
||||
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"));
|
||||
});
|
||||
});
|
||||
@@ -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<CompanyScope>({
|
||||
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<number | undefined>(readStored);
|
||||
const [companies, setCompanies] = useState<AdminCompany[]>([]);
|
||||
|
||||
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<CompanyScope>(() => {
|
||||
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 <Ctx.Provider value={value}>{children}</Ctx.Provider>;
|
||||
}
|
||||
@@ -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]);
|
||||
}
|
||||
@@ -17,6 +17,10 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
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",
|
||||
|
||||
@@ -9,6 +9,7 @@ export interface EmailRow {
|
||||
subject: string;
|
||||
/** P pending, N failed, Y success. */
|
||||
status: string;
|
||||
companyId?: number;
|
||||
}
|
||||
|
||||
export interface EmailDetail extends Omit<EmailRow, "recipients"> {
|
||||
@@ -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}`);
|
||||
|
||||
@@ -18,9 +18,11 @@ export interface EventLeadListParams extends EventLeadFilters {
|
||||
/** 1-based. */
|
||||
page: number;
|
||||
pageSize: number;
|
||||
companyId?: number;
|
||||
}
|
||||
|
||||
export const listEventLeadEvents = () => apiGet<EventLeadEvent[]>(`${BASE}/events`);
|
||||
export const listEventLeadEvents = (companyId?: number) =>
|
||||
apiGet<EventLeadEvent[]>(`${BASE}/events${companyId ? `?companyId=${companyId}` : ""}`);
|
||||
export const listEventLeadInterests = () => apiGet<InterestOption[]>(`${BASE}/interest-options`);
|
||||
export const listEventSalespeople = (eventUuid: string) =>
|
||||
apiGet<SalespersonOption[]>(`${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<LeadMatchResult>(`${BASE}/${eventUuid}/match`, contact);
|
||||
export const matchLead = (eventUuid: string, contact: { mobile: string | null; email: string | null }, companyId?: number) =>
|
||||
apiPost<LeadMatchResult>(`${BASE}/${eventUuid}/match`, companyId ? { ...contact, companyId } : contact);
|
||||
export const captureEventLead = (eventUuid: string, payload: EventLeadCapturePayload) =>
|
||||
apiPost<EventLeadRow>(`${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<EventLeadRow>(`${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");
|
||||
}
|
||||
@@ -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<Adm
|
||||
const qs = new URLSearchParams();
|
||||
if (params.q) qs.set("q", params.q);
|
||||
if (params.enabled) qs.set("enabled", params.enabled);
|
||||
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));
|
||||
if (params.sortBy) qs.set("sortBy", params.sortBy);
|
||||
@@ -45,6 +47,6 @@ export async function saveAdminEvent(payload: AdminEventPayload, uuid?: string):
|
||||
: apiPost<AdminEvent>("/api/events", payload);
|
||||
}
|
||||
|
||||
export async function listSalespersonOptions(): Promise<SalespersonOption[]> {
|
||||
return apiGet<SalespersonOption[]>("/api/events/salesperson-options");
|
||||
export async function listSalespersonOptions(companyId?: number): Promise<SalespersonOption[]> {
|
||||
return apiGet<SalespersonOption[]>(`/api/events/salesperson-options${companyId ? `?companyId=${companyId}` : ""}`);
|
||||
}
|
||||
@@ -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<LeadDetail>(`${BASE}/${uuid}`);
|
||||
export const updateLead = (uuid: string, payload: LeadUpdatePayload) => apiPut<LeadDetail>(`${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");
|
||||
}
|
||||
@@ -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<Admin
|
||||
if (params.searchKey) qs.set("searchKey", params.searchKey);
|
||||
if (params.q) qs.set("q", params.q);
|
||||
if (params.enabled) qs.set("enabled", params.enabled);
|
||||
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));
|
||||
if (params.sortBy) qs.set("sortBy", params.sortBy);
|
||||
|
||||
@@ -29,6 +29,7 @@ export interface AuditLogParams {
|
||||
/** 1-based. */
|
||||
page: number;
|
||||
pageSize: number;
|
||||
companyId?: number;
|
||||
}
|
||||
|
||||
const BASE = "/api/audit-log";
|
||||
@@ -36,6 +37,7 @@ const BASE = "/api/audit-log";
|
||||
export async function searchAuditLog(params: AuditLogParams): Promise<{ items: AuditEvent[]; total: number }> {
|
||||
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}`);
|
||||
|
||||
@@ -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 });
|
||||
});
|
||||
});
|
||||
@@ -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<LockedAccount[]>(`${BASE}/locked`);
|
||||
export const unlock = (username: string) => apiPost<void>(`${BASE}/locked/${encodeURIComponent(username)}/unlock`);
|
||||
const scoped = (companyId?: number) => (companyId ? `?companyId=${companyId}` : "");
|
||||
export const listLocked = (companyId?: number) => apiGet<LockedAccount[]>(`${BASE}/locked${scoped(companyId)}`);
|
||||
export const unlock = (username: string, companyId?: number) =>
|
||||
apiPost<void>(`${BASE}/locked/${encodeURIComponent(username)}/unlock${scoped(companyId)}`);
|
||||
export const getConfig = () => apiGet<LockoutConfig>(`${BASE}/config`);
|
||||
export const saveConfig = (cfg: LockoutConfig) => apiPut<LockoutConfig>(`${BASE}/config`, cfg);
|
||||
export const getPasswordRules = () => apiGet<PasswordRule[]>(`${BASE}/password-rules`);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<ColumnDef<AuditRow, unknown>[]>(
|
||||
() => [
|
||||
{ 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<AuditRow, unknown>] : []),
|
||||
{ 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<LockedAccount[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(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<LockoutConfig | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [notice, setNotice] = useState<Notice>(null);
|
||||
@@ -241,21 +250,21 @@ function LockoutForm() {
|
||||
<section className="space-y-4 rounded-xl border bg-card p-4">
|
||||
<h2 className="text-base font-semibold">{t("LsLockoutTitle")}</h2>
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch id="ls-enabled" checked={cfg.enabled} onCheckedChange={(enabled) => setCfg({ ...cfg, enabled })} />
|
||||
<Switch id="ls-enabled" disabled={readOnly} checked={cfg.enabled} onCheckedChange={(enabled) => setCfg({ ...cfg, enabled })} />
|
||||
<Label htmlFor="ls-enabled">{t("LsLockoutOn")}</Label>
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="ls-max">{t("LsMaxAttempts")}</Label>
|
||||
<Input id="ls-max" type="number" min={1} value={cfg.maxAttempts || ""} onChange={(e) => setCfg({ ...cfg, maxAttempts: num(e.target.value) })} />
|
||||
<Input id="ls-max" disabled={readOnly} type="number" min={1} value={cfg.maxAttempts || ""} onChange={(e) => setCfg({ ...cfg, maxAttempts: num(e.target.value) })} />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="ls-period">{t("LsPeriod")}</Label>
|
||||
<Input id="ls-period" type="number" min={1} value={cfg.period || ""} onChange={(e) => setCfg({ ...cfg, period: num(e.target.value) })} />
|
||||
<Input id="ls-period" disabled={readOnly} type="number" min={1} value={cfg.period || ""} onChange={(e) => setCfg({ ...cfg, period: num(e.target.value) })} />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label>{t("LsUnit")}</Label>
|
||||
<Select value={cfg.unit} onValueChange={(unit) => setCfg({ ...cfg, unit: unit as LockoutConfig["unit"] })}>
|
||||
<Select disabled={readOnly} value={cfg.unit} onValueChange={(unit) => setCfg({ ...cfg, unit: unit as LockoutConfig["unit"] })}>
|
||||
<SelectTrigger aria-label={t("LsUnit")} className="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{LOCKOUT_UNITS.map((u) => <SelectItem key={u} value={u}>{t(`LsUnit${u}`)}</SelectItem>)}
|
||||
@@ -264,7 +273,7 @@ function LockoutForm() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Button onClick={save} disabled={saving}>{t("LsSaveLockout")}</Button>
|
||||
{!readOnly && <Button onClick={save} disabled={saving}>{t("LsSaveLockout")}</Button>}
|
||||
<NoticeLine notice={notice} />
|
||||
</div>
|
||||
</section>
|
||||
@@ -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<PasswordRule[] | null>(null);
|
||||
const [edits, setEdits] = useState<Record<number, RuleEdit>>({});
|
||||
const [saving, setSaving] = useState(false);
|
||||
@@ -329,11 +339,11 @@ function PasswordRulesForm() {
|
||||
<TableRow key={r.id}>
|
||||
<TableCell>{label}</TableCell>
|
||||
<TableCell>
|
||||
<Switch aria-label={label} checked={e.status === "Y"} onCheckedChange={(on) => edit(r.id, { status: on ? "Y" : "N" })} />
|
||||
<Switch aria-label={label} disabled={readOnly} checked={e.status === "Y"} onCheckedChange={(on) => edit(r.id, { status: on ? "Y" : "N" })} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{!FLAG_RULE_PARAMS.includes(r.param) && (
|
||||
<Input aria-label={`${label} ${t("LsRuleValue").toLowerCase()}`} type="number" min={0} className="w-24" value={e.value ?? ""} onChange={(ev) => edit(r.id, { value: ev.target.value })} />
|
||||
<Input aria-label={`${label} ${t("LsRuleValue").toLowerCase()}`} disabled={readOnly} type="number" min={0} className="w-24" value={e.value ?? ""} onChange={(ev) => edit(r.id, { value: ev.target.value })} />
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
@@ -342,7 +352,7 @@ function PasswordRulesForm() {
|
||||
</TableBody>
|
||||
</Table>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Button onClick={save} disabled={saving}>{t("LsSaveRules")}</Button>
|
||||
{!readOnly && <Button onClick={save} disabled={saving}>{t("LsSaveRules")}</Button>}
|
||||
<NoticeLine notice={notice} />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -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(<RoleAccessPage />);
|
||||
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(<RoleAccessPage />);
|
||||
await waitFor(() => expect(screen.getByLabelText("Users")).toBeInTheDocument());
|
||||
expect(screen.getByRole("button", { name: /save/i })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -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<ModuleGrantRow[]>([]);
|
||||
@@ -226,9 +226,11 @@ function RoleAccessPageContent() {
|
||||
<Button variant="outline" disabled={!hasChanges} onClick={() => setChecked(new Set(original))}>
|
||||
{t("RolReset")}
|
||||
</Button>
|
||||
<Button disabled={!hasChanges} onClick={() => setConfirming(true)}>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
{isSuper !== false && (
|
||||
<Button disabled={!hasChanges} onClick={() => setConfirming(true)}>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{confirming && (
|
||||
|
||||
@@ -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<AdminRoleEntity[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(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 } }) => (
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
@@ -165,21 +167,21 @@ function RolesPageContent() {
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
}]),
|
||||
],
|
||||
[parentLabel, t],
|
||||
[parentLabel, t, readOnly],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={t("BO_ROLES")}
|
||||
actions={
|
||||
actions={readOnly ? undefined : (
|
||||
<Button onClick={() => setDialog(EMPTY_FORM)}>
|
||||
<Plus aria-hidden="true" className="size-4" />
|
||||
{t("RolAddRole")}
|
||||
</Button>
|
||||
}
|
||||
)}
|
||||
/>
|
||||
|
||||
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
|
||||
|
||||
@@ -15,10 +15,12 @@ import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { roleLabel } from "@/app/lib/roleLabel";
|
||||
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 { listAdminUsers, sendAdminUserPasswordReset, USER_STATUS_FILTER_OPTIONS } from "@/app/lib/services/adminUsers";
|
||||
import type { AdminUser } 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 type { MessageParams } from "@/app/lib/i18n/t";
|
||||
|
||||
@@ -26,8 +28,10 @@ const DEFAULTS = { q: "", enabled: "" };
|
||||
|
||||
function UsersPageContent() {
|
||||
const t = useT();
|
||||
const { companyId, showCompanyColumn } = useCompanyScope();
|
||||
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: AdminUser[]; total: number }>({ items: [], total: 0 });
|
||||
const [loading, setLoading] = useState(true);
|
||||
@@ -68,7 +72,7 @@ function UsersPageContent() {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets ahead of the filter/page/reloadKey-triggered fetch below.
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
listAdminUsers({ q: filters.q || undefined, enabled: filters.enabled || undefined, page, pageSize, sortBy, sortDir })
|
||||
listAdminUsers({ q: filters.q || undefined, enabled: filters.enabled || undefined, page, pageSize, sortBy, sortDir, companyId })
|
||||
.then((result) => {
|
||||
if (!cancelled) setData(result);
|
||||
})
|
||||
@@ -81,7 +85,7 @@ function UsersPageContent() {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [filters, page, reloadKey, pageSize, sortBy, sortDir]);
|
||||
}, [filters, page, reloadKey, pageSize, sortBy, sortDir, companyId]);
|
||||
|
||||
const statusOptions = useMemo(
|
||||
() => USER_STATUS_FILTER_OPTIONS.map((o) => ({ value: o.value, label: t(o.label) })),
|
||||
@@ -99,6 +103,7 @@ function UsersPageContent() {
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
...(showCompanyColumn ? [{ id: "company", accessorFn: (u: AdminUser) => u.companyCode ?? "", header: t("Company"), enableSorting: false } as ColumnDef<AdminUser, unknown>] : []),
|
||||
{ accessorKey: "name", header: t("Name") },
|
||||
{ accessorKey: "email", header: t("Email") },
|
||||
{
|
||||
@@ -154,7 +159,7 @@ function UsersPageContent() {
|
||||
),
|
||||
},
|
||||
],
|
||||
[t],
|
||||
[t, showCompanyColumn],
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
Reference in new issue
Block a user