feat(admin-portal): events list, create and edit screens with team picker
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
33f1e7a505
commit
c57aa3e7cc
20 files changed
+2121
-1
No files matched your search
@@ -0,0 +1,67 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
||||
|
||||
import { GET, PUT } from "./route";
|
||||
|
||||
function ctx(uuid: string) {
|
||||
return { params: Promise.resolve({ uuid }) };
|
||||
}
|
||||
function getReq() {
|
||||
return new Request("http://localhost/api/events/abc-123") as unknown as Parameters<typeof GET>[0];
|
||||
}
|
||||
function putReq(body: unknown) {
|
||||
return new Request("http://localhost/api/events/abc-123", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(body),
|
||||
}) as unknown as Parameters<typeof PUT>[0];
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset();
|
||||
mocks.getToken.mockReset();
|
||||
});
|
||||
|
||||
describe("GET /api/events/[uuid]", () => {
|
||||
it("returns 401 when there is no session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
const res = await GET(getReq(), ctx("abc-123"));
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("forwards to GET /api/admin/events/{uuid}", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "abc-123" } });
|
||||
await GET(getReq(), ctx("abc-123"));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/events/abc-123", { token: "jwt-abc" });
|
||||
});
|
||||
|
||||
it("encodes special characters in uuid", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "encoded" } });
|
||||
await GET(getReq(), ctx("some:uuid/with-slashes"));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/events/some%3Auuid%2Fwith-slashes", { token: "jwt-abc" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("PUT /api/events/[uuid]", () => {
|
||||
it("returns 401 when there is no session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
const res = await PUT(putReq({ name: "Updated" }), ctx("abc-123"));
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("forwards the body to PUT /api/admin/events/{uuid}", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
const body = { name: "Updated", location: "New Place", startDate: "2025-02-01", endDate: "2025-02-02", enabled: true, salespersonIds: [3] };
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "abc-123", ...body } });
|
||||
await PUT(putReq(body), ctx("abc-123"));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/events/abc-123", {
|
||||
method: "PUT",
|
||||
body,
|
||||
token: "jwt-abc",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
type Ctx = { params: Promise<{ uuid: string }> };
|
||||
|
||||
export async function GET(_req: NextRequest, { params }: Ctx) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { uuid } = await params;
|
||||
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/events/${encodeURIComponent(uuid)}`, { token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
|
||||
export async function PUT(req: NextRequest, { params }: Ctx) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { uuid } = await params;
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/events/${encodeURIComponent(uuid)}`, {
|
||||
method: "PUT",
|
||||
body,
|
||||
token,
|
||||
});
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
callMobileApi: vi.fn(),
|
||||
getToken: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
||||
|
||||
import { GET, POST } from "./route";
|
||||
|
||||
function getReq(query = "") {
|
||||
return new Request(`http://localhost/api/events${query}`) as unknown as Parameters<typeof GET>[0];
|
||||
}
|
||||
function postReq(body: unknown) {
|
||||
return new Request("http://localhost/api/events", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
}) as unknown as Parameters<typeof POST>[0];
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset();
|
||||
mocks.getToken.mockReset();
|
||||
});
|
||||
|
||||
describe("GET /api/events", () => {
|
||||
it("returns 401 when there is no session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
const res = await GET(getReq());
|
||||
expect(res.status).toBe(401);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("forwards q/page/size/sortBy/sortDir to /api/admin/events", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0 } });
|
||||
await GET(getReq("?q=event1&page=1&size=10&sortBy=name&sortDir=asc"));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith(
|
||||
"/api/admin/events?q=event1&page=1&size=10&sortBy=name&sortDir=asc",
|
||||
{ token: "jwt-abc" },
|
||||
);
|
||||
});
|
||||
|
||||
it("forwards enabled=Y/N to /api/admin/events", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0 } });
|
||||
await GET(getReq("?enabled=Y&page=0&size=20"));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith(
|
||||
"/api/admin/events?enabled=Y&page=0&size=20",
|
||||
{ token: "jwt-abc" },
|
||||
);
|
||||
});
|
||||
|
||||
it("returns 400 when enabled is not Y or N", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
const res = await GET(getReq("?enabled=true"));
|
||||
expect(res.status).toBe(400);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns 400 when enabled is false", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
const res = await GET(getReq("?enabled=false"));
|
||||
expect(res.status).toBe(400);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses default page=0 and size=20 when absent", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0 } });
|
||||
await GET(getReq(""));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith(
|
||||
"/api/admin/events?page=0&size=20",
|
||||
{ token: "jwt-abc" },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/events", () => {
|
||||
it("returns 401 when there is no session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
const res = await POST(postReq({ name: "Event", location: "Place", startDate: "2025-01-01", endDate: "2025-01-02", enabled: true, salespersonIds: [] }));
|
||||
expect(res.status).toBe(401);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("forwards the body to POST /api/admin/events", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
const body = { name: "Event", location: "Place", startDate: "2025-01-01", endDate: "2025-01-02", enabled: true, salespersonIds: [1, 2] };
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "abc123", ...body } });
|
||||
await POST(postReq(body));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/events", {
|
||||
method: "POST",
|
||||
body,
|
||||
token: "jwt-abc",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { errorResponse, unauthorized, badRequest } from "@/app/lib/server/apiRoute";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
|
||||
const params = new URL(req.url).searchParams;
|
||||
const qs = new URLSearchParams();
|
||||
const q = params.get("q");
|
||||
if (q) qs.set("q", q);
|
||||
const enabled = params.get("enabled");
|
||||
if (enabled) {
|
||||
if (enabled !== "Y" && enabled !== "N") return badRequest("enabled must be Y or N.");
|
||||
qs.set("enabled", enabled);
|
||||
}
|
||||
qs.set("page", params.get("page") ?? "0");
|
||||
qs.set("size", params.get("size") ?? "20");
|
||||
const sortBy = params.get("sortBy");
|
||||
if (sortBy) {
|
||||
qs.set("sortBy", sortBy);
|
||||
const sortDir = params.get("sortDir");
|
||||
if (sortDir) qs.set("sortDir", sortDir);
|
||||
}
|
||||
|
||||
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/events?${qs.toString()}`, {
|
||||
token,
|
||||
});
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
|
||||
const body = await req.json().catch(() => ({}));
|
||||
|
||||
const result = await callMobileApi<Record<string, unknown>>("/api/admin/events", { method: "POST", body, token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
callMobileApi: vi.fn(),
|
||||
getToken: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
||||
|
||||
import { GET } from "./route";
|
||||
|
||||
function getReq() {
|
||||
return new Request("http://localhost/api/events/salesperson-options") as unknown as Parameters<typeof GET>[0];
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset();
|
||||
mocks.getToken.mockReset();
|
||||
});
|
||||
|
||||
describe("GET /api/events/salesperson-options", () => {
|
||||
it("returns 401 when there is no session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
const res = await GET(getReq());
|
||||
expect(res.status).toBe(401);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("forwards to GET /api/admin/events/salesperson-options", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: [{ id: 1, name: "Jane", username: "jane.doe" }] });
|
||||
await GET(getReq());
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/events/salesperson-options", { token: "jwt-abc" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
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 });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,568 @@
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listSalespersonOptions: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminEvents", () => ({
|
||||
listSalespersonOptions: mocks.listSalespersonOptions,
|
||||
}));
|
||||
|
||||
import { EventForm } from "./EventForm";
|
||||
import { pickDate } from "@/test/pickDate";
|
||||
|
||||
const SALESPEOPLE = [
|
||||
{ id: 1, name: "Alice", username: "alice.smith" },
|
||||
{ id: 2, name: "Bob", username: "bob.jones" },
|
||||
{ id: 3, name: "Charlie", username: "charlie.brown" },
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.listSalespersonOptions.mockReset().mockResolvedValue(SALESPEOPLE);
|
||||
});
|
||||
|
||||
async function waitForOptions() {
|
||||
await waitFor(() => expect(screen.getByText("Alice (alice.smith)")).toBeInTheDocument());
|
||||
}
|
||||
|
||||
describe("EventForm", () => {
|
||||
it("renders all fields on the create form", async () => {
|
||||
render(<EventForm onSubmit={vi.fn()} />);
|
||||
await waitForOptions();
|
||||
|
||||
expect(screen.getByLabelText("Name")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Location")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Start date")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("End date")).toBeInTheDocument();
|
||||
expect(screen.getByRole("checkbox", { name: "Alice (alice.smith)" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("checkbox", { name: "Bob (bob.jones)" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("checkbox", { name: "Charlie (charlie.brown)" })).toBeInTheDocument();
|
||||
// Enabled switch must NOT be present on create form.
|
||||
expect(screen.queryByLabelText("Enabled")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders the Enabled switch on the edit form", async () => {
|
||||
render(
|
||||
<EventForm
|
||||
initial={{
|
||||
uuid: "e1",
|
||||
name: "Conference",
|
||||
location: "Convention Center",
|
||||
startDate: "2025-06-01",
|
||||
endDate: "2025-06-03",
|
||||
enabled: true,
|
||||
}}
|
||||
onSubmit={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
await waitForOptions();
|
||||
|
||||
expect(screen.getByLabelText("Enabled")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("prefills from initial on edit form", async () => {
|
||||
render(
|
||||
<EventForm
|
||||
initial={{
|
||||
uuid: "e1",
|
||||
name: "Conference",
|
||||
location: "Convention Center",
|
||||
startDate: "2025-06-01",
|
||||
endDate: "2025-06-03",
|
||||
enabled: false,
|
||||
}}
|
||||
onSubmit={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
await waitForOptions();
|
||||
|
||||
expect(screen.getByLabelText("Name")).toHaveValue("Conference");
|
||||
expect(screen.getByLabelText("Location")).toHaveValue("Convention Center");
|
||||
});
|
||||
|
||||
it("blocks submit and shows errors when required fields are missing", async () => {
|
||||
const onSubmit = vi.fn();
|
||||
render(<EventForm onSubmit={onSubmit} />);
|
||||
await waitForOptions();
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: /create/i }));
|
||||
|
||||
expect(await screen.findByText("Name is required.")).toBeInTheDocument();
|
||||
expect(await screen.findByText("Location is required.")).toBeInTheDocument();
|
||||
expect(await screen.findByText("Start date is required.")).toBeInTheDocument();
|
||||
expect(await screen.findByText("End date is required.")).toBeInTheDocument();
|
||||
expect(onSubmit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("blocks submit when end date is before start date", async () => {
|
||||
const onSubmit = vi.fn();
|
||||
// Start with valid dates, then make start after end.
|
||||
render(
|
||||
<EventForm
|
||||
initial={{
|
||||
uuid: "e1",
|
||||
name: "Conference",
|
||||
location: "Convention Center",
|
||||
startDate: "2025-06-01",
|
||||
endDate: "2025-06-03",
|
||||
enabled: true,
|
||||
}}
|
||||
onSubmit={onSubmit}
|
||||
/>,
|
||||
);
|
||||
await waitForOptions();
|
||||
|
||||
// Change start to 2025-06-10, which is after the existing end 2025-06-03.
|
||||
pickDate("Start date", "2025-06-10");
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
|
||||
|
||||
expect(await screen.findByText("End date must not be before start date.")).toBeInTheDocument();
|
||||
expect(onSubmit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows name-too-long validation error", async () => {
|
||||
const onSubmit = vi.fn();
|
||||
render(<EventForm onSubmit={onSubmit} />);
|
||||
await waitForOptions();
|
||||
|
||||
// Name > 100 chars
|
||||
await userEvent.type(screen.getByLabelText("Name"), "a".repeat(101));
|
||||
await userEvent.type(screen.getByLabelText("Location"), "Somewhere");
|
||||
// Set dates via initial + changing end to be before start doesn't help for name length.
|
||||
// We need to get dates past the required check. Use an initial with valid dates,
|
||||
// make name too long, clear name, type long name, and save.
|
||||
render(
|
||||
<EventForm
|
||||
initial={{
|
||||
uuid: "e1",
|
||||
name: "a".repeat(101),
|
||||
location: "Somewhere",
|
||||
startDate: "2025-06-01",
|
||||
endDate: "2025-06-03",
|
||||
enabled: true,
|
||||
}}
|
||||
onSubmit={onSubmit}
|
||||
/>,
|
||||
);
|
||||
await waitForOptions();
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
|
||||
|
||||
expect(await screen.findByText("Name must be 100 characters or fewer.")).toBeInTheDocument();
|
||||
expect(onSubmit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows location-too-long validation error", async () => {
|
||||
const onSubmit = vi.fn();
|
||||
render(
|
||||
<EventForm
|
||||
initial={{
|
||||
uuid: "e1",
|
||||
name: "Event",
|
||||
location: "x".repeat(201),
|
||||
startDate: "2025-06-01",
|
||||
endDate: "2025-06-03",
|
||||
enabled: true,
|
||||
}}
|
||||
onSubmit={onSubmit}
|
||||
/>,
|
||||
);
|
||||
await waitForOptions();
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
|
||||
|
||||
expect(await screen.findByText("Location must be 200 characters or fewer.")).toBeInTheDocument();
|
||||
expect(onSubmit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("builds the correct payload on create", async () => {
|
||||
const onSubmit = vi.fn().mockResolvedValue(undefined);
|
||||
render(<EventForm onSubmit={onSubmit} submitLabel="Create" />);
|
||||
await waitForOptions();
|
||||
|
||||
await userEvent.type(screen.getByLabelText("Name"), "Conference");
|
||||
await userEvent.type(screen.getByLabelText("Location"), "Convention Center");
|
||||
|
||||
// Pick dates through the calendar
|
||||
pickDate("Start date", "2025-06-01");
|
||||
pickDate("End date", "2025-06-03");
|
||||
|
||||
await userEvent.click(screen.getByRole("checkbox", { name: "Alice (alice.smith)" }));
|
||||
await userEvent.click(screen.getByRole("checkbox", { name: "Bob (bob.jones)" }));
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: /create/i }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(onSubmit).toHaveBeenCalledWith({
|
||||
name: "Conference",
|
||||
location: "Convention Center",
|
||||
startDate: "2025-06-01",
|
||||
endDate: "2025-06-03",
|
||||
salespersonIds: [1, 2],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("builds the correct payload on edit (includes enabled)", async () => {
|
||||
const onSubmit = vi.fn().mockResolvedValue(undefined);
|
||||
render(
|
||||
<EventForm
|
||||
initial={{
|
||||
uuid: "e1",
|
||||
name: "Conference",
|
||||
location: "Convention Center",
|
||||
startDate: "2025-06-01",
|
||||
endDate: "2025-06-03",
|
||||
enabled: true,
|
||||
team: [],
|
||||
}}
|
||||
onSubmit={onSubmit}
|
||||
submitLabel="Edit"
|
||||
/>,
|
||||
);
|
||||
await waitForOptions();
|
||||
|
||||
// Toggle the enabled switch off.
|
||||
await userEvent.click(screen.getByRole("switch", { name: "Enabled" }));
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(onSubmit).toHaveBeenCalledWith({
|
||||
name: "Conference",
|
||||
location: "Convention Center",
|
||||
startDate: "2025-06-01",
|
||||
endDate: "2025-06-03",
|
||||
enabled: false,
|
||||
salespersonIds: [],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("submits a one-day event when start equals end", async () => {
|
||||
const onSubmit = vi.fn().mockResolvedValue(undefined);
|
||||
render(<EventForm onSubmit={onSubmit} submitLabel="Create" />);
|
||||
await waitForOptions();
|
||||
|
||||
await userEvent.type(screen.getByLabelText("Name"), "Workshop");
|
||||
await userEvent.type(screen.getByLabelText("Location"), "Room 1");
|
||||
pickDate("Start date", "2025-07-01");
|
||||
pickDate("End date", "2025-07-01");
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: /create/i }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(onSubmit).toHaveBeenCalledWith({
|
||||
name: "Workshop",
|
||||
location: "Room 1",
|
||||
startDate: "2025-07-01",
|
||||
endDate: "2025-07-01",
|
||||
salespersonIds: [],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("unchecking an inactive member removes it from salespersonIds", async () => {
|
||||
const onSubmit = vi.fn().mockResolvedValue(undefined);
|
||||
render(
|
||||
<EventForm
|
||||
initial={{
|
||||
uuid: "e1",
|
||||
name: "Conference",
|
||||
location: "Convention Center",
|
||||
startDate: "2025-06-01",
|
||||
endDate: "2025-06-03",
|
||||
enabled: true,
|
||||
team: [
|
||||
{ id: 1, name: "Alice", username: "alice.smith", enabled: true },
|
||||
{ id: 99, name: "Deactivated", username: "old.user", enabled: false },
|
||||
],
|
||||
}}
|
||||
onSubmit={onSubmit}
|
||||
submitLabel="Edit"
|
||||
/>,
|
||||
);
|
||||
await waitForOptions();
|
||||
|
||||
// Both should be checked initially.
|
||||
expect(screen.getByRole("checkbox", { name: "Alice (alice.smith)" })).toBeChecked();
|
||||
expect(screen.getByRole("checkbox", { name: "Deactivated (old.user)" })).toBeChecked();
|
||||
|
||||
// Uncheck the inactive member, keep Alice.
|
||||
await userEvent.click(screen.getByRole("checkbox", { name: "Deactivated (old.user)" }));
|
||||
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(onSubmit).toHaveBeenCalledWith({
|
||||
name: "Conference",
|
||||
location: "Convention Center",
|
||||
startDate: "2025-06-01",
|
||||
endDate: "2025-06-03",
|
||||
enabled: true,
|
||||
salespersonIds: [1],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("shows username or id for inactive member with null name", async () => {
|
||||
const onSubmit = vi.fn().mockResolvedValue(undefined);
|
||||
render(
|
||||
<EventForm
|
||||
initial={{
|
||||
uuid: "e1",
|
||||
name: "Conference",
|
||||
location: "Convention Center",
|
||||
startDate: "2025-06-01",
|
||||
endDate: "2025-06-03",
|
||||
enabled: true,
|
||||
team: [
|
||||
{ id: 5, name: null, username: null, enabled: false },
|
||||
{ id: 6, name: "Ghost", username: null, enabled: false },
|
||||
],
|
||||
}}
|
||||
onSubmit={onSubmit}
|
||||
submitLabel="Edit"
|
||||
/>,
|
||||
);
|
||||
await waitForOptions();
|
||||
|
||||
// Member with null name and null username should show id.
|
||||
expect(screen.getByRole("checkbox", { name: "5" })).toBeChecked();
|
||||
// Member with name but null username should show just name.
|
||||
expect(screen.getByRole("checkbox", { name: "Ghost" })).toBeChecked();
|
||||
});
|
||||
|
||||
it("builds the correct payload on edit with team", async () => {
|
||||
const onSubmit = vi.fn().mockResolvedValue(undefined);
|
||||
render(
|
||||
<EventForm
|
||||
initial={{
|
||||
uuid: "e1",
|
||||
name: "Conference",
|
||||
location: "Convention Center",
|
||||
startDate: "2025-06-01",
|
||||
endDate: "2025-06-03",
|
||||
enabled: true,
|
||||
team: [
|
||||
{ id: 1, name: "Alice", username: "alice.smith", enabled: true },
|
||||
{ id: 99, name: "Deactivated", username: "old.user", enabled: false },
|
||||
],
|
||||
}}
|
||||
onSubmit={onSubmit}
|
||||
submitLabel="Edit"
|
||||
/>,
|
||||
);
|
||||
await waitForOptions();
|
||||
|
||||
// Alice should be checked, deactivated member should be checked with "Inactive" marker.
|
||||
expect(screen.getByRole("checkbox", { name: "Alice (alice.smith)" })).toBeChecked();
|
||||
expect(screen.getByRole("checkbox", { name: "Deactivated (old.user)" })).toBeChecked();
|
||||
expect(screen.getByText(/Inactive/)).toBeInTheDocument();
|
||||
|
||||
// Uncheck Alice, keep deactivated member
|
||||
await userEvent.click(screen.getByRole("checkbox", { name: "Alice (alice.smith)" }));
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(onSubmit).toHaveBeenCalledWith({
|
||||
name: "Conference",
|
||||
location: "Convention Center",
|
||||
startDate: "2025-06-01",
|
||||
endDate: "2025-06-03",
|
||||
enabled: true,
|
||||
salespersonIds: [99],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("shows an API REQUIRED_FIELD error under each listed field", async () => {
|
||||
class ApiError extends Error {
|
||||
status: number;
|
||||
data?: unknown;
|
||||
constructor(message: string, status: number, data?: unknown) {
|
||||
super(message);
|
||||
this.name = "ApiError";
|
||||
this.status = status;
|
||||
this.data = data;
|
||||
}
|
||||
}
|
||||
|
||||
const onSubmit = vi.fn().mockRejectedValue(
|
||||
new ApiError("Validation failed", 422, {
|
||||
errors: ["location", "startDate"],
|
||||
}),
|
||||
);
|
||||
|
||||
render(
|
||||
<EventForm
|
||||
initial={{
|
||||
uuid: "e1",
|
||||
name: "Conference",
|
||||
location: "",
|
||||
startDate: "",
|
||||
endDate: "2025-06-03",
|
||||
enabled: true,
|
||||
}}
|
||||
onSubmit={onSubmit}
|
||||
submitLabel="Edit"
|
||||
/>,
|
||||
);
|
||||
await waitForOptions();
|
||||
|
||||
// Pre-fill all required fields so client-side validation passes,
|
||||
// but the API returns REQUIRED_FIELD errors for location and startDate.
|
||||
await userEvent.type(screen.getByLabelText("Name"), "X");
|
||||
await userEvent.type(screen.getByLabelText("Location"), "Somewhere");
|
||||
|
||||
pickDate("Start date", "2025-06-01");
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
|
||||
|
||||
// Each field listed in errors[] gets the required message.
|
||||
expect(await screen.findByText("Location is required.")).toBeInTheDocument();
|
||||
expect(await screen.findByText("Start date is required.")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Location")).toHaveAttribute("aria-invalid", "true");
|
||||
expect(screen.getByLabelText("Start date")).toHaveAttribute("aria-invalid", "true");
|
||||
expect(onSubmit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("shows a team error from the API under the Team list, and an unknown missing field at the top", async () => {
|
||||
class ApiError extends Error {
|
||||
status: number;
|
||||
data?: unknown;
|
||||
constructor(message: string, status: number, data?: unknown) {
|
||||
super(message);
|
||||
this.name = "ApiError";
|
||||
this.status = status;
|
||||
this.data = data;
|
||||
}
|
||||
}
|
||||
const onSubmit = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new ApiError("Unknown or inactive admin user 7", 400, { code: "UNKNOWN_USER", details: { field: "salespersonIds" } }))
|
||||
.mockRejectedValueOnce(new ApiError("Required: venue", 400, { code: "REQUIRED_FIELD", errors: ["venue"], details: { field: "venue" } }));
|
||||
|
||||
render(
|
||||
<EventForm
|
||||
initial={{ uuid: "e1", name: "Conference", location: "Hall", startDate: "2025-06-01", endDate: "2025-06-03", enabled: true }}
|
||||
onSubmit={onSubmit}
|
||||
submitLabel="Edit"
|
||||
/>,
|
||||
);
|
||||
await waitForOptions();
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
|
||||
const team = screen.getByRole("group", { name: "Team" });
|
||||
expect(await within(team).findByText("Unknown or inactive admin user 7")).toBeInTheDocument();
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
|
||||
expect(await screen.findByText("Required: venue")).toBeInTheDocument();
|
||||
expect(within(team).queryByText("Required: venue")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows an API field error under the correct field", async () => {
|
||||
class ApiError extends Error {
|
||||
status: number;
|
||||
data?: unknown;
|
||||
constructor(message: string, status: number, data?: unknown) {
|
||||
super(message);
|
||||
this.name = "ApiError";
|
||||
this.status = status;
|
||||
this.data = data;
|
||||
}
|
||||
}
|
||||
|
||||
const onSubmit = vi.fn().mockRejectedValue(
|
||||
new ApiError("Validation failed", 422, {
|
||||
details: { field: "name" },
|
||||
errors: ["location", "startDate"],
|
||||
}),
|
||||
);
|
||||
|
||||
render(
|
||||
<EventForm
|
||||
initial={{
|
||||
uuid: "e1",
|
||||
name: "Conference",
|
||||
location: "",
|
||||
startDate: "",
|
||||
endDate: "2025-06-03",
|
||||
enabled: true,
|
||||
}}
|
||||
onSubmit={onSubmit}
|
||||
submitLabel="Edit"
|
||||
/>,
|
||||
);
|
||||
await waitForOptions();
|
||||
|
||||
// Pre-fill required fields so only the API error shows.
|
||||
await userEvent.type(screen.getByLabelText("Name"), "X");
|
||||
await userEvent.type(screen.getByLabelText("Location"), "Somewhere");
|
||||
|
||||
pickDate("Start date", "2025-06-01");
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
|
||||
|
||||
// errors[] takes priority over details.field, so location and startDate get the errors.
|
||||
expect(await screen.findByText("Location is required.")).toBeInTheDocument();
|
||||
expect(await screen.findByText("Start date is required.")).toBeInTheDocument();
|
||||
expect(onSubmit).toHaveBeenCalledTimes(1);
|
||||
// The error should be under the listed fields (aria-invalid=true).
|
||||
expect(screen.getByLabelText("Location")).toHaveAttribute("aria-invalid", "true");
|
||||
expect(screen.getByLabelText("Start date")).toHaveAttribute("aria-invalid", "true");
|
||||
});
|
||||
|
||||
it("shows a general error at the top when onSubmit throws a non-field API error", async () => {
|
||||
class ApiError extends Error {
|
||||
status: number;
|
||||
data?: unknown;
|
||||
constructor(message: string, status: number, data?: unknown) {
|
||||
super(message);
|
||||
this.name = "ApiError";
|
||||
this.status = status;
|
||||
this.data = data;
|
||||
}
|
||||
}
|
||||
|
||||
const onSubmit = vi.fn().mockRejectedValue(new ApiError("Network error", 500));
|
||||
|
||||
render(<EventForm onSubmit={onSubmit} />);
|
||||
await waitForOptions();
|
||||
|
||||
await userEvent.type(screen.getByLabelText("Name"), "Event");
|
||||
await userEvent.type(screen.getByLabelText("Location"), "Here");
|
||||
pickDate("Start date", "2025-06-01");
|
||||
pickDate("End date", "2025-06-03");
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: /create/i }));
|
||||
|
||||
expect(await screen.findByText("Network error")).toBeInTheDocument();
|
||||
// onSubmit was called (it IS the mock).
|
||||
expect(onSubmit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("disables submit while saving", async () => {
|
||||
let resolveSubmit!: () => void;
|
||||
const onSubmit = vi.fn(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
resolveSubmit = resolve;
|
||||
}),
|
||||
);
|
||||
render(<EventForm onSubmit={onSubmit} />);
|
||||
await waitForOptions();
|
||||
|
||||
await userEvent.type(screen.getByLabelText("Name"), "Event");
|
||||
await userEvent.type(screen.getByLabelText("Location"), "Here");
|
||||
pickDate("Start date", "2025-06-01");
|
||||
pickDate("End date", "2025-06-03");
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: /create/i }));
|
||||
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: /create/i })).toBeDisabled());
|
||||
resolveSubmit();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,300 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Checkbox } from "@/app/components/ui/checkbox";
|
||||
import { Input } from "@/app/components/ui/input";
|
||||
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 { listSalespersonOptions } from "@/app/lib/services/adminEvents";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import type { AdminEvent, AdminEventPayload, SalespersonOption } from "@/app/lib/types";
|
||||
import type { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
interface SalespersonOptionExtended extends SalespersonOption {
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
export interface EventFormProps {
|
||||
initial?: AdminEvent;
|
||||
onSubmit: (payload: AdminEventPayload) => Promise<void>;
|
||||
submitLabel?: string;
|
||||
}
|
||||
|
||||
/** Missing-field codes the API lists in errors[], mapped to the message shown under that field. */
|
||||
const REQUIRED_MESSAGE: Record<string, string> = {
|
||||
name: "EvtNameRequired",
|
||||
location: "EvtLocationRequired",
|
||||
startDate: "EvtStartRequired",
|
||||
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"];
|
||||
|
||||
export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
|
||||
const t = useT();
|
||||
|
||||
const [name, setName] = useState(initial?.name ?? "");
|
||||
const [location, setLocation] = useState(initial?.location ?? "");
|
||||
const [startDate, setStartDate] = useState(initial?.startDate ?? "");
|
||||
const [endDate, setEndDate] = useState(initial?.endDate ?? "");
|
||||
const [enabled, setEnabled] = useState(initial?.enabled ?? true);
|
||||
|
||||
const [optionList, setOptionList] = useState<SalespersonOptionExtended[]>([]);
|
||||
const [loadingPickers, setLoadingPickers] = useState(true);
|
||||
const [pickersError, setPickersError] = useState<string | null>(null);
|
||||
|
||||
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
// 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()
|
||||
.then((opts) => {
|
||||
if (cancelled) return;
|
||||
const activeOpts = opts.map((o) => ({ ...o, active: true } as SalespersonOptionExtended));
|
||||
// Merge deactivated team members from initial.
|
||||
const activeIds = new Set(activeOpts.map((o) => o.id));
|
||||
if (initial?.team) {
|
||||
for (const m of initial.team) {
|
||||
if (m.id != null && !activeIds.has(m.id)) {
|
||||
activeOpts.push({
|
||||
id: m.id as number,
|
||||
name: m.name ?? "",
|
||||
username: m.username ?? "",
|
||||
active: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
setOptionList(activeOpts);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (!cancelled) {
|
||||
setPickersError(err instanceof Error ? err.message : "SetupLoadOptionsFailed");
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoadingPickers(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [initial]);
|
||||
|
||||
// Build the set of initially selected team member IDs.
|
||||
// Members from initial.team that are also in the active options → checked.
|
||||
// Members from initial.team that are NOT in the options (deactivated) → still shown, checked, with "Inactive" marker.
|
||||
const [selectedIds, setSelectedIds] = useState<Set<number>>(() => {
|
||||
if (!initial?.team) return new Set<number>();
|
||||
return new Set(initial.team.map((m) => m.id).filter((id): id is number => id != null));
|
||||
});
|
||||
|
||||
function toggleSalesperson(id: number) {
|
||||
setSelectedIds((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
|
||||
const trimmedName = name.trim();
|
||||
const trimmedLocation = location.trim();
|
||||
const errors: Record<string, string> = {};
|
||||
|
||||
if (!trimmedName) errors.name = t("EvtNameRequired");
|
||||
if (!trimmedLocation) errors.location = t("EvtLocationRequired");
|
||||
if (!startDate) errors.startDate = t("EvtStartRequired");
|
||||
if (!endDate) errors.endDate = t("EvtEndRequired");
|
||||
if (endDate && startDate && endDate < startDate) errors.endDate = t("EvtEndBeforeStart");
|
||||
if (trimmedName.length > 100) errors.name = t("EvtNameTooLong");
|
||||
if (trimmedLocation.length > 200) errors.location = t("EvtLocationTooLong");
|
||||
|
||||
setFieldErrors(errors);
|
||||
if (Object.keys(errors).length > 0) return;
|
||||
|
||||
setFormError(null);
|
||||
setSaving(true);
|
||||
try {
|
||||
const payload: AdminEventPayload = {
|
||||
name: trimmedName,
|
||||
location: trimmedLocation,
|
||||
startDate,
|
||||
endDate,
|
||||
salespersonIds: Array.from(selectedIds).filter((id): id is number => id != null),
|
||||
};
|
||||
// `enabled` is only sent on edit (when initial exists).
|
||||
if (initial) {
|
||||
payload.enabled = enabled;
|
||||
}
|
||||
await onSubmit(payload);
|
||||
} catch (err) {
|
||||
if (err instanceof Error && "status" in err && "data" in err) {
|
||||
// The API sends errors[] (every missing field) and details.field (the failing field).
|
||||
const data = (err as ApiError).data as { errors?: unknown; details?: { field?: unknown } } | undefined;
|
||||
const missing = (Array.isArray(data?.errors) ? data.errors : []).filter((f): f is string => typeof f === "string" && Object.hasOwn(REQUIRED_MESSAGE, f));
|
||||
const field = data?.details?.field;
|
||||
if (missing.length > 0) {
|
||||
setFieldErrors(Object.fromEntries(missing.map((f) => [f, t(REQUIRED_MESSAGE[f])])));
|
||||
return;
|
||||
}
|
||||
if (typeof field === "string" && FIELD_ERROR_SLOTS.includes(field)) {
|
||||
setFieldErrors({ [field]: err.message });
|
||||
return;
|
||||
}
|
||||
}
|
||||
setFormError(err instanceof Error ? err.message : "EvtSaveFailed");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
const label = submitLabel ?? (initial ? t("Edit") : t("Create"));
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
|
||||
{formError && <ErrorState message={t(formError)} />}
|
||||
{pickersError && <ErrorState message={t(pickersError)} />}
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="evt-name">{t("Name")}</Label>
|
||||
<Input
|
||||
id="evt-name"
|
||||
required
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
disabled={saving}
|
||||
aria-invalid={!!fieldErrors.name}
|
||||
/>
|
||||
{fieldErrors.name && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{fieldErrors.name}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="evt-location">{t("Location")}</Label>
|
||||
<Input
|
||||
id="evt-location"
|
||||
required
|
||||
value={location}
|
||||
onChange={(e) => setLocation(e.target.value)}
|
||||
disabled={saving}
|
||||
aria-invalid={!!fieldErrors.location}
|
||||
/>
|
||||
{fieldErrors.location && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{fieldErrors.location}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="evt-start">{t("EvtStartDate")}</Label>
|
||||
<DatePicker
|
||||
id="evt-start"
|
||||
value={startDate}
|
||||
onChange={setStartDate}
|
||||
aria-label={t("EvtStartDate")}
|
||||
required
|
||||
disabled={saving}
|
||||
aria-invalid={!!fieldErrors.startDate}
|
||||
/>
|
||||
{fieldErrors.startDate && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{fieldErrors.startDate}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="evt-end">{t("EvtEndDate")}</Label>
|
||||
<DatePicker
|
||||
id="evt-end"
|
||||
value={endDate}
|
||||
onChange={setEndDate}
|
||||
aria-label={t("EvtEndDate")}
|
||||
required
|
||||
disabled={saving}
|
||||
min={startDate}
|
||||
aria-invalid={!!fieldErrors.endDate}
|
||||
/>
|
||||
{fieldErrors.endDate && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{fieldErrors.endDate}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{initial && (
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
id="evt-enabled"
|
||||
checked={enabled}
|
||||
onCheckedChange={setEnabled}
|
||||
disabled={saving}
|
||||
/>
|
||||
<Label htmlFor="evt-enabled">{t("Enabled")}</Label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<fieldset className="space-y-1.5">
|
||||
<legend className="text-sm font-medium">{t("EvtTeamLabel")}</legend>
|
||||
{fieldErrors.salespersonIds && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{fieldErrors.salespersonIds}
|
||||
</p>
|
||||
)}
|
||||
<div className="max-h-48 space-y-1 overflow-y-auto rounded-md border p-2">
|
||||
{loadingPickers ? (
|
||||
<p className="text-sm text-muted-foreground">{t("Loading")}</p>
|
||||
) : (
|
||||
optionList.map((opt) => {
|
||||
const name = opt.name ?? "";
|
||||
const username = opt.username ?? "";
|
||||
const displayName = name || username || String(opt.id);
|
||||
const displayUsername = name ? username : undefined;
|
||||
return (
|
||||
<div key={opt.id} className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id={`salesperson-${opt.id}`}
|
||||
checked={selectedIds.has(opt.id)}
|
||||
disabled={saving}
|
||||
onCheckedChange={() => toggleSalesperson(opt.id)}
|
||||
aria-label={displayUsername ? `${displayName} (${displayUsername})` : displayName}
|
||||
/>
|
||||
<Label htmlFor={`salesperson-${opt.id}`}>
|
||||
{displayName}
|
||||
{displayUsername && ` (${displayUsername})`}
|
||||
{!opt.active && (
|
||||
<span className="ml-1 text-xs text-muted-foreground">
|
||||
({t("EvtInactiveMember")})
|
||||
</span>
|
||||
)}
|
||||
</Label>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<Button type="submit" disabled={saving}>
|
||||
{label}
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getAdminEvent: vi.fn(),
|
||||
saveAdminEvent: vi.fn(),
|
||||
useAdminAuth: vi.fn(),
|
||||
searchParamsGet: vi.fn(),
|
||||
listSalespersonOptions: vi.fn().mockResolvedValue([]),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminEvents", () => ({
|
||||
getAdminEvent: mocks.getAdminEvent,
|
||||
saveAdminEvent: mocks.saveAdminEvent,
|
||||
listSalespersonOptions: mocks.listSalespersonOptions,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("next/navigation", () => ({
|
||||
useParams: () => ({ uuid: "evt-9" }),
|
||||
useSearchParams: () => ({ get: mocks.searchParamsGet }),
|
||||
}));
|
||||
|
||||
import EditEventPage from "./page";
|
||||
|
||||
const EVENT = {
|
||||
uuid: "evt-9",
|
||||
name: "Jane",
|
||||
location: "Place",
|
||||
startDate: "2025-01-01",
|
||||
endDate: "2025-01-02",
|
||||
enabled: true,
|
||||
team: [],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.getAdminEvent.mockReset();
|
||||
mocks.saveAdminEvent.mockReset();
|
||||
mocks.listSalespersonOptions.mockReset().mockResolvedValue([]);
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
|
||||
mocks.searchParamsGet.mockReset().mockReturnValue(null);
|
||||
});
|
||||
|
||||
describe("EditEventPage", () => {
|
||||
it("keeps the page header in the loading and not-found states", async () => {
|
||||
mocks.getAdminEvent.mockReturnValueOnce(new Promise(() => {}));
|
||||
const { unmount } = render(<EditEventPage />);
|
||||
expect(screen.getByRole("heading", { level: 1, name: "Edit event" })).toBeInTheDocument();
|
||||
unmount();
|
||||
mocks.getAdminEvent.mockRejectedValue(new ApiError("Request failed (404)", 404));
|
||||
render(<EditEventPage />);
|
||||
expect(await screen.findByText(/no event found/i)).toBeInTheDocument();
|
||||
expect(screen.getByRole("heading", { level: 1, name: "Edit event" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows a loading state, then prefills the form from getAdminEvent", async () => {
|
||||
mocks.getAdminEvent.mockResolvedValue(EVENT);
|
||||
render(<EditEventPage />);
|
||||
|
||||
await waitFor(() => expect(screen.getByLabelText("Name")).toHaveValue("Jane"));
|
||||
expect(mocks.getAdminEvent).toHaveBeenCalledWith("evt-9");
|
||||
expect(screen.getByLabelText("Location")).toHaveValue("Place");
|
||||
});
|
||||
|
||||
it("shows a not-found state when the event does not exist", async () => {
|
||||
mocks.getAdminEvent.mockRejectedValue(new ApiError("Request failed (404)", 404));
|
||||
render(<EditEventPage />);
|
||||
|
||||
expect(await screen.findByText(/no event found/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows an error state with retry on a load failure", async () => {
|
||||
mocks.getAdminEvent.mockRejectedValueOnce(new Error("network down"));
|
||||
mocks.getAdminEvent.mockResolvedValueOnce(EVENT);
|
||||
render(<EditEventPage />);
|
||||
|
||||
await waitFor(() => expect(screen.getByText(/network down/i)).toBeInTheDocument());
|
||||
await userEvent.click(screen.getByRole("button", { name: /retry/i }));
|
||||
await waitFor(() => expect(screen.getByLabelText("Name")).toHaveValue("Jane"));
|
||||
});
|
||||
|
||||
it("shows the generic error state (not not-found) for a non-404 ApiError", async () => {
|
||||
mocks.getAdminEvent.mockRejectedValue(new ApiError("Request failed (400)", 400));
|
||||
render(<EditEventPage />);
|
||||
|
||||
await waitFor(() => expect(screen.getByText(/request failed \(400\)/i)).toBeInTheDocument());
|
||||
expect(screen.queryByText(/no event found/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("submits edits by calling saveAdminEvent with the uuid", async () => {
|
||||
mocks.getAdminEvent.mockResolvedValue(EVENT);
|
||||
mocks.saveAdminEvent.mockResolvedValue({ ...EVENT, name: "Janet" });
|
||||
render(<EditEventPage />);
|
||||
|
||||
await waitFor(() => expect(screen.getByLabelText("Name")).toHaveValue("Jane"));
|
||||
await userEvent.clear(screen.getByLabelText("Name"));
|
||||
await userEvent.type(screen.getByLabelText("Name"), "Janet");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Save" }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mocks.saveAdminEvent).toHaveBeenCalledWith(expect.objectContaining({ name: "Janet", enabled: true }), "evt-9"),
|
||||
);
|
||||
});
|
||||
|
||||
it("after a successful save shows 'Event saved.', keeps the form, updates the header and clears the team warning", async () => {
|
||||
mocks.searchParamsGet.mockImplementation((key: string) => (key === "teamNotSaved" ? "1" : null));
|
||||
mocks.getAdminEvent.mockResolvedValue(EVENT);
|
||||
mocks.saveAdminEvent.mockResolvedValue({ ...EVENT, name: "Janet" });
|
||||
render(<EditEventPage />);
|
||||
|
||||
await waitFor(() => expect(screen.getByLabelText("Name")).toHaveValue("Jane"));
|
||||
await userEvent.clear(screen.getByLabelText("Name"));
|
||||
await userEvent.type(screen.getByLabelText("Name"), "Janet");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Save" }));
|
||||
|
||||
expect(await screen.findByText("Event saved.")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Name")).toHaveValue("Janet");
|
||||
expect(screen.getByRole("heading", { level: 1 })).toHaveTextContent("Janet");
|
||||
expect(screen.queryByText(/its team was not/i)).not.toBeInTheDocument();
|
||||
expect(mocks.getAdminEvent).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("shows the error and no 'Event saved.' banner when the save fails", async () => {
|
||||
mocks.getAdminEvent.mockResolvedValue(EVENT);
|
||||
mocks.saveAdminEvent.mockRejectedValue(new Error("The event could not be saved. Please try again."));
|
||||
render(<EditEventPage />);
|
||||
|
||||
await waitFor(() => expect(screen.getByLabelText("Name")).toHaveValue("Jane"));
|
||||
await userEvent.click(screen.getByRole("button", { name: "Save" }));
|
||||
|
||||
expect(await screen.findByText(/could not be saved/i)).toBeInTheDocument();
|
||||
expect(screen.queryByText("Event saved.")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the created banner when navigated here right after create", async () => {
|
||||
mocks.searchParamsGet.mockImplementation((key: string) => (key === "created" ? "1" : null));
|
||||
mocks.getAdminEvent.mockResolvedValue(EVENT);
|
||||
render(<EditEventPage />);
|
||||
|
||||
await waitFor(() => expect(screen.getByLabelText("Name")).toHaveValue("Jane"));
|
||||
expect(screen.getByText("Event created.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the team-not-saved warning banner", async () => {
|
||||
mocks.searchParamsGet.mockImplementation((key: string) => (key === "teamNotSaved" ? "1" : null));
|
||||
mocks.getAdminEvent.mockResolvedValue(EVENT);
|
||||
render(<EditEventPage />);
|
||||
|
||||
await waitFor(() => expect(screen.getByLabelText("Name")).toHaveValue("Jane"));
|
||||
expect(
|
||||
screen.getByText("The event was saved but its team was not. Check the team and save again."),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders NotAuthorized when the Events module is absent from aclMenu", () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
|
||||
render(<EditEventPage />);
|
||||
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useParams, useSearchParams } from "next/navigation";
|
||||
import { Alert, AlertDescription } from "@/app/components/ui/alert";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { Skeleton } from "@/app/components/ui/skeleton";
|
||||
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { getAdminEvent, saveAdminEvent } from "@/app/lib/services/adminEvents";
|
||||
import { EventForm } from "@/app/components/events/EventForm";
|
||||
import type { AdminEvent, AdminEventPayload } from "@/app/lib/types";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
function EditEventPageContent() {
|
||||
const t = useT();
|
||||
const { uuid } = useParams<{ uuid: string }>();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const [event, setEvent] = useState<AdminEvent | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [notFound, setNotFound] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(
|
||||
searchParams?.get("created") === "1"
|
||||
? "EvtCreatedBanner"
|
||||
: null,
|
||||
);
|
||||
const [teamNotSaved, setTeamNotSaved] = useState(
|
||||
searchParams?.get("teamNotSaved") === "1",
|
||||
);
|
||||
|
||||
const retry = useCallback(() => setReloadKey((k) => k + 1), []);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error/notFound ahead of the uuid/reloadKey-triggered fetch below, which is the actual synchronization.
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
setNotFound(false);
|
||||
getAdminEvent(uuid)
|
||||
.then((data) => {
|
||||
if (!cancelled) setEvent(data);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (cancelled) return;
|
||||
if (err instanceof ApiError && err.status === 404) {
|
||||
setNotFound(true);
|
||||
} else {
|
||||
setError(err instanceof Error ? err.message : "EvtLoadFailed");
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [uuid, reloadKey]);
|
||||
|
||||
async function handleSubmit(payload: AdminEventPayload) {
|
||||
const saved = await saveAdminEvent(payload, uuid);
|
||||
// The form already holds what was saved; the PUT response has no team, so keep the loaded one.
|
||||
setEvent((prev) => ({ ...saved, team: prev?.team }));
|
||||
setSuccessMessage("EvtSaved");
|
||||
setTeamNotSaved(false);
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("EvtEditEvent")} />
|
||||
<Skeleton className="h-64 w-full" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
if (notFound) {
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("EvtEditEvent")} />
|
||||
<EmptyState title={t("EvtNotFound", { uuid })} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("EvtEditEvent")} />
|
||||
<ErrorState message={t(error)} onRetry={retry} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
if (!event) return null;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<PageHeader title={t("EvtEditNamed", { name: event.name })} />
|
||||
|
||||
{successMessage && (
|
||||
<Alert>
|
||||
<AlertDescription>{t(successMessage)}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{teamNotSaved && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{t("EvtTeamNotSaved")}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<EventForm initial={event} onSubmit={handleSubmit} submitLabel={t("Save")} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function EditEventPage() {
|
||||
return (
|
||||
<RequireModule pathname="/events">
|
||||
<EditEventPageContent />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { pickDate } from "@/test/pickDate";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
saveAdminEvent: vi.fn(),
|
||||
useAdminAuth: vi.fn(),
|
||||
push: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminEvents", () => ({
|
||||
saveAdminEvent: mocks.saveAdminEvent,
|
||||
listSalespersonOptions: vi.fn().mockResolvedValue([]),
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("next/navigation", () => ({ useRouter: () => ({ push: mocks.push }) }));
|
||||
|
||||
import NewEventPage from "./page";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.saveAdminEvent.mockReset();
|
||||
mocks.push.mockReset();
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
|
||||
});
|
||||
|
||||
describe("NewEventPage", () => {
|
||||
it("renders the title through the shared page header", async () => {
|
||||
render(<NewEventPage />);
|
||||
expect(screen.getByRole("heading", { level: 1, name: "New event" })).toBeInTheDocument();
|
||||
await waitFor(() => expect(screen.getByLabelText("Name")).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it("renders an empty EventForm", async () => {
|
||||
render(<NewEventPage />);
|
||||
await waitFor(() => expect(screen.getByLabelText("Name")).toHaveValue(""));
|
||||
expect(screen.getByLabelText("Location")).toHaveValue("");
|
||||
});
|
||||
|
||||
it("calls saveAdminEvent without a uuid and redirects to the returned event's uuid", async () => {
|
||||
mocks.saveAdminEvent.mockResolvedValue({ uuid: "evt-42", name: "Jane" });
|
||||
render(<NewEventPage />);
|
||||
await waitFor(() => expect(screen.getByLabelText("Name")).toBeInTheDocument());
|
||||
|
||||
await userEvent.type(screen.getByLabelText("Name"), "Jane");
|
||||
await userEvent.type(screen.getByLabelText("Location"), "Place");
|
||||
await pickDate("Start date", "2025-06-15");
|
||||
await pickDate("End date", "2025-06-16");
|
||||
await userEvent.click(screen.getByRole("button", { name: /create/i }));
|
||||
|
||||
await waitFor(() => expect(mocks.saveAdminEvent).toHaveBeenCalledTimes(1));
|
||||
const payload = mocks.saveAdminEvent.mock.calls[0][0];
|
||||
expect(payload.name).toBe("Jane");
|
||||
await waitFor(() => expect(mocks.push).toHaveBeenCalledWith("/events/evt-42?created=1"));
|
||||
});
|
||||
|
||||
it("when TEAM_NOT_SAVED is returned, redirects with teamNotSaved=1", async () => {
|
||||
mocks.saveAdminEvent.mockRejectedValue(
|
||||
new ApiError("Team not saved", 400, {
|
||||
code: "TEAM_NOT_SAVED",
|
||||
details: { eventUuid: "evt-99" },
|
||||
}),
|
||||
);
|
||||
render(<NewEventPage />);
|
||||
await waitFor(() => expect(screen.getByLabelText("Name")).toBeInTheDocument());
|
||||
|
||||
await userEvent.type(screen.getByLabelText("Name"), "Jane");
|
||||
await userEvent.type(screen.getByLabelText("Location"), "Place");
|
||||
await pickDate("Start date", "2025-06-15");
|
||||
await pickDate("End date", "2025-06-16");
|
||||
await userEvent.click(screen.getByRole("button", { name: /create/i }));
|
||||
|
||||
await waitFor(() => expect(mocks.push).toHaveBeenCalledWith("/events/evt-99?teamNotSaved=1"));
|
||||
});
|
||||
|
||||
it("renders NotAuthorized when the Events module is absent from aclMenu", () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
|
||||
render(<NewEventPage />);
|
||||
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { ErrorState } from "@/app/components/ui/states";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { EventForm } from "@/app/components/events/EventForm";
|
||||
import { saveAdminEvent } from "@/app/lib/services/adminEvents";
|
||||
import type { AdminEventPayload } from "@/app/lib/types";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
function NewEventPageContent() {
|
||||
const t = useT();
|
||||
const router = useRouter();
|
||||
|
||||
async function handleSubmit(payload: AdminEventPayload) {
|
||||
try {
|
||||
const created = await saveAdminEvent(payload);
|
||||
if (created.uuid) {
|
||||
router.push(`/events/${created.uuid}?created=1`);
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError) {
|
||||
const data = err.data as { code?: string; details?: { eventUuid?: string } } | undefined;
|
||||
if (data?.code === "TEAM_NOT_SAVED" && data.details?.eventUuid) {
|
||||
router.push(`/events/${data.details.eventUuid}?teamNotSaved=1`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("EvtNewEvent")} />
|
||||
<EventForm onSubmit={handleSubmit} submitLabel={t("Create")} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function NewEventPage() {
|
||||
return (
|
||||
<RequireModule pathname="/events">
|
||||
<NewEventPageContent />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import { act, 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(() => ({
|
||||
listAdminEvents: vi.fn(),
|
||||
useAdminAuth: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminEvents", async (importActual) => ({
|
||||
...(await importActual<typeof import("@/app/lib/services/adminEvents")>()),
|
||||
listAdminEvents: mocks.listAdminEvents,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
|
||||
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
||||
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import EventsPage from "./page";
|
||||
|
||||
beforeEach(() => {
|
||||
memoryRouter.reset("/events");
|
||||
mocks.listAdminEvents.mockReset();
|
||||
mocks.useAdminAuth.mockReset();
|
||||
mocks.useAdminAuth.mockReturnValue({
|
||||
loading: false,
|
||||
hasModule: () => true,
|
||||
});
|
||||
});
|
||||
|
||||
// unify-admin-listing-toolbar: "Send password reset" sits in the row's ⋯ menu, not as a row button.
|
||||
async function openResetFromRowMenu() {
|
||||
await userEvent.click(screen.getAllByRole("button", { name: /more actions for/i })[0]);
|
||||
await userEvent.click(await screen.findByRole("menuitem", { name: /send password reset/i }));
|
||||
}
|
||||
|
||||
describe("EventsPage filters", () => {
|
||||
beforeEach(() => mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 }));
|
||||
|
||||
it("sends q after the debounce, as page 1, and puts it in the URL", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<EventsPage />);
|
||||
await waitFor(() => expect(mocks.listAdminEvents).toHaveBeenCalled());
|
||||
await user.type(screen.getByRole("searchbox", { name: "Event name" }), "jane");
|
||||
await waitFor(() => expect(mocks.listAdminEvents).toHaveBeenLastCalledWith(expect.objectContaining({ q: "jane", page: 1 })));
|
||||
expect(memoryRouter.getSearch().get("q")).toBe("jane");
|
||||
expect(mocks.listAdminEvents.mock.calls.filter((c) => (c[0] as { q?: string }).q).length).toBe(1);
|
||||
});
|
||||
|
||||
it("sends enabled from the Status filter", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<EventsPage />);
|
||||
await waitFor(() => expect(mocks.listAdminEvents).toHaveBeenCalled());
|
||||
await user.click(screen.getByRole("combobox", { name: /status filter/i }));
|
||||
await user.click(await screen.findByRole("option", { name: "Disabled" }));
|
||||
await waitFor(() => expect(mocks.listAdminEvents).toHaveBeenLastCalledWith(expect.objectContaining({ enabled: "N", page: 1 })));
|
||||
expect(memoryRouter.getSearch().get("enabled")).toBe("N");
|
||||
});
|
||||
|
||||
it("populates the controls and the request from the URL on mount", async () => {
|
||||
memoryRouter.reset("/events", "enabled=Y&q=jo");
|
||||
render(<EventsPage />);
|
||||
await waitFor(() => expect(mocks.listAdminEvents).toHaveBeenLastCalledWith(expect.objectContaining({ enabled: "Y", q: "jo" })));
|
||||
expect(screen.getByRole("searchbox", { name: "Event name" })).toHaveValue("jo");
|
||||
expect(screen.getByRole("combobox", { name: /status filter/i })).toHaveTextContent("Enabled");
|
||||
});
|
||||
|
||||
it("Clear filters empties the URL", async () => {
|
||||
memoryRouter.reset("/events", "enabled=Y&q=jo");
|
||||
render(<EventsPage />);
|
||||
await userEvent.click(await screen.findByRole("button", { name: "Clear filters" }));
|
||||
await waitFor(() => expect(memoryRouter.getSearch().toString()).toBe(""));
|
||||
});
|
||||
});
|
||||
|
||||
describe("EventsPage", () => {
|
||||
it("shows the empty state when there are no events", async () => {
|
||||
mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 });
|
||||
render(<EventsPage />);
|
||||
await waitFor(() => expect(screen.getByText(/no events/i)).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it("shows the error state and lets the user retry on a load failure", async () => {
|
||||
mocks.listAdminEvents.mockRejectedValueOnce(new Error("network down"));
|
||||
mocks.listAdminEvents.mockResolvedValueOnce({ items: [], total: 0 });
|
||||
render(<EventsPage />);
|
||||
await waitFor(() => expect(screen.getByText(/network down/i)).toBeInTheDocument());
|
||||
await userEvent.click(screen.getByRole("button", { name: /retry/i }));
|
||||
await waitFor(() => expect(mocks.listAdminEvents).toHaveBeenCalledTimes(2));
|
||||
});
|
||||
|
||||
it("links the New event button to the create form", async () => {
|
||||
mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 });
|
||||
render(<EventsPage />);
|
||||
await waitFor(() => expect(screen.getByText(/no events/i)).toBeInTheDocument());
|
||||
|
||||
const addEventLink = screen.getByRole("link", { name: /new event/i });
|
||||
expect(addEventLink).toHaveAttribute("href", "/events/new");
|
||||
expect(addEventLink).not.toHaveAttribute("aria-disabled");
|
||||
});
|
||||
|
||||
it("links each event row to its edit page", async () => {
|
||||
mocks.listAdminEvents.mockResolvedValue({
|
||||
items: [{ uuid: "abc-123", name: "My Event", location: "Hall A", startDate: "2025-06-15", endDate: "2025-06-16", enabled: true, team: [] }],
|
||||
total: 1,
|
||||
});
|
||||
render(<EventsPage />);
|
||||
|
||||
const edit = await screen.findByRole("link", { name: "Edit My Event" });
|
||||
expect(edit).toHaveAttribute("href", "/events/abc-123");
|
||||
expect(screen.getByRole("link", { name: "My Event" })).toHaveAttribute("href", "/events/abc-123");
|
||||
});
|
||||
|
||||
it("renders NotAuthorized when the Events module is absent from aclMenu", () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
|
||||
render(<EventsPage />);
|
||||
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows a toned status badge under a level-1 heading", async () => {
|
||||
mocks.listAdminEvents.mockResolvedValue({
|
||||
items: [
|
||||
{ uuid: "e1", name: "A", location: "Place", startDate: "2025-01-01", endDate: "2025-01-02", enabled: true, team: [] },
|
||||
{ uuid: "e2", name: "B", location: "Place2", startDate: "2025-02-01", endDate: "2025-02-02", enabled: false, team: [] },
|
||||
],
|
||||
total: 2,
|
||||
});
|
||||
render(<EventsPage />);
|
||||
expect(await screen.findByText("Enabled")).toHaveAttribute("data-variant", "positive");
|
||||
expect(screen.getByText("Disabled")).toHaveAttribute("data-variant", "neutral");
|
||||
expect(screen.getByRole("heading", { level: 1, name: "Events" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("End column header requests sortBy endDate", async () => {
|
||||
mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 });
|
||||
render(<EventsPage />);
|
||||
await waitFor(() => expect(mocks.listAdminEvents).toHaveBeenCalled());
|
||||
|
||||
await userEvent.click(await screen.findByRole("button", { name: /end date/i }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mocks.listAdminEvents).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ sortBy: "endDate" }),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it("Start column header requests sortBy startDate", async () => {
|
||||
mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 });
|
||||
render(<EventsPage />);
|
||||
await waitFor(() => expect(mocks.listAdminEvents).toHaveBeenCalled());
|
||||
|
||||
await userEvent.click(await screen.findByRole("button", { name: /start date/i }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mocks.listAdminEvents).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ sortBy: "startDate" }),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it("Edit action navigates to the edit page", async () => {
|
||||
mocks.listAdminEvents.mockResolvedValue({
|
||||
items: [{ uuid: "evt-55", name: "Test Event", location: "Room", startDate: "2025-01-01", endDate: "2025-01-02", enabled: true, team: [] }],
|
||||
total: 1,
|
||||
});
|
||||
render(<EventsPage />);
|
||||
await waitFor(() => expect(screen.getByText("Test Event")).toBeInTheDocument());
|
||||
|
||||
await userEvent.click(screen.getAllByRole("button", { name: /more actions for/i })[0]);
|
||||
await userEvent.click(await screen.findByRole("menuitem", { name: /edit/i }));
|
||||
|
||||
expect(memoryRouter.push).toHaveBeenCalledWith("/events/evt-55");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,174 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { Pencil, Plus } from "lucide-react";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { Badge } from "@/app/components/ui/badge";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { FilterField, FilterPanel, FilterSearch, FilterSelect } from "@/app/components/ui/filter-panel";
|
||||
import { DataTable } from "@/app/components/ui/data-table";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
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 { 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 { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { formatDmy } from "@/app/lib/date-input";
|
||||
|
||||
const DEFAULTS = { q: "", enabled: "" };
|
||||
|
||||
export const EVENT_STATUS_FILTER_OPTIONS = [{ value: "Y", label: "Enabled" }, { value: "N", label: "Disabled" }];
|
||||
|
||||
function EventsPageContent() {
|
||||
const t = useT();
|
||||
const router = useRouter();
|
||||
const { tableRef, pageSize } = useFitPageSize();
|
||||
const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS);
|
||||
const { sorting, onSortingChange, sortBy, sortDir } = useTableSort();
|
||||
const [data, setData] = useState<{ items: AdminEvent[]; total: number }>({ items: [], total: 0 });
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
|
||||
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
|
||||
|
||||
useEffect(() => {
|
||||
if (pageSize == null) return;
|
||||
let cancelled = false;
|
||||
// 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 })
|
||||
.then((result) => {
|
||||
if (!cancelled) setData(result);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (!cancelled) setError(err instanceof Error ? err.message : "EvtListLoadFailed");
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [filters, page, reloadKey, pageSize, sortBy, sortDir]);
|
||||
|
||||
const statusOptions = useMemo(
|
||||
() => EVENT_STATUS_FILTER_OPTIONS.map((o) => ({ value: o.value, label: t(o.label) })),
|
||||
[t],
|
||||
);
|
||||
|
||||
const columns = useMemo<ColumnDef<AdminEvent, unknown>[]>(
|
||||
() => [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: t("Name"),
|
||||
cell: ({ row }) => (
|
||||
<Link href={`/events/${row.original.uuid}`} className="font-medium text-primary underline-offset-4 hover:underline focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
|
||||
{row.original.name}
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
{ accessorKey: "location", header: t("Location"), enableSorting: false },
|
||||
{
|
||||
accessorKey: "startDate",
|
||||
header: t("EvtStartDate"),
|
||||
cell: ({ row }) => <span>{formatDmy(row.original.startDate)}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "endDate",
|
||||
header: t("EvtEndDate"),
|
||||
cell: ({ row }) => <span>{formatDmy(row.original.endDate)}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "enabled",
|
||||
header: t("Status"),
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => (
|
||||
<Badge variant={row.original.enabled ? "positive" : "neutral"}>
|
||||
{row.original.enabled ? t("Enabled") : t("Disabled")}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
enableSorting: false,
|
||||
header: t("CatActions"),
|
||||
meta: { numeric: true },
|
||||
cell: ({ row }) => (
|
||||
<RowActions
|
||||
label={row.original.name}
|
||||
items={[{
|
||||
label: t("EvtEdit"),
|
||||
onSelect: () => router.push(`/events/${row.original.uuid}`),
|
||||
}]}
|
||||
>
|
||||
<Button variant="ghost" size="sm" asChild className="h-8 px-2">
|
||||
<Link href={`/events/${row.original.uuid}`} aria-label={t("EvtEditNamed", { name: row.original.name })}>
|
||||
<Pencil aria-hidden="true" className="size-3.5" />
|
||||
</Link>
|
||||
</Button>
|
||||
</RowActions>
|
||||
),
|
||||
},
|
||||
],
|
||||
[t, router],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={t("BO_EVENTS")}
|
||||
actions={
|
||||
<Button asChild>
|
||||
<Link href="/events/new">
|
||||
<Plus aria-hidden="true" className="size-4" />
|
||||
{t("EvtNewEvent")}
|
||||
</Link>
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
|
||||
|
||||
<FilterPanel activeCount={activeCount} onClear={clear}>
|
||||
<FilterField label={t("EvtEventNameFilter")}>
|
||||
<FilterSearch className="w-full" aria-label={t("EvtEventNameFilter")} placeholder={t("EvtEventNameFilter")} value={filters.q} onChange={q => set({ q })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("EvtStatusFilter")}>
|
||||
<FilterSelect className="w-full" aria-label={t("EvtStatusFilter")} allLabel={t("AllStatuses")} options={statusOptions} value={filters.enabled} onChange={enabled => set({ enabled })} />
|
||||
</FilterField>
|
||||
</FilterPanel>
|
||||
|
||||
<DataTable
|
||||
label={t("BO_EVENTS")}
|
||||
columns={columns}
|
||||
data={data.items}
|
||||
total={data.total}
|
||||
page={page}
|
||||
pageSize={pageSize ?? MIN_PAGE_SIZE}
|
||||
sorting={sorting}
|
||||
onSortingChange={onSortingChange}
|
||||
tableRef={tableRef}
|
||||
onPageChange={setPage}
|
||||
isLoading={loading}
|
||||
rowKey={(e) => String(e.uuid)}
|
||||
empty={<EmptyState title={activeCount > 0 ? t("EvtNoMatch") : t("EvtNoEvents")} />}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function EventsPage() {
|
||||
return (
|
||||
<RequireModule pathname="/events">
|
||||
<EventsPageContent />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -174,4 +174,34 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
RolManageAccess: "Manage access",
|
||||
RolNoRoles: "No roles found",
|
||||
No: "No",
|
||||
// Event form messages
|
||||
EvtNameRequired: "Name is required.",
|
||||
EvtLocationRequired: "Location is required.",
|
||||
EvtStartDate: "Start date",
|
||||
EvtEndDate: "End date",
|
||||
EvtStartRequired: "Start date is required.",
|
||||
EvtEndRequired: "End date is required.",
|
||||
EvtEndBeforeStart: "End date must not be before start date.",
|
||||
EvtNameTooLong: "Name must be 100 characters or fewer.",
|
||||
EvtLocationTooLong: "Location must be 200 characters or fewer.",
|
||||
EvtSaveFailed: "Failed to save event.",
|
||||
EvtInactiveMember: "Inactive",
|
||||
EvtTeamLabel: "Team",
|
||||
Location: "Location",
|
||||
Create: "Create",
|
||||
BO_EVENTS: "Events",
|
||||
EvtNewEvent: "New event",
|
||||
EvtEdit: "Edit",
|
||||
EvtNoEvents: "No events found",
|
||||
EvtNoMatch: "No events match your filters",
|
||||
EvtListLoadFailed: "Failed to load events",
|
||||
EvtLoadFailed: "Failed to load event",
|
||||
EvtEditEvent: "Edit event",
|
||||
EvtEditNamed: "Edit {name}",
|
||||
EvtNotFound: "No event found for \"{uuid}\"",
|
||||
EvtCreatedBanner: "Event created.",
|
||||
EvtSaved: "Event saved.",
|
||||
EvtTeamNotSaved: "The event was saved but its team was not. Check the team and save again.",
|
||||
EvtEventNameFilter: "Event name",
|
||||
EvtStatusFilter: "Status filter",
|
||||
};
|
||||
@@ -5,12 +5,13 @@ describe("routeModules", () => {
|
||||
it("gates /users and /roles by the seeded module name", () => {
|
||||
expect(requiredModuleFor("/users")).toBe("BO_USERS");
|
||||
expect(requiredModuleFor("/roles")).toBe("BO_ROLES");
|
||||
expect(requiredModuleFor("/events")).toBe("BO_EVENTS");
|
||||
expect(requiredModulesFor("/roles")).toEqual(["BO_ROLES"]);
|
||||
});
|
||||
|
||||
it("leaves other routes ungated", () => {
|
||||
expect(requiredModuleFor("/")).toBeUndefined();
|
||||
expect(requiredModulesFor("/members")).toBeUndefined();
|
||||
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/roles", "/users"]);
|
||||
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/events", "/roles", "/users"]);
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@
|
||||
export const ROUTE_MODULES: Record<string, string> = {
|
||||
"/users": "BO_USERS",
|
||||
"/roles": "BO_ROLES",
|
||||
"/events": "BO_EVENTS",
|
||||
};
|
||||
|
||||
export function requiredModuleFor(pathname: string): string | undefined {
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), apiPut: vi.fn() }));
|
||||
vi.mock("@/app/lib/clientApi", () => mocks);
|
||||
|
||||
import {
|
||||
listAdminEvents,
|
||||
getAdminEvent,
|
||||
saveAdminEvent,
|
||||
listSalespersonOptions,
|
||||
} from "./adminEvents";
|
||||
import type { AdminEventPayload } from "@/app/lib/types";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.apiGet.mockReset();
|
||||
mocks.apiPost.mockReset();
|
||||
mocks.apiPut.mockReset();
|
||||
});
|
||||
|
||||
describe("listAdminEvents", () => {
|
||||
it("translates 1-based page to a 0-based query and normalizes the page shape", async () => {
|
||||
mocks.apiGet.mockResolvedValue({ content: [{ uuid: "e1" }], totalElements: 1 });
|
||||
const result = await listAdminEvents({ page: 2, pageSize: 20 });
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/events?page=1&size=20");
|
||||
expect(result).toEqual({ items: [{ uuid: "e1" }], total: 1 });
|
||||
});
|
||||
|
||||
it("sends q, enabled, sortBy, sortDir when given", async () => {
|
||||
mocks.apiGet.mockResolvedValue({ content: [], totalElements: 0 });
|
||||
await listAdminEvents({ q: "event", enabled: "true", page: 1, pageSize: 20, sortBy: "name", sortDir: "asc" });
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/events?q=event&enabled=true&page=0&size=20&sortBy=name&sortDir=asc");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAdminEvent", () => {
|
||||
it("calls GET /api/events/{uuid}", async () => {
|
||||
mocks.apiGet.mockResolvedValue({ uuid: "abc-123", name: "Event" });
|
||||
const result = await getAdminEvent("abc-123");
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/events/abc-123");
|
||||
expect(result).toEqual({ uuid: "abc-123", name: "Event" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("saveAdminEvent", () => {
|
||||
it("POSTs when no uuid given", async () => {
|
||||
mocks.apiPost.mockResolvedValue({ uuid: "new-1", name: "New Event" });
|
||||
const payload: AdminEventPayload = {
|
||||
name: "New Event",
|
||||
location: "Place",
|
||||
startDate: "2025-01-01",
|
||||
endDate: "2025-01-02",
|
||||
enabled: true,
|
||||
salespersonIds: [],
|
||||
};
|
||||
const result = await saveAdminEvent(payload);
|
||||
expect(mocks.apiPost).toHaveBeenCalledWith("/api/events", payload);
|
||||
expect(result).toEqual({ uuid: "new-1", name: "New Event" });
|
||||
});
|
||||
|
||||
it("PUTs to /api/events/{uuid} when uuid is present", async () => {
|
||||
mocks.apiPut.mockResolvedValue({ uuid: "existing", name: "Updated" });
|
||||
const payload: AdminEventPayload = {
|
||||
name: "Updated",
|
||||
location: "Place",
|
||||
startDate: "2025-01-01",
|
||||
endDate: "2025-01-02",
|
||||
enabled: true,
|
||||
salespersonIds: [],
|
||||
};
|
||||
const result = await saveAdminEvent(payload, "existing");
|
||||
expect(mocks.apiPut).toHaveBeenCalledWith("/api/events/existing", payload);
|
||||
expect(result).toEqual({ uuid: "existing", name: "Updated" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("listSalespersonOptions", () => {
|
||||
it("calls GET /api/events/salesperson-options", async () => {
|
||||
mocks.apiGet.mockResolvedValue([{ id: 1, name: "Jane", username: "jane.doe" }]);
|
||||
const result = await listSalespersonOptions();
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/events/salesperson-options");
|
||||
expect(result).toEqual([{ id: 1, name: "Jane", username: "jane.doe" }]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import { apiGet, apiPost, apiPut } from "@/app/lib/clientApi";
|
||||
import type { AdminEvent, AdminEventPayload, SalespersonOption } from "@/app/lib/types";
|
||||
|
||||
export interface AdminEventListParams {
|
||||
q?: string;
|
||||
enabled?: string;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
sortBy?: string;
|
||||
sortDir?: "asc" | "desc";
|
||||
}
|
||||
|
||||
export interface AdminEventListResult {
|
||||
items: AdminEvent[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
export function normalizeAdminEventPage(raw: unknown): AdminEventListResult {
|
||||
if (!raw || typeof raw !== "object") return { items: [], total: 0 };
|
||||
const obj = raw as Record<string, unknown>;
|
||||
const events = Array.isArray(obj.content) ? (obj.content as AdminEvent[]) : [];
|
||||
const total = typeof obj.totalElements === "number" ? obj.totalElements : events.length;
|
||||
return { items: events, total };
|
||||
}
|
||||
|
||||
export async function listAdminEvents(params: AdminEventListParams): Promise<AdminEventListResult> {
|
||||
const qs = new URLSearchParams();
|
||||
if (params.q) qs.set("q", params.q);
|
||||
if (params.enabled) qs.set("enabled", params.enabled);
|
||||
qs.set("page", String(Math.max(0, params.page - 1)));
|
||||
qs.set("size", String(params.pageSize));
|
||||
if (params.sortBy) qs.set("sortBy", params.sortBy);
|
||||
if (params.sortDir && params.sortBy) qs.set("sortDir", params.sortDir);
|
||||
const raw = await apiGet<unknown>(`/api/events?${qs.toString()}`);
|
||||
return normalizeAdminEventPage(raw);
|
||||
}
|
||||
|
||||
export async function getAdminEvent(uuid: string): Promise<AdminEvent> {
|
||||
return apiGet<AdminEvent>(`/api/events/${uuid}`);
|
||||
}
|
||||
|
||||
export async function saveAdminEvent(payload: AdminEventPayload, uuid?: string): Promise<AdminEvent> {
|
||||
return uuid
|
||||
? apiPut<AdminEvent>(`/api/events/${uuid}`, payload)
|
||||
: apiPost<AdminEvent>("/api/events", payload);
|
||||
}
|
||||
|
||||
export async function listSalespersonOptions(): Promise<SalespersonOption[]> {
|
||||
return apiGet<SalespersonOption[]>("/api/events/salesperson-options");
|
||||
}
|
||||
@@ -115,3 +115,38 @@ export interface ModuleGrantRow {
|
||||
parentId: number | null;
|
||||
granted: boolean;
|
||||
}
|
||||
|
||||
/** An event as returned by the mobile admin API and displayed in the portal. */
|
||||
export interface AdminEvent {
|
||||
uuid: string;
|
||||
name: string;
|
||||
location: string;
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
enabled: boolean;
|
||||
team?: AdminEventMember[];
|
||||
}
|
||||
|
||||
export interface AdminEventMember {
|
||||
id: number;
|
||||
name: string | null;
|
||||
username: string | null;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
/** Payload shape for creating/updating an event via the BFF client API. */
|
||||
export interface AdminEventPayload {
|
||||
name: string;
|
||||
location: string;
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
enabled?: boolean;
|
||||
salespersonIds: number[];
|
||||
}
|
||||
|
||||
/** A salesperson row from the salesperson-options endpoint. */
|
||||
export interface SalespersonOption {
|
||||
id: number;
|
||||
name: string;
|
||||
username: string;
|
||||
}
|
||||
Reference in new issue
Block a user