Compare commits
10
Commits
48507979bd
...
8ce641ea86
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ce641ea86 | ||
|
|
fad639d690 | ||
|
|
29f5c6f094 | ||
|
|
adaca0a4eb | ||
|
|
7fe8dcc8a5 | ||
|
|
94e1e7fdde | ||
|
|
90f25debc2 | ||
|
|
18672ba173 | ||
|
|
fe9d9bd38d | ||
|
|
5d768b1566 |
No files matched your search
@@ -37,7 +37,7 @@
|
||||
- Columns: `event_lead_id`, `interest_id`, `company_id` NOT NULL.
|
||||
- PK `(event_lead_id, interest_id)`.
|
||||
|
||||
`user_id` and `event_uuid` cross into other tables without foreign keys, like `event_salesperson`. Every query filters on `company_id`, which comes from the logged-in admin and never from the request.
|
||||
`user_id` and `event_uuid` cross into other tables without foreign keys, like `event_salesperson`. Every query on the new tables filters on `company_id`, which comes from the logged-in admin and never from the request. `ponytail:` the change-3 `event` table has no `company_id`, so event lookups are not company-scoped; add it with the multi-company move.
|
||||
|
||||
**Calls I made:**
|
||||
- Name is required: a lead with no name cannot be followed up.
|
||||
@@ -122,7 +122,7 @@ The event picker and capture accept enabled events only. `GET /api/admin/event-l
|
||||
|
||||
**Capture form options:** `GET /api/admin/event-leads/interest-options` (`BO_EVENT_LEADS`) returns active interests. An inactive interest already on an event lead still shows on that lead and can be removed, but cannot be newly added (`INACTIVE_INTEREST`).
|
||||
|
||||
**Backend:** `services-counter` provides `/counter/interest/findByCompany/{companyId}`, `/counter/interest/save`, and a `findByIds` used by the listing.
|
||||
**Backend:** `services-counter` provides `/counter/interest/findByCompany/{companyId}`, `/counter/interest/save`, and `findByIds` (unused in phase 1: `mobile-api` reads the whole company list once per request).
|
||||
|
||||
### 9. Modules and access
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ Design: `design.md` (decision numbers below refer to it). Every task runs serial
|
||||
|
||||
## 3. mobile-api
|
||||
|
||||
- [ ] 3.1 Add the interests admin API (design decision 8). `AdminInterestController` with `GET`, `POST` and `PUT /api/admin/interests`, all `@AppAuth @AdminModule("BO_INTERESTS")`. The company id comes from the caller.
|
||||
- [x] 3.1 Add the interests admin API (design decision 8). `AdminInterestController` with `GET`, `POST` and `PUT /api/admin/interests`, all `@AppAuth @AdminModule("BO_INTERESTS")`. The company id comes from the caller.
|
||||
|
||||
Validation:
|
||||
- Name is required, else `REQUIRED_FIELD`.
|
||||
@@ -69,7 +69,7 @@ Design: `design.md` (decision numbers below refer to it). Every task runs serial
|
||||
- Scope: `solvway-mobile-api/src/**/*Interest*`, `solvway-mobile-api/src/main/java/**/constants/**`
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`.
|
||||
|
||||
- [ ] 3.2 Add the event-leads admin API (design decisions 2–7).
|
||||
- [x] 3.2 Add the event-leads admin API (design decisions 2–7).
|
||||
- Add `com.googlecode.libphonenumber:libphonenumber` (latest 8.x, exact version) to `solvway-mobile-api/pom.xml`.
|
||||
- `AdminEventLeadController` and `AdminEventLeadService` under `/api/admin/event-leads`, all `@AppAuth @AdminModule("BO_EVENT_LEADS")`:
|
||||
- `GET /events`
|
||||
@@ -102,13 +102,13 @@ Design: `design.md` (decision numbers below refer to it). Every task runs serial
|
||||
|
||||
## 4. Admin portal
|
||||
|
||||
- [ ] 4.1 Add the Interests screen (`app/interests/page.tsx`, desktop-first, following the Roles page pattern). It provides a table with add, rename, active toggle and sort order. It needs route handlers `app/api/interests/**`, a service, types, `Int*` i18n keys and `/interests` mapped to `BO_INTERESTS` in `routeModules`.
|
||||
- [x] 4.1 Add the Interests screen (`app/interests/page.tsx`, desktop-first, following the Roles page pattern). It provides a table with add, rename, active toggle and sort order. It needs route handlers `app/api/interests/**`, a service, types, `Int*` i18n keys and `/interests` mapped to `BO_INTERESTS` in `routeModules`.
|
||||
|
||||
Tests first (vitest), for each portal-visible `lead-interests` scenario.
|
||||
- Scope: `solvway-admin-portal/app/interests/**`, `solvway-admin-portal/app/api/interests/**`, `solvway-admin-portal/app/lib/**`
|
||||
- Verify: `cd solvway-admin-portal && npx vitest run && npx tsc --noEmit && npm run lint && npm run build`.
|
||||
|
||||
- [ ] 4.2 Add the event-floor screens (design decision 10):
|
||||
- [x] 4.2 Add the event-floor screens (design decision 10):
|
||||
- Pages:
|
||||
- `app/event-leads/page.tsx`: event picker.
|
||||
- `app/event-leads/[eventUuid]/page.tsx`: listing. `DataTable` at `md` and up; a card list below `md`, with filters.
|
||||
@@ -129,7 +129,7 @@ Design: `design.md` (decision numbers below refer to it). Every task runs serial
|
||||
|
||||
## 5. Verification
|
||||
|
||||
- [ ] 5.1 Rebuild the stack and drive the portal with Playwright, using only local dev data and test leads made up for this check.
|
||||
- [x] 5.1 Rebuild the stack and drive the portal with Playwright, using only local dev data and test leads made up for this check.
|
||||
- At desktop width:
|
||||
- Grant `BO_EVENT_LEADS` and `BO_INTERESTS` to a role.
|
||||
- Add interests, try a duplicate, and deactivate one.
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
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, PUT } from "./route";
|
||||
|
||||
type Req = Parameters<typeof GET>[0];
|
||||
const ctx = (...path: string[]) => ({ params: Promise.resolve({ path }) });
|
||||
const req = (url: string, init?: RequestInit) => new Request(`http://localhost${url}`, init) as unknown as Req;
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset();
|
||||
mocks.getToken.mockReset();
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { ok: 1 } });
|
||||
});
|
||||
|
||||
describe("/api/event-leads/[...path]", () => {
|
||||
it("returns 401 without a session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
const res = await GET(req("/api/event-leads/events"), ctx("events"));
|
||||
expect(res.status).toBe(401);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("forwards GET with the query string", async () => {
|
||||
const res = await GET(req("/api/event-leads/9/leads?status=OPEN&page=0&size=20"), ctx("9", "leads"));
|
||||
expect(res.status).toBe(200);
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-leads/9/leads?status=OPEN&page=0&size=20", { token: "jwt-abc" });
|
||||
});
|
||||
|
||||
it("forwards POST and PUT bodies", async () => {
|
||||
await POST(req("/api/event-leads/9/match", { method: "POST", body: JSON.stringify({ mobile: "0123" }) }), ctx("9", "match"));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-leads/9/match", { method: "POST", body: { mobile: "0123" }, token: "jwt-abc" });
|
||||
await PUT(req("/api/event-leads/9/leads/7", { method: "PUT", body: JSON.stringify({ status: "WON" }) }), ctx("9", "leads", "7"));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-leads/9/leads/7", { method: "PUT", body: { status: "WON" }, token: "jwt-abc" });
|
||||
});
|
||||
|
||||
it("rejects dot segments so the proxy cannot leave /api/admin/event-leads", async () => {
|
||||
const res = await GET(req("/api/event-leads/x"), ctx("..", "users"));
|
||||
expect(res.status).toBe(400);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("encodes path segments", async () => {
|
||||
await GET(req("/api/event-leads/a"), ctx("a/b"));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-leads/a%2Fb", { token: "jwt-abc" });
|
||||
});
|
||||
|
||||
it("passes upstream 409 with code and details", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({
|
||||
ok: false, error: "Already captured", status: 409, code: "ALREADY_CAPTURED", details: { eventLeadUuid: "55" },
|
||||
});
|
||||
const res = await POST(req("/api/event-leads/9", { method: "POST", body: "{}" }), ctx("9"));
|
||||
expect(res.status).toBe(409);
|
||||
const json = (await res.json()) as Record<string, unknown>;
|
||||
expect(json.code).toBe("ALREADY_CAPTURED");
|
||||
expect(json.details).toEqual({ eventLeadUuid: "55" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
// One proxy for every /api/admin/event-leads endpoint; mobile-api owns validation and the BO_EVENT_LEADS guard.
|
||||
type Ctx = { params: Promise<{ path: string[] }> };
|
||||
|
||||
async function forward(req: NextRequest, { params }: Ctx, method?: "POST" | "PUT") {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { path } = await params;
|
||||
if (path.some((s) => s === "." || s === "..")) return badRequest("Invalid path.");
|
||||
const target = `/api/admin/event-leads/${path.map(encodeURIComponent).join("/")}${new URL(req.url).search}`;
|
||||
const result = method
|
||||
? await callMobileApi<unknown>(target, { method, body: await req.json().catch(() => ({})), token })
|
||||
: await callMobileApi<unknown>(target, { token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
|
||||
export const GET = (req: NextRequest, ctx: Ctx) => forward(req, ctx);
|
||||
export const POST = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "POST");
|
||||
export const PUT = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "PUT");
|
||||
@@ -0,0 +1,106 @@
|
||||
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 { PUT } from "./route";
|
||||
|
||||
function ctx(id: string) {
|
||||
return { params: Promise.resolve({ id }) };
|
||||
}
|
||||
function putReq(body: unknown) {
|
||||
return new Request("http://localhost/api/interests/4", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(body),
|
||||
}) as unknown as Parameters<typeof PUT>[0];
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset();
|
||||
mocks.getToken.mockReset();
|
||||
});
|
||||
|
||||
describe("PUT /api/interests/[id]", () => {
|
||||
it("returns 401 when there is no session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
const res = await PUT(putReq({ name: "New" }), ctx("4"));
|
||||
expect(res.status).toBe(401);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("requires a name when updating name", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
const empty = await PUT(putReq({}), ctx("4"));
|
||||
expect(empty.status).toBe(400);
|
||||
const ws = await PUT(putReq({ name: " " }), ctx("4"));
|
||||
expect(ws.status).toBe(400);
|
||||
expect(((await ws.json()) as Record<string, unknown>).code).toBe("REQUIRED_FIELD");
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("trims the name before sending", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 4, name: "Updated" } });
|
||||
await PUT(putReq({ name: " Updated " }), ctx("4"));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/interests/4", {
|
||||
method: "PUT",
|
||||
body: { name: "Updated" },
|
||||
token: "jwt-abc",
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards { name } to PUT /api/admin/interests/{id}", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 4, name: "New" } });
|
||||
await PUT(putReq({ name: "New", active: true, sortOrder: 10 }), ctx("4"));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/interests/4", {
|
||||
method: "PUT",
|
||||
body: { name: "New", active: true, sortOrder: 10 },
|
||||
token: "jwt-abc",
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards { active: false } without name for deactivation", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 4, active: false, name: "Old" } });
|
||||
await PUT(putReq({ active: false }), ctx("4"));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/interests/4", {
|
||||
method: "PUT",
|
||||
body: { active: false },
|
||||
token: "jwt-abc",
|
||||
});
|
||||
});
|
||||
|
||||
it("passes upstream 409 with code and details to the client", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
mocks.callMobileApi.mockResolvedValue({
|
||||
ok: false,
|
||||
error: "Duplicate name",
|
||||
status: 409,
|
||||
code: "DUPLICATE_NAME",
|
||||
details: { field: "name" },
|
||||
});
|
||||
const res = await PUT(putReq({ name: "Dup" }), ctx("4"));
|
||||
expect(res.status).toBe(409);
|
||||
const json = await res.json() as Record<string, unknown>;
|
||||
expect(json.error).toBe("Duplicate name");
|
||||
expect(json.code).toBe("DUPLICATE_NAME");
|
||||
expect(json.details).toEqual({ field: "name" });
|
||||
});
|
||||
|
||||
it("passes upstream 403 with code to the client", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
mocks.callMobileApi.mockResolvedValue({
|
||||
ok: false,
|
||||
error: "Not authorized",
|
||||
status: 403,
|
||||
code: "NOT_AUTHORIZED",
|
||||
});
|
||||
const res = await PUT(putReq({ active: true }), ctx("4"));
|
||||
expect(res.status).toBe(403);
|
||||
const json = await res.json() as Record<string, unknown>;
|
||||
expect(json.error).toBe("Not authorized");
|
||||
expect(json.code).toBe("NOT_AUTHORIZED");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
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";
|
||||
import type { AdminInterestEntity } from "@/app/lib/types";
|
||||
|
||||
type Ctx = { params: Promise<{ id: string }> };
|
||||
|
||||
export async function PUT(req: NextRequest, { params }: Ctx) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { id } = await params;
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const payload: Record<string, unknown> = {};
|
||||
if ("name" in body && body.name !== undefined) {
|
||||
const trimmed = String(body.name).trim();
|
||||
if (!trimmed) return badRequest("Name is required.", { code: "REQUIRED_FIELD", details: { field: "name" } });
|
||||
payload.name = trimmed;
|
||||
}
|
||||
if ("active" in body) payload.active = body.active;
|
||||
if ("sortOrder" in body) payload.sortOrder = body.sortOrder;
|
||||
if (Object.keys(payload).length === 0) {
|
||||
return badRequest("At least one field is required.");
|
||||
}
|
||||
const result = await callMobileApi<AdminInterestEntity>(
|
||||
`/api/admin/interests/${encodeURIComponent(id)}`,
|
||||
{
|
||||
method: "PUT",
|
||||
body: payload,
|
||||
token,
|
||||
},
|
||||
);
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
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() {
|
||||
return new Request("http://localhost/api/interests") as unknown as Parameters<typeof GET>[0];
|
||||
}
|
||||
function postReq(body: unknown) {
|
||||
return new Request("http://localhost/api/interests", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
}) as unknown as Parameters<typeof POST>[0];
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset();
|
||||
mocks.getToken.mockReset();
|
||||
});
|
||||
|
||||
describe("GET /api/interests", () => {
|
||||
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/interests", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: [] });
|
||||
await GET(getReq());
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/interests", { token: "jwt-abc" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/interests", () => {
|
||||
it("returns 401 when there is no session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
const res = await POST(postReq({ name: "Test" }));
|
||||
expect(res.status).toBe(401);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("requires a name, blocks empty/whitespace", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
const empty = await POST(postReq({}));
|
||||
expect(empty.status).toBe(400);
|
||||
const ws = await POST(postReq({ name: " " }));
|
||||
expect(ws.status).toBe(400);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("trims the name before sending", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 1, name: "Workshop" } });
|
||||
await POST(postReq({ name: " Workshop " }));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/interests", {
|
||||
method: "POST",
|
||||
body: { name: "Workshop" },
|
||||
token: "jwt-abc",
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards name, active, sortOrder to POST /api/admin/interests", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 1, name: "Test" } });
|
||||
await POST(postReq({ name: "Test", active: true, sortOrder: 5 }));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/interests", {
|
||||
method: "POST",
|
||||
body: { name: "Test", active: true, sortOrder: 5 },
|
||||
token: "jwt-abc",
|
||||
});
|
||||
});
|
||||
|
||||
it("returns REQUIRED_FIELD code for a blank name", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
const res = await POST(postReq({ name: " " }));
|
||||
expect(res.status).toBe(400);
|
||||
expect(((await res.json()) as Record<string, unknown>).code).toBe("REQUIRED_FIELD");
|
||||
});
|
||||
|
||||
it("passes upstream 409 with code and details to the client", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
mocks.callMobileApi.mockResolvedValue({
|
||||
ok: false, error: "Duplicate name", status: 409, code: "DUPLICATE_NAME", details: { field: "name" },
|
||||
});
|
||||
const res = await POST(postReq({ name: "Dup" }));
|
||||
expect(res.status).toBe(409);
|
||||
const json = (await res.json()) as Record<string, unknown>;
|
||||
expect(json.code).toBe("DUPLICATE_NAME");
|
||||
expect(json.details).toEqual({ field: "name" });
|
||||
});
|
||||
|
||||
it("passes upstream 403 with code to the client", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Not authorized", status: 403, code: "NOT_AUTHORIZED" });
|
||||
const res = await POST(postReq({ name: "X" }));
|
||||
expect(res.status).toBe(403);
|
||||
expect(((await res.json()) as Record<string, unknown>).code).toBe("NOT_AUTHORIZED");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
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";
|
||||
import type { AdminInterestEntity } from "@/app/lib/types";
|
||||
|
||||
export async function GET(_req: NextRequest) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const result = await callMobileApi<AdminInterestEntity[]>("/api/admin/interests", { 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 name = (body as Partial<AdminInterestEntity>).name?.trim();
|
||||
if (!name) {
|
||||
return badRequest("Name is required.", { code: "REQUIRED_FIELD", details: { field: "name" } });
|
||||
}
|
||||
const result = await callMobileApi<AdminInterestEntity>(
|
||||
"/api/admin/interests",
|
||||
{
|
||||
method: "POST",
|
||||
body: { name, active: (body as Partial<AdminInterestEntity>).active, sortOrder: (body as Partial<AdminInterestEntity>).sortOrder },
|
||||
token,
|
||||
},
|
||||
);
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { pickDate } from "@/test/pickDate";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getEventLead: vi.fn(),
|
||||
updateEventLead: vi.fn(),
|
||||
listEventSalespeople: vi.fn(),
|
||||
listEventLeadInterests: vi.fn(),
|
||||
useAdminAuth: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminEventLeads", async (importActual) => ({
|
||||
...(await importActual<typeof import("@/app/lib/services/adminEventLeads")>()),
|
||||
getEventLead: mocks.getEventLead,
|
||||
updateEventLead: mocks.updateEventLead,
|
||||
listEventSalespeople: mocks.listEventSalespeople,
|
||||
listEventLeadInterests: mocks.listEventLeadInterests,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("next/navigation", async () => ({
|
||||
...(await import("@/test/memoryRouter")).navigationMock,
|
||||
useParams: () => ({ eventUuid: "evt-1", eventLeadUuid: "el-1" }),
|
||||
}));
|
||||
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import EventLeadPage from "./page";
|
||||
|
||||
const SERVER_MSG = "Server says: internal detail xyz";
|
||||
const apiError = (code: string, extra: { details?: Record<string, unknown> } = {}, status = 400) =>
|
||||
new ApiError(SERVER_MSG, status, { code, errors: [], details: {}, ...extra });
|
||||
|
||||
const LEAD = {
|
||||
eventLeadUuid: "el-1", eventUuid: "evt-1", leadUuid: "l-1",
|
||||
name: "Ann Lead", mobile: "+6591111111", email: "ann@x.com", companyName: "Acme", jobTitle: "CEO",
|
||||
leadType: "NEW", salesperson: { id: 7, name: "Jane Sales" }, temperature: "WARM", status: "CONTACTED",
|
||||
interests: [{ id: 1, name: "Product A", active: true }, { id: 2, name: "Product B", active: false }],
|
||||
nextFollowUpDate: "2026-12-01", notes: "Call back", capturedAt: "2026-11-20T09:30:00Z",
|
||||
};
|
||||
const PAYLOAD = { salespersonId: 7, temperature: "WARM", status: "CONTACTED", interestIds: [1, 2], nextFollowUpDate: "2026-12-01", notes: "Call back" };
|
||||
|
||||
async function open(lead: Record<string, unknown> = {}) {
|
||||
mocks.getEventLead.mockResolvedValue({ ...LEAD, ...lead });
|
||||
render(<EventLeadPage />);
|
||||
await screen.findByLabelText("Status");
|
||||
return userEvent.setup();
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
memoryRouter.reset("/event-leads/evt-1/el-1");
|
||||
mocks.getEventLead.mockReset();
|
||||
mocks.updateEventLead.mockReset().mockResolvedValue(LEAD);
|
||||
mocks.listEventSalespeople.mockReset().mockResolvedValue([{ id: 8, name: "Bob Other", username: "bob" }]);
|
||||
mocks.listEventLeadInterests.mockReset().mockResolvedValue([
|
||||
{ id: 1, name: "Product A", active: true },
|
||||
{ id: 3, name: "Product C", active: true },
|
||||
]);
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
|
||||
});
|
||||
|
||||
describe("EventLeadPage", { timeout: 20000 }, () => {
|
||||
it("renders NotAuthorized when the module is absent", () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
|
||||
render(<EventLeadPage />);
|
||||
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the lead contact read-only with type badge and captured date", async () => {
|
||||
await open();
|
||||
expect(screen.getByText("Ann Lead")).toBeVisible();
|
||||
expect(screen.getByText("+6591111111")).toBeVisible();
|
||||
expect(screen.getByText("ann@x.com")).toBeVisible();
|
||||
expect(screen.getByText("Acme")).toBeVisible();
|
||||
expect(screen.getByText("CEO")).toBeVisible();
|
||||
expect(screen.getByText("New")).toBeVisible();
|
||||
expect(screen.getByText(/20\/11\/2026/)).toBeVisible();
|
||||
expect(screen.queryByLabelText("Name")).toBeNull();
|
||||
expect(screen.queryByLabelText("Mobile")).toBeNull();
|
||||
});
|
||||
|
||||
it("shows the Existing badge for an existing lead", async () => {
|
||||
await open({ leadType: "EXISTING" });
|
||||
expect(screen.getByText("Existing")).toBeVisible();
|
||||
});
|
||||
|
||||
it("prefills the editable fields from the event lead", async () => {
|
||||
await open();
|
||||
expect(screen.getByLabelText("Salesperson")).toHaveValue("7");
|
||||
expect(screen.getByLabelText("Temperature")).toHaveValue("WARM");
|
||||
expect(screen.getByLabelText("Status")).toHaveValue("CONTACTED");
|
||||
expect(screen.getByLabelText("Product A")).toBeChecked();
|
||||
expect(screen.getByLabelText("Next follow-up")).toHaveValue("01/12/2026");
|
||||
expect(screen.getByLabelText("Notes")).toHaveValue("Call back");
|
||||
});
|
||||
|
||||
it("keeps the current salesperson selectable when not on the event team list", async () => {
|
||||
await open();
|
||||
const select = screen.getByLabelText("Salesperson");
|
||||
expect(within(select).getByRole("option", { name: "Jane Sales" })).toBeInTheDocument();
|
||||
expect(within(select).getByRole("option", { name: "Bob Other" })).toBeInTheDocument();
|
||||
expect(within(select).getByRole("option", { name: "None" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("lists an inactive interest already on the lead (not in the options list) as checked, once", async () => {
|
||||
await open();
|
||||
expect(screen.getByLabelText("Product A")).toBeChecked();
|
||||
expect(screen.getByLabelText("Product B")).toBeChecked();
|
||||
expect(screen.getByLabelText("Product C")).not.toBeChecked();
|
||||
expect(screen.getAllByLabelText("Product A")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("unchecking the inactive interest saves interestIds without it", async () => {
|
||||
const user = await open();
|
||||
await user.click(screen.getByLabelText("Product B"));
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.updateEventLead).toHaveBeenCalledTimes(1));
|
||||
expect(mocks.updateEventLead).toHaveBeenCalledWith("evt-1", "el-1", { ...PAYLOAD, interestIds: [1] });
|
||||
});
|
||||
|
||||
it("saves unchanged values with all six fields, then goes back to the list", async () => {
|
||||
const user = await open();
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.updateEventLead).toHaveBeenCalledTimes(1));
|
||||
expect(mocks.updateEventLead).toHaveBeenCalledWith("evt-1", "el-1", PAYLOAD);
|
||||
await waitFor(() => expect(memoryRouter.push).toHaveBeenCalledWith("/event-leads/evt-1"));
|
||||
});
|
||||
|
||||
it("saves edited values", async () => {
|
||||
const user = await open();
|
||||
await user.selectOptions(screen.getByLabelText("Salesperson"), "8");
|
||||
await user.selectOptions(screen.getByLabelText("Temperature"), "HOT");
|
||||
await user.selectOptions(screen.getByLabelText("Status"), "WON");
|
||||
await user.click(screen.getByLabelText("Product B"));
|
||||
await user.click(screen.getByLabelText("Product C"));
|
||||
pickDate("Next follow-up", "2026-12-05");
|
||||
const notes = screen.getByLabelText("Notes");
|
||||
await user.clear(notes);
|
||||
await user.type(notes, "Signed");
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.updateEventLead).toHaveBeenCalledTimes(1));
|
||||
expect(mocks.updateEventLead).toHaveBeenCalledWith("evt-1", "el-1", {
|
||||
salespersonId: 8, temperature: "HOT", status: "WON", interestIds: [1, 3], nextFollowUpDate: "2026-12-05", notes: "Signed",
|
||||
});
|
||||
});
|
||||
|
||||
it("sends null for emptied fields", async () => {
|
||||
const user = await open();
|
||||
await user.selectOptions(screen.getByLabelText("Salesperson"), "");
|
||||
await user.selectOptions(screen.getByLabelText("Temperature"), "");
|
||||
await user.clear(screen.getByLabelText("Notes"));
|
||||
await user.click(screen.getByLabelText("Product A"));
|
||||
await user.click(screen.getByLabelText("Product B"));
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.updateEventLead).toHaveBeenCalledTimes(1));
|
||||
expect(mocks.updateEventLead).toHaveBeenCalledWith("evt-1", "el-1", {
|
||||
salespersonId: null, temperature: null, status: "CONTACTED", interestIds: [], nextFollowUpDate: "2026-12-01", notes: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("has a Back link to the event's leads", async () => {
|
||||
await open();
|
||||
expect(screen.getByRole("link", { name: "Back" })).toHaveAttribute("href", "/event-leads/evt-1");
|
||||
});
|
||||
|
||||
it("uses touch targets of at least 44px", async () => {
|
||||
await open();
|
||||
for (const label of ["Salesperson", "Temperature", "Status"]) expect(screen.getByLabelText(label)).toHaveClass("min-h-11");
|
||||
expect(screen.getByLabelText("Product A").closest("label")).toHaveClass("min-h-11");
|
||||
expect(screen.getByRole("button", { name: "Save" })).toHaveClass("min-h-11");
|
||||
expect(screen.getByRole("link", { name: "Back" })).toHaveClass("min-h-11");
|
||||
});
|
||||
|
||||
it("shows a not-found state with a Back link for EVENT_LEAD_NOT_FOUND", async () => {
|
||||
mocks.getEventLead.mockRejectedValue(apiError("EVENT_LEAD_NOT_FOUND", {}, 404));
|
||||
render(<EventLeadPage />);
|
||||
expect(await screen.findByText("Lead not found")).toBeVisible();
|
||||
expect(screen.getByRole("link", { name: "Back" })).toHaveAttribute("href", "/event-leads/evt-1");
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
expect(screen.queryByRole("button", { name: "Save" })).toBeNull();
|
||||
});
|
||||
|
||||
it("shows an error with retry for other load failures, and retry reloads", async () => {
|
||||
mocks.getEventLead.mockRejectedValueOnce(apiError("BOOM", {}, 500)).mockResolvedValue(LEAD);
|
||||
render(<EventLeadPage />);
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Failed to load the lead");
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
await userEvent.setup().click(screen.getByRole("button", { name: "Retry" }));
|
||||
expect(await screen.findByLabelText("Status")).toBeVisible();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["TOO_LONG", "notes", "Notes", "Too long."],
|
||||
["INVALID_DATE", "nextFollowUpDate", "Next follow-up", "Enter a valid date."],
|
||||
["NOT_ON_TEAM", "salespersonId", "Salesperson", "This person is not on the event team."],
|
||||
["INVALID_VALUE", "temperature", "Temperature", "Invalid value."],
|
||||
["INVALID_VALUE", "status", "Status", "Invalid value."],
|
||||
])("%s on %s shows the mapped message under the field", async (code, field, label, text) => {
|
||||
mocks.updateEventLead.mockRejectedValue(apiError(code, { details: { field } }));
|
||||
const user = await open();
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByText(text)).toBeVisible();
|
||||
const el = screen.getByLabelText(label);
|
||||
expect(el).toHaveAttribute("aria-invalid", "true");
|
||||
expect(document.getElementById(el.getAttribute("aria-describedby")!)).toHaveTextContent(text);
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
expect(memoryRouter.push).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("INACTIVE_INTEREST shows the mapped message under the interests group", async () => {
|
||||
mocks.updateEventLead.mockRejectedValue(apiError("INACTIVE_INTEREST", { details: { field: "interestIds" } }));
|
||||
const user = await open();
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByText("An interest is no longer active.")).toBeVisible();
|
||||
const group = screen.getByRole("group", { name: "Interests" });
|
||||
expect(group).toHaveAttribute("aria-invalid", "true");
|
||||
expect(document.getElementById(group.getAttribute("aria-describedby")!)).toHaveTextContent("An interest is no longer active.");
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
});
|
||||
|
||||
it("other save errors show a form-level message and stay on the page", async () => {
|
||||
mocks.updateEventLead.mockRejectedValue(apiError("SOMETHING_ELSE"));
|
||||
const user = await open();
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Could not save the lead. Please try again.");
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
expect(memoryRouter.push).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("an unknown field in a field error gives a form-level message", async () => {
|
||||
mocks.updateEventLead.mockRejectedValue(apiError("TOO_LONG", { details: { field: "bogus" } }));
|
||||
const user = await open();
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Could not save the lead. Please try again.");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,197 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { Badge } from "@/app/components/ui/badge";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { DatePicker } from "@/app/components/ui/date-picker";
|
||||
import { Label } from "@/app/components/ui/label";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { EmptyState, ErrorState, TableSkeleton } from "@/app/components/ui/states";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { formatDmy } from "@/app/lib/date-input";
|
||||
import { getEventLead, listEventLeadInterests, listEventSalespeople, updateEventLead } from "@/app/lib/services/adminEventLeads";
|
||||
import type { EventLeadRow, InterestOption, LeadStatus, LeadTemperature, SalespersonOption } from "@/app/lib/types";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
const TEMPERATURES: [LeadTemperature, string][] = [["HOT", "LeadHot"], ["WARM", "LeadWarm"], ["COLD", "LeadCold"]];
|
||||
const STATUSES: [LeadStatus, string][] = [["OPEN", "LeadOpen"], ["CONTACTED", "LeadContacted"], ["QUALIFIED", "LeadQualified"], ["WON", "LeadWon"], ["LOST", "LeadLost"]];
|
||||
const CODE_MESSAGE: Record<string, string> = {
|
||||
TOO_LONG: "LeadErrTooLong",
|
||||
INVALID_DATE: "LeadErrInvalidDate",
|
||||
NOT_ON_TEAM: "LeadErrNotOnTeam",
|
||||
INACTIVE_INTEREST: "LeadErrInactiveInterest",
|
||||
INVALID_VALUE: "LeadErrInvalidValue",
|
||||
};
|
||||
const FIELDS = ["salespersonId", "temperature", "status", "interestIds", "nextFollowUpDate", "notes"];
|
||||
const SELECT_CLASS = "min-h-11 w-full rounded-md border border-input bg-transparent px-3 text-base shadow-sm outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-[invalid=true]:border-destructive dark:bg-input/30";
|
||||
const TALL = "min-h-11";
|
||||
|
||||
type Loaded = { lead: EventLeadRow; salespeople: SalespersonOption[]; interests: InterestOption[] };
|
||||
type LoadState = "loading" | "notFound" | "error" | Loaded;
|
||||
|
||||
function EventLead() {
|
||||
const t = useT();
|
||||
const router = useRouter();
|
||||
const { eventUuid, eventLeadUuid } = useParams<{ eventUuid: string; eventLeadUuid: string }>();
|
||||
const [state, setState] = useState<LoadState>("loading");
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const [salespersonId, setSalespersonId] = useState("");
|
||||
const [temperature, setTemperature] = useState("");
|
||||
const [status, setStatus] = useState("");
|
||||
const [interestIds, setInterestIds] = useState<number[]>([]);
|
||||
const [nextFollowUpDate, setNextFollowUpDate] = useState("");
|
||||
const [notes, setNotes] = useState("");
|
||||
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const back = `/event-leads/${eventUuid}`;
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
Promise.all([getEventLead(eventUuid, eventLeadUuid), listEventSalespeople(eventUuid), listEventLeadInterests()])
|
||||
.then(([lead, salespeople, interests]) => {
|
||||
if (cancelled) return;
|
||||
setSalespersonId(lead.salesperson ? String(lead.salesperson.id) : "");
|
||||
setTemperature(lead.temperature ?? "");
|
||||
setStatus(lead.status);
|
||||
setInterestIds(lead.interests.map((i) => i.id));
|
||||
setNextFollowUpDate(lead.nextFollowUpDate ?? "");
|
||||
setNotes(lead.notes ?? "");
|
||||
setState({
|
||||
lead,
|
||||
// The current salesperson stays selectable even when no longer on the team list.
|
||||
salespeople: lead.salesperson && !salespeople.some((s) => s.id === lead.salesperson!.id)
|
||||
? [...salespeople, { id: lead.salesperson.id, name: lead.salesperson.name, username: "" }]
|
||||
: salespeople,
|
||||
// The options list is active-only; an inactive interest on the lead comes from the lead itself.
|
||||
interests: [...interests, ...lead.interests.filter((i) => !interests.some((o) => o.id === i.id))],
|
||||
});
|
||||
})
|
||||
.catch((err) => {
|
||||
if (cancelled) return;
|
||||
const code = err instanceof ApiError ? (err.data as { code?: string } | undefined)?.code : undefined;
|
||||
setState(code === "EVENT_LEAD_NOT_FOUND" ? "notFound" : "error");
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [eventUuid, eventLeadUuid, reloadKey]);
|
||||
|
||||
const backLink = (
|
||||
<Button asChild variant="outline" className={TALL}>
|
||||
<Link href={back}>{t("Back")}</Link>
|
||||
</Button>
|
||||
);
|
||||
|
||||
if (state === "loading") return <TableSkeleton rows={4} columns={2} />;
|
||||
if (state === "notFound") return <EmptyState title={t("LeadNotFound")} action={backLink} />;
|
||||
if (state === "error") {
|
||||
return <ErrorState message={t("LeadGetFailed")} onRetry={() => { setState("loading"); setReloadKey((k) => k + 1); }} />;
|
||||
}
|
||||
const { lead, salespeople, interests } = state;
|
||||
|
||||
const fieldProps = (f: string) => ({
|
||||
id: `lead-${f}`,
|
||||
"aria-invalid": fieldErrors[f] ? (true as const) : undefined,
|
||||
"aria-describedby": fieldErrors[f] ? `lead-${f}-error` : undefined,
|
||||
});
|
||||
const fieldError = (f: string) =>
|
||||
fieldErrors[f] ? <p id={`lead-${f}-error`} role="alert" className="text-sm text-destructive">{fieldErrors[f]}</p> : null;
|
||||
const field = (f: string, label: string, control: React.ReactNode) => (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor={`lead-${f}`}>{label}</Label>
|
||||
{control}
|
||||
{fieldError(f)}
|
||||
</div>
|
||||
);
|
||||
|
||||
async function onSave(event: FormEvent) {
|
||||
event.preventDefault();
|
||||
setFieldErrors({});
|
||||
setFormError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
await updateEventLead(eventUuid, eventLeadUuid, {
|
||||
salespersonId: salespersonId ? Number(salespersonId) : null,
|
||||
temperature: (temperature || null) as LeadTemperature | null,
|
||||
status: status as LeadStatus,
|
||||
interestIds,
|
||||
nextFollowUpDate: nextFollowUpDate || null,
|
||||
notes: notes.trim() || null,
|
||||
});
|
||||
router.push(back);
|
||||
} catch (err) {
|
||||
const data = err instanceof ApiError ? (err.data as { code?: string; details?: { field?: unknown } } | undefined) : undefined;
|
||||
const f = data?.details?.field;
|
||||
const key = data?.code ? CODE_MESSAGE[data.code] : undefined;
|
||||
if (key && typeof f === "string" && FIELDS.includes(f)) setFieldErrors({ [f]: t(key) });
|
||||
else setFormError(t("LeadSaveFailed"));
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const toggleInterest = (id: number) =>
|
||||
setInterestIds((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-xl">
|
||||
<PageHeader title={lead.name} />
|
||||
{formError && <ErrorState message={formError} />}
|
||||
<form onSubmit={onSave} className="space-y-4" noValidate>
|
||||
<div className="space-y-1 rounded-lg border p-4">
|
||||
<Badge variant={lead.leadType === "NEW" ? "default" : "secondary"}>{t(lead.leadType === "NEW" ? "LeadNew" : "LeadExisting")}</Badge>
|
||||
{lead.mobile && <p className="text-sm">{lead.mobile}</p>}
|
||||
{lead.email && <p className="text-sm">{lead.email}</p>}
|
||||
{lead.companyName && <p className="text-sm text-muted-foreground">{lead.companyName}</p>}
|
||||
{lead.jobTitle && <p className="text-sm text-muted-foreground">{lead.jobTitle}</p>}
|
||||
<p className="text-sm text-muted-foreground">{t("LeadCaptured")} {formatDmy(lead.capturedAt.slice(0, 10))}</p>
|
||||
</div>
|
||||
|
||||
{field("salespersonId", t("LeadSalesperson"),
|
||||
<select {...fieldProps("salespersonId")} className={SELECT_CLASS} value={salespersonId} onChange={(e) => setSalespersonId(e.target.value)} disabled={busy}>
|
||||
<option value="">{t("LeadNone")}</option>
|
||||
{salespeople.map((s) => <option key={s.id} value={String(s.id)}>{s.name}</option>)}
|
||||
</select>)}
|
||||
{field("temperature", t("LeadTemperature"),
|
||||
<select {...fieldProps("temperature")} className={SELECT_CLASS} value={temperature} onChange={(e) => setTemperature(e.target.value)} disabled={busy}>
|
||||
<option value="">{t("LeadNone")}</option>
|
||||
{TEMPERATURES.map(([v, k]) => <option key={v} value={v}>{t(k)}</option>)}
|
||||
</select>)}
|
||||
{field("status", t("LeadStatus"),
|
||||
<select {...fieldProps("status")} className={SELECT_CLASS} value={status} onChange={(e) => setStatus(e.target.value)} disabled={busy}>
|
||||
{STATUSES.map(([v, k]) => <option key={v} value={v}>{t(k)}</option>)}
|
||||
</select>)}
|
||||
|
||||
<fieldset {...fieldProps("interestIds")} className="space-y-1">
|
||||
<legend className="mb-1.5 text-sm font-medium">{t("LeadInterests")}</legend>
|
||||
{interests.map((i) => (
|
||||
<label key={i.id} className="flex min-h-11 items-center gap-3 text-sm">
|
||||
<input type="checkbox" className="size-5" checked={interestIds.includes(i.id)} onChange={() => toggleInterest(i.id)} disabled={busy} />
|
||||
{i.name}
|
||||
</label>
|
||||
))}
|
||||
{fieldError("interestIds")}
|
||||
</fieldset>
|
||||
|
||||
{field("nextFollowUpDate", t("LeadNextFollowUp"),
|
||||
<DatePicker {...fieldProps("nextFollowUpDate")} className="h-11" value={nextFollowUpDate} onChange={setNextFollowUpDate} disabled={busy} />)}
|
||||
{field("notes", t("LeadNotes"),
|
||||
<textarea {...fieldProps("notes")} className={`${SELECT_CLASS} py-2`} rows={3} value={notes} onChange={(e) => setNotes(e.target.value)} disabled={busy} />)}
|
||||
|
||||
<div className="flex flex-col-reverse gap-3 sm:flex-row">
|
||||
{backLink}
|
||||
<Button type="submit" className={TALL} disabled={busy}>{t("Save")}</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function EventLeadPage() {
|
||||
return (
|
||||
<RequireModule pathname="/event-leads">
|
||||
<EventLead />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { pickDate } from "@/test/pickDate";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
matchLead: vi.fn(),
|
||||
captureEventLead: vi.fn(),
|
||||
listEventSalespeople: vi.fn(),
|
||||
listEventLeadInterests: vi.fn(),
|
||||
useAdminAuth: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminEventLeads", async (importActual) => ({
|
||||
...(await importActual<typeof import("@/app/lib/services/adminEventLeads")>()),
|
||||
matchLead: mocks.matchLead,
|
||||
captureEventLead: mocks.captureEventLead,
|
||||
listEventSalespeople: mocks.listEventSalespeople,
|
||||
listEventLeadInterests: mocks.listEventLeadInterests,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("next/navigation", async () => ({
|
||||
...(await import("@/test/memoryRouter")).navigationMock,
|
||||
useParams: () => ({ eventUuid: "evt-1" }),
|
||||
}));
|
||||
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import NewEventLeadPage from "./page";
|
||||
|
||||
const SERVER_MSG = "Server says: internal detail xyz";
|
||||
const apiError = (code: string, extra: { errors?: string[]; details?: Record<string, unknown> } = {}) =>
|
||||
new ApiError(SERVER_MSG, 400, { code, errors: [], details: {}, ...extra });
|
||||
|
||||
const CAPTURED = { leadUuid: "l-1", name: "Ann Captured", mobile: "+6591111111", email: "ann@x.com", companyName: "Acme", jobTitle: "CEO", eventLeadUuid: "el-9" };
|
||||
const FRESH = { leadUuid: "l-2", name: "Bob Fresh", mobile: "+6592222222", email: "bob@x.com", companyName: "Globex", jobTitle: "CTO", eventLeadUuid: null };
|
||||
|
||||
async function toStep1Match(candidates: unknown[], match = { mobile: "+6591234567", email: "a@b.com" }) {
|
||||
mocks.matchLead.mockResolvedValue({ ...match, candidates });
|
||||
const user = userEvent.setup();
|
||||
render(<NewEventLeadPage />);
|
||||
await user.type(screen.getByLabelText("Mobile"), "91234567");
|
||||
await user.type(screen.getByLabelText("Email"), "a@b.com");
|
||||
await user.click(screen.getByRole("button", { name: "Next" }));
|
||||
return user;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
memoryRouter.reset("/event-leads/evt-1/new");
|
||||
mocks.matchLead.mockReset();
|
||||
mocks.captureEventLead.mockReset().mockResolvedValue({ eventLeadUuid: "el-new" });
|
||||
mocks.listEventSalespeople.mockReset().mockResolvedValue([{ id: 7, name: "Jane Sales", username: "jane" }]);
|
||||
mocks.listEventLeadInterests.mockReset().mockResolvedValue([
|
||||
{ id: 1, name: "Product A", active: true },
|
||||
{ id: 2, name: "Product B", active: false },
|
||||
]);
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
|
||||
});
|
||||
|
||||
describe("NewEventLeadPage", { timeout: 20000 }, () => {
|
||||
it("renders NotAuthorized when the module is absent", () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
|
||||
render(<NewEventLeadPage />);
|
||||
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("step 1 has phone-friendly mobile and email inputs of at least 44px", () => {
|
||||
render(<NewEventLeadPage />);
|
||||
const mobile = screen.getByLabelText("Mobile");
|
||||
expect(mobile).toHaveAttribute("type", "tel");
|
||||
expect(mobile).toHaveAttribute("inputmode", "tel");
|
||||
expect(mobile).toHaveAttribute("autocomplete", "tel");
|
||||
expect(mobile).toHaveClass("min-h-11");
|
||||
const email = screen.getByLabelText("Email");
|
||||
expect(email).toHaveAttribute("type", "email");
|
||||
expect(email).toHaveAttribute("autocomplete", "email");
|
||||
expect(email).toHaveClass("min-h-11");
|
||||
expect(screen.getByRole("button", { name: "Next" })).toHaveClass("min-h-11");
|
||||
});
|
||||
|
||||
it("Next calls matchLead with the typed values, null for empty ones", async () => {
|
||||
mocks.matchLead.mockResolvedValue({ mobile: null, email: null, candidates: [] });
|
||||
const user = userEvent.setup();
|
||||
render(<NewEventLeadPage />);
|
||||
await user.type(screen.getByLabelText("Mobile"), "91234567");
|
||||
await user.click(screen.getByRole("button", { name: "Next" }));
|
||||
await waitFor(() => expect(mocks.matchLead).toHaveBeenCalledWith("evt-1", { mobile: "91234567", email: null }));
|
||||
});
|
||||
|
||||
it("shows each candidate as a card; captured ones link to the lead, others offer This person", async () => {
|
||||
await toStep1Match([CAPTURED, FRESH]);
|
||||
const ann = (await screen.findByText("Ann Captured")).closest("li")!;
|
||||
expect(within(ann).getByText("+6591111111")).toBeVisible();
|
||||
expect(within(ann).getByText("ann@x.com")).toBeVisible();
|
||||
expect(within(ann).getByText("Acme")).toBeVisible();
|
||||
expect(within(ann).getByText("Already captured")).toBeVisible();
|
||||
expect(within(ann).getByRole("link", { name: "Open" })).toHaveAttribute("href", "/event-leads/evt-1/el-9");
|
||||
expect(within(ann).queryByRole("button", { name: "This person" })).toBeNull();
|
||||
const bob = screen.getByText("Bob Fresh").closest("li")!;
|
||||
expect(within(bob).getByText("Globex")).toBeVisible();
|
||||
expect(within(bob).getByRole("button", { name: "This person" })).toHaveClass("min-h-11");
|
||||
expect(within(bob).queryByText("Already captured")).toBeNull();
|
||||
expect(screen.getByRole("button", { name: "Different person" })).toBeVisible();
|
||||
});
|
||||
|
||||
it("goes straight to step 2 as new, prefilled with the normalised match values, when nothing matches", async () => {
|
||||
await toStep1Match([]);
|
||||
expect(await screen.findByLabelText("Name")).toHaveValue("");
|
||||
expect(screen.getByLabelText("Mobile")).toHaveValue("+6591234567");
|
||||
expect(screen.getByLabelText("Email")).toHaveValue("a@b.com");
|
||||
expect(screen.getByLabelText("Company")).toBeVisible();
|
||||
expect(screen.getByLabelText("Job title")).toBeVisible();
|
||||
});
|
||||
|
||||
it("Different person goes to step 2 as new", async () => {
|
||||
const user = await toStep1Match([FRESH]);
|
||||
await user.click(await screen.findByRole("button", { name: "Different person" }));
|
||||
expect(await screen.findByLabelText("Name")).toHaveValue("");
|
||||
expect(screen.getByLabelText("Mobile")).toHaveValue("+6591234567");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["REQUIRED_FIELD", ["mobile", "email"], "Mobile or email is required.", ["Mobile", "Email"]],
|
||||
["INVALID_MOBILE", [], "Enter a valid mobile number.", ["Mobile"]],
|
||||
["INVALID_EMAIL", [], "Enter a valid email address.", ["Email"]],
|
||||
])("step 1 %s shows the mapped message under the field", async (code, errors, text, labels) => {
|
||||
mocks.matchLead.mockRejectedValue(apiError(code, { errors }));
|
||||
const user = userEvent.setup();
|
||||
render(<NewEventLeadPage />);
|
||||
await user.click(screen.getByRole("button", { name: "Next" }));
|
||||
const msgs = await screen.findAllByText(text);
|
||||
expect(msgs).toHaveLength(labels.length);
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
for (const label of labels) {
|
||||
const input = screen.getByLabelText(label);
|
||||
expect(input).toHaveAttribute("aria-invalid", "true");
|
||||
const described = document.getElementById(input.getAttribute("aria-describedby")!);
|
||||
expect(described).toHaveTextContent(text);
|
||||
}
|
||||
});
|
||||
|
||||
it("This person shows the lead read-only and saves with leadUuid, filling only its blank contact field", async () => {
|
||||
// Matched on mobile; the lead has no email yet, so the entered email fills it.
|
||||
const picked = { ...FRESH, mobile: "+60198887777", email: null };
|
||||
const user = await toStep1Match([picked], { mobile: "+60198887777", email: "a@b.com" });
|
||||
await user.click(await screen.findByRole("button", { name: "This person" }));
|
||||
expect(await screen.findByText("Bob Fresh")).toBeVisible();
|
||||
expect(screen.queryByLabelText("Name")).toBeNull();
|
||||
expect(screen.queryByLabelText("Company")).toBeNull();
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.captureEventLead).toHaveBeenCalledTimes(1));
|
||||
const [uuid, payload] = mocks.captureEventLead.mock.calls[0];
|
||||
expect(uuid).toBe("evt-1");
|
||||
expect(payload).toMatchObject({ leadUuid: "l-2", name: "Bob Fresh", mobile: "+60198887777", email: "a@b.com", status: "OPEN" });
|
||||
await waitFor(() => expect(memoryRouter.push).toHaveBeenCalledWith("/event-leads/evt-1"));
|
||||
});
|
||||
|
||||
it("picking one of two people never copies the other person's contact onto it", async () => {
|
||||
// Mobile matched A, email matched B. Picking A must not send B's email (no merge).
|
||||
const a = { ...FRESH, leadUuid: "l-a", name: "Amy Mobile", mobile: "+60198887777", email: null };
|
||||
const b = { ...FRESH, leadUuid: "l-b", name: "Ben Email", mobile: null, email: "a@b.com" };
|
||||
const user = await toStep1Match([a, b], { mobile: "+60198887777", email: "a@b.com" });
|
||||
await user.click((await screen.findAllByRole("button", { name: "This person" }))[0]);
|
||||
await user.click(await screen.findByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.captureEventLead).toHaveBeenCalledTimes(1));
|
||||
expect(mocks.captureEventLead.mock.calls[0][1]).toMatchObject({ leadUuid: "l-a", mobile: "+60198887777", email: null });
|
||||
});
|
||||
|
||||
it("step 2 offers salespeople, interests (active only), temperature and status, and saves a new lead", async () => {
|
||||
const user = await toStep1Match([]);
|
||||
await user.type(await screen.findByLabelText("Name"), "Carl New");
|
||||
await user.type(screen.getByLabelText("Company"), "Initech");
|
||||
await user.type(screen.getByLabelText("Job title"), "COO");
|
||||
await user.type(screen.getByLabelText("Notes"), "Met at booth");
|
||||
expect(screen.getByLabelText("Status")).toHaveValue("OPEN");
|
||||
expect(screen.getByLabelText("Status")).toHaveClass("min-h-11");
|
||||
expect(within(screen.getByLabelText("Temperature")).getByRole("option", { name: "Hot" })).toBeInTheDocument();
|
||||
expect(await screen.findByRole("option", { name: "Jane Sales" })).toBeInTheDocument();
|
||||
await user.selectOptions(screen.getByLabelText("Salesperson"), "7");
|
||||
await user.selectOptions(screen.getByLabelText("Temperature"), "HOT");
|
||||
await user.selectOptions(screen.getByLabelText("Status"), "QUALIFIED");
|
||||
expect(screen.queryByLabelText("Product B")).toBeNull();
|
||||
await user.click(await screen.findByLabelText("Product A"));
|
||||
pickDate("Next follow-up", "2026-12-05");
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.captureEventLead).toHaveBeenCalledTimes(1));
|
||||
expect(mocks.captureEventLead).toHaveBeenCalledWith("evt-1", {
|
||||
name: "Carl New",
|
||||
mobile: "+6591234567",
|
||||
email: "a@b.com",
|
||||
companyName: "Initech",
|
||||
jobTitle: "COO",
|
||||
salespersonId: 7,
|
||||
temperature: "HOT",
|
||||
status: "QUALIFIED",
|
||||
interestIds: [1],
|
||||
nextFollowUpDate: "2026-12-05",
|
||||
notes: "Met at booth",
|
||||
});
|
||||
await waitFor(() => expect(memoryRouter.push).toHaveBeenCalledWith("/event-leads/evt-1"));
|
||||
});
|
||||
|
||||
it("Back returns to step 1", async () => {
|
||||
const user = await toStep1Match([]);
|
||||
await user.click(await screen.findByRole("button", { name: "Back" }));
|
||||
expect(await screen.findByRole("button", { name: "Next" })).toBeVisible();
|
||||
});
|
||||
|
||||
it("step 2 REQUIRED_FIELD marks each field in errors[]", async () => {
|
||||
mocks.captureEventLead.mockRejectedValue(apiError("REQUIRED_FIELD", { errors: ["name", "salespersonId"] }));
|
||||
const user = await toStep1Match([]);
|
||||
await user.click(await screen.findByRole("button", { name: "Save" }));
|
||||
const msgs = await screen.findAllByText("This field is required.");
|
||||
expect(msgs).toHaveLength(2);
|
||||
for (const label of ["Name", "Salesperson"]) {
|
||||
const el = screen.getByLabelText(label);
|
||||
expect(el).toHaveAttribute("aria-invalid", "true");
|
||||
expect(document.getElementById(el.getAttribute("aria-describedby")!)).toHaveTextContent("This field is required.");
|
||||
}
|
||||
expect(screen.getByLabelText("Company")).not.toHaveAttribute("aria-invalid", "true");
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["TOO_LONG", "name", "Name", "Too long."],
|
||||
["TOO_LONG", "companyName", "Company", "Too long."],
|
||||
["TOO_LONG", "jobTitle", "Job title", "Too long."],
|
||||
["INVALID_MOBILE", "mobile", "Mobile", "Enter a valid mobile number."],
|
||||
["INVALID_EMAIL", "email", "Email", "Enter a valid email address."],
|
||||
["INVALID_DATE", "nextFollowUpDate", "Next follow-up", "Enter a valid date."],
|
||||
["NOT_ON_TEAM", "salespersonId", "Salesperson", "This person is not on the event team."],
|
||||
["INVALID_VALUE", "temperature", "Temperature", "Invalid value."],
|
||||
["INVALID_VALUE", "status", "Status", "Invalid value."],
|
||||
])("step 2 %s on %s shows the mapped message under the field", async (code, field, label, text) => {
|
||||
mocks.captureEventLead.mockRejectedValue(apiError(code, { details: { field } }));
|
||||
const user = await toStep1Match([]);
|
||||
await user.click(await screen.findByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByText(text)).toBeVisible();
|
||||
const el = screen.getByLabelText(label);
|
||||
expect(el).toHaveAttribute("aria-invalid", "true");
|
||||
expect(document.getElementById(el.getAttribute("aria-describedby")!)).toHaveTextContent(text);
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
expect(memoryRouter.push).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("step 2 INACTIVE_INTEREST shows the mapped message under the interests group", async () => {
|
||||
mocks.captureEventLead.mockRejectedValue(apiError("INACTIVE_INTEREST", { details: { field: "interestIds" } }));
|
||||
const user = await toStep1Match([]);
|
||||
await screen.findByLabelText("Product A");
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByText("An interest is no longer active.")).toBeVisible();
|
||||
const group = screen.getByRole("group", { name: "Interests" });
|
||||
expect(group).toHaveAttribute("aria-invalid", "true");
|
||||
expect(document.getElementById(group.getAttribute("aria-describedby")!)).toHaveTextContent("An interest is no longer active.");
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
});
|
||||
|
||||
it("step 2 ALREADY_CAPTURED navigates to the existing event lead", async () => {
|
||||
mocks.captureEventLead.mockRejectedValue(apiError("ALREADY_CAPTURED", { details: { eventLeadUuid: "el-77" } }));
|
||||
const user = await toStep1Match([]);
|
||||
await user.click(await screen.findByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(memoryRouter.push).toHaveBeenCalledWith("/event-leads/evt-1/el-77"));
|
||||
});
|
||||
|
||||
it("step 2 other errors show a form-level message", async () => {
|
||||
mocks.captureEventLead.mockRejectedValue(apiError("SOMETHING_ELSE"));
|
||||
const user = await toStep1Match([]);
|
||||
await user.click(await screen.findByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Could not save the lead. Please try again.");
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
expect(memoryRouter.push).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("picked lead: a field error for a field not shown on this step still gives a form-level message", async () => {
|
||||
mocks.captureEventLead.mockRejectedValue(apiError("REQUIRED_FIELD", { errors: ["name"] }));
|
||||
const user = await toStep1Match([FRESH]);
|
||||
await user.click(await screen.findByRole("button", { name: "This person" }));
|
||||
await user.click(await screen.findByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Could not save the lead. Please try again.");
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
});
|
||||
|
||||
it("unknown field in a field error gives a form-level message", async () => {
|
||||
mocks.captureEventLead.mockRejectedValue(apiError("TOO_LONG", { details: { field: "bogus" } }));
|
||||
const user = await toStep1Match([]);
|
||||
await user.click(await screen.findByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Could not save the lead. Please try again.");
|
||||
});
|
||||
|
||||
it("Back on the candidate list returns to editable mobile and email", async () => {
|
||||
const user = await toStep1Match([FRESH]);
|
||||
await screen.findByText("Bob Fresh");
|
||||
await user.click(screen.getByRole("button", { name: "Back" }));
|
||||
expect(screen.queryByText("Bob Fresh")).toBeNull();
|
||||
expect(screen.getByLabelText("Mobile")).toHaveValue("91234567");
|
||||
expect(screen.getByRole("button", { name: "Next" })).toBeVisible();
|
||||
});
|
||||
|
||||
it("preselects the capturing user as salesperson when on the team", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => true, id: 7 });
|
||||
const user = await toStep1Match([]);
|
||||
await screen.findByRole("option", { name: "Jane Sales" });
|
||||
await waitFor(() => expect(screen.getByLabelText("Salesperson")).toHaveValue("7"));
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.captureEventLead).toHaveBeenCalledWith("evt-1", expect.objectContaining({ salespersonId: 7 })));
|
||||
});
|
||||
|
||||
it("leaves the salesperson empty when the capturing user is not on the team", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => true, id: 99 });
|
||||
await toStep1Match([]);
|
||||
await screen.findByRole("option", { name: "Jane Sales" });
|
||||
expect(screen.getByLabelText("Salesperson")).toHaveValue("");
|
||||
});
|
||||
|
||||
it("keeps the options-load failure visible after matching", async () => {
|
||||
mocks.listEventSalespeople.mockRejectedValue(new Error("boom"));
|
||||
await toStep1Match([]);
|
||||
expect(await screen.findByText("Failed to load salespeople or interests")).toBeVisible();
|
||||
await screen.findByLabelText("Name");
|
||||
expect(screen.getByText("Failed to load salespeople or interests")).toBeVisible();
|
||||
});
|
||||
|
||||
it("step 2 EVENT_DISABLED shows a specific form-level message", async () => {
|
||||
mocks.captureEventLead.mockRejectedValue(apiError("EVENT_DISABLED"));
|
||||
const user = await toStep1Match([]);
|
||||
await user.click(await screen.findByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("This event is closed for new leads.");
|
||||
expect(screen.queryByText(SERVER_MSG)).toBeNull();
|
||||
});
|
||||
|
||||
it("step 2 ALREADY_CAPTURED without an event lead uuid shows Already captured", async () => {
|
||||
mocks.captureEventLead.mockRejectedValue(apiError("ALREADY_CAPTURED"));
|
||||
const user = await toStep1Match([]);
|
||||
await user.click(await screen.findByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Already captured");
|
||||
expect(memoryRouter.push).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,306 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { DatePicker } from "@/app/components/ui/date-picker";
|
||||
import { Input } from "@/app/components/ui/input";
|
||||
import { Label } from "@/app/components/ui/label";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
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 type { InterestOption, LeadCandidate, LeadMatchResult, LeadStatus, LeadTemperature, SalespersonOption } from "@/app/lib/types";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
const TEMPERATURES: [LeadTemperature, string][] = [["HOT", "LeadHot"], ["WARM", "LeadWarm"], ["COLD", "LeadCold"]];
|
||||
const STATUSES: [LeadStatus, string][] = [["OPEN", "LeadOpen"], ["CONTACTED", "LeadContacted"], ["QUALIFIED", "LeadQualified"], ["WON", "LeadWon"], ["LOST", "LeadLost"]];
|
||||
const CODE_MESSAGE: Record<string, string> = {
|
||||
REQUIRED_FIELD: "LeadErrRequired",
|
||||
TOO_LONG: "LeadErrTooLong",
|
||||
INVALID_MOBILE: "LeadErrInvalidMobile",
|
||||
INVALID_EMAIL: "LeadErrInvalidEmail",
|
||||
INVALID_DATE: "LeadErrInvalidDate",
|
||||
NOT_ON_TEAM: "LeadErrNotOnTeam",
|
||||
INACTIVE_INTEREST: "LeadErrInactiveInterest",
|
||||
INVALID_VALUE: "LeadErrInvalidValue",
|
||||
};
|
||||
// Codes that name their field themselves when the server omits details.field.
|
||||
const IMPLIED_FIELD: Record<string, string> = { INVALID_MOBILE: "mobile", INVALID_EMAIL: "email" };
|
||||
const SELECT_CLASS = "min-h-11 w-full rounded-md border border-input bg-transparent px-3 text-base shadow-sm outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-[invalid=true]:border-destructive dark:bg-input/30";
|
||||
const TALL = "min-h-11";
|
||||
|
||||
type Step = "match" | "details";
|
||||
const STEP1_FIELDS = ["mobile", "email"];
|
||||
const PICKED_FIELDS = ["salespersonId", "temperature", "status", "interestIds", "nextFollowUpDate", "notes"];
|
||||
const NEW_FIELDS = [...PICKED_FIELDS, "name", "mobile", "email", "companyName", "jobTitle"];
|
||||
// Codes that are never tied to a field.
|
||||
const FORM_CODE_MESSAGE: Record<string, string> = { EVENT_DISABLED: "LeadEventDisabled", ALREADY_CAPTURED: "LeadAlreadyCaptured" };
|
||||
|
||||
type Errors = { fields: Record<string, string>; form: string | null; code?: string; details: Record<string, unknown> };
|
||||
|
||||
function readError(err: unknown, t: (k: string) => string, fallbackKey: string, rendered: string[], requiredKey?: string): Errors {
|
||||
const data = err instanceof ApiError ? (err.data as { code?: string; errors?: string[]; details?: Record<string, unknown> } | undefined) : undefined;
|
||||
const code = data?.code;
|
||||
const details = data?.details ?? {};
|
||||
const fields: Record<string, string> = {};
|
||||
let hidden = false; // a named field this step does not render must not make the failure silent
|
||||
const mark = (f: string, key: string) => {
|
||||
if (rendered.includes(f)) fields[f] = t(key);
|
||||
else hidden = true;
|
||||
};
|
||||
if (code === "REQUIRED_FIELD") {
|
||||
for (const f of data?.errors ?? []) mark(f, requiredKey ?? CODE_MESSAGE.REQUIRED_FIELD);
|
||||
} else if (code && CODE_MESSAGE[code]) {
|
||||
const field = typeof details.field === "string" ? details.field : IMPLIED_FIELD[code];
|
||||
if (field) mark(field, CODE_MESSAGE[code]);
|
||||
}
|
||||
const key = (code && FORM_CODE_MESSAGE[code]) || fallbackKey;
|
||||
const form = hidden || !Object.keys(fields).length ? t(key) : null;
|
||||
return { fields, form, code, details };
|
||||
}
|
||||
|
||||
function NewEventLead() {
|
||||
const t = useT();
|
||||
const router = useRouter();
|
||||
const { id: myId } = useAdminAuth();
|
||||
const { eventUuid } = useParams<{ eventUuid: string }>();
|
||||
const [step, setStep] = useState<Step>("match");
|
||||
const [candidates, setCandidates] = useState<LeadCandidate[] | null>(null);
|
||||
const [match, setMatch] = useState<LeadMatchResult | null>(null);
|
||||
const [existing, setExisting] = useState<LeadCandidate | null>(null);
|
||||
const [mobile, setMobile] = useState("");
|
||||
const [email, setEmail] = useState("");
|
||||
const [name, setName] = useState("");
|
||||
const [companyName, setCompanyName] = useState("");
|
||||
const [jobTitle, setJobTitle] = useState("");
|
||||
const [salespersonId, setSalespersonId] = useState("");
|
||||
const [temperature, setTemperature] = useState("");
|
||||
const [status, setStatus] = useState<string>("OPEN");
|
||||
const [interestIds, setInterestIds] = useState<number[]>([]);
|
||||
const [nextFollowUpDate, setNextFollowUpDate] = useState("");
|
||||
const [notes, setNotes] = useState("");
|
||||
const [salespeople, setSalespeople] = useState<SalespersonOption[]>([]);
|
||||
const [interests, setInterests] = useState<InterestOption[]>([]);
|
||||
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [optionsError, setOptionsError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
Promise.all([listEventSalespeople(eventUuid), listEventLeadInterests()])
|
||||
.then(([s, i]) => {
|
||||
if (cancelled) return;
|
||||
setSalespeople(s);
|
||||
setInterests(i.filter((o) => o.active));
|
||||
if (myId != null && s.some((o) => o.id === myId)) setSalespersonId(String(myId));
|
||||
})
|
||||
.catch(() => { if (!cancelled) setOptionsError(t("LeadOptionsLoadFailed")); });
|
||||
return () => { cancelled = true; };
|
||||
}, [eventUuid, t, myId]);
|
||||
|
||||
const fieldProps = (f: string) => ({
|
||||
id: `lead-${f}`,
|
||||
"aria-invalid": fieldErrors[f] ? (true as const) : undefined,
|
||||
"aria-describedby": fieldErrors[f] ? `lead-${f}-error` : undefined,
|
||||
});
|
||||
const fieldError = (f: string) =>
|
||||
fieldErrors[f] ? <p id={`lead-${f}-error`} role="alert" className="text-sm text-destructive">{fieldErrors[f]}</p> : null;
|
||||
|
||||
function fail(e: Errors) {
|
||||
setFieldErrors(e.fields);
|
||||
setFormError(e.form);
|
||||
}
|
||||
|
||||
async function onMatch(event: FormEvent) {
|
||||
event.preventDefault();
|
||||
setFieldErrors({});
|
||||
setFormError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
const result = await matchLead(eventUuid, { mobile: mobile.trim() || null, email: email.trim() || null });
|
||||
setMatch(result);
|
||||
if (result.candidates.length === 0) startDetails(result, null);
|
||||
else setCandidates(result.candidates);
|
||||
} catch (err) {
|
||||
fail(readError(err, t, "LeadMatchFailed", STEP1_FIELDS, "LeadErrRequiredContact"));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
function startDetails(result: LeadMatchResult, lead: LeadCandidate | null) {
|
||||
setExisting(lead);
|
||||
setMobile(result.mobile ?? "");
|
||||
setEmail(result.email ?? "");
|
||||
setFieldErrors({});
|
||||
setFormError(null);
|
||||
setStep("details");
|
||||
}
|
||||
|
||||
// A picked lead gets an entered contact value only if it is already its own, or fills its blank field and
|
||||
// belongs to no other candidate: copying another person's mobile or email onto it would merge two people.
|
||||
function ownValue(field: "mobile" | "email"): string | null {
|
||||
const value = match?.[field] ?? null;
|
||||
if (!value || !existing) return null;
|
||||
if (existing[field] === value) return value;
|
||||
if (existing[field]) return null;
|
||||
return candidates?.some((c) => c.leadUuid !== existing.leadUuid && c[field] === value) ? null : value;
|
||||
}
|
||||
|
||||
async function onSave(event: FormEvent) {
|
||||
event.preventDefault();
|
||||
setFieldErrors({});
|
||||
setFormError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
await captureEventLead(eventUuid, {
|
||||
...(existing
|
||||
? { leadUuid: existing.leadUuid, name: existing.name, mobile: ownValue("mobile"), email: ownValue("email") }
|
||||
: { name: name.trim(), mobile: mobile.trim() || null, email: email.trim() || null, companyName: companyName.trim() || null, jobTitle: jobTitle.trim() || null }),
|
||||
salespersonId: salespersonId ? Number(salespersonId) : null,
|
||||
temperature: (temperature || null) as LeadTemperature | null,
|
||||
status: status as LeadStatus,
|
||||
interestIds,
|
||||
nextFollowUpDate: nextFollowUpDate || null,
|
||||
notes: notes.trim() || null,
|
||||
});
|
||||
router.push(`/event-leads/${eventUuid}`);
|
||||
} catch (err) {
|
||||
const e = readError(err, t, "LeadSaveFailed", existing ? PICKED_FIELDS : NEW_FIELDS);
|
||||
if (e.code === "ALREADY_CAPTURED" && typeof e.details.eventLeadUuid === "string") {
|
||||
router.push(`/event-leads/${eventUuid}/${e.details.eventLeadUuid}`);
|
||||
return;
|
||||
}
|
||||
fail(e);
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const toggleInterest = (id: number) =>
|
||||
setInterestIds((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));
|
||||
|
||||
const field = (f: string, label: string, control: React.ReactNode) => (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor={`lead-${f}`}>{label}</Label>
|
||||
{control}
|
||||
{fieldError(f)}
|
||||
</div>
|
||||
);
|
||||
const textInput = (f: string, label: string, value: string, set: (v: string) => void, extra: React.ComponentProps<typeof Input> = {}) =>
|
||||
field(f, label, <Input {...fieldProps(f)} className={TALL} value={value} onChange={(e) => set(e.target.value)} disabled={busy} {...extra} />);
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-xl">
|
||||
<PageHeader title={t("LeadAddLead")} />
|
||||
{optionsError && <ErrorState message={optionsError} />}
|
||||
{formError && <ErrorState message={formError} />}
|
||||
|
||||
{step === "match" && !candidates && (
|
||||
<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>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{step === "match" && candidates && match && (
|
||||
<div className="space-y-4">
|
||||
<ul className="space-y-3">
|
||||
{candidates.map((c) => (
|
||||
<li key={c.leadUuid} className="space-y-2 rounded-lg border p-4">
|
||||
<p className="font-medium">{c.name}</p>
|
||||
{c.mobile && <p className="text-sm">{c.mobile}</p>}
|
||||
{c.email && <p className="text-sm">{c.email}</p>}
|
||||
{c.companyName && <p className="text-sm text-muted-foreground">{c.companyName}</p>}
|
||||
{c.eventLeadUuid ? (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<span className="text-sm font-medium">{t("LeadAlreadyCaptured")}</span>
|
||||
<Button asChild variant="outline" className={TALL}>
|
||||
<Link href={`/event-leads/${eventUuid}/${c.eventLeadUuid}`}>{t("LeadOpen")}</Link>
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<Button type="button" className={`${TALL} w-full sm:w-auto`} onClick={() => startDetails(match, c)}>{t("LeadThisPerson")}</Button>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="flex flex-col gap-3 sm:flex-row">
|
||||
<Button type="button" variant="outline" className={TALL} onClick={() => startDetails(match, null)}>{t("LeadDifferentPerson")}</Button>
|
||||
<Button type="button" variant="ghost" className={TALL} onClick={() => setCandidates(null)}>{t("Back")}</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === "details" && (
|
||||
<form onSubmit={onSave} className="space-y-4" noValidate>
|
||||
{existing ? (
|
||||
<div className="space-y-1 rounded-lg border p-4">
|
||||
<p className="font-medium">{existing.name}</p>
|
||||
{existing.mobile && <p className="text-sm">{existing.mobile}</p>}
|
||||
{existing.email && <p className="text-sm">{existing.email}</p>}
|
||||
{existing.companyName && <p className="text-sm text-muted-foreground">{existing.companyName}</p>}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{textInput("name", t("LeadName"), name, setName)}
|
||||
{textInput("mobile", t("LeadMobile"), mobile, setMobile, { type: "tel", inputMode: "tel", autoComplete: "tel" })}
|
||||
{textInput("email", t("Email"), email, setEmail, { type: "email", autoComplete: "email" })}
|
||||
{textInput("companyName", t("LeadCompany"), companyName, setCompanyName)}
|
||||
{textInput("jobTitle", t("LeadJobTitle"), jobTitle, setJobTitle)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{field("salespersonId", t("LeadSalesperson"),
|
||||
<select {...fieldProps("salespersonId")} className={SELECT_CLASS} value={salespersonId} onChange={(e) => setSalespersonId(e.target.value)} disabled={busy}>
|
||||
<option value="">{t("LeadNone")}</option>
|
||||
{salespeople.map((s) => <option key={s.id} value={String(s.id)}>{s.name}</option>)}
|
||||
</select>)}
|
||||
{field("temperature", t("LeadTemperature"),
|
||||
<select {...fieldProps("temperature")} className={SELECT_CLASS} value={temperature} onChange={(e) => setTemperature(e.target.value)} disabled={busy}>
|
||||
<option value="">{t("LeadNone")}</option>
|
||||
{TEMPERATURES.map(([v, k]) => <option key={v} value={v}>{t(k)}</option>)}
|
||||
</select>)}
|
||||
{field("status", t("LeadStatus"),
|
||||
<select {...fieldProps("status")} className={SELECT_CLASS} value={status} onChange={(e) => setStatus(e.target.value)} disabled={busy}>
|
||||
{STATUSES.map(([v, k]) => <option key={v} value={v}>{t(k)}</option>)}
|
||||
</select>)}
|
||||
|
||||
<fieldset {...fieldProps("interestIds")} className="space-y-1">
|
||||
<legend className="mb-1.5 text-sm font-medium">{t("LeadInterests")}</legend>
|
||||
{interests.map((i) => (
|
||||
<label key={i.id} className="flex min-h-11 items-center gap-3 text-sm">
|
||||
<input type="checkbox" className="size-5" checked={interestIds.includes(i.id)} onChange={() => toggleInterest(i.id)} disabled={busy} />
|
||||
{i.name}
|
||||
</label>
|
||||
))}
|
||||
{fieldError("interestIds")}
|
||||
</fieldset>
|
||||
|
||||
{field("nextFollowUpDate", t("LeadNextFollowUp"),
|
||||
<DatePicker {...fieldProps("nextFollowUpDate")} className="h-11" value={nextFollowUpDate} onChange={setNextFollowUpDate} disabled={busy} />)}
|
||||
{field("notes", t("LeadNotes"),
|
||||
<textarea {...fieldProps("notes")} className={`${SELECT_CLASS} py-2`} rows={3} value={notes} onChange={(e) => setNotes(e.target.value)} disabled={busy} />)}
|
||||
|
||||
<div className="flex flex-col-reverse gap-3 sm:flex-row">
|
||||
<Button type="button" variant="outline" className={TALL} onClick={() => { setFieldErrors({}); setFormError(null); setStep("match"); }} disabled={busy}>{t("Back")}</Button>
|
||||
<Button type="submit" className={TALL} disabled={busy}>{t("Save")}</Button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function NewEventLeadPage() {
|
||||
return (
|
||||
<RequireModule pathname="/event-leads">
|
||||
<NewEventLead />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
// --- test mocks ---
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listEventLeads: vi.fn(),
|
||||
listEventSalespeople: vi.fn(),
|
||||
listEventLeadInterests: vi.fn(),
|
||||
listEventLeadEvents: vi.fn(),
|
||||
useAdminAuth: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminEventLeads", async (importActual) => ({
|
||||
...(await importActual<typeof import("@/app/lib/services/adminEventLeads")>()),
|
||||
listEventLeads: mocks.listEventLeads,
|
||||
listEventSalespeople: mocks.listEventSalespeople,
|
||||
listEventLeadInterests: mocks.listEventLeadInterests,
|
||||
listEventLeadEvents: mocks.listEventLeadEvents,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("next/navigation", async () => ({
|
||||
...(await import("@/test/memoryRouter")).navigationMock,
|
||||
useParams: () => ({ eventUuid: "evt-1" }),
|
||||
}));
|
||||
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import EventLeadsDetailPage from "./page";
|
||||
|
||||
beforeEach(() => {
|
||||
memoryRouter.reset("/event-leads/evt-1");
|
||||
mocks.listEventLeads.mockReset().mockResolvedValue({ items: [], total: 0 });
|
||||
mocks.listEventSalespeople.mockReset().mockResolvedValue([{ id: 1, name: "Jane Sales", username: "jane" }]);
|
||||
mocks.listEventLeadInterests.mockReset().mockResolvedValue([{ id: 1, name: "Product A", active: true }]);
|
||||
mocks.listEventLeadEvents.mockReset().mockResolvedValue([{ uuid: "evt-1", name: "Test Event", location: "Hall A", startDate: "2025-06-01", endDate: "2025-06-02" }]);
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({
|
||||
loading: false,
|
||||
hasModule: () => true,
|
||||
});
|
||||
});
|
||||
|
||||
describe("EventLeadsDetailPage (listing)", { timeout: 20000 }, () => {
|
||||
|
||||
it("renders NotAuthorized when the EventLeads module is absent", () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
|
||||
render(<EventLeadsDetailPage />);
|
||||
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("sends eventUuid and each filter to listEventLeads", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<EventLeadsDetailPage />);
|
||||
|
||||
await waitFor(() => expect(mocks.listEventLeads).toHaveBeenCalledWith("evt-1", expect.objectContaining({ page: 1, pageSize: expect.any(Number) })));
|
||||
|
||||
// Filter by temperature
|
||||
await user.click(screen.getByRole("combobox", { name: /temperature filter/i }));
|
||||
await user.click(await screen.findByRole("option", { name: "Hot" }));
|
||||
await waitFor(() =>
|
||||
expect(mocks.listEventLeads).toHaveBeenLastCalledWith("evt-1", expect.objectContaining({ temperature: "HOT", page: 1 })),
|
||||
);
|
||||
|
||||
// Filter by status
|
||||
await user.click(screen.getByRole("combobox", { name: /status filter/i }));
|
||||
await user.click(await screen.findByRole("option", { name: "Won" }));
|
||||
await waitFor(() =>
|
||||
expect(mocks.listEventLeads).toHaveBeenLastCalledWith("evt-1", expect.objectContaining({ status: "WON", page: 1 })),
|
||||
);
|
||||
|
||||
// Filter by lead type
|
||||
await user.click(screen.getByRole("combobox", { name: /lead type filter/i }));
|
||||
await user.click(await screen.findByRole("option", { name: "New" }));
|
||||
await waitFor(() =>
|
||||
expect(mocks.listEventLeads).toHaveBeenLastCalledWith("evt-1", expect.objectContaining({ leadType: "NEW", page: 1 })),
|
||||
);
|
||||
|
||||
// Filter by salesperson
|
||||
await user.click(screen.getByRole("combobox", { name: /salesperson filter/i }));
|
||||
await user.click(await screen.findByRole("option", { name: "Jane Sales" }));
|
||||
await waitFor(() =>
|
||||
expect(mocks.listEventLeads).toHaveBeenLastCalledWith("evt-1", expect.objectContaining({ salespersonId: "1", page: 1 })),
|
||||
);
|
||||
|
||||
// Filter by interest
|
||||
await user.click(screen.getByRole("combobox", { name: /interest filter/i }));
|
||||
await user.click(await screen.findByRole("option", { name: "Product A" }));
|
||||
await waitFor(() =>
|
||||
expect(mocks.listEventLeads).toHaveBeenLastCalledWith("evt-1", expect.objectContaining({ interestId: "1", page: 1 })),
|
||||
);
|
||||
});
|
||||
|
||||
it("renders lead cards on mobile view with data-testid", async () => {
|
||||
mocks.listEventLeads.mockResolvedValue({
|
||||
items: [{
|
||||
eventLeadUuid: "el-1",
|
||||
eventUuid: "evt-1",
|
||||
leadUuid: "lead-1",
|
||||
name: "John Doe",
|
||||
mobile: "+60123456789",
|
||||
email: "john@example.com",
|
||||
companyName: "Acme",
|
||||
jobTitle: "Manager",
|
||||
leadType: "NEW",
|
||||
salesperson: { id: 1, name: "Jane Sales" },
|
||||
temperature: "HOT",
|
||||
status: "OPEN",
|
||||
interests: [{ id: 1, name: "Product A", active: true }],
|
||||
nextFollowUpDate: "2025-06-15",
|
||||
notes: null,
|
||||
capturedAt: "2025-06-01",
|
||||
}],
|
||||
total: 1,
|
||||
});
|
||||
render(<EventLeadsDetailPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("lead-card")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("links each lead row/card to its detail page", async () => {
|
||||
mocks.listEventLeads.mockResolvedValue({
|
||||
items: [{
|
||||
eventLeadUuid: "el-1",
|
||||
eventUuid: "evt-1",
|
||||
leadUuid: "lead-1",
|
||||
name: "John Doe",
|
||||
mobile: "+60123456789",
|
||||
email: "john@example.com",
|
||||
companyName: "Acme",
|
||||
jobTitle: "Manager",
|
||||
leadType: "NEW",
|
||||
salesperson: { id: 1, name: "Jane Sales" },
|
||||
temperature: "HOT",
|
||||
status: "OPEN",
|
||||
interests: [{ id: 1, name: "Product A", active: true }],
|
||||
nextFollowUpDate: "2025-06-15",
|
||||
notes: null,
|
||||
capturedAt: "2025-06-01",
|
||||
}],
|
||||
total: 1,
|
||||
});
|
||||
render(<EventLeadsDetailPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
// The lead card is a link to the detail page
|
||||
const card = screen.getByTestId("lead-card");
|
||||
expect(card).toHaveAttribute("href", "/event-leads/evt-1/el-1");
|
||||
});
|
||||
const card = within(screen.getByTestId("lead-card"));
|
||||
for (const text of ["John Doe", "+60123456789", "New", "Hot", "Open"]) expect(card.getByText(text)).toBeInTheDocument();
|
||||
expect(card.getByText(/Next follow-up.*15\/06\/2025/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("offers each filter's All choice once", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<EventLeadsDetailPage />);
|
||||
await user.click(screen.getByRole("combobox", { name: /salesperson filter/i }));
|
||||
await screen.findByRole("option", { name: "Jane Sales" });
|
||||
expect(screen.getAllByRole("option").map((o) => o.textContent)).toEqual(["All", "Jane Sales"]);
|
||||
});
|
||||
|
||||
it("falls back to the module title when the event is not in the list", async () => {
|
||||
mocks.listEventLeadEvents.mockResolvedValue([]);
|
||||
render(<EventLeadsDetailPage />);
|
||||
await waitFor(() => expect(screen.getByRole("heading", { level: 1, name: "Event leads" })).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it("shows the Add lead link to /event-leads/{eventUuid}/new", async () => {
|
||||
render(<EventLeadsDetailPage />);
|
||||
await waitFor(() => expect(screen.getByRole("link", { name: /add lead/i })).toHaveAttribute("href", "/event-leads/evt-1/new"));
|
||||
});
|
||||
|
||||
it("renders the header with the event name", async () => {
|
||||
render(<EventLeadsDetailPage />);
|
||||
await waitFor(() => expect(screen.getByRole("heading", { level: 1, name: "Test Event" })).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it("shows the empty state when there are no leads", async () => {
|
||||
render(<EventLeadsDetailPage />);
|
||||
await waitFor(() => expect(screen.queryByText("John Doe")).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it("shows the error state and lets the user retry on a load failure", async () => {
|
||||
mocks.listEventLeads.mockRejectedValueOnce(new Error("network down"));
|
||||
mocks.listEventLeads.mockResolvedValueOnce({ items: [], total: 0 });
|
||||
render(<EventLeadsDetailPage />);
|
||||
await waitFor(() => expect(screen.getByText(/network down/i)).toBeInTheDocument());
|
||||
await userEvent.click(screen.getByRole("button", { name: /retry/i }));
|
||||
await waitFor(() => expect(mocks.listEventLeads).toHaveBeenCalledTimes(2));
|
||||
});
|
||||
|
||||
it("hides the table below md and shows one pager per layout", async () => {
|
||||
mocks.listEventLeads.mockResolvedValue({ items: [], total: 45 });
|
||||
const { container } = render(<EventLeadsDetailPage />);
|
||||
await waitFor(() => expect(mocks.listEventLeads).toHaveBeenCalled());
|
||||
const table = screen.getByRole("table").closest("div.hidden");
|
||||
expect(table).not.toBeNull();
|
||||
expect(table!.className).toContain("md:block");
|
||||
// DataTable brings its own pager; the phone pager (44px targets) must sit inside the md:hidden card list.
|
||||
expect(container.querySelectorAll('[data-slot="table-pager"]')).toHaveLength(1);
|
||||
const next = screen.getAllByRole("button", { name: /next/i }).find((b) => !b.closest('[data-slot="table-pager"]'));
|
||||
expect(next?.closest(".md\\:hidden")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("labels temperature and status options through i18n keys", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<EventLeadsDetailPage />);
|
||||
await user.click(screen.getByRole("combobox", { name: /temperature filter/i }));
|
||||
expect(await screen.findByRole("option", { name: "Hot" })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,317 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useParams } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { 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, FilterSelect } from "@/app/components/ui/filter-panel";
|
||||
import { DataTable } from "@/app/components/ui/data-table";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { useListFilters } from "@/app/lib/hooks/useListFilters";
|
||||
import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
|
||||
import { listEventLeads, listEventSalespeople, listEventLeadInterests, listEventLeadEvents } from "@/app/lib/services/adminEventLeads";
|
||||
import type { EventLeadRow, InterestOption, SalespersonOption } from "@/app/lib/types";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { formatDmy } from "@/app/lib/date-input";
|
||||
|
||||
const DEFAULTS = { salespersonId: "", temperature: "", status: "", interestId: "", leadType: "" };
|
||||
const TEMPERATURE_OPTIONS = [{ value: "HOT", label: "LeadHot" }, { value: "WARM", label: "LeadWarm" }, { value: "COLD", label: "LeadCold" }];
|
||||
const STATUS_OPTIONS = [{ value: "OPEN", label: "LeadOpen" }, { value: "CONTACTED", label: "LeadContacted" }, { value: "QUALIFIED", label: "LeadQualified" }, { value: "WON", label: "LeadWon" }, { value: "LOST", label: "LeadLost" }];
|
||||
const LEAD_TYPE_OPTIONS = [{ value: "NEW", label: "LeadNew" }, { value: "EXISTING", label: "LeadExisting" }];
|
||||
const TEMPERATURE_BADGE = { HOT: "negative", WARM: "warning", COLD: "neutral" } as const;
|
||||
const STATUS_BADGE = { OPEN: "neutral", CONTACTED: "neutral", QUALIFIED: "contrast", WON: "positive", LOST: "negative" } as const;
|
||||
|
||||
function EventLeadsDetailPageContent() {
|
||||
const t = useT();
|
||||
const { eventUuid } = useParams<{ eventUuid: string }>();
|
||||
const { tableRef, pageSize } = useFitPageSize();
|
||||
const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS);
|
||||
const [data, setData] = useState<{ items: EventLeadRow[]; total: number }>({ items: [], total: 0 });
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const [salespeople, setSalespeople] = useState<SalespersonOption[]>([]);
|
||||
const [interests, setInterests] = useState<InterestOption[]>([]);
|
||||
// undefined while loading; null when the event is unknown or the lookup failed.
|
||||
const [eventName, setEventName] = useState<string | null | undefined>(undefined);
|
||||
|
||||
// Load event name from the events list
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
listEventLeadEvents()
|
||||
.then((events) => {
|
||||
if (!cancelled) {
|
||||
const found = events.find((e) => e.uuid === eventUuid);
|
||||
setEventName(found ? found.name : null);
|
||||
}
|
||||
})
|
||||
.catch(() => { if (!cancelled) setEventName(null); });
|
||||
return () => { cancelled = true; };
|
||||
}, [eventUuid]);
|
||||
|
||||
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
|
||||
|
||||
// Load lookup options
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
Promise.allSettled([
|
||||
listEventSalespeople(eventUuid),
|
||||
listEventLeadInterests(),
|
||||
]).then(([salesRes, interestRes]) => {
|
||||
if (!cancelled) {
|
||||
if (salesRes.status === "fulfilled") setSalespeople(salesRes.value);
|
||||
if (interestRes.status === "fulfilled") setInterests(interestRes.value);
|
||||
}
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [eventUuid]);
|
||||
|
||||
// Fetch leads
|
||||
useEffect(() => {
|
||||
if (pageSize == null) return;
|
||||
let cancelled = false;
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error before the eventUuid/page/reloadKey-triggered fetch below.
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
listEventLeads(eventUuid, { page, pageSize, ...filters })
|
||||
.then((result) => {
|
||||
if (!cancelled) setData(result);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (!cancelled) setError(err instanceof Error ? err.message : "LeadListLoadFailed");
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [eventUuid, filters, page, pageSize, reloadKey]);
|
||||
|
||||
const salespersonOptions = useMemo(
|
||||
() => salespeople.map((o) => ({ value: String(o.id), label: o.name })),
|
||||
[salespeople],
|
||||
);
|
||||
|
||||
const interestOptions = useMemo(
|
||||
() => interests.map((o) => ({ value: String(o.id), label: o.name })),
|
||||
[interests],
|
||||
);
|
||||
|
||||
const temperatureOptions = useMemo(
|
||||
() => TEMPERATURE_OPTIONS.map((o) => ({ value: o.value, label: t(o.label) })),
|
||||
[t],
|
||||
);
|
||||
|
||||
const statusOptions = useMemo(
|
||||
() => STATUS_OPTIONS.map((o) => ({ value: o.value, label: t(o.label) })),
|
||||
[t],
|
||||
);
|
||||
|
||||
const leadTypeOptions = useMemo(
|
||||
() => LEAD_TYPE_OPTIONS.map((o) => ({ value: o.value, label: t(o.label) })),
|
||||
[t],
|
||||
);
|
||||
|
||||
const columns = useMemo<ColumnDef<EventLeadRow, unknown>[]>(
|
||||
() => [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: t("LeadName"),
|
||||
cell: ({ row }) => (
|
||||
<Link
|
||||
href={`/event-leads/${row.original.eventUuid}/${row.original.eventLeadUuid}`}
|
||||
className="font-medium text-primary underline-offset-4 hover:underline focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none min-h-11 flex items-center"
|
||||
>
|
||||
{row.original.name}
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "mobile",
|
||||
header: t("LeadMobile"),
|
||||
cell: ({ row }) => <span>{row.original.mobile || "—"}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "email",
|
||||
header: t("Email"),
|
||||
cell: ({ row }) => <span>{row.original.email || "—"}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "leadType",
|
||||
header: t("LeadType"),
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => (
|
||||
<Badge variant={row.original.leadType === "NEW" ? "default" : "secondary"}>
|
||||
{t(row.original.leadType === "NEW" ? "LeadNew" : "LeadExisting")}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "salesperson",
|
||||
header: t("LeadSalesperson"),
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => <span>{row.original.salesperson?.name || "—"}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "temperature",
|
||||
header: t("LeadTemperature"),
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => {
|
||||
const temp = row.original.temperature;
|
||||
if (!temp) return <span>—</span>;
|
||||
return <Badge variant={TEMPERATURE_BADGE[temp]}>{t(TEMPERATURE_OPTIONS.find((o) => o.value === temp)!.label)}</Badge>;
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: t("Status"),
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => {
|
||||
const s = row.original.status;
|
||||
return <Badge variant={STATUS_BADGE[s]}>{t(STATUS_OPTIONS.find((o) => o.value === s)!.label)}</Badge>;
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "interests",
|
||||
header: t("LeadInterests"),
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => <span>{row.original.interests.map(i => i.name).join(", ") || "—"}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "nextFollowUpDate",
|
||||
header: t("LeadNextFollowUp"),
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => <span>{row.original.nextFollowUpDate ? formatDmy(row.original.nextFollowUpDate) : "—"}</span>,
|
||||
},
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={eventName === undefined ? "…" : (eventName ?? t("BO_EVENT_LEADS"))}
|
||||
actions={
|
||||
<Button asChild>
|
||||
<Link href={`/event-leads/${eventUuid}/new`}>
|
||||
<Plus aria-hidden="true" className="size-4" />
|
||||
{t("LeadAddLead")}
|
||||
</Link>
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
|
||||
|
||||
<FilterPanel activeCount={activeCount} onClear={clear}>
|
||||
<FilterField label={t("LeadSalespersonFilter")}>
|
||||
<FilterSelect className="w-full" aria-label={t("LeadSalespersonFilter")} allLabel={t("All")} options={salespersonOptions} value={filters.salespersonId} onChange={salespersonId => set({ salespersonId })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("LeadTemperatureFilter")}>
|
||||
<FilterSelect className="w-full" aria-label={t("LeadTemperatureFilter")} allLabel={t("All")} options={temperatureOptions} value={filters.temperature} onChange={temperature => set({ temperature })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("LeadStatusFilter")}>
|
||||
<FilterSelect className="w-full" aria-label={t("LeadStatusFilter")} allLabel={t("All")} options={statusOptions} value={filters.status} onChange={status => set({ status })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("LeadInterestFilter")}>
|
||||
<FilterSelect className="w-full" aria-label={t("LeadInterestFilter")} allLabel={t("All")} options={interestOptions} value={filters.interestId} onChange={interestId => set({ interestId })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("LeadLeadTypeFilter")}>
|
||||
<FilterSelect className="w-full" aria-label={t("LeadLeadTypeFilter")} allLabel={t("All")} options={leadTypeOptions} value={filters.leadType} onChange={leadType => set({ leadType })} />
|
||||
</FilterField>
|
||||
</FilterPanel>
|
||||
|
||||
{/* Desktop table (md+) */}
|
||||
<div className="hidden md:block">
|
||||
<DataTable
|
||||
label={t("BO_EVENT_LEADS")}
|
||||
columns={columns}
|
||||
data={data.items}
|
||||
total={data.total}
|
||||
page={page}
|
||||
pageSize={pageSize ?? MIN_PAGE_SIZE}
|
||||
tableRef={tableRef}
|
||||
onPageChange={setPage}
|
||||
isLoading={loading}
|
||||
rowKey={(e) => String(e.eventLeadUuid)}
|
||||
empty={<EmptyState title={activeCount > 0 ? t("LeadNoMatch") : t("LeadNoLeads")} />}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Mobile cards (below md) */}
|
||||
<div className="md:hidden space-y-3" aria-busy={loading}>
|
||||
{data.items.map((lead) => (
|
||||
<Link
|
||||
key={lead.eventLeadUuid}
|
||||
href={`/event-leads/${lead.eventUuid}/${lead.eventLeadUuid}`}
|
||||
data-testid="lead-card"
|
||||
className={`flex flex-col gap-1 rounded-lg border p-3 transition-colors hover:bg-accent min-h-11${loading ? " opacity-60" : ""}`}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="font-medium">{lead.name}</span>
|
||||
<Badge variant={lead.leadType === "NEW" ? "default" : "secondary"}>{t(lead.leadType === "NEW" ? "LeadNew" : "LeadExisting")}</Badge>
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{lead.mobile || "—"}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
{lead.temperature && <Badge variant={TEMPERATURE_BADGE[lead.temperature]} className="shrink-0">{t(TEMPERATURE_OPTIONS.find((o) => o.value === lead.temperature)!.label)}</Badge>}
|
||||
<Badge variant={STATUS_BADGE[lead.status]} className="shrink-0">{t(STATUS_OPTIONS.find((o) => o.value === lead.status)!.label)}</Badge>
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{t("LeadNextFollowUp")}: {lead.nextFollowUpDate ? formatDmy(lead.nextFollowUpDate) : "—"}
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
{data.items.length === 0 && !loading && (
|
||||
<EmptyState title={activeCount > 0 ? t("LeadNoMatch") : t("LeadNoLeads")} />
|
||||
)}
|
||||
{/* Phone pager: 44px targets; DataTable has its own above md */}
|
||||
{data.total > (pageSize ?? MIN_PAGE_SIZE) && (
|
||||
<div className="flex items-center justify-between mt-4">
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{t("PagerRange", {
|
||||
first: data.total === 0 ? 0 : (page - 1) * (pageSize ?? MIN_PAGE_SIZE) + 1,
|
||||
last: Math.min(page * (pageSize ?? MIN_PAGE_SIZE), data.total),
|
||||
total: data.total,
|
||||
})}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={page <= 1}
|
||||
onClick={() => setPage(page - 1)}
|
||||
className="min-h-11"
|
||||
>
|
||||
{t("PagerPrevious")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={page * (pageSize ?? MIN_PAGE_SIZE) >= data.total}
|
||||
onClick={() => setPage(page + 1)}
|
||||
className="min-h-11"
|
||||
>
|
||||
{t("PagerNext")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function EventLeadsDetailPage() {
|
||||
return (
|
||||
<RequireModule pathname="/event-leads">
|
||||
<EventLeadsDetailPageContent />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { act, render, screen, waitFor } from "@testing-library/react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listEventLeadEvents: vi.fn(),
|
||||
useAdminAuth: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminEventLeads", async (importActual) => ({
|
||||
...(await importActual<typeof import("@/app/lib/services/adminEventLeads")>()),
|
||||
listEventLeadEvents: mocks.listEventLeadEvents,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
|
||||
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
||||
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import EventLeadsPage from "./page";
|
||||
|
||||
beforeEach(() => {
|
||||
memoryRouter.reset("/event-leads");
|
||||
mocks.listEventLeadEvents.mockReset();
|
||||
mocks.useAdminAuth.mockReset();
|
||||
mocks.useAdminAuth.mockReturnValue({
|
||||
loading: false,
|
||||
hasModule: () => true,
|
||||
});
|
||||
});
|
||||
|
||||
describe("EventLeadsPage (picker)", () => {
|
||||
it("renders NotAuthorized when the EventLeads module is absent from aclMenu", () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
|
||||
render(<EventLeadsPage />);
|
||||
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("lists events as tappable card links", async () => {
|
||||
mocks.listEventLeadEvents.mockResolvedValue([
|
||||
{ uuid: "evt-1", name: "Event Alpha", location: "Hall A", startDate: "2025-06-01", endDate: "2025-06-02" },
|
||||
{ uuid: "evt-2", name: "Event Beta", location: "Hall B", startDate: "2025-07-01", endDate: "2025-07-02" },
|
||||
]);
|
||||
render(<EventLeadsPage />);
|
||||
|
||||
expect(await screen.findByText("Event Alpha")).toBeInTheDocument();
|
||||
expect(screen.getByText("Event Beta")).toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: /Event Alpha/ })).toHaveAttribute("href", "/event-leads/evt-1");
|
||||
expect(screen.getByRole("link", { name: /Event Beta/ })).toHaveAttribute("href", "/event-leads/evt-2");
|
||||
});
|
||||
|
||||
it("shows location and dates formatted with formatDmy", async () => {
|
||||
mocks.listEventLeadEvents.mockResolvedValue([
|
||||
{ uuid: "evt-1", name: "Event Alpha", location: "Hall A", startDate: "2025-06-01", endDate: "2025-06-02" },
|
||||
]);
|
||||
render(<EventLeadsPage />);
|
||||
|
||||
expect(await screen.findByText("Hall A")).toBeInTheDocument();
|
||||
expect(screen.getByText(/01\/06\/2025/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/02\/06\/2025/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("puts events running today first", async () => {
|
||||
// Use a date that's "today" relative to the test run
|
||||
const today = new Date();
|
||||
const iso = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;
|
||||
mocks.listEventLeadEvents.mockResolvedValue([
|
||||
{ uuid: "evt-far", name: "Far Event", location: "Hall A", startDate: "2099-01-01", endDate: "2099-01-02" },
|
||||
{ uuid: "evt-today", name: "Today Event", location: "Hall B", startDate: iso, endDate: iso },
|
||||
]);
|
||||
render(<EventLeadsPage />);
|
||||
|
||||
await screen.findByText("Today Event");
|
||||
const links = Array.from(screen.getAllByRole("link").filter((l) => l.getAttribute("href")?.startsWith("/event-leads/")));
|
||||
expect(links[0]).toHaveAttribute("href", "/event-leads/evt-today");
|
||||
expect(links[1]).toHaveAttribute("href", "/event-leads/evt-far");
|
||||
});
|
||||
|
||||
it("shows an error state on load failure", async () => {
|
||||
mocks.listEventLeadEvents.mockRejectedValueOnce(new Error("network down"));
|
||||
render(<EventLeadsPage />);
|
||||
await waitFor(() => expect(screen.getByText(/network down/i)).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it("counts an event that started earlier and ends later as running today", async () => {
|
||||
const d = (offset: number) => {
|
||||
const x = new Date();
|
||||
x.setDate(x.getDate() + offset);
|
||||
return `${x.getFullYear()}-${String(x.getMonth() + 1).padStart(2, "0")}-${String(x.getDate()).padStart(2, "0")}`;
|
||||
};
|
||||
mocks.listEventLeadEvents.mockResolvedValue([
|
||||
{ uuid: "evt-later", name: "Later", location: null, startDate: d(5), endDate: d(6) },
|
||||
{ uuid: "evt-running", name: "Running", location: null, startDate: d(-1), endDate: d(1) },
|
||||
]);
|
||||
render(<EventLeadsPage />);
|
||||
await waitFor(() => expect(screen.getByText("Running")).toBeInTheDocument());
|
||||
const links = screen.getAllByRole("link").filter((l) => l.getAttribute("href")?.startsWith("/event-leads/"));
|
||||
expect(links[0]).toHaveAttribute("href", "/event-leads/evt-running");
|
||||
});
|
||||
|
||||
it("retries the load after a failure", async () => {
|
||||
mocks.listEventLeadEvents.mockRejectedValueOnce(new Error("network down"))
|
||||
.mockResolvedValueOnce([{ uuid: "evt-1", name: "Back", location: null, startDate: null, endDate: null }]);
|
||||
render(<EventLeadsPage />);
|
||||
const retry = await screen.findByRole("button", { name: /retry/i });
|
||||
await act(async () => retry.click());
|
||||
expect(await screen.findByText("Back")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Calendar, MapPin } from "lucide-react";
|
||||
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
||||
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 { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { formatDmy } from "@/app/lib/date-input";
|
||||
|
||||
const isoToday = () => {
|
||||
const d = new Date();
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
||||
};
|
||||
|
||||
function EventLeadsPageContent() {
|
||||
const t = useT();
|
||||
const [events, setEvents] = useState<EventLeadEvent[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
// 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()
|
||||
.then((data) => {
|
||||
if (!cancelled) setEvents(data);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (!cancelled) setError(err instanceof Error ? err.message : "LeadLoadFailed");
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [reloadKey]);
|
||||
|
||||
const today = isoToday();
|
||||
const sorted = events
|
||||
.slice()
|
||||
.sort((a, b) => {
|
||||
// ISO dates compare as strings; an event runs today when start <= today <= end.
|
||||
const running = (e: EventLeadEvent) => (e.startDate ?? "9") <= today && today <= (e.endDate ?? e.startDate ?? "");
|
||||
return Number(running(b)) - Number(running(a));
|
||||
});
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("BO_EVENT_LEADS")} />
|
||||
<ErrorState message={t(error)} onRetry={() => setReloadKey((k) => k + 1)} className="mb-4" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("BO_EVENT_LEADS")} />
|
||||
<div className="space-y-3">
|
||||
{Array.from({ length: 3 }).map((_, i) => (
|
||||
<div key={i} className="h-20 animate-pulse rounded-lg bg-muted" />
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("BO_EVENT_LEADS")} />
|
||||
{sorted.length === 0 ? (
|
||||
<EmptyState title={t("LeadNoEvents")} />
|
||||
) : (
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{sorted.map((evt) => (
|
||||
<Link
|
||||
key={evt.uuid}
|
||||
href={`/event-leads/${evt.uuid}`}
|
||||
className="flex flex-col gap-2 rounded-lg border p-4 transition-colors hover:bg-accent min-h-[8.5rem]"
|
||||
>
|
||||
<h2 className="font-semibold text-lg">{evt.name}</h2>
|
||||
{evt.location && (
|
||||
<div className="flex items-center gap-1 text-sm text-muted-foreground">
|
||||
<MapPin className="size-3.5 shrink-0" aria-hidden="true" />
|
||||
<span>{evt.location}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-1 text-sm text-muted-foreground">
|
||||
<Calendar className="size-3.5 shrink-0" aria-hidden="true" />
|
||||
<span>{evt.startDate ? formatDmy(evt.startDate) : ""} – {evt.endDate ? formatDmy(evt.endDate) : ""}</span>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function EventLeadsPage() {
|
||||
return (
|
||||
<RequireModule pathname="/event-leads">
|
||||
<EventLeadsPageContent />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
import { fireEvent, 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(() => ({
|
||||
listAdminInterests: vi.fn(),
|
||||
apiGet: vi.fn(),
|
||||
apiPost: vi.fn(),
|
||||
apiPut: vi.fn(),
|
||||
useAdminAuth: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/clientApi", async (importOriginal) => ({
|
||||
ApiError: (await importOriginal<typeof import("@/app/lib/clientApi")>()).ApiError,
|
||||
apiGet: mocks.apiGet,
|
||||
apiPost: mocks.apiPost,
|
||||
apiPut: mocks.apiPut,
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminInterests", async (importOriginal) => {
|
||||
const mod = await importOriginal<typeof import("@/app/lib/services/adminInterests")>();
|
||||
return { ...mod, listAdminInterests: mocks.listAdminInterests };
|
||||
});
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
|
||||
import InterestsPage from "./page";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.listAdminInterests.mockReset();
|
||||
mocks.apiGet.mockReset();
|
||||
mocks.apiPost.mockReset();
|
||||
mocks.apiPut.mockReset();
|
||||
mocks.useAdminAuth.mockReset();
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => true });
|
||||
});
|
||||
|
||||
describe("InterestsPage", () => {
|
||||
it("renders an empty table with no interests", async () => {
|
||||
mocks.listAdminInterests.mockResolvedValue([]);
|
||||
render(<InterestsPage />);
|
||||
await waitFor(() => expect(screen.getByRole("table")).toBeInTheDocument());
|
||||
expect(screen.getByText(/no interests/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders rows with name, order, and status badge", async () => {
|
||||
mocks.listAdminInterests.mockResolvedValue([
|
||||
{ id: 1, name: "Workshop", active: true, sortOrder: 1 },
|
||||
{ id: 2, name: "Webinar", active: false, sortOrder: 2 },
|
||||
]);
|
||||
render(<InterestsPage />);
|
||||
await waitFor(() => expect(screen.getByText("Workshop")).toBeInTheDocument());
|
||||
const row1 = screen.getByText("Workshop").closest("tr")!;
|
||||
expect(within(row1).getByText("1")).toBeInTheDocument();
|
||||
expect(within(row1).getByText("Active")).toBeInTheDocument();
|
||||
|
||||
const row2 = screen.getByText("Webinar").closest("tr")!;
|
||||
expect(within(row2).getByText("2")).toBeInTheDocument();
|
||||
expect(within(row2).getByText("Inactive")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("posts trimmed name on create", async () => {
|
||||
mocks.listAdminInterests.mockResolvedValue([]);
|
||||
mocks.apiPost.mockResolvedValue({ id: 1, name: "New Interest", active: true, sortOrder: 0 });
|
||||
render(<InterestsPage />);
|
||||
await waitFor(() => expect(screen.getByText(/Add interest/i)).toBeInTheDocument());
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: /Add interest/i }));
|
||||
expect(screen.getByRole("dialog")).toBeInTheDocument();
|
||||
await userEvent.type(screen.getByLabelText(/Name/i), " New Interest ");
|
||||
await userEvent.click(screen.getByRole("button", { name: /Save/i }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mocks.apiPost).toHaveBeenCalledWith("/api/interests", {
|
||||
name: "New Interest",
|
||||
active: true,
|
||||
sortOrder: 0,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("blocks submit when name is empty", async () => {
|
||||
mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Existing", active: true, sortOrder: 1 }]);
|
||||
render(<InterestsPage />);
|
||||
await waitFor(() => expect(screen.getByText("Existing")).toBeInTheDocument());
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: /Add interest/i }));
|
||||
await userEvent.click(screen.getByRole("button", { name: /Save/i }));
|
||||
|
||||
expect(screen.getByText(/Name is required/i)).toBeInTheDocument();
|
||||
expect(mocks.apiPost).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows an unexpected save error at form level", async () => {
|
||||
mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Existing", active: true, sortOrder: 1 }]);
|
||||
mocks.apiPost.mockRejectedValue(new Error("An interest with this name already exists."));
|
||||
render(<InterestsPage />);
|
||||
await waitFor(() => expect(screen.getByText("Existing")).toBeInTheDocument());
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: /Add interest/i }));
|
||||
await userEvent.type(screen.getByLabelText(/Name/i), "Existing");
|
||||
await userEvent.click(screen.getByRole("button", { name: /Save/i }));
|
||||
|
||||
expect(await screen.findByText(/An interest with this name already exists/i)).toBeInTheDocument();
|
||||
expect(screen.getByRole("dialog")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("deactivates interest via PUT { active: false }", async () => {
|
||||
mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Workshop", active: true, sortOrder: 1 }]);
|
||||
mocks.apiPut.mockResolvedValue({ id: 1, name: "Workshop", active: false, sortOrder: 1 });
|
||||
render(<InterestsPage />);
|
||||
await waitFor(() => expect(screen.getByText("Workshop")).toBeInTheDocument());
|
||||
|
||||
const row = screen.getByText("Workshop").closest("tr")!;
|
||||
await userEvent.click(within(row).getByRole("button", { name: /Deactivate/i }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mocks.apiPut).toHaveBeenCalledWith("/api/interests/1", expect.objectContaining({ active: false })),
|
||||
);
|
||||
});
|
||||
|
||||
it("activates interest via PUT { active: true }", async () => {
|
||||
mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Workshop", active: false, sortOrder: 1 }]);
|
||||
mocks.apiPut.mockResolvedValue({ id: 1, name: "Workshop", active: true, sortOrder: 1 });
|
||||
render(<InterestsPage />);
|
||||
await waitFor(() => expect(screen.getByText("Workshop")).toBeInTheDocument());
|
||||
|
||||
const row = screen.getByText("Workshop").closest("tr")!;
|
||||
await userEvent.click(within(row).getByRole("button", { name: /Activate/i }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mocks.apiPut).toHaveBeenCalledWith("/api/interests/1", expect.objectContaining({ active: true })),
|
||||
);
|
||||
});
|
||||
|
||||
it("edit dialog: name field, order number input, PUTs on save", async () => {
|
||||
mocks.listAdminInterests.mockResolvedValue([
|
||||
{ id: 1, name: "Workshop", active: true, sortOrder: 5 },
|
||||
]);
|
||||
mocks.apiPut.mockResolvedValue({ id: 1, name: "Workshop Edited", active: true, sortOrder: 10 });
|
||||
render(<InterestsPage />);
|
||||
await waitFor(() => expect(screen.getByText("Workshop")).toBeInTheDocument());
|
||||
|
||||
const row = screen.getByText("Workshop").closest("tr")!;
|
||||
await userEvent.click(within(row).getByRole("button", { name: /Edit/i }));
|
||||
|
||||
expect(screen.getByRole("dialog")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/Name/i)).toHaveValue("Workshop");
|
||||
expect(screen.getByLabelText(/Order/i)).toHaveValue(5);
|
||||
|
||||
await userEvent.clear(screen.getByLabelText(/Name/i));
|
||||
await userEvent.type(screen.getByLabelText(/Name/i), "Workshop Edited");
|
||||
await userEvent.clear(screen.getByLabelText(/Order/i));
|
||||
await userEvent.type(screen.getByLabelText(/Order/i), "10");
|
||||
await userEvent.click(screen.getByRole("button", { name: /Save/i }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mocks.apiPut).toHaveBeenCalledWith("/api/interests/1", {
|
||||
id: 1,
|
||||
name: "Workshop Edited",
|
||||
sortOrder: 10,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("shows NotAuthorized when the module is missing", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
|
||||
render(<InterestsPage />);
|
||||
await waitFor(() => expect(screen.getByRole("alert")).toBeInTheDocument());
|
||||
expect(screen.getByText(/not authorised/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows IntDuplicateName under Name when API returns DUPLICATE_NAME error", async () => {
|
||||
mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Existing", active: true, sortOrder: 1 }]);
|
||||
const dupErr = new ApiError("Conflict", 409, { code: "DUPLICATE_NAME", details: { field: "name" } });
|
||||
mocks.apiPost.mockRejectedValue(dupErr);
|
||||
render(<InterestsPage />);
|
||||
await waitFor(() => expect(screen.getByText("Existing")).toBeInTheDocument());
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: /Add interest/i }));
|
||||
await userEvent.type(screen.getByLabelText(/Name/i), "Existing");
|
||||
await userEvent.click(screen.getByRole("button", { name: /Save/i }));
|
||||
|
||||
// The field error for DUPLICATE_NAME should appear under the Name input
|
||||
const nameInput = screen.getByLabelText(/Name/i);
|
||||
const nameField = nameInput.closest(".space-y-1\\.5")!;
|
||||
await waitFor(() => {
|
||||
expect(nameField.querySelector('[role="alert"]')?.textContent).toContain("An interest with this name already exists.");
|
||||
});
|
||||
});
|
||||
|
||||
it("shows IntNameTooLong under Name when API returns TOO_LONG error", async () => {
|
||||
mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Existing", active: true, sortOrder: 1 }]);
|
||||
const tooLongErr = new ApiError("Name is too long.", 422, { code: "TOO_LONG", details: { field: "name" } });
|
||||
mocks.apiPost.mockRejectedValue(tooLongErr);
|
||||
render(<InterestsPage />);
|
||||
await waitFor(() => expect(screen.getByText("Existing")).toBeInTheDocument());
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: /Add interest/i }));
|
||||
await userEvent.type(screen.getByLabelText(/Name/i), "A name that is way too long to be valid for an interest");
|
||||
await userEvent.click(screen.getByRole("button", { name: /Save/i }));
|
||||
|
||||
const nameInput = screen.getByLabelText(/Name/i);
|
||||
const nameField = nameInput.closest(".space-y-1\\.5")!;
|
||||
await waitFor(() => {
|
||||
expect(nameField.querySelector('[role="alert"]')?.textContent).toContain("Name must be 100 characters or fewer.");
|
||||
});
|
||||
});
|
||||
|
||||
it("submits successfully with a 100-character name", async () => {
|
||||
// maxLength={100} on the input prevents typing 101+ chars.
|
||||
// The handleSubmit guard (trimmed.length > 100) is defense-in-depth.
|
||||
// We verify the boundary works by submitting exactly 100 characters.
|
||||
mocks.listAdminInterests.mockResolvedValue([]);
|
||||
render(<InterestsPage />);
|
||||
await waitFor(() => expect(screen.getByText(/Add interest/i)).toBeInTheDocument());
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: /Add interest/i }));
|
||||
await userEvent.type(screen.getByLabelText(/Name/i), "A".repeat(100));
|
||||
await userEvent.click(screen.getByRole("button", { name: /Save/i }));
|
||||
await waitFor(() =>
|
||||
expect(mocks.apiPost).toHaveBeenCalledWith("/api/interests", expect.objectContaining({ name: "A".repeat(100) })),
|
||||
);
|
||||
});
|
||||
|
||||
it("shows activate/deactivate failure error on the page", async () => {
|
||||
mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Workshop", active: true, sortOrder: 1 }]);
|
||||
mocks.apiPut.mockRejectedValue(new ApiError("Network error", 0));
|
||||
render(<InterestsPage />);
|
||||
await waitFor(() => expect(screen.getByText("Workshop")).toBeInTheDocument());
|
||||
|
||||
const row = screen.getByText("Workshop").closest("tr")!;
|
||||
await userEvent.click(within(row).getByRole("button", { name: /Deactivate/i }));
|
||||
|
||||
expect(await screen.findByText("Failed to deactivate interest.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows activate failure on the page", async () => {
|
||||
mocks.listAdminInterests.mockResolvedValue([{ id: 1, name: "Workshop", active: false, sortOrder: 1 }]);
|
||||
mocks.apiPut.mockRejectedValue(new ApiError("Network error", 0));
|
||||
render(<InterestsPage />);
|
||||
await waitFor(() => expect(screen.getByText("Workshop")).toBeInTheDocument());
|
||||
|
||||
const row = screen.getByText("Workshop").closest("tr")!;
|
||||
await userEvent.click(within(row).getByRole("button", { name: /^Activate$/i }));
|
||||
|
||||
expect(await screen.findByText("Failed to activate interest.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("blocks a name over 100 characters before submit", async () => {
|
||||
mocks.listAdminInterests.mockResolvedValue([]);
|
||||
render(<InterestsPage />);
|
||||
await waitFor(() => expect(screen.getByText(/Add interest/i)).toBeInTheDocument());
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: /Add interest/i }));
|
||||
fireEvent.change(screen.getByLabelText(/Name/i), { target: { value: "A".repeat(101) } });
|
||||
await userEvent.click(screen.getByRole("button", { name: /Save/i }));
|
||||
|
||||
expect(await screen.findByText("Name must be 100 characters or fewer.")).toBeInTheDocument();
|
||||
expect(mocks.apiPost).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,284 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState, type FormEvent } from "react";
|
||||
import { Plus } from "lucide-react";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Input } from "@/app/components/ui/input";
|
||||
import { Label } from "@/app/components/ui/label";
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog";
|
||||
import { DataTable } from "@/app/components/ui/data-table";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
||||
import { Badge } from "@/app/components/ui/badge";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { listAdminInterests, saveAdminInterest } from "@/app/lib/services/adminInterests";
|
||||
import type { AdminInterestEntity } from "@/app/lib/types";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
interface FormState {
|
||||
id?: number;
|
||||
name: string;
|
||||
sortOrder?: number;
|
||||
}
|
||||
|
||||
const EMPTY_FORM: FormState = { name: "", sortOrder: 0 };
|
||||
|
||||
function InterestFormDialog({
|
||||
initial,
|
||||
onClose,
|
||||
onSaved,
|
||||
}: {
|
||||
initial: FormState;
|
||||
onClose: () => void;
|
||||
onSaved: () => void;
|
||||
}) {
|
||||
const t = useT();
|
||||
const [form, setForm] = useState<FormState>(initial);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
|
||||
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
const trimmed = form.name.trim();
|
||||
|
||||
const errors: Record<string, string> = {};
|
||||
if (!trimmed) errors.name = t("IntNameRequired");
|
||||
else if (trimmed.length > 100) errors.name = t("IntNameTooLong");
|
||||
setFieldErrors(errors);
|
||||
if (Object.keys(errors).length > 0) return;
|
||||
|
||||
setFormError(null);
|
||||
setSaving(true);
|
||||
try {
|
||||
if (form.id) {
|
||||
// Edit: only send name and sortOrder
|
||||
await saveAdminInterest({ id: form.id, name: trimmed, sortOrder: form.sortOrder });
|
||||
} else {
|
||||
// Create: send active=true and sortOrder
|
||||
await saveAdminInterest({ name: trimmed, active: true, sortOrder: form.sortOrder ?? 0 });
|
||||
}
|
||||
onSaved();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
if (err instanceof Error && "status" in err && "data" in err) {
|
||||
const apiErr = err as Error & { status?: number; data?: unknown };
|
||||
const code = (apiErr.data as { code?: string } | undefined)?.code;
|
||||
if (code === "DUPLICATE_NAME") {
|
||||
setFieldErrors({ name: t("IntDuplicateName") });
|
||||
} else if (code === "TOO_LONG") {
|
||||
setFieldErrors({ name: t("IntNameTooLong") });
|
||||
} else if (code === "REQUIRED_FIELD") {
|
||||
setFieldErrors({ name: t("IntNameRequired") });
|
||||
} else {
|
||||
setFormError(err.message || "IntSaveFailed");
|
||||
}
|
||||
} else {
|
||||
setFormError(err instanceof Error ? err.message : "IntSaveFailed");
|
||||
}
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{form.id ? t("IntEditInterest") : t("IntAddInterest")}</DialogTitle>
|
||||
</DialogHeader>
|
||||
{formError && (
|
||||
<div className="text-sm text-destructive" role="alert">
|
||||
{t(formError)}
|
||||
</div>
|
||||
)}
|
||||
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="interest-name">{t("IntInterestName")}</Label>
|
||||
<Input
|
||||
id="interest-name"
|
||||
required
|
||||
maxLength={100}
|
||||
value={form.name}
|
||||
onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
|
||||
disabled={saving}
|
||||
aria-invalid={!!fieldErrors.name}
|
||||
aria-describedby={fieldErrors.name ? "interest-name-error" : undefined}
|
||||
/>
|
||||
{fieldErrors.name && (
|
||||
<p id="interest-name-error" role="alert" className="text-sm text-destructive">
|
||||
{fieldErrors.name}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="interest-order">{t("IntInterestOrder")}</Label>
|
||||
<Input
|
||||
id="interest-order"
|
||||
type="number"
|
||||
min={0}
|
||||
value={form.sortOrder ?? 0}
|
||||
onChange={(e) => setForm((f) => ({ ...f, sortOrder: parseInt(e.target.value, 10) || 0 }))}
|
||||
disabled={saving}
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="submit" disabled={saving}>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function InterestsPageContent() {
|
||||
const t = useT();
|
||||
const [interests, setInterests] = useState<AdminInterestEntity[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const [dialog, setDialog] = useState<FormState | null>(null);
|
||||
|
||||
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets ahead of the reloadKey-triggered fetch below.
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
listAdminInterests()
|
||||
.then((result) => {
|
||||
if (!cancelled) setInterests(result);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (!cancelled) setError(err instanceof Error ? err.message : "IntLoadFailed");
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [reloadKey]);
|
||||
|
||||
const columns = useMemo<ColumnDef<AdminInterestEntity, unknown>[]>(
|
||||
() => [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: t("IntColInterest"),
|
||||
cell: ({ row }) => <div>{row.original.name}</div>,
|
||||
},
|
||||
{
|
||||
accessorKey: "sortOrder",
|
||||
header: t("IntColOrder"),
|
||||
cell: ({ row }) => <div>{row.original.sortOrder ?? 0}</div>,
|
||||
},
|
||||
{
|
||||
accessorKey: "active",
|
||||
header: t("IntColStatus"),
|
||||
cell: ({ row }) => (
|
||||
<Badge variant={row.original.active ? "positive" : "neutral"}>
|
||||
{row.original.active ? t("IntActive") : t("IntInactive")}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: t("CatActions"),
|
||||
cell: ({ row }) => (
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
setDialog({
|
||||
id: row.original.id,
|
||||
name: row.original.name ?? "",
|
||||
sortOrder: row.original.sortOrder,
|
||||
})
|
||||
}
|
||||
>
|
||||
{t("Edit")}
|
||||
</Button>
|
||||
{row.original.active ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await saveAdminInterest({ id: row.original.id, active: false });
|
||||
refetch();
|
||||
} catch {
|
||||
setError("IntDeactivateFailed");
|
||||
}
|
||||
}}
|
||||
>
|
||||
{t("IntDeactivate")}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await saveAdminInterest({ id: row.original.id, active: true });
|
||||
refetch();
|
||||
} catch {
|
||||
setError("IntActivateFailed");
|
||||
}
|
||||
}}
|
||||
>
|
||||
{t("IntActivate")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
],
|
||||
[t, refetch],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={t("BO_INTERESTS")}
|
||||
actions={
|
||||
<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" />}
|
||||
|
||||
<DataTable
|
||||
label={t("BO_INTERESTS")}
|
||||
columns={columns}
|
||||
data={interests}
|
||||
total={interests.length}
|
||||
page={1}
|
||||
pageSize={interests.length || 1}
|
||||
onPageChange={() => {}}
|
||||
isLoading={loading}
|
||||
rowKey={(r) => String(r.id ?? r.name)}
|
||||
empty={<EmptyState title={t("IntNoInterests")} />}
|
||||
/>
|
||||
|
||||
{dialog && (
|
||||
<InterestFormDialog initial={dialog} onClose={() => setDialog(null)} onSaved={refetch} />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function InterestsPage() {
|
||||
return (
|
||||
<RequireModule pathname="/interests">
|
||||
<InterestsPageContent />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -204,4 +204,80 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
EvtTeamNotSaved: "The event was saved but its team was not. Check the team and save again.",
|
||||
EvtEventNameFilter: "Event name",
|
||||
EvtStatusFilter: "Status filter",
|
||||
// Interest (product/service) messages
|
||||
BO_INTERESTS: "Interests",
|
||||
IntAddInterest: "Add interest",
|
||||
IntEditInterest: "Edit interest",
|
||||
IntInterestName: "Name",
|
||||
IntInterestOrder: "Order",
|
||||
IntColInterest: "Name",
|
||||
IntColOrder: "Order",
|
||||
IntColStatus: "Status",
|
||||
IntNoInterests: "No interests found",
|
||||
IntLoadFailed: "Failed to load interests",
|
||||
IntNameRequired: "Name is required.",
|
||||
IntNameTooLong: "Name must be 100 characters or fewer.",
|
||||
IntSaveFailed: "Failed to save interest.",
|
||||
IntDuplicateName: "An interest with this name already exists.",
|
||||
IntActive: "Active",
|
||||
IntInactive: "Inactive",
|
||||
IntActivate: "Activate",
|
||||
IntDeactivate: "Deactivate",
|
||||
IntActivateFailed: "Failed to activate interest.",
|
||||
IntDeactivateFailed: "Failed to deactivate interest.",
|
||||
// Event leads messages
|
||||
BO_EVENT_LEADS: "Event leads",
|
||||
LeadName: "Name",
|
||||
LeadMobile: "Mobile",
|
||||
LeadType: "Lead type",
|
||||
LeadSalesperson: "Salesperson",
|
||||
LeadTemperature: "Temperature",
|
||||
LeadInterests: "Interests",
|
||||
LeadNextFollowUp: "Next follow-up",
|
||||
LeadAddLead: "Add lead",
|
||||
LeadNoEvents: "No events found",
|
||||
LeadNoLeads: "No leads found",
|
||||
LeadNoMatch: "No leads match your filters",
|
||||
LeadLoadFailed: "Failed to load events",
|
||||
LeadListLoadFailed: "Failed to load leads",
|
||||
LeadSalespersonFilter: "Salesperson filter",
|
||||
LeadTemperatureFilter: "Temperature filter",
|
||||
LeadStatusFilter: "Status filter",
|
||||
LeadInterestFilter: "Interest filter",
|
||||
LeadLeadTypeFilter: "Lead type filter",
|
||||
LeadHot: "Hot",
|
||||
LeadWarm: "Warm",
|
||||
LeadCold: "Cold",
|
||||
LeadOpen: "Open",
|
||||
LeadContacted: "Contacted",
|
||||
LeadQualified: "Qualified",
|
||||
LeadWon: "Won",
|
||||
LeadLost: "Lost",
|
||||
LeadNew: "New",
|
||||
LeadExisting: "Existing",
|
||||
LeadCompany: "Company",
|
||||
LeadJobTitle: "Job title",
|
||||
LeadStatus: "Status",
|
||||
LeadNotes: "Notes",
|
||||
LeadNext: "Next",
|
||||
LeadNone: "None",
|
||||
LeadAlreadyCaptured: "Already captured",
|
||||
LeadThisPerson: "This person",
|
||||
LeadDifferentPerson: "Different person",
|
||||
LeadOptionsLoadFailed: "Failed to load salespeople or interests",
|
||||
LeadEventDisabled: "This event is closed for new leads.",
|
||||
LeadSaveFailed: "Could not save the lead. Please try again.",
|
||||
LeadMatchFailed: "Could not look up this contact. Please try again.",
|
||||
LeadErrRequiredContact: "Mobile or email is required.",
|
||||
LeadErrRequired: "This field is required.",
|
||||
LeadErrTooLong: "Too long.",
|
||||
LeadErrInvalidMobile: "Enter a valid mobile number.",
|
||||
LeadErrInvalidEmail: "Enter a valid email address.",
|
||||
LeadErrInvalidDate: "Enter a valid date.",
|
||||
LeadErrNotOnTeam: "This person is not on the event team.",
|
||||
LeadErrInactiveInterest: "An interest is no longer active.",
|
||||
LeadErrInvalidValue: "Invalid value.",
|
||||
LeadCaptured: "Captured",
|
||||
LeadNotFound: "Lead not found",
|
||||
LeadGetFailed: "Failed to load the lead",
|
||||
};
|
||||
@@ -3,6 +3,8 @@ import { ROUTE_MODULES, requiredModuleFor, requiredModulesFor } from "./routeMod
|
||||
|
||||
describe("routeModules", () => {
|
||||
it("gates /users and /roles by the seeded module name", () => {
|
||||
expect(requiredModuleFor("/interests")).toBe("BO_INTERESTS");
|
||||
expect(requiredModuleFor("/event-leads")).toBe("BO_EVENT_LEADS");
|
||||
expect(requiredModuleFor("/users")).toBe("BO_USERS");
|
||||
expect(requiredModuleFor("/roles")).toBe("BO_ROLES");
|
||||
expect(requiredModuleFor("/events")).toBe("BO_EVENTS");
|
||||
@@ -12,6 +14,6 @@ describe("routeModules", () => {
|
||||
it("leaves other routes ungated", () => {
|
||||
expect(requiredModuleFor("/")).toBeUndefined();
|
||||
expect(requiredModulesFor("/members")).toBeUndefined();
|
||||
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/events", "/roles", "/users"]);
|
||||
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/event-leads", "/events", "/interests", "/roles", "/users"]);
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,8 @@ export const ROUTE_MODULES: Record<string, string> = {
|
||||
"/users": "BO_USERS",
|
||||
"/roles": "BO_ROLES",
|
||||
"/events": "BO_EVENTS",
|
||||
"/interests": "BO_INTERESTS",
|
||||
"/event-leads": "BO_EVENT_LEADS",
|
||||
};
|
||||
|
||||
export function requiredModuleFor(pathname: string): string | undefined {
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
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 {
|
||||
captureEventLead,
|
||||
getEventLead,
|
||||
listEventLeadEvents,
|
||||
listEventLeadInterests,
|
||||
listEventLeads,
|
||||
listEventSalespeople,
|
||||
matchLead,
|
||||
updateEventLead,
|
||||
} from "./adminEventLeads";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.apiGet.mockReset();
|
||||
mocks.apiPost.mockReset();
|
||||
mocks.apiPut.mockReset();
|
||||
});
|
||||
|
||||
describe("adminEventLeads", () => {
|
||||
it("loads events, interest options and the event's salespeople", async () => {
|
||||
mocks.apiGet.mockResolvedValue([]);
|
||||
await listEventLeadEvents();
|
||||
await listEventLeadInterests();
|
||||
await listEventSalespeople("9");
|
||||
expect(mocks.apiGet.mock.calls.map((c) => c[0])).toEqual([
|
||||
"/api/event-leads/events",
|
||||
"/api/event-leads/interest-options",
|
||||
"/api/event-leads/9/salesperson-options",
|
||||
]);
|
||||
});
|
||||
|
||||
it("lists with only the set filters and a 0-based page", async () => {
|
||||
mocks.apiGet.mockResolvedValue({ content: [{ eventLeadUuid: "1" }], totalElements: 41 });
|
||||
const out = await listEventLeads("9", { page: 3, pageSize: 20, status: "OPEN", temperature: "", interestId: "4" });
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/event-leads/9/leads?status=OPEN&interestId=4&page=2&size=20");
|
||||
expect(out).toEqual({ items: [{ eventLeadUuid: "1" }], total: 41 });
|
||||
});
|
||||
|
||||
it("treats a malformed page as empty", async () => {
|
||||
mocks.apiGet.mockResolvedValue(null);
|
||||
expect(await listEventLeads("9", { page: 1, pageSize: 20 })).toEqual({ items: [], total: 0 });
|
||||
});
|
||||
|
||||
it("matches, captures, gets and updates under the event", async () => {
|
||||
await matchLead("9", { mobile: "0123", email: null });
|
||||
expect(mocks.apiPost).toHaveBeenCalledWith("/api/event-leads/9/match", { mobile: "0123", email: null });
|
||||
await captureEventLead("9", { name: "A", mobile: "0123" });
|
||||
expect(mocks.apiPost).toHaveBeenCalledWith("/api/event-leads/9", { name: "A", mobile: "0123" });
|
||||
await getEventLead("9", "7");
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/event-leads/9/leads/7");
|
||||
await updateEventLead("9", "7", { status: "WON" });
|
||||
expect(mocks.apiPut).toHaveBeenCalledWith("/api/event-leads/9/leads/7", { status: "WON" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { apiGet, apiPost, apiPut } from "@/app/lib/clientApi";
|
||||
import type {
|
||||
EventLeadCapturePayload,
|
||||
EventLeadEvent,
|
||||
EventLeadRow,
|
||||
EventLeadUpdatePayload,
|
||||
InterestOption,
|
||||
LeadMatchResult,
|
||||
SalespersonOption,
|
||||
} from "@/app/lib/types";
|
||||
|
||||
const BASE = "/api/event-leads";
|
||||
const FILTERS = ["salespersonId", "temperature", "status", "interestId", "leadType"] as const;
|
||||
|
||||
export type EventLeadFilters = Partial<Record<(typeof FILTERS)[number], string>>;
|
||||
|
||||
export interface EventLeadListParams extends EventLeadFilters {
|
||||
/** 1-based. */
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
export const listEventLeadEvents = () => apiGet<EventLeadEvent[]>(`${BASE}/events`);
|
||||
export const listEventLeadInterests = () => apiGet<InterestOption[]>(`${BASE}/interest-options`);
|
||||
export const listEventSalespeople = (eventUuid: string) =>
|
||||
apiGet<SalespersonOption[]>(`${BASE}/${eventUuid}/salesperson-options`);
|
||||
|
||||
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]);
|
||||
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}`);
|
||||
const items = Array.isArray(raw?.content) ? raw.content : [];
|
||||
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 captureEventLead = (eventUuid: string, payload: EventLeadCapturePayload) =>
|
||||
apiPost<EventLeadRow>(`${BASE}/${eventUuid}`, payload);
|
||||
export const getEventLead = (eventUuid: string, eventLeadUuid: string) =>
|
||||
apiGet<EventLeadRow>(`${BASE}/${eventUuid}/leads/${eventLeadUuid}`);
|
||||
export const updateEventLead = (eventUuid: string, eventLeadUuid: string, payload: EventLeadUpdatePayload) =>
|
||||
apiPut<EventLeadRow>(`${BASE}/${eventUuid}/leads/${eventLeadUuid}`, payload);
|
||||
@@ -0,0 +1,35 @@
|
||||
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 { listAdminInterests, saveAdminInterest } from "./adminInterests";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.apiGet.mockReset();
|
||||
mocks.apiPost.mockReset();
|
||||
mocks.apiPut.mockReset();
|
||||
});
|
||||
|
||||
describe("listAdminInterests", () => {
|
||||
it("GETs /api/interests", async () => {
|
||||
mocks.apiGet.mockResolvedValue([{ id: 1, name: "Workshop", active: true, sortOrder: 1 }]);
|
||||
const result = await listAdminInterests();
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/interests");
|
||||
expect(result).toEqual([{ id: 1, name: "Workshop", active: true, sortOrder: 1 }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("saveAdminInterest", () => {
|
||||
it("POSTs when id is absent", async () => {
|
||||
mocks.apiPost.mockResolvedValue({ id: 1, name: "New Interest" });
|
||||
await saveAdminInterest({ name: "New Interest", active: true, sortOrder: 5 });
|
||||
expect(mocks.apiPost).toHaveBeenCalledWith("/api/interests", { name: "New Interest", active: true, sortOrder: 5 });
|
||||
});
|
||||
|
||||
it("PUTs to /api/interests/{id} when id is present", async () => {
|
||||
mocks.apiPut.mockResolvedValue({ id: 200, name: "Edited Interest", active: false, sortOrder: 10 });
|
||||
await saveAdminInterest({ id: 200, name: "Edited Interest", active: false, sortOrder: 10 });
|
||||
expect(mocks.apiPut).toHaveBeenCalledWith("/api/interests/200", { id: 200, name: "Edited Interest", active: false, sortOrder: 10 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import { apiGet, apiPost, apiPut } from "@/app/lib/clientApi";
|
||||
import type { AdminInterestEntity } from "@/app/lib/types";
|
||||
|
||||
export async function listAdminInterests(): Promise<AdminInterestEntity[]> {
|
||||
return apiGet<AdminInterestEntity[]>("/api/interests");
|
||||
}
|
||||
|
||||
export async function saveAdminInterest(payload: AdminInterestEntity): Promise<AdminInterestEntity> {
|
||||
return payload.id
|
||||
? apiPut<AdminInterestEntity>(`/api/interests/${payload.id}`, payload)
|
||||
: apiPost<AdminInterestEntity>("/api/interests", payload);
|
||||
}
|
||||
@@ -150,3 +150,86 @@ export interface SalespersonOption {
|
||||
name: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
/** An interest (product/service) row used to tag leads.
|
||||
* Stored in services-counter (`interest`), served by mobile-api `/api/admin/interests`, sorted by sortOrder. */
|
||||
export interface AdminInterestEntity {
|
||||
id?: number;
|
||||
name?: string;
|
||||
active?: boolean;
|
||||
sortOrder?: number;
|
||||
}
|
||||
|
||||
/** Event-floor lead capture (`/api/admin/event-leads`). All uuids are strings. */
|
||||
export type LeadTemperature = "HOT" | "WARM" | "COLD";
|
||||
export type LeadStatus = "OPEN" | "CONTACTED" | "QUALIFIED" | "WON" | "LOST";
|
||||
export type LeadType = "NEW" | "EXISTING";
|
||||
|
||||
export interface EventLeadEvent {
|
||||
uuid: string;
|
||||
name: string;
|
||||
location: string | null;
|
||||
startDate: string | null;
|
||||
endDate: string | null;
|
||||
}
|
||||
|
||||
export interface InterestOption {
|
||||
id: number;
|
||||
name: string;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
export interface LeadCandidate {
|
||||
leadUuid: string;
|
||||
name: string;
|
||||
mobile: string | null;
|
||||
email: string | null;
|
||||
companyName: string | null;
|
||||
jobTitle: string | null;
|
||||
/** Set when this lead is already captured at the event. */
|
||||
eventLeadUuid: string | null;
|
||||
}
|
||||
|
||||
export interface LeadMatchResult {
|
||||
mobile: string | null;
|
||||
email: string | null;
|
||||
candidates: LeadCandidate[];
|
||||
}
|
||||
|
||||
export interface EventLeadRow {
|
||||
eventLeadUuid: string;
|
||||
eventUuid: string;
|
||||
leadUuid: string;
|
||||
name: string;
|
||||
mobile: string | null;
|
||||
email: string | null;
|
||||
companyName: string | null;
|
||||
jobTitle: string | null;
|
||||
leadType: LeadType;
|
||||
salesperson: { id: number; name: string } | null;
|
||||
temperature: LeadTemperature | null;
|
||||
status: LeadStatus;
|
||||
interests: InterestOption[];
|
||||
nextFollowUpDate: string | null;
|
||||
notes: string | null;
|
||||
capturedAt: string;
|
||||
}
|
||||
|
||||
export interface EventLeadUpdatePayload {
|
||||
salespersonId?: number | null;
|
||||
temperature?: LeadTemperature | null;
|
||||
status?: LeadStatus;
|
||||
interestIds?: number[];
|
||||
nextFollowUpDate?: string | null;
|
||||
notes?: string | null;
|
||||
}
|
||||
|
||||
export interface EventLeadCapturePayload extends EventLeadUpdatePayload {
|
||||
/** Set to attach an existing lead; omit for a new one. */
|
||||
leadUuid?: string;
|
||||
name?: string;
|
||||
mobile?: string | null;
|
||||
email?: string | null;
|
||||
companyName?: string | null;
|
||||
jobTitle?: string | null;
|
||||
}
|
||||
@@ -7,7 +7,8 @@ import { describe, expect, it } from "vitest";
|
||||
// no PAGE_SIZE of its own.
|
||||
|
||||
// Roles loads every role and has no real paging (its DataTable shows one page of everything).
|
||||
const EXEMPT = new Set(["roles/page.tsx"]);
|
||||
// Interests loads every interest and has no real paging (same pattern).
|
||||
const EXEMPT = new Set(["roles/page.tsx", "interests/page.tsx"]);
|
||||
|
||||
function sources(dir: string): string[] {
|
||||
return readdirSync(dir).flatMap((name) => {
|
||||
|
||||
@@ -61,6 +61,12 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<!-- Lead capture: mobile numbers normalised to E.164 (add-event-lead-capture). -->
|
||||
<dependency>
|
||||
<groupId>com.googlecode.libphonenumber</groupId>
|
||||
<artifactId>libphonenumber</artifactId>
|
||||
<version>8.13.55</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
|
||||
+8
@@ -37,6 +37,14 @@ public class RestApiCounterServiceConstants {
|
||||
public static final String API_REST_COUNTER_EVENT_SAVE="/counter/event/save";
|
||||
public static final String API_REST_COUNTER_EVENT_SALESPERSON_FIND_BY_EVENT_UUID="/counter/eventSalesperson/findByEventUuid/{eventUuid}";
|
||||
public static final String API_REST_COUNTER_EVENT_SALESPERSON_REPLACE="/counter/eventSalesperson/replace";
|
||||
public static final String API_REST_COUNTER_INTEREST_FIND_BY_COMPANY="/counter/interest/findByCompany/{companyId}";
|
||||
public static final String API_REST_COUNTER_INTEREST_SAVE="/counter/interest/save";
|
||||
public static final String API_REST_COUNTER_INTEREST_FIND_BY_IDS="/counter/interest/findByIds";
|
||||
public static final String API_REST_COUNTER_LEAD_FIND_MATCHES="/counter/lead/findMatches";
|
||||
public static final String API_REST_COUNTER_EVENT_LEAD_CAPTURE="/counter/eventLead/capture";
|
||||
public static final String API_REST_COUNTER_EVENT_LEAD_FIND_BY_UUID="/counter/eventLead/findByUuid/{companyId}/{eventLeadUuid}";
|
||||
public static final String API_REST_COUNTER_EVENT_LEAD_UPDATE="/counter/eventLead/update";
|
||||
public static final String API_REST_COUNTER_EVENT_LEAD_FIND_BY_EVENT="/counter/eventLead/findByEvent";
|
||||
|
||||
//Event Product
|
||||
public static final String API_REST_COUNTER_EVENT_PRODUCT_FIND_BY_EVENT_UUID = "/counter/eventProduct/findByEventUuid/{eventUuid}";
|
||||
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.dto.admin.AdminEventLeadCaptureRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminEventLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLeadMatchRequest;
|
||||
import com.solvway.mobile.api.service.AdminEventLeadService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** Event-floor lead capture: events, options, match, capture, listing and edit. Must stay under {@code controller..} for AppAccessAspect. */
|
||||
@RestController
|
||||
@RequestMapping("/api/admin/event-leads")
|
||||
@RequiredArgsConstructor
|
||||
public class AdminEventLeadController {
|
||||
private final AdminEventLeadService adminEventLeadService;
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@GetMapping("/events")
|
||||
public ResponseEntity<List<Map<String, Object>>> events() {
|
||||
return ResponseEntity.ok(adminEventLeadService.events());
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@GetMapping("/interest-options")
|
||||
public ResponseEntity<List<Map<String, Object>>> interestOptions() {
|
||||
return ResponseEntity.ok(adminEventLeadService.interestOptions());
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@GetMapping("/{eventUuid}/salesperson-options")
|
||||
public ResponseEntity<List<Map<String, Object>>> salespersonOptions(@PathVariable String eventUuid) {
|
||||
return ResponseEntity.ok(adminEventLeadService.salespersonOptions(eventUuid));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@PostMapping("/{eventUuid}/match")
|
||||
public ResponseEntity<Map<String, Object>> match(@PathVariable String eventUuid, @RequestBody AdminLeadMatchRequest request) {
|
||||
return ResponseEntity.ok(adminEventLeadService.match(eventUuid, request));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@PostMapping("/{eventUuid}")
|
||||
public ResponseEntity<Map<String, Object>> capture(@PathVariable String eventUuid, @RequestBody AdminEventLeadCaptureRequest request) {
|
||||
return ResponseEntity.ok(adminEventLeadService.capture(eventUuid, request));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@GetMapping("/{eventUuid}/leads")
|
||||
public ResponseEntity<Map<String, Object>> list(@PathVariable String eventUuid,
|
||||
@RequestParam(required = false) Long salespersonId,
|
||||
@RequestParam(required = false) String temperature,
|
||||
@RequestParam(required = false) String status,
|
||||
@RequestParam(required = false) Long interestId,
|
||||
@RequestParam(required = false) String leadType,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
return ResponseEntity.ok(adminEventLeadService.list(eventUuid, salespersonId, temperature, status, interestId, leadType, page, size));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@GetMapping("/{eventUuid}/leads/{eventLeadUuid}")
|
||||
public ResponseEntity<Map<String, Object>> get(@PathVariable String eventUuid, @PathVariable String eventLeadUuid) {
|
||||
return ResponseEntity.ok(adminEventLeadService.get(eventUuid, eventLeadUuid));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@PutMapping("/{eventUuid}/leads/{eventLeadUuid}")
|
||||
public ResponseEntity<Map<String, Object>> update(@PathVariable String eventUuid, @PathVariable String eventLeadUuid,
|
||||
@RequestBody AdminEventLeadUpdateRequest request) {
|
||||
return ResponseEntity.ok(adminEventLeadService.update(eventUuid, eventLeadUuid, request));
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.dto.admin.AdminInterestRequest;
|
||||
import com.solvway.mobile.api.service.AdminInterestService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** Admin interest list. Must stay under {@code controller..} for AppAccessAspect. */
|
||||
@RestController
|
||||
@RequestMapping("/api/admin")
|
||||
@RequiredArgsConstructor
|
||||
public class AdminInterestController {
|
||||
private final AdminInterestService adminInterestService;
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_INTERESTS")
|
||||
@GetMapping("/interests")
|
||||
public ResponseEntity<List<Map<String, Object>>> list() {
|
||||
return ResponseEntity.ok(adminInterestService.list());
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_INTERESTS")
|
||||
@PostMapping("/interests")
|
||||
public ResponseEntity<Map<String, Object>> create(@RequestBody AdminInterestRequest request) {
|
||||
return ResponseEntity.ok(adminInterestService.create(request));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_INTERESTS")
|
||||
@PutMapping("/interests/{id}")
|
||||
public ResponseEntity<Map<String, Object>> update(@PathVariable long id, @RequestBody AdminInterestRequest request) {
|
||||
return ResponseEntity.ok(adminInterestService.update(id, request));
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.solvway.mobile.api.dto.admin;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** Step 2 of capture. leadUuid is the picked match as a string, or null for a new person. nextFollowUpDate is YYYY-MM-DD. */
|
||||
public record AdminEventLeadCaptureRequest(String leadUuid, String name, String mobile, String email, String companyName,
|
||||
String jobTitle, Long salespersonId, String temperature, String status,
|
||||
List<Long> interestIds, String nextFollowUpDate, String notes) {}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.solvway.mobile.api.dto.admin;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** An event lead's working fields. nextFollowUpDate is YYYY-MM-DD; null clears it. */
|
||||
public record AdminEventLeadUpdateRequest(Long salespersonId, String temperature, String status, List<Long> interestIds,
|
||||
String nextFollowUpDate, String notes) {}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
package com.solvway.mobile.api.dto.admin;
|
||||
|
||||
/** Create (name) or update (any field; omitted fields keep their stored value) an interest. */
|
||||
public record AdminInterestRequest(String name, Boolean active, Integer sortOrder) {}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
package com.solvway.mobile.api.dto.admin;
|
||||
|
||||
/** Step 1 of capture: the mobile and/or email to look up. */
|
||||
public record AdminLeadMatchRequest(String mobile, String email) {}
|
||||
+447
@@ -0,0 +1,447 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.model.Event;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.dto.admin.AdminEventLeadCaptureRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminEventLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLeadMatchRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Lead capture at events for the admin portal. Validates and normalises at this boundary; services-counter stores.
|
||||
* Company comes from the logged-in admin, never the request. Uuids leave as strings (Snowflake longs).
|
||||
* Never log a lead's name, mobile or email.
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@SuppressWarnings("unchecked")
|
||||
public class AdminEventLeadService {
|
||||
private static final Set<String> TEMPERATURES = Set.of("HOT", "WARM", "COLD");
|
||||
private static final Set<String> STATUSES = Set.of("OPEN", "CONTACTED", "QUALIFIED", "WON", "LOST");
|
||||
private static final Set<String> LEAD_TYPES = Set.of("NEW", "EXISTING");
|
||||
private static final int EVENT_PAGE = 100;
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
|
||||
private static final ParameterizedTypeReference<AdminEventService.EventPage> PAGE = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<Event> EVENT = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<List<Map<String, Object>>> MAP_LIST = new ParameterizedTypeReference<>() {};
|
||||
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
private final AdminAuthenticationService adminAuthenticationService;
|
||||
|
||||
// --- options ---
|
||||
|
||||
/** Enabled events, newest start first. ponytail: one page of 100; add paging when a company has more enabled events. */
|
||||
public List<Map<String, Object>> events() {
|
||||
Map<String, Object> request = Map.of("property", Map.of("name", "", "enabled", "Y"),
|
||||
"pageableRest", Map.of("number", 0, "size", EVENT_PAGE, "sorts", List.of(Map.of("direction", "DESC", "property", "dateStart"))));
|
||||
AdminEventService.EventPage p = restTemplateUtil.postForEntity(
|
||||
url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_BY_PROPERTY_AND_PAGEABLE), PAGE, request).getBody();
|
||||
if (p == null || p.content() == null) return List.of();
|
||||
return p.content().stream().map(e -> {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("uuid", String.valueOf(e.getUuid()));
|
||||
m.put("name", e.getName());
|
||||
m.put("location", e.getLocation());
|
||||
m.put("startDate", e.getDateStart() == null ? null : e.getDateStart().toLocalDate().toString());
|
||||
m.put("endDate", e.getDateEnd() == null ? null : e.getDateEnd().toLocalDate().toString());
|
||||
return m;
|
||||
}).toList();
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> interestOptions() {
|
||||
return interests(caller().getCompanyId()).values().stream().filter(i -> Boolean.TRUE.equals(i.get("active"))).toList();
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> salespersonOptions(String eventUuid) {
|
||||
Event event = loadEvent(eventUuid);
|
||||
List<Map<String, Object>> out = new ArrayList<>();
|
||||
for (Long id : teamIds(event.getUuid())) {
|
||||
Map<String, Object> u = user(id);
|
||||
if (isActiveAdmin(u)) out.add(Map.of("id", id, "name", String.valueOf(u.get("name")), "username", String.valueOf(u.get("username"))));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// --- capture ---
|
||||
|
||||
public Map<String, Object> match(String eventUuid, AdminLeadMatchRequest r) {
|
||||
User caller = caller();
|
||||
String mobile = mobile(r.mobile());
|
||||
String email = email(r.email());
|
||||
if (mobile == null && email == null) throw required(List.of("mobile", "email"));
|
||||
Event event = loadEvent(eventUuid);
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("mobile", mobile);
|
||||
out.put("email", email);
|
||||
out.put("candidates", findMatches(caller.getCompanyId(), event.getUuid(), mobile, email).stream().map(m -> {
|
||||
Map<String, Object> c = new LinkedHashMap<>();
|
||||
c.put("leadUuid", str(m.get("leadUuid")));
|
||||
c.put("name", m.get("name"));
|
||||
c.put("mobile", m.get("mobileE164"));
|
||||
c.put("email", m.get("email"));
|
||||
c.put("companyName", m.get("companyName"));
|
||||
c.put("jobTitle", m.get("jobTitle"));
|
||||
c.put("eventLeadUuid", str(m.get("eventLeadUuid")));
|
||||
return c;
|
||||
}).toList());
|
||||
return out;
|
||||
}
|
||||
|
||||
public Map<String, Object> capture(String eventUuid, AdminEventLeadCaptureRequest r) {
|
||||
User caller = caller();
|
||||
String name = trimmed(r.name());
|
||||
String mobile = mobile(r.mobile());
|
||||
String email = email(r.email());
|
||||
List<String> missing = new ArrayList<>();
|
||||
if (name == null) missing.add("name");
|
||||
if (mobile == null && email == null) { missing.add("mobile"); missing.add("email"); }
|
||||
if (!missing.isEmpty()) throw required(missing);
|
||||
maxLength("name", name, 100);
|
||||
maxLength("email", email, 254);
|
||||
String companyName = maxLength("companyName", trimmed(r.companyName()), 150);
|
||||
String jobTitle = maxLength("jobTitle", trimmed(r.jobTitle()), 100);
|
||||
String temperature = oneOf("temperature", r.temperature(), TEMPERATURES);
|
||||
String status = oneOf("status", r.status(), STATUSES);
|
||||
LocalDate followUp = date(r.nextFollowUpDate());
|
||||
Long leadUuid = r.leadUuid() == null ? null : parseOr(r.leadUuid(), () -> error(HttpStatus.NOT_FOUND, "Lead not found", "LEAD_NOT_FOUND", null));
|
||||
|
||||
Event event = loadEvent(eventUuid);
|
||||
if (event.getEnabled() != GeneralEnum.FlagYesNo.Y) {
|
||||
throw error(HttpStatus.CONFLICT, "This event is disabled and cannot take new leads", "EVENT_DISABLED", null);
|
||||
}
|
||||
if (r.salespersonId() != null) checkOnTeam(event.getUuid(), r.salespersonId());
|
||||
Map<Long, Map<String, Object>> known = interests(caller.getCompanyId());
|
||||
List<Long> interestIds = checkedInterests(known, r.interestIds(), List.of());
|
||||
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", caller.getCompanyId());
|
||||
body.put("eventUuid", event.getUuid());
|
||||
body.put("leadUuid", leadUuid);
|
||||
body.put("name", name);
|
||||
body.put("mobileE164", mobile);
|
||||
body.put("email", email);
|
||||
body.put("companyName", companyName);
|
||||
body.put("jobTitle", jobTitle);
|
||||
body.put("salespersonUserId", r.salespersonId());
|
||||
body.put("temperature", temperature);
|
||||
body.put("status", status);
|
||||
body.put("interestIds", interestIds);
|
||||
body.put("nextFollowUpDate", followUp == null ? null : followUp.toString());
|
||||
body.put("notes", trimmed(r.notes()));
|
||||
body.put("doneBy", caller.getUsername());
|
||||
try {
|
||||
return view(restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_CAPTURE), MAP, body).getBody(),
|
||||
known, new HashMap<>());
|
||||
} catch (HttpClientErrorException.Conflict e) {
|
||||
Object existing = conflictEventLeadUuid(e);
|
||||
if (existing == null) existing = findMatches(caller.getCompanyId(), event.getUuid(), mobile, email).stream()
|
||||
.filter(m -> Objects.equals(str(m.get("leadUuid")), str(leadUuid))).map(m -> m.get("eventLeadUuid"))
|
||||
.filter(Objects::nonNull).findFirst().orElse(null);
|
||||
CodedResponseStatusException ex = new CodedResponseStatusException(HttpStatus.CONFLICT,
|
||||
"This person is already captured at this event", "ALREADY_CAPTURED");
|
||||
if (existing != null) ex.getBody().setProperty("details", Map.of("eventLeadUuid", str(existing)));
|
||||
throw ex;
|
||||
} catch (HttpClientErrorException.NotFound e) {
|
||||
throw error(HttpStatus.NOT_FOUND, "Lead not found", "LEAD_NOT_FOUND", null);
|
||||
}
|
||||
}
|
||||
|
||||
// --- listing and edit ---
|
||||
|
||||
public Map<String, Object> list(String eventUuid, Long salespersonId, String temperature, String status, Long interestId,
|
||||
String leadType, int page, int size) {
|
||||
User caller = caller();
|
||||
Event event = loadEvent(eventUuid);
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", caller.getCompanyId());
|
||||
body.put("eventUuid", event.getUuid());
|
||||
body.put("salespersonUserId", salespersonId);
|
||||
body.put("temperature", oneOf("temperature", temperature, TEMPERATURES));
|
||||
body.put("status", oneOf("status", status, STATUSES));
|
||||
body.put("interestId", interestId);
|
||||
body.put("leadType", oneOf("leadType", leadType, LEAD_TYPES));
|
||||
body.put("page", Math.max(page, 0));
|
||||
body.put("size", size);
|
||||
Map<String, Object> p = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_FIND_BY_EVENT), MAP, body).getBody();
|
||||
List<Map<String, Object>> rows = p == null || p.get("content") == null ? List.of() : (List<Map<String, Object>>) p.get("content");
|
||||
Map<Long, Map<String, Object>> interests = rows.isEmpty() ? Map.of() : interests(caller.getCompanyId());
|
||||
Map<Long, Map<String, Object>> users = new HashMap<>();
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("content", rows.stream().map(row -> view(row, interests, users)).toList());
|
||||
out.put("totalElements", p == null ? 0 : p.get("totalElements"));
|
||||
out.put("totalPages", p == null ? 0 : p.get("totalPages"));
|
||||
out.put("number", p == null ? 0 : p.get("number"));
|
||||
out.put("size", p == null ? size : p.get("size"));
|
||||
return out;
|
||||
}
|
||||
|
||||
public Map<String, Object> get(String eventUuid, String eventLeadUuid) {
|
||||
User caller = caller();
|
||||
return view(stored(caller.getCompanyId(), eventUuid, eventLeadUuid), caller.getCompanyId());
|
||||
}
|
||||
|
||||
public Map<String, Object> update(String eventUuid, String eventLeadUuid, AdminEventLeadUpdateRequest r) {
|
||||
User caller = caller();
|
||||
String temperature = oneOf("temperature", r.temperature(), TEMPERATURES);
|
||||
String status = oneOf("status", r.status(), STATUSES);
|
||||
LocalDate followUp = date(r.nextFollowUpDate());
|
||||
Map<String, Object> current = stored(caller.getCompanyId(), eventUuid, eventLeadUuid);
|
||||
Long currentSalesperson = current.get("salespersonUserId") == null ? null : ((Number) current.get("salespersonUserId")).longValue();
|
||||
if (r.salespersonId() != null && !r.salespersonId().equals(currentSalesperson)) {
|
||||
checkOnTeam(((Number) current.get("eventUuid")).longValue(), r.salespersonId());
|
||||
}
|
||||
Map<Long, Map<String, Object>> known = interests(caller.getCompanyId());
|
||||
List<Long> interestIds = checkedInterests(known, r.interestIds(), longs(current.get("interestIds")));
|
||||
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", caller.getCompanyId());
|
||||
body.put("eventLeadUuid", ((Number) current.get("eventLeadUuid")).longValue());
|
||||
body.put("salespersonUserId", r.salespersonId());
|
||||
body.put("temperature", temperature);
|
||||
body.put("status", status);
|
||||
body.put("interestIds", interestIds);
|
||||
body.put("nextFollowUpDate", followUp == null ? null : followUp.toString());
|
||||
body.put("notes", trimmed(r.notes()));
|
||||
body.put("doneBy", caller.getUsername());
|
||||
return view(restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_UPDATE), MAP, body).getBody(),
|
||||
known, new HashMap<>());
|
||||
}
|
||||
|
||||
// --- rules ---
|
||||
|
||||
/** A salesperson newly set must be an active admin on the event's current team. */
|
||||
private void checkOnTeam(long eventUuid, long userId) {
|
||||
if (!teamIds(eventUuid).contains(userId) || !isActiveAdmin(user(userId))) {
|
||||
throw error(HttpStatus.BAD_REQUEST, "The salesperson must be an active member of the event's team", "NOT_ON_TEAM", "salespersonId");
|
||||
}
|
||||
}
|
||||
|
||||
/** Ids must be the company's interests; one newly added must be active, one already on the lead may stay. */
|
||||
private static List<Long> checkedInterests(Map<Long, Map<String, Object>> known, List<Long> requested, List<Long> current) {
|
||||
List<Long> ids = requested == null ? List.of() : new ArrayList<>(new LinkedHashSet<>(requested.stream().filter(Objects::nonNull).toList()));
|
||||
for (Long id : ids) {
|
||||
Map<String, Object> interest = known.get(id);
|
||||
if (interest == null) throw error(HttpStatus.BAD_REQUEST, "Unknown interest " + id, "INVALID_VALUE", "interestIds");
|
||||
if (!Boolean.TRUE.equals(interest.get("active")) && !current.contains(id)) {
|
||||
throw error(HttpStatus.BAD_REQUEST, "Interest " + interest.get("name") + " is no longer active", "INACTIVE_INTEREST", "interestIds");
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
private Map<String, Object> stored(long companyId, String eventUuid, String eventLeadUuid) {
|
||||
Event event = loadEvent(eventUuid);
|
||||
long id = parseOr(eventLeadUuid, AdminEventLeadService::eventLeadNotFound);
|
||||
Map<String, Object> d;
|
||||
try {
|
||||
d = restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_FIND_BY_UUID), MAP, companyId, id).getBody();
|
||||
} catch (HttpClientErrorException.NotFound e) {
|
||||
throw eventLeadNotFound();
|
||||
}
|
||||
if (d == null || !(d.get("eventUuid") instanceof Number n) || n.longValue() != event.getUuid()) throw eventLeadNotFound();
|
||||
return d;
|
||||
}
|
||||
|
||||
// --- views ---
|
||||
|
||||
private Map<String, Object> view(Map<String, Object> d, long companyId) {
|
||||
return view(d, interests(companyId), new HashMap<>());
|
||||
}
|
||||
|
||||
private Map<String, Object> view(Map<String, Object> d, Map<Long, Map<String, Object>> interests, Map<Long, Map<String, Object>> users) {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("eventLeadUuid", str(d.get("eventLeadUuid")));
|
||||
m.put("eventUuid", str(d.get("eventUuid")));
|
||||
m.put("leadUuid", str(d.get("leadUuid")));
|
||||
m.put("name", d.get("name"));
|
||||
m.put("mobile", d.get("mobileE164"));
|
||||
m.put("email", d.get("email"));
|
||||
m.put("companyName", d.get("companyName"));
|
||||
m.put("jobTitle", d.get("jobTitle"));
|
||||
m.put("leadType", d.get("leadType"));
|
||||
Object sp = d.get("salespersonUserId");
|
||||
if (sp instanceof Number n) {
|
||||
Map<String, Object> u = users.computeIfAbsent(n.longValue(), this::user);
|
||||
m.put("salesperson", Map.of("id", n.longValue(), "name", u == null ? String.valueOf(n) : String.valueOf(u.get("name"))));
|
||||
} else {
|
||||
m.put("salesperson", null);
|
||||
}
|
||||
m.put("temperature", d.get("temperature"));
|
||||
m.put("status", d.get("status"));
|
||||
m.put("interests", longs(d.get("interestIds")).stream().map(id -> {
|
||||
Map<String, Object> i = interests.get(id);
|
||||
return Map.<String, Object>of("id", id, "name", i == null ? String.valueOf(id) : i.get("name"),
|
||||
"active", i != null && Boolean.TRUE.equals(i.get("active")));
|
||||
}).toList());
|
||||
m.put("nextFollowUpDate", d.get("nextFollowUpDate"));
|
||||
m.put("notes", d.get("notes"));
|
||||
m.put("capturedAt", d.get("capturedAt"));
|
||||
return m;
|
||||
}
|
||||
|
||||
// --- lookups ---
|
||||
|
||||
private List<Map<String, Object>> findMatches(long companyId, long eventUuid, String mobile, String email) {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", companyId);
|
||||
body.put("eventUuid", eventUuid);
|
||||
body.put("mobileE164", mobile);
|
||||
body.put("email", email);
|
||||
List<Map<String, Object>> rows = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_FIND_MATCHES), MAP_LIST, body).getBody();
|
||||
return rows == null ? List.of() : rows;
|
||||
}
|
||||
|
||||
/** id -> {id, name, active}, in the counter's order (sort order, then name). */
|
||||
private Map<Long, Map<String, Object>> interests(long companyId) {
|
||||
List<Map<String, Object>> rows = restTemplateUtil.getForEntity(
|
||||
url(RestApiCounterServiceConstants.API_REST_COUNTER_INTEREST_FIND_BY_COMPANY), MAP_LIST, companyId).getBody();
|
||||
Map<Long, Map<String, Object>> out = new LinkedHashMap<>();
|
||||
if (rows != null) for (Map<String, Object> r : rows) {
|
||||
long id = ((Number) r.get("id")).longValue();
|
||||
out.put(id, Map.of("id", id, "name", String.valueOf(r.get("name")), "active", Boolean.TRUE.equals(r.get("active"))));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private List<Long> teamIds(long eventUuid) {
|
||||
List<Map<String, Object>> rows = restTemplateUtil.getForEntity(
|
||||
url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_SALESPERSON_FIND_BY_EVENT_UUID), MAP_LIST, eventUuid).getBody();
|
||||
return rows == null ? List.of() : rows.stream().map(m -> ((Number) m.get("userId")).longValue()).toList();
|
||||
}
|
||||
|
||||
private Map<String, Object> user(Long id) {
|
||||
return restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_ID), MAP, id).getBody();
|
||||
}
|
||||
|
||||
private Event loadEvent(String uuid) {
|
||||
long id = parseOr(uuid, AdminEventLeadService::eventNotFound);
|
||||
Event event = restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_BY_UUID), EVENT, id).getBody();
|
||||
if (event == null) throw eventNotFound();
|
||||
return event;
|
||||
}
|
||||
|
||||
private User caller() {
|
||||
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
|
||||
if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED", null);
|
||||
return caller;
|
||||
}
|
||||
|
||||
private String url(String api) {
|
||||
return restTemplateUtil.getURLforApiService(api);
|
||||
}
|
||||
|
||||
// --- small helpers ---
|
||||
|
||||
private static Object conflictEventLeadUuid(HttpClientErrorException e) {
|
||||
try {
|
||||
return JSON.readValue(e.getResponseBodyAsString(), Map.class).get("eventLeadUuid");
|
||||
} catch (Exception ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isActiveAdmin(Map<String, Object> user) {
|
||||
return user != null && "A".equals(user.get("type")) && Boolean.TRUE.equals(user.get("enabled"));
|
||||
}
|
||||
|
||||
private static String mobile(String input) {
|
||||
try {
|
||||
return EventLeadContact.mobile(input);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw error(HttpStatus.BAD_REQUEST, "Enter a valid mobile number", "INVALID_MOBILE", "mobile");
|
||||
}
|
||||
}
|
||||
|
||||
private static String email(String input) {
|
||||
try {
|
||||
return EventLeadContact.email(input);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw error(HttpStatus.BAD_REQUEST, "Enter a valid email address", "INVALID_EMAIL", "email");
|
||||
}
|
||||
}
|
||||
|
||||
private static LocalDate date(String input) {
|
||||
if (input == null || input.isBlank()) return null;
|
||||
try {
|
||||
return LocalDate.parse(input.trim());
|
||||
} catch (DateTimeParseException e) {
|
||||
throw error(HttpStatus.BAD_REQUEST, "Use a date like 2027-01-20", "INVALID_DATE", "nextFollowUpDate");
|
||||
}
|
||||
}
|
||||
|
||||
private static String oneOf(String field, String value, Set<String> allowed) {
|
||||
if (value == null || value.isBlank()) return null;
|
||||
if (!allowed.contains(value)) throw error(HttpStatus.BAD_REQUEST, "Unknown " + field + " " + value, "INVALID_VALUE", field);
|
||||
return value;
|
||||
}
|
||||
|
||||
private static String maxLength(String field, String value, int max) {
|
||||
if (value != null && value.length() > max) throw error(HttpStatus.BAD_REQUEST, field + " is too long", "TOO_LONG", field);
|
||||
return value;
|
||||
}
|
||||
|
||||
private static String trimmed(String s) {
|
||||
return s == null || s.isBlank() ? null : s.trim();
|
||||
}
|
||||
|
||||
private static long parseOr(String s, java.util.function.Supplier<CodedResponseStatusException> notFound) {
|
||||
try {
|
||||
return Long.parseLong(s.trim());
|
||||
} catch (RuntimeException e) {
|
||||
throw notFound.get();
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Long> longs(Object list) {
|
||||
if (!(list instanceof List<?> l)) return List.of();
|
||||
return l.stream().filter(Number.class::isInstance).map(o -> ((Number) o).longValue()).toList();
|
||||
}
|
||||
|
||||
private static String str(Object o) {
|
||||
return o == null ? null : String.valueOf(o);
|
||||
}
|
||||
|
||||
private static CodedResponseStatusException required(List<String> fields) {
|
||||
CodedResponseStatusException e = error(HttpStatus.BAD_REQUEST, "Required: " + String.join(", ", fields), "REQUIRED_FIELD", fields.get(0));
|
||||
e.getBody().setProperty("errors", fields);
|
||||
return e;
|
||||
}
|
||||
|
||||
private static CodedResponseStatusException eventNotFound() {
|
||||
return error(HttpStatus.NOT_FOUND, "Event not found", "EVENT_NOT_FOUND", null);
|
||||
}
|
||||
|
||||
private static CodedResponseStatusException eventLeadNotFound() {
|
||||
return error(HttpStatus.NOT_FOUND, "Event lead not found", "EVENT_LEAD_NOT_FOUND", null);
|
||||
}
|
||||
|
||||
private static CodedResponseStatusException error(HttpStatus status, String reason, String code, String field) {
|
||||
CodedResponseStatusException e = new CodedResponseStatusException(status, reason, code);
|
||||
if (field != null) e.getBody().setProperty("details", Map.of("field", field));
|
||||
return e;
|
||||
}
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants;
|
||||
import com.solvway.mobile.api.dto.admin.AdminInterestRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** The company's interest list (tags for leads). Company comes from the logged-in admin, never the request. */
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AdminInterestService {
|
||||
private static final int NAME_MAX = 100;
|
||||
private static final ParameterizedTypeReference<List<Map<String, Object>>> LIST = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
private final AdminAuthenticationService adminAuthenticationService;
|
||||
|
||||
public List<Map<String, Object>> list() {
|
||||
return load(caller().getCompanyId()).stream().map(AdminInterestService::row).toList();
|
||||
}
|
||||
|
||||
public Map<String, Object> create(AdminInterestRequest r) {
|
||||
User caller = caller();
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", caller.getCompanyId());
|
||||
body.put("name", checkedName(r.name()));
|
||||
body.put("active", r.active() == null || r.active());
|
||||
body.put("sortOrder", r.sortOrder() == null ? 0 : r.sortOrder());
|
||||
return save(body);
|
||||
}
|
||||
|
||||
public Map<String, Object> update(long id, AdminInterestRequest r) {
|
||||
User caller = caller();
|
||||
Map<String, Object> stored = load(caller.getCompanyId()).stream()
|
||||
.filter(m -> m.get("id") instanceof Number n && n.longValue() == id).findFirst()
|
||||
.orElseThrow(() -> error(HttpStatus.NOT_FOUND, "Interest not found", "INTEREST_NOT_FOUND", null));
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("id", id);
|
||||
body.put("companyId", caller.getCompanyId());
|
||||
body.put("name", r.name() == null ? stored.get("name") : checkedName(r.name()));
|
||||
body.put("active", r.active() == null ? stored.get("active") : r.active());
|
||||
body.put("sortOrder", r.sortOrder() == null ? stored.get("sortOrder") : r.sortOrder());
|
||||
return save(body);
|
||||
}
|
||||
|
||||
private Map<String, Object> save(Map<String, Object> body) {
|
||||
try {
|
||||
return row(restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_INTEREST_SAVE), MAP, body).getBody());
|
||||
} catch (HttpClientErrorException.Conflict e) {
|
||||
throw error(HttpStatus.CONFLICT, "An interest with this name already exists", "DUPLICATE_NAME", "name");
|
||||
}
|
||||
}
|
||||
|
||||
private List<Map<String, Object>> load(long companyId) {
|
||||
List<Map<String, Object>> rows = restTemplateUtil.getForEntity(
|
||||
url(RestApiCounterServiceConstants.API_REST_COUNTER_INTEREST_FIND_BY_COMPANY), LIST, companyId).getBody();
|
||||
return rows == null ? List.of() : rows;
|
||||
}
|
||||
|
||||
private static String checkedName(String name) {
|
||||
String n = name == null ? "" : name.trim();
|
||||
if (n.isEmpty()) {
|
||||
CodedResponseStatusException e = error(HttpStatus.BAD_REQUEST, "Required: name", "REQUIRED_FIELD", "name");
|
||||
e.getBody().setProperty("errors", List.of("name"));
|
||||
throw e;
|
||||
}
|
||||
if (n.length() > NAME_MAX) throw error(HttpStatus.BAD_REQUEST, "Name is too long", "TOO_LONG", "name");
|
||||
return n;
|
||||
}
|
||||
|
||||
private static Map<String, Object> row(Map<String, Object> m) {
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("id", m.get("id"));
|
||||
out.put("name", m.get("name"));
|
||||
out.put("active", m.get("active"));
|
||||
out.put("sortOrder", m.get("sortOrder"));
|
||||
return out;
|
||||
}
|
||||
|
||||
private User caller() {
|
||||
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
|
||||
if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED", null);
|
||||
return caller;
|
||||
}
|
||||
|
||||
private String url(String api) {
|
||||
return restTemplateUtil.getURLforApiService(api);
|
||||
}
|
||||
|
||||
private static CodedResponseStatusException error(HttpStatus status, String reason, String code, String field) {
|
||||
CodedResponseStatusException e = new CodedResponseStatusException(status, reason, code);
|
||||
if (field != null) e.getBody().setProperty("details", Map.of("field", field));
|
||||
return e;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.google.i18n.phonenumbers.NumberParseException;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Normalises a lead's contact values so the same person always has the same value: mobile numbers to E.164
|
||||
* (a number without a country code is Malaysian), emails trimmed and lowercased. Blank input is null;
|
||||
* anything that is not a valid number or email address throws IllegalArgumentException.
|
||||
*/
|
||||
final class EventLeadContact {
|
||||
private static final PhoneNumberUtil PHONES = PhoneNumberUtil.getInstance();
|
||||
private static final Pattern EMAIL = Pattern.compile("[^\\s@]+@[^\\s@]+\\.[^\\s@]+");
|
||||
|
||||
private EventLeadContact() {}
|
||||
|
||||
static String mobile(String input) {
|
||||
if (input == null || input.isBlank()) return null;
|
||||
try {
|
||||
Phonenumber.PhoneNumber number = PHONES.parse(input.trim(), "MY");
|
||||
if (PHONES.isValidNumber(number)) return PHONES.format(number, PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
} catch (NumberParseException ignored) {
|
||||
// falls through to the refusal below
|
||||
}
|
||||
throw new IllegalArgumentException("not a valid phone number");
|
||||
}
|
||||
|
||||
static String email(String input) {
|
||||
if (input == null || input.isBlank()) return null;
|
||||
String email = input.trim().toLowerCase(Locale.ROOT);
|
||||
if (!EMAIL.matcher(email).matches()) throw new IllegalArgumentException("not an email address");
|
||||
return email;
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.dto.admin.AdminEventLeadCaptureRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminEventLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLeadMatchRequest;
|
||||
import com.solvway.mobile.api.service.AdminEventLeadService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AdminEventLeadControllerTest {
|
||||
|
||||
private static final String EV = "3312726793093644288";
|
||||
private static final String EL = "3312853897594494976";
|
||||
|
||||
@Mock private AdminEventLeadService eventLeads;
|
||||
@InjectMocks private AdminEventLeadController controller;
|
||||
private MockMvc mvc;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mvc = MockMvcBuilders.standaloneSetup(controller).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyHandlerIsAuthenticatedAndGuardedByBoEventLeads() {
|
||||
List<Method> handlers = Arrays.stream(AdminEventLeadController.class.getDeclaredMethods())
|
||||
.filter(m -> Modifier.isPublic(m.getModifiers()) && !m.isSynthetic()).toList();
|
||||
assertThat(handlers).hasSize(8);
|
||||
for (Method m : handlers) {
|
||||
assertThat(m.isAnnotationPresent(AppAuth.class)).as(m.getName() + " @AppAuth").isTrue();
|
||||
assertThat(Arrays.asList(m.getAnnotation(AdminModule.class).value())).as(m.getName()).containsExactly("BO_EVENT_LEADS");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void optionsEndpoints() throws Exception {
|
||||
when(eventLeads.events()).thenReturn(List.of(Map.of("uuid", EV, "name", "Fair")));
|
||||
mvc.perform(get("/api/admin/event-leads/events")).andExpect(status().isOk())
|
||||
.andExpect(content().json("[{\"uuid\":\"" + EV + "\",\"name\":\"Fair\"}]", true));
|
||||
when(eventLeads.interestOptions()).thenReturn(List.of(Map.of("id", 3, "name", "Cookware", "active", true)));
|
||||
mvc.perform(get("/api/admin/event-leads/interest-options")).andExpect(status().isOk());
|
||||
when(eventLeads.salespersonOptions(EV)).thenReturn(List.of(Map.of("id", 21, "name", "Sales One", "username", "sales1")));
|
||||
mvc.perform(get("/api/admin/event-leads/" + EV + "/salesperson-options")).andExpect(status().isOk())
|
||||
.andExpect(content().json("[{\"id\":21,\"username\":\"sales1\"}]"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchAndCaptureBindTheirBodies() throws Exception {
|
||||
when(eventLeads.match(EV, new AdminLeadMatchRequest("0123456789", null))).thenReturn(Map.of("candidates", List.of()));
|
||||
mvc.perform(post("/api/admin/event-leads/" + EV + "/match").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"mobile\":\"0123456789\"}")).andExpect(status().isOk());
|
||||
|
||||
AdminEventLeadCaptureRequest req = new AdminEventLeadCaptureRequest(null, "Aisyah", "0123456789", null, null, null,
|
||||
21L, "HOT", null, List.of(3L), "2027-01-20", null);
|
||||
when(eventLeads.capture(EV, req)).thenReturn(Map.of("eventLeadUuid", EL));
|
||||
mvc.perform(post("/api/admin/event-leads/" + EV).contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"name\":\"Aisyah\",\"mobile\":\"0123456789\",\"salespersonId\":21,\"temperature\":\"HOT\",\"interestIds\":[3],\"nextFollowUpDate\":\"2027-01-20\"}"))
|
||||
.andExpect(status().isOk()).andExpect(content().json("{\"eventLeadUuid\":\"" + EL + "\"}", true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listPassesFiltersAndPaging() throws Exception {
|
||||
when(eventLeads.list(EV, 21L, "HOT", "OPEN", 3L, "NEW", 1, 25)).thenReturn(Map.of("content", List.of(), "totalElements", 0));
|
||||
mvc.perform(get("/api/admin/event-leads/" + EV + "/leads").param("salespersonId", "21").param("temperature", "HOT")
|
||||
.param("status", "OPEN").param("interestId", "3").param("leadType", "NEW").param("page", "1").param("size", "25"))
|
||||
.andExpect(status().isOk());
|
||||
verify(eventLeads).list(EV, 21L, "HOT", "OPEN", 3L, "NEW", 1, 25);
|
||||
|
||||
when(eventLeads.list(EV, null, null, null, null, null, 0, 20)).thenReturn(Map.of("content", List.of()));
|
||||
mvc.perform(get("/api/admin/event-leads/" + EV + "/leads")).andExpect(status().isOk());
|
||||
verify(eventLeads).list(EV, null, null, null, null, null, 0, 20);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAndUpdateAnEventLead() throws Exception {
|
||||
when(eventLeads.get(EV, EL)).thenReturn(Map.of("eventLeadUuid", EL));
|
||||
mvc.perform(get("/api/admin/event-leads/" + EV + "/leads/" + EL)).andExpect(status().isOk());
|
||||
|
||||
AdminEventLeadUpdateRequest req = new AdminEventLeadUpdateRequest(21L, "COLD", "CONTACTED", List.of(3L), "2027-01-20", "call");
|
||||
when(eventLeads.update(EV, EL, req)).thenReturn(Map.of("eventLeadUuid", EL));
|
||||
mvc.perform(put("/api/admin/event-leads/" + EV + "/leads/" + EL).contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"salespersonId\":21,\"temperature\":\"COLD\",\"status\":\"CONTACTED\",\"interestIds\":[3],\"nextFollowUpDate\":\"2027-01-20\",\"notes\":\"call\"}"))
|
||||
.andExpect(status().isOk());
|
||||
verify(eventLeads).update(EV, EL, req);
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.dto.admin.AdminInterestRequest;
|
||||
import com.solvway.mobile.api.service.AdminInterestService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AdminInterestControllerTest {
|
||||
|
||||
@Mock private AdminInterestService interests;
|
||||
@InjectMocks private AdminInterestController controller;
|
||||
private MockMvc mvc;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mvc = MockMvcBuilders.standaloneSetup(controller).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyHandlerIsAuthenticatedAndGuardedByBoInterests() {
|
||||
List<Method> handlers = Arrays.stream(AdminInterestController.class.getDeclaredMethods())
|
||||
.filter(m -> Modifier.isPublic(m.getModifiers()) && !m.isSynthetic()).toList();
|
||||
assertThat(handlers).hasSize(3);
|
||||
for (Method m : handlers) {
|
||||
assertThat(m.isAnnotationPresent(AppAuth.class)).as(m.getName() + " @AppAuth").isTrue();
|
||||
assertThat(Arrays.asList(m.getAnnotation(AdminModule.class).value())).as(m.getName()).containsExactly("BO_INTERESTS");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void listReturnsTheInterests() throws Exception {
|
||||
when(interests.list()).thenReturn(List.of(Map.of("id", 1, "name", "Cookware")));
|
||||
mvc.perform(get("/api/admin/interests")).andExpect(status().isOk())
|
||||
.andExpect(content().json("[{\"id\":1,\"name\":\"Cookware\"}]"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createAndUpdateBindTheBody() throws Exception {
|
||||
when(interests.create(new AdminInterestRequest("Cookware", null, null))).thenReturn(Map.of("id", 1));
|
||||
mvc.perform(post("/api/admin/interests").contentType(MediaType.APPLICATION_JSON).content("{\"name\":\"Cookware\"}"))
|
||||
.andExpect(status().isOk());
|
||||
verify(interests).create(new AdminInterestRequest("Cookware", null, null));
|
||||
|
||||
when(interests.update(2L, new AdminInterestRequest(null, false, null))).thenReturn(Map.of("id", 2));
|
||||
mvc.perform(put("/api/admin/interests/2").contentType(MediaType.APPLICATION_JSON).content("{\"active\":false}"))
|
||||
.andExpect(status().isOk());
|
||||
verify(interests).update(2L, new AdminInterestRequest(null, false, null));
|
||||
}
|
||||
}
|
||||
+536
@@ -0,0 +1,536 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.model.Event;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.dto.admin.AdminEventLeadCaptureRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminEventLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLeadMatchRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminEventLeadServiceTest {
|
||||
|
||||
private static final String EVENTS = "/counter/event/findByPropertyAndPageable";
|
||||
private static final String EVENT = "/counter/event/findByUuid/{uuid}";
|
||||
private static final String TEAM = "/counter/eventSalesperson/findByEventUuid/{eventUuid}";
|
||||
private static final String USER = "/user/findById/{id}";
|
||||
private static final String INTERESTS = "/counter/interest/findByCompany/{companyId}";
|
||||
private static final String MATCHES = "/counter/lead/findMatches";
|
||||
private static final String CAPTURE = "/counter/eventLead/capture";
|
||||
private static final String FIND = "/counter/eventLead/findByUuid/{companyId}/{eventLeadUuid}";
|
||||
private static final String UPDATE = "/counter/eventLead/update";
|
||||
private static final String SEARCH = "/counter/eventLead/findByEvent";
|
||||
|
||||
private static final long EV = 3312726793093644288L;
|
||||
private static final long EL = 3312853897594494976L;
|
||||
private static final long LEAD = 3312853897040846848L;
|
||||
private static final long COMPANY = 5L;
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminEventLeadService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminEventLeadService(rest, auth);
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
User caller = new User();
|
||||
caller.setId(21L);
|
||||
caller.setUsername("sales1");
|
||||
caller.setCompanyId(COMPANY);
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
stubEvent(true);
|
||||
stubTeam(21L, 22L);
|
||||
stubUser(21L, "Sales One", true);
|
||||
stubUser(22L, "Sales Two", true);
|
||||
stubUser(23L, "Sales Three", true);
|
||||
stubInterests(interest(3, "Cookware", true), interest(4, "Kitchen appliances", true), interest(5, "Old", false));
|
||||
when(rest.postForEntity(eq(CAPTURE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenAnswer(i -> ResponseEntity.ok(detailFrom((Map<String, Object>) i.getArgument(2))));
|
||||
when(rest.postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenAnswer(i -> ResponseEntity.ok(detailFrom((Map<String, Object>) i.getArgument(2))));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() { http.close(); }
|
||||
|
||||
// --- stubs ---
|
||||
|
||||
private void stubEvent(boolean enabled) {
|
||||
Event e = new Event();
|
||||
e.setUuid(EV);
|
||||
e.setName("KL Food Fair 2027");
|
||||
e.setLocation("MITEC");
|
||||
e.setDateStart(LocalDateTime.of(2027, 1, 15, 0, 0));
|
||||
e.setDateEnd(LocalDateTime.of(2027, 1, 17, 23, 59, 59));
|
||||
e.setEnabled(enabled ? GeneralEnum.FlagYesNo.Y : GeneralEnum.FlagYesNo.N);
|
||||
when(rest.getForEntity(eq(EVENT), any(ParameterizedTypeReference.class), eq(EV))).thenReturn(ResponseEntity.ok(e));
|
||||
}
|
||||
|
||||
private void stubTeam(long... userIds) {
|
||||
List<Map<String, Object>> rows = new java.util.ArrayList<>();
|
||||
for (long id : userIds) rows.add(Map.of("userId", id));
|
||||
when(rest.getForEntity(eq(TEAM), any(ParameterizedTypeReference.class), eq(EV))).thenReturn(ResponseEntity.ok(rows));
|
||||
}
|
||||
|
||||
private void stubUser(long id, String name, boolean enabled) {
|
||||
Map<String, Object> u = new HashMap<>();
|
||||
u.put("id", id);
|
||||
u.put("name", name);
|
||||
u.put("username", "u" + id);
|
||||
u.put("type", "A");
|
||||
u.put("enabled", enabled);
|
||||
when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(id))).thenReturn(ResponseEntity.ok(u));
|
||||
}
|
||||
|
||||
private static Map<String, Object> interest(long id, String name, boolean active) {
|
||||
return Map.of("id", id, "companyId", COMPANY, "name", name, "active", active, "sortOrder", 0);
|
||||
}
|
||||
|
||||
private void stubInterests(Map<String, Object>... rows) {
|
||||
when(rest.getForEntity(eq(INTERESTS), any(ParameterizedTypeReference.class), eq(COMPANY))).thenReturn(ResponseEntity.ok(List.of(rows)));
|
||||
}
|
||||
|
||||
/** What the counter returns for a capture or update body. */
|
||||
private static Map<String, Object> detailFrom(Map<String, Object> body) {
|
||||
Map<String, Object> d = new LinkedHashMap<>();
|
||||
d.put("eventLeadUuid", EL);
|
||||
d.put("eventUuid", body.getOrDefault("eventUuid", EV));
|
||||
d.put("leadUuid", body.get("leadUuid") == null ? LEAD : body.get("leadUuid"));
|
||||
d.put("name", body.getOrDefault("name", "Aisyah"));
|
||||
d.put("mobileE164", body.get("mobileE164"));
|
||||
d.put("email", body.get("email"));
|
||||
d.put("companyName", body.get("companyName"));
|
||||
d.put("jobTitle", body.get("jobTitle"));
|
||||
d.put("leadType", body.get("leadUuid") == null ? "NEW" : "EXISTING");
|
||||
d.put("salespersonUserId", body.get("salespersonUserId"));
|
||||
d.put("temperature", body.get("temperature"));
|
||||
d.put("status", body.get("status") == null ? "OPEN" : body.get("status"));
|
||||
d.put("nextFollowUpDate", body.get("nextFollowUpDate") == null ? null : body.get("nextFollowUpDate").toString());
|
||||
d.put("notes", body.get("notes"));
|
||||
d.put("capturedAt", "2027-01-15T10:00:00");
|
||||
d.put("interestIds", body.getOrDefault("interestIds", List.of()));
|
||||
return d;
|
||||
}
|
||||
|
||||
private void stubStored(long eventUuid, Long salespersonUserId, List<Long> interestIds) {
|
||||
Map<String, Object> d = new LinkedHashMap<>();
|
||||
d.put("eventLeadUuid", EL);
|
||||
d.put("eventUuid", eventUuid);
|
||||
d.put("leadUuid", LEAD);
|
||||
d.put("name", "Aisyah");
|
||||
d.put("mobileE164", "+60123456789");
|
||||
d.put("leadType", "NEW");
|
||||
d.put("salespersonUserId", salespersonUserId);
|
||||
d.put("status", "OPEN");
|
||||
d.put("interestIds", interestIds);
|
||||
when(rest.getForEntity(eq(FIND), any(ParameterizedTypeReference.class), eq(COMPANY), eq(EL))).thenReturn(ResponseEntity.ok(d));
|
||||
}
|
||||
|
||||
private static AdminEventLeadCaptureRequest capture(String leadUuid, String name, String mobile, String email) {
|
||||
return new AdminEventLeadCaptureRequest(leadUuid, name, mobile, email, null, null, null, null, null, List.of(), null, null);
|
||||
}
|
||||
|
||||
private static AdminEventLeadCaptureRequest captureWith(Long salespersonId, String temperature, String status, List<Long> interests, String followUp) {
|
||||
return new AdminEventLeadCaptureRequest(null, "Aisyah", "0123456789", null, null, null, salespersonId, temperature, status, interests, followUp, null);
|
||||
}
|
||||
|
||||
private Map<String, Object> sent(String api) {
|
||||
ArgumentCaptor<Object> c = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(api), any(ParameterizedTypeReference.class), c.capture());
|
||||
return (Map<String, Object>) c.getValue();
|
||||
}
|
||||
|
||||
private void assertNothingSent(String api) {
|
||||
verify(rest, never()).postForEntity(eq(api), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
private static void assertCoded(Runnable r, HttpStatus status, String code, String field) {
|
||||
assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(status);
|
||||
assertThat(e.getCode()).isEqualTo(code);
|
||||
if (field != null) assertThat((Map<String, Object>) e.getBody().getProperties().get("details")).containsEntry("field", field);
|
||||
});
|
||||
}
|
||||
|
||||
// --- events and options ---
|
||||
|
||||
@Test
|
||||
void eventsAreTheEnabledOnesNewestFirst() {
|
||||
Event e = new Event();
|
||||
e.setUuid(EV);
|
||||
e.setName("KL Food Fair 2027");
|
||||
e.setLocation("MITEC");
|
||||
e.setDateStart(LocalDateTime.of(2027, 1, 15, 0, 0));
|
||||
e.setDateEnd(LocalDateTime.of(2027, 1, 17, 23, 59, 59));
|
||||
when(rest.postForEntity(eq(EVENTS), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(new AdminEventService.EventPage(List.of(e), 1, 1, 0, 100)));
|
||||
|
||||
List<Map<String, Object>> events = service.events();
|
||||
|
||||
assertThat(events).containsExactly(Map.of("uuid", String.valueOf(EV), "name", "KL Food Fair 2027", "location", "MITEC",
|
||||
"startDate", "2027-01-15", "endDate", "2027-01-17"));
|
||||
Map<String, Object> body = sent(EVENTS);
|
||||
assertThat((Map<String, Object>) body.get("property")).containsEntry("enabled", "Y");
|
||||
Map<String, Object> pageable = (Map<String, Object>) body.get("pageableRest");
|
||||
assertThat(pageable).containsEntry("size", 100);
|
||||
assertThat((List<Map<String, Object>>) pageable.get("sorts")).containsExactly(Map.of("direction", "DESC", "property", "dateStart"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void eventWithEmptyFieldsStillListsWithNulls() {
|
||||
Event e = new Event();
|
||||
e.setUuid(EV);
|
||||
when(rest.postForEntity(eq(EVENTS), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(new AdminEventService.EventPage(List.of(e), 1, 1, 0, 100)));
|
||||
|
||||
Map<String, Object> row = service.events().get(0);
|
||||
|
||||
assertThat(row).containsEntry("uuid", String.valueOf(EV)).containsEntry("name", null)
|
||||
.containsEntry("location", null).containsEntry("startDate", null).containsEntry("endDate", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailLongerThanTheColumnIsTooLong() {
|
||||
String email = "a".repeat(250) + "@x.co";
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), capture(null, "Aisyah", null, email)), HttpStatus.BAD_REQUEST, "TOO_LONG", "email");
|
||||
assertNothingSent(CAPTURE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void captureReadsTheInterestListOnce() {
|
||||
service.capture(String.valueOf(EV), captureWith(null, null, null, List.of(3L), null));
|
||||
|
||||
verify(rest, org.mockito.Mockito.times(1)).getForEntity(eq(INTERESTS), any(ParameterizedTypeReference.class), eq(COMPANY));
|
||||
}
|
||||
|
||||
@Test
|
||||
void interestOptionsAreActiveOnly() {
|
||||
assertThat(service.interestOptions()).extracting(m -> m.get("name")).containsExactly("Cookware", "Kitchen appliances");
|
||||
}
|
||||
|
||||
@Test
|
||||
void salespersonOptionsAreTheActiveTeam() {
|
||||
stubTeam(21L, 22L, 23L);
|
||||
stubUser(23L, "Sales Three", false);
|
||||
|
||||
assertThat(service.salespersonOptions(String.valueOf(EV))).extracting(m -> m.get("id")).containsExactly(21L, 22L);
|
||||
}
|
||||
|
||||
// --- normalisation and validation ---
|
||||
|
||||
@Test
|
||||
void matchNormalisesBothValuesAndReturnsCandidates() {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("leadUuid", LEAD);
|
||||
m.put("name", "Aisyah");
|
||||
m.put("mobileE164", "+60123456789");
|
||||
m.put("email", null);
|
||||
m.put("companyName", "Acme");
|
||||
m.put("jobTitle", null);
|
||||
m.put("eventLeadUuid", EL);
|
||||
when(rest.postForEntity(eq(MATCHES), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(List.of(m)));
|
||||
|
||||
Map<String, Object> out = service.match(String.valueOf(EV), new AdminLeadMatchRequest("012-345 6789", " Aisyah@Example.COM "));
|
||||
|
||||
assertThat(out).containsEntry("mobile", "+60123456789").containsEntry("email", "aisyah@example.com");
|
||||
assertThat(sent(MATCHES)).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV)
|
||||
.containsEntry("mobileE164", "+60123456789").containsEntry("email", "aisyah@example.com");
|
||||
Map<String, Object> candidate = ((List<Map<String, Object>>) out.get("candidates")).get(0);
|
||||
assertThat(candidate).containsEntry("leadUuid", String.valueOf(LEAD)).containsEntry("eventLeadUuid", String.valueOf(EL))
|
||||
.containsEntry("mobile", "+60123456789").containsEntry("companyName", "Acme");
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchWithNeitherValueNamesBothFields() {
|
||||
assertThatThrownBy(() -> service.match(String.valueOf(EV), new AdminLeadMatchRequest(" ", null)))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getCode()).isEqualTo("REQUIRED_FIELD");
|
||||
assertThat(e.getBody().getProperties().get("errors")).isEqualTo(List.of("mobile", "email"));
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void captureNormalisesAndSendsTheCallersCompanyAndUsername() {
|
||||
Map<String, Object> out = service.capture(String.valueOf(EV), capture(null, " Aisyah ", "+60 12-345 6789", " Aisyah@Example.COM "));
|
||||
|
||||
Map<String, Object> body = sent(CAPTURE);
|
||||
assertThat(body).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV).containsEntry("name", "Aisyah")
|
||||
.containsEntry("mobileE164", "+60123456789").containsEntry("email", "aisyah@example.com")
|
||||
.containsEntry("doneBy", "sales1").containsEntry("leadUuid", null);
|
||||
assertThat(out).containsEntry("eventLeadUuid", String.valueOf(EL)).containsEntry("leadUuid", String.valueOf(LEAD))
|
||||
.containsEntry("eventUuid", String.valueOf(EV)).containsEntry("leadType", "NEW").containsEntry("mobile", "+60123456789");
|
||||
}
|
||||
|
||||
@Test
|
||||
void neitherMobileNorEmailIsRefusedNamingBoth() {
|
||||
assertThatThrownBy(() -> service.capture(String.valueOf(EV), capture(null, "Aisyah", "", " ")))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
|
||||
assertThat(e.getCode()).isEqualTo("REQUIRED_FIELD");
|
||||
assertThat(e.getBody().getProperties().get("errors")).isEqualTo(List.of("mobile", "email"));
|
||||
});
|
||||
assertNothingSent(CAPTURE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingNameAndContactAreAllNamed() {
|
||||
assertThatThrownBy(() -> service.capture(String.valueOf(EV), capture(null, " ", null, null)))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e ->
|
||||
assertThat(e.getBody().getProperties().get("errors")).isEqualTo(List.of("name", "mobile", "email")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidMobileIsRefusedOnTheMobileField() {
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), capture(null, "Aisyah", "12345", null)), HttpStatus.BAD_REQUEST, "INVALID_MOBILE", "mobile");
|
||||
assertNothingSent(CAPTURE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidEmailIsRefusedOnTheEmailField() {
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), capture(null, "Aisyah", null, "aisyah@")), HttpStatus.BAD_REQUEST, "INVALID_EMAIL", "email");
|
||||
}
|
||||
|
||||
@Test
|
||||
void tooLongValuesAreRefused() {
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), capture(null, "x".repeat(101), "0123456789", null)), HttpStatus.BAD_REQUEST, "TOO_LONG", "name");
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), new AdminEventLeadCaptureRequest(null, "A", "0123456789", null,
|
||||
"x".repeat(151), null, null, null, null, List.of(), null, null)), HttpStatus.BAD_REQUEST, "TOO_LONG", "companyName");
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), new AdminEventLeadCaptureRequest(null, "A", "0123456789", null,
|
||||
null, "x".repeat(101), null, null, null, List.of(), null, null)), HttpStatus.BAD_REQUEST, "TOO_LONG", "jobTitle");
|
||||
}
|
||||
|
||||
@Test
|
||||
void temperatureStatusAndDateMustBeKnownValues() {
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), captureWith(null, "WARMISH", null, List.of(), null)), HttpStatus.BAD_REQUEST, "INVALID_VALUE", "temperature");
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), captureWith(null, null, "DONE", List.of(), null)), HttpStatus.BAD_REQUEST, "INVALID_VALUE", "status");
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), captureWith(null, null, null, List.of(), "20/01/2027")), HttpStatus.BAD_REQUEST, "INVALID_DATE", "nextFollowUpDate");
|
||||
}
|
||||
|
||||
@Test
|
||||
void workingFieldsAreSentWhenValid() {
|
||||
service.capture(String.valueOf(EV), captureWith(22L, "HOT", "CONTACTED", List.of(3L, 4L), "2027-01-20"));
|
||||
|
||||
assertThat(sent(CAPTURE)).containsEntry("salespersonUserId", 22L).containsEntry("temperature", "HOT")
|
||||
.containsEntry("status", "CONTACTED").containsEntry("interestIds", List.of(3L, 4L))
|
||||
.containsEntry("nextFollowUpDate", "2027-01-20");
|
||||
}
|
||||
|
||||
// --- events open for capture ---
|
||||
|
||||
@Test
|
||||
void disabledEventRefusesCapture() {
|
||||
stubEvent(false);
|
||||
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), capture(null, "Aisyah", "0123456789", null)), HttpStatus.CONFLICT, "EVENT_DISABLED", null);
|
||||
assertNothingSent(CAPTURE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownEventIsNotFound() {
|
||||
when(rest.getForEntity(eq(EVENT), any(ParameterizedTypeReference.class), eq(1L))).thenReturn(ResponseEntity.ok().build());
|
||||
|
||||
assertCoded(() -> service.capture("1", capture(null, "Aisyah", "0123456789", null)), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND", null);
|
||||
assertCoded(() -> service.list("not-a-number", null, null, null, null, null, 0, 20), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND", null);
|
||||
}
|
||||
|
||||
// --- salesperson from the team ---
|
||||
|
||||
@Test
|
||||
void outsiderSalespersonIsRefused() {
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), captureWith(23L, null, null, List.of(), null)), HttpStatus.BAD_REQUEST, "NOT_ON_TEAM", "salespersonId");
|
||||
assertNothingSent(CAPTURE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deactivatedTeamMemberCannotBeNewlyAssigned() {
|
||||
stubUser(22L, "Sales Two", false);
|
||||
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), captureWith(22L, null, null, List.of(), null)), HttpStatus.BAD_REQUEST, "NOT_ON_TEAM", "salespersonId");
|
||||
}
|
||||
|
||||
@Test
|
||||
void salespersonAlreadySetStaysAllowedAfterLeavingTheTeam() {
|
||||
stubStored(EV, 23L, List.of());
|
||||
|
||||
service.update(String.valueOf(EV), String.valueOf(EL), new AdminEventLeadUpdateRequest(23L, null, "CONTACTED", List.of(), null, null));
|
||||
|
||||
assertThat(sent(UPDATE)).containsEntry("salespersonUserId", 23L).containsEntry("status", "CONTACTED")
|
||||
.containsEntry("companyId", COMPANY).containsEntry("eventLeadUuid", EL).containsEntry("doneBy", "sales1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingToAnOutsiderOnEditIsRefused() {
|
||||
stubStored(EV, 21L, List.of());
|
||||
|
||||
assertCoded(() -> service.update(String.valueOf(EV), String.valueOf(EL), new AdminEventLeadUpdateRequest(23L, null, "OPEN", List.of(), null, null)),
|
||||
HttpStatus.BAD_REQUEST, "NOT_ON_TEAM", "salespersonId");
|
||||
assertNothingSent(UPDATE);
|
||||
}
|
||||
|
||||
// --- interests ---
|
||||
|
||||
@Test
|
||||
void inactiveInterestCannotBeAddedAtCapture() {
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), captureWith(null, null, null, List.of(5L), null)), HttpStatus.BAD_REQUEST, "INACTIVE_INTEREST", "interestIds");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anotherCompanysInterestIsRefused() {
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), captureWith(null, null, null, List.of(99L), null)), HttpStatus.BAD_REQUEST, "INVALID_VALUE", "interestIds");
|
||||
}
|
||||
|
||||
@Test
|
||||
void inactiveInterestAlreadyOnTheLeadIsKeptOnEdit() {
|
||||
stubStored(EV, null, List.of(5L));
|
||||
|
||||
service.update(String.valueOf(EV), String.valueOf(EL), new AdminEventLeadUpdateRequest(null, null, "CONTACTED", List.of(5L, 3L), null, null));
|
||||
|
||||
assertThat(sent(UPDATE)).containsEntry("interestIds", List.of(5L, 3L));
|
||||
}
|
||||
|
||||
// --- already captured ---
|
||||
|
||||
@Test
|
||||
void alreadyCapturedCarriesTheExistingEventLeadUuid() {
|
||||
byte[] body = ("{\"status\":409,\"detail\":\"ALREADY_CAPTURED\",\"eventLeadUuid\":\"" + EL + "\"}").getBytes(StandardCharsets.UTF_8);
|
||||
when(rest.postForEntity(eq(CAPTURE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenThrow(HttpClientErrorException.create(HttpStatus.CONFLICT, "Conflict", null, body, StandardCharsets.UTF_8));
|
||||
|
||||
assertThatThrownBy(() -> service.capture(String.valueOf(EV), capture(String.valueOf(LEAD), "Aisyah", "0123456789", null)))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
|
||||
assertThat(e.getCode()).isEqualTo("ALREADY_CAPTURED");
|
||||
assertThat((Map<String, Object>) e.getBody().getProperties().get("details")).containsEntry("eventLeadUuid", String.valueOf(EL));
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void alreadyCapturedByARaceFindsTheEventLeadThroughMatching() {
|
||||
when(rest.postForEntity(eq(CAPTURE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenThrow(HttpClientErrorException.create(HttpStatus.CONFLICT, "Conflict", null, "{\"status\":409}".getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
|
||||
Map<String, Object> m = new HashMap<>();
|
||||
m.put("leadUuid", LEAD);
|
||||
m.put("eventLeadUuid", EL);
|
||||
when(rest.postForEntity(eq(MATCHES), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(List.of(m)));
|
||||
|
||||
assertThatThrownBy(() -> service.capture(String.valueOf(EV), capture(String.valueOf(LEAD), "Aisyah", "0123456789", null)))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e ->
|
||||
assertThat((Map<String, Object>) e.getBody().getProperties().get("details")).containsEntry("eventLeadUuid", String.valueOf(EL)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pickedLeadOfAnotherCompanyIsNotFound() {
|
||||
when(rest.postForEntity(eq(CAPTURE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "Not Found", null, null, null));
|
||||
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), capture(String.valueOf(LEAD), "Aisyah", "0123456789", null)), HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND", null);
|
||||
assertCoded(() -> service.capture(String.valueOf(EV), capture("abc", "Aisyah", "0123456789", null)), HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND", null);
|
||||
}
|
||||
|
||||
// --- listing, get, update ---
|
||||
|
||||
@Test
|
||||
void listingSendsFiltersAndNamesSalespeopleAndInterests() {
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
row.put("eventLeadUuid", EL);
|
||||
row.put("eventUuid", EV);
|
||||
row.put("leadUuid", LEAD);
|
||||
row.put("name", "Aisyah");
|
||||
row.put("mobileE164", "+60123456789");
|
||||
row.put("leadType", "EXISTING");
|
||||
row.put("salespersonUserId", 22L);
|
||||
row.put("temperature", "HOT");
|
||||
row.put("status", "OPEN");
|
||||
row.put("nextFollowUpDate", "2027-01-20");
|
||||
row.put("interestIds", List.of(3, 5));
|
||||
when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(Map.of("content", List.of(row), "totalElements", 1, "totalPages", 1, "number", 0, "size", 20)));
|
||||
|
||||
Map<String, Object> out = service.list(String.valueOf(EV), 22L, "HOT", "OPEN", 3L, "EXISTING", 0, 20);
|
||||
|
||||
assertThat(sent(SEARCH)).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV).containsEntry("salespersonUserId", 22L)
|
||||
.containsEntry("temperature", "HOT").containsEntry("status", "OPEN").containsEntry("interestId", 3L)
|
||||
.containsEntry("leadType", "EXISTING").containsEntry("page", 0).containsEntry("size", 20);
|
||||
assertThat(out).containsEntry("totalElements", 1);
|
||||
Map<String, Object> first = ((List<Map<String, Object>>) out.get("content")).get(0);
|
||||
assertThat(first).containsEntry("eventLeadUuid", String.valueOf(EL)).containsEntry("mobile", "+60123456789")
|
||||
.containsEntry("salesperson", Map.of("id", 22L, "name", "Sales Two")).containsEntry("nextFollowUpDate", "2027-01-20");
|
||||
assertThat((List<Map<String, Object>>) first.get("interests")).containsExactly(
|
||||
Map.of("id", 3L, "name", "Cookware", "active", true), Map.of("id", 5L, "name", "Old", "active", false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void eventLeadOfAnotherEventIsNotFound() {
|
||||
stubStored(EV + 1, null, List.of());
|
||||
|
||||
assertCoded(() -> service.get(String.valueOf(EV), String.valueOf(EL)), HttpStatus.NOT_FOUND, "EVENT_LEAD_NOT_FOUND", null);
|
||||
assertCoded(() -> service.update(String.valueOf(EV), String.valueOf(EL), new AdminEventLeadUpdateRequest(null, null, "OPEN", List.of(), null, null)),
|
||||
HttpStatus.NOT_FOUND, "EVENT_LEAD_NOT_FOUND", null);
|
||||
assertNothingSent(UPDATE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownEventLeadIsNotFound() {
|
||||
when(rest.getForEntity(eq(FIND), any(ParameterizedTypeReference.class), eq(COMPANY), eq(EL)))
|
||||
.thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "Not Found", null, null, null));
|
||||
|
||||
assertCoded(() -> service.get(String.valueOf(EV), String.valueOf(EL)), HttpStatus.NOT_FOUND, "EVENT_LEAD_NOT_FOUND", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getShowsSalespersonAndInterestsByName() {
|
||||
stubStored(EV, 21L, List.of(4L));
|
||||
|
||||
Map<String, Object> out = service.get(String.valueOf(EV), String.valueOf(EL));
|
||||
|
||||
assertThat(out).containsEntry("salesperson", Map.of("id", 21L, "name", "Sales One"))
|
||||
.containsEntry("name", "Aisyah").containsEntry("leadType", "NEW");
|
||||
assertThat((List<Map<String, Object>>) out.get("interests")).containsExactly(Map.of("id", 4L, "name", "Kitchen appliances", "active", true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateWorksALead() {
|
||||
stubStored(EV, null, List.of());
|
||||
|
||||
Map<String, Object> out = service.update(String.valueOf(EV), String.valueOf(EL),
|
||||
new AdminEventLeadUpdateRequest(21L, "HOT", "CONTACTED", List.of(3L), "2027-01-20", " call back "));
|
||||
|
||||
assertThat(sent(UPDATE)).containsEntry("temperature", "HOT").containsEntry("status", "CONTACTED")
|
||||
.containsEntry("nextFollowUpDate", "2027-01-20").containsEntry("notes", "call back").containsEntry("interestIds", List.of(3L));
|
||||
assertThat(out).containsEntry("status", "CONTACTED").containsEntry("temperature", "HOT");
|
||||
}
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.dto.admin.AdminInterestRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminInterestServiceTest {
|
||||
|
||||
private static final String LIST = "/counter/interest/findByCompany/{companyId}";
|
||||
private static final String SAVE = "/counter/interest/save";
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminInterestService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminInterestService(rest, auth);
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
User caller = new User();
|
||||
caller.setUsername("boss");
|
||||
caller.setCompanyId(5L);
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenAnswer(i -> ResponseEntity.ok(i.getArgument(2)));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() { http.close(); }
|
||||
|
||||
private static Map<String, Object> row(long id, String name, boolean active, int sort) {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("id", id);
|
||||
m.put("companyId", 5);
|
||||
m.put("name", name);
|
||||
m.put("active", active);
|
||||
m.put("sortOrder", sort);
|
||||
return m;
|
||||
}
|
||||
|
||||
private void stubList(Map<String, Object>... rows) {
|
||||
when(rest.getForEntity(eq(LIST), any(ParameterizedTypeReference.class), eq(5L))).thenReturn(ResponseEntity.ok(List.of(rows)));
|
||||
}
|
||||
|
||||
private Map<String, Object> saved() {
|
||||
ArgumentCaptor<Object> c = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), c.capture());
|
||||
return (Map<String, Object>) c.getValue();
|
||||
}
|
||||
|
||||
private static void assertCoded(Runnable r, HttpStatus status, String code, String field) {
|
||||
assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(status);
|
||||
assertThat(e.getCode()).isEqualTo(code);
|
||||
if (field != null) assertThat((Map<String, Object>) e.getBody().getProperties().get("details")).containsEntry("field", field);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void listIsTheCallersCompanyInterests() {
|
||||
stubList(row(1, "Cookware", true, 0), row(2, "Old", false, 1));
|
||||
|
||||
assertThat(service.list()).extracting(m -> m.get("name")).containsExactly("Cookware", "Old");
|
||||
assertThat(service.list().get(1)).containsEntry("active", false).doesNotContainKey("companyId");
|
||||
}
|
||||
|
||||
@Test
|
||||
void createSendsTrimmedActiveInterestForTheCallersCompany() {
|
||||
service.create(new AdminInterestRequest(" Kitchen appliances ", null, null));
|
||||
|
||||
assertThat(saved()).containsEntry("companyId", 5L).containsEntry("name", "Kitchen appliances")
|
||||
.containsEntry("active", true).containsEntry("sortOrder", 0).doesNotContainKey("id");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nameIsRequired() {
|
||||
assertCoded(() -> service.create(new AdminInterestRequest(" ", null, null)), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD", "name");
|
||||
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nameAtMostHundredCharacters() {
|
||||
assertCoded(() -> service.create(new AdminInterestRequest("x".repeat(101), null, null)), HttpStatus.BAD_REQUEST, "TOO_LONG", "name");
|
||||
service.create(new AdminInterestRequest("x".repeat(100), null, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateNameIsAConflictOnTheNameField() {
|
||||
when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenThrow(HttpClientErrorException.create(HttpStatus.CONFLICT, "Conflict", null, null, null));
|
||||
|
||||
assertCoded(() -> service.create(new AdminInterestRequest("kitchen APPLIANCES", null, null)), HttpStatus.CONFLICT, "DUPLICATE_NAME", "name");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateDeactivatesKeepingNameAndOrder() {
|
||||
stubList(row(2, "Cookware", true, 3));
|
||||
|
||||
service.update(2L, new AdminInterestRequest(null, false, null));
|
||||
|
||||
assertThat(saved()).containsEntry("id", 2L).containsEntry("companyId", 5L).containsEntry("name", "Cookware")
|
||||
.containsEntry("active", false).containsEntry("sortOrder", 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateRenamesAndReorders() {
|
||||
stubList(row(2, "Cookware", true, 3));
|
||||
|
||||
service.update(2L, new AdminInterestRequest(" Pots ", null, 1));
|
||||
|
||||
assertThat(saved()).containsEntry("name", "Pots").containsEntry("sortOrder", 1).containsEntry("active", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateOfAnInterestNotInTheCallersCompanyIsNotFound() {
|
||||
stubList(row(2, "Cookware", true, 3));
|
||||
|
||||
assertCoded(() -> service.update(99L, new AdminInterestRequest("X", true, 0)), HttpStatus.NOT_FOUND, "INTEREST_NOT_FOUND", null);
|
||||
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.NullAndEmptySource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
/** Mobile numbers become E.164 (Malaysia by default) and emails are trimmed and lowercased, so one person is one value. */
|
||||
class EventLeadContactTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"012-345 6789", "0123456789", "+60 12-345 6789", "60123456789", " +60123456789 ", "(012) 345-6789"})
|
||||
void malaysianFormatsAreOneNumber(String input) {
|
||||
assertThat(EventLeadContact.mobile(input)).isEqualTo("+60123456789");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"+65 9123 4567", "+6591234567"})
|
||||
void foreignNumbersKeepTheirCountryCode(String input) {
|
||||
assertThat(EventLeadContact.mobile(input)).isEqualTo("+6591234567");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"12345", "abc", "0123", "+60 1"})
|
||||
void invalidNumbersAreRefused(String input) {
|
||||
assertThatThrownBy(() -> EventLeadContact.mobile(input)).isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
@ValueSource(strings = {" "})
|
||||
void blankMobileIsNull(String input) {
|
||||
assertThat(EventLeadContact.mobile(input)).isNull();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {" Aisyah@Example.COM ", "aisyah@example.com", "AISYAH@EXAMPLE.COM"})
|
||||
void emailIsTrimmedAndLowercased(String input) {
|
||||
assertThat(EventLeadContact.email(input)).isEqualTo("aisyah@example.com");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"aisyah", "aisyah@", "@example.com", "a b@example.com", "a@b@example.com", "aisyah@example"})
|
||||
void invalidEmailsAreRefused(String input) {
|
||||
assertThatThrownBy(() -> EventLeadContact.email(input)).isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
@ValueSource(strings = {" "})
|
||||
void blankEmailIsNull(String input) {
|
||||
assertThat(EventLeadContact.email(input)).isNull();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user