feat(portal): Emails list and detail, with the body in a sandboxed frame
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
1 parent
0961a10bb2
commit
0904808e81
12 files changed
+531
-1
No files matched your search
@@ -0,0 +1,46 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
||||
|
||||
import { GET } from "./route";
|
||||
|
||||
const req = (url: string) => new Request(url) as unknown as Parameters<typeof GET>[0];
|
||||
const ctx = (path?: string[]) => ({ params: Promise.resolve({ path }) });
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset();
|
||||
mocks.getToken.mockReset().mockResolvedValue("jwt");
|
||||
});
|
||||
|
||||
describe("GET /api/emails/[[...path]]", () => {
|
||||
it("returns 401 without a session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
expect((await GET(req("http://localhost/api/emails"), ctx())).status).toBe(401);
|
||||
});
|
||||
|
||||
it("forwards the list query", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [] } });
|
||||
await GET(req("http://localhost/api/emails?recipient=s&page=0&size=20"), ctx());
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/emails?recipient=s&page=0&size=20", { token: "jwt" });
|
||||
});
|
||||
|
||||
it("forwards the detail id", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 7 } });
|
||||
await GET(req("http://localhost/api/emails/7"), ctx(["7"]));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/emails/7", { token: "jwt" });
|
||||
});
|
||||
|
||||
it("refuses dot segments", async () => {
|
||||
expect((await GET(req("http://localhost/api/emails/.."), ctx([".."]))).status).toBe(400);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("passes a refusal through with its code", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 403, error: "Only a super admin can read this email", code: "SUPER_ADMIN_REQUIRED" });
|
||||
const res = await GET(req("http://localhost/api/emails/3"), ctx(["3"]));
|
||||
expect(res.status).toBe(403);
|
||||
expect(await res.json()).toMatchObject({ code: "SUPER_ADMIN_REQUIRED" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
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";
|
||||
|
||||
// Read-only proxy for /api/admin/emails; mobile-api owns the BO_EMAILS and super-admin guards.
|
||||
type Ctx = { params: Promise<{ path?: string[] }> };
|
||||
|
||||
export async function GET(req: NextRequest, { params }: Ctx) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { path = [] } = await params; // [[...path]]: the list call has no segment
|
||||
if (path.some((s) => s === "." || s === "..")) return badRequest("Invalid path.");
|
||||
const target = `/api/admin/emails${path.map(encodeURIComponent).map((s) => `/${s}`).join("")}${new URL(req.url).search}`;
|
||||
const result = await callMobileApi<unknown>(target, { token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -25,6 +25,8 @@ const ALLOW: Record<string, string[]> = {
|
||||
// A sent email's HTML is authored for a white mail-client canvas; a theme surface would put the
|
||||
// email's dark text on dark in dark mode.
|
||||
"app/email-templates/logs/[id]/page.tsx": ["bg-white"],
|
||||
// Same reason for the saved-email detail (add-admin-email-listing).
|
||||
"app/emails/[id]/page.tsx": ["bg-white"],
|
||||
// The template preview frame shows the same email HTML (F09 moved it into a sandboxed iframe).
|
||||
"app/email-templates/TemplatePreviewPane.tsx": ["bg-white"],
|
||||
};
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ getEmail: vi.fn(), useAdminAuth: vi.fn() }));
|
||||
vi.mock("@/app/lib/services/adminEmails", async (importActual) => ({
|
||||
...(await importActual<typeof import("@/app/lib/services/adminEmails")>()),
|
||||
getEmail: mocks.getEmail,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
const params = vi.hoisted(() => ({ id: "9" }));
|
||||
vi.mock("next/navigation", () => ({ useParams: () => params }));
|
||||
|
||||
import EmailPage from "./page";
|
||||
|
||||
const EMAIL = {
|
||||
id: 9,
|
||||
datetime: "2026-11-30T11:44:26",
|
||||
sender: "noreply@example.com",
|
||||
subject: "Reset Admin Password",
|
||||
status: "Y",
|
||||
recipients: [{ recipient: "sales1@example.com", type: "R" }],
|
||||
body: "<p>Hi sales1,</p><p>Your temporary password: Xy7kPq2m</p><script>window.pwned=1</script>",
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
params.id = "9";
|
||||
mocks.getEmail.mockReset();
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
|
||||
});
|
||||
|
||||
describe("EmailPage", () => {
|
||||
it("renders NotAuthorized without BO_EMAILS", () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
|
||||
render(<EmailPage />);
|
||||
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
|
||||
expect(mocks.getEmail).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows the metadata and puts the body only in a sandboxed frame", async () => {
|
||||
mocks.getEmail.mockResolvedValue(EMAIL);
|
||||
const { container } = render(<EmailPage />);
|
||||
expect(await screen.findByRole("heading", { level: 1, name: "Reset Admin Password" })).toBeInTheDocument();
|
||||
expect(mocks.getEmail).toHaveBeenCalledWith(9);
|
||||
expect(screen.getByText("sales1@example.com")).toBeInTheDocument();
|
||||
expect(screen.getByText("30/11/2026 11:44")).toBeInTheDocument();
|
||||
expect(screen.getByText("Success")).toBeInTheDocument();
|
||||
const frame = screen.getByTitle("Email body") as HTMLIFrameElement;
|
||||
expect(frame.getAttribute("sandbox")).toBe("");
|
||||
expect(frame.getAttribute("srcdoc")).toBe(EMAIL.body);
|
||||
// The body never becomes part of the portal's own DOM.
|
||||
expect(container.textContent).not.toContain("Xy7kPq2m");
|
||||
expect((window as unknown as { pwned?: number }).pwned).toBeUndefined();
|
||||
});
|
||||
|
||||
it("shows not-found for a 404", async () => {
|
||||
mocks.getEmail.mockRejectedValue(new ApiError("Email not found", 404, { code: "EMAIL_NOT_FOUND" }));
|
||||
render(<EmailPage />);
|
||||
expect(await screen.findByText("Email not found")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the super-admin refusal for a 403", async () => {
|
||||
mocks.getEmail.mockRejectedValue(new ApiError("Only a super admin can read this email", 403, { code: "SUPER_ADMIN_REQUIRED" }));
|
||||
render(<EmailPage />);
|
||||
expect(await screen.findByText("Only a super admin can read this email.")).toBeInTheDocument();
|
||||
expect(screen.queryByTitle("Email body")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("treats a non-numeric id as not found without calling the server", async () => {
|
||||
params.id = "abc";
|
||||
render(<EmailPage />);
|
||||
expect(await screen.findByText("Email not found")).toBeInTheDocument();
|
||||
expect(mocks.getEmail).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useParams } from "next/navigation";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { Skeleton } from "@/app/components/ui/skeleton";
|
||||
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { EMAIL_STATUS_KEYS, formatEmailDate, getEmail, type EmailDetail } from "@/app/lib/services/adminEmails";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
// One saved email. The body is HTML, so it only ever goes into an <iframe sandbox="" srcDoc>: no scripts,
|
||||
// no same-origin access, and its CSS cannot restyle the portal. It is never put into the portal's own DOM.
|
||||
function EmailPageContent() {
|
||||
const t = useT();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const [email, setEmail] = useState<EmailDetail | null>(null);
|
||||
const [error, setError] = useState<"notFound" | "superAdmin" | "failed" | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const emailId = Number(id);
|
||||
if (!Number.isInteger(emailId) || emailId <= 0) {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- a malformed id in the URL is known at once; there is nothing to fetch.
|
||||
setError("notFound");
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
getEmail(emailId)
|
||||
.then((e) => { if (!cancelled) setEmail(e); })
|
||||
.catch((err: unknown) => {
|
||||
if (cancelled) return;
|
||||
const status = err instanceof ApiError ? err.status : 0;
|
||||
setError(status === 404 ? "notFound" : status === 403 ? "superAdmin" : "failed");
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [id]);
|
||||
|
||||
const back = (
|
||||
<Link href="/emails" className="text-primary underline-offset-4 hover:underline">
|
||||
{t("EmlBackToEmails")}
|
||||
</Link>
|
||||
);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("BO_EMAILS")} />
|
||||
{error === "notFound" && <EmptyState title={t("EmlNotFound")} />}
|
||||
{error === "superAdmin" && <ErrorState message={t("EmlSuperAdminOnly")} className="mb-4" />}
|
||||
{error === "failed" && <ErrorState message={t("EmlLoadFailed")} className="mb-4" />}
|
||||
{back}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
if (!email) {
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("BO_EMAILS")} />
|
||||
<Skeleton className="h-64 w-full" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<PageHeader title={email.subject} />
|
||||
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1 text-sm">
|
||||
<dt className="text-muted-foreground">{t("EmlDate")}</dt>
|
||||
<dd>{formatEmailDate(email.datetime)}</dd>
|
||||
<dt className="text-muted-foreground">{t("EmlRecipient")}</dt>
|
||||
<dd className="break-all">{email.recipients.map((r) => r.recipient).join(", ")}</dd>
|
||||
<dt className="text-muted-foreground">{t("EmlSender")}</dt>
|
||||
<dd className="break-all">{email.sender}</dd>
|
||||
<dt className="text-muted-foreground">{t("Status")}</dt>
|
||||
<dd>{t(EMAIL_STATUS_KEYS[email.status] ?? email.status)}</dd>
|
||||
</dl>
|
||||
<iframe
|
||||
title={t("EmlBody")}
|
||||
sandbox=""
|
||||
srcDoc={email.body ?? ""}
|
||||
className="h-96 w-full rounded-md border bg-white"
|
||||
/>
|
||||
{back}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function EmailPage() {
|
||||
return (
|
||||
<RequireModule pathname="/emails">
|
||||
<EmailPageContent />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ listEmails: vi.fn(), useAdminAuth: vi.fn() }));
|
||||
vi.mock("@/app/lib/services/adminEmails", async (importActual) => ({
|
||||
...(await importActual<typeof import("@/app/lib/services/adminEmails")>()),
|
||||
listEmails: mocks.listEmails,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
||||
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import EmailsPage from "./page";
|
||||
|
||||
const ROWS = [
|
||||
{ id: 9, datetime: "2026-11-30T11:44:26", recipients: ["sales1@example.com"], subject: "Reset Admin Password", status: "Y" },
|
||||
{ id: 8, datetime: "2026-11-29T09:05:00", recipients: ["a@example.com", "b@example.com"], subject: "Welcome", status: "N" },
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
memoryRouter.reset("/emails");
|
||||
mocks.listEmails.mockReset().mockResolvedValue({ items: ROWS, total: 2 });
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
|
||||
});
|
||||
|
||||
describe("EmailsPage", () => {
|
||||
it("renders NotAuthorized without BO_EMAILS", () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
|
||||
render(<EmailsPage />);
|
||||
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
|
||||
expect(mocks.listEmails).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("puts the subject link first so it is reachable on a phone", async () => {
|
||||
render(<EmailsPage />);
|
||||
const table = await screen.findByRole("table");
|
||||
const headers = within(table).getAllByRole("columnheader").map((h) => h.textContent);
|
||||
expect(headers).toEqual(["Subject", "Recipient", "Date", "Status"]);
|
||||
});
|
||||
|
||||
it("lists date, recipients, subject and status in the order given, with the subject linking to the detail", async () => {
|
||||
render(<EmailsPage />);
|
||||
const table = await screen.findByRole("table");
|
||||
const rows = within(table).getAllByRole("row").slice(1);
|
||||
expect(rows[0]).toHaveTextContent("30/11/2026 11:44");
|
||||
expect(rows[0]).toHaveTextContent("sales1@example.com");
|
||||
expect(rows[0]).toHaveTextContent("Success");
|
||||
expect(rows[1]).toHaveTextContent("a@example.com, b@example.com");
|
||||
expect(rows[1]).toHaveTextContent("Failed");
|
||||
expect(within(rows[0]).getByRole("link", { name: "Reset Admin Password" })).toHaveAttribute("href", "/emails/9");
|
||||
});
|
||||
|
||||
it("sends the recipient and subject filters", async () => {
|
||||
render(<EmailsPage />);
|
||||
await screen.findByRole("table");
|
||||
await userEvent.type(screen.getByRole("searchbox", { name: "Recipient" }), "sales1");
|
||||
await waitFor(() => expect(mocks.listEmails).toHaveBeenLastCalledWith(expect.objectContaining({ recipient: "sales1" })));
|
||||
await userEvent.type(screen.getByRole("searchbox", { name: "Subject" }), "Reset");
|
||||
await waitFor(() => expect(mocks.listEmails).toHaveBeenLastCalledWith(expect.objectContaining({ recipient: "sales1", subject: "Reset" })));
|
||||
});
|
||||
|
||||
it("asks for the page it shows", async () => {
|
||||
render(<EmailsPage />);
|
||||
await screen.findByRole("table");
|
||||
expect(mocks.listEmails).toHaveBeenCalledWith(expect.objectContaining({ page: 1, pageSize: 20 }));
|
||||
});
|
||||
|
||||
it("asks for the next page when paging forward", async () => {
|
||||
mocks.listEmails.mockResolvedValue({ items: ROWS, total: 45 });
|
||||
render(<EmailsPage />);
|
||||
await screen.findByRole("table");
|
||||
await userEvent.click(screen.getByRole("button", { name: /next/i }));
|
||||
await waitFor(() => expect(mocks.listEmails).toHaveBeenLastCalledWith(expect.objectContaining({ page: 2 })));
|
||||
});
|
||||
|
||||
it("shows an empty state", async () => {
|
||||
mocks.listEmails.mockResolvedValue({ items: [], total: 0 });
|
||||
render(<EmailsPage />);
|
||||
expect(await screen.findByText("No emails found")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { FilterField, FilterPanel, FilterSearch } from "@/app/components/ui/filter-panel";
|
||||
import { DataTable } from "@/app/components/ui/data-table";
|
||||
import { DatePicker } from "@/app/components/ui/date-picker";
|
||||
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 { EMAIL_STATUS_KEYS, formatEmailDate, listEmails, type EmailRow } from "@/app/lib/services/adminEmails";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
// Saved emails, newest first, so a temporary password can be read while no email provider is configured.
|
||||
// The list never carries a body; the detail page shows it in a sandboxed frame.
|
||||
const DEFAULTS = { recipient: "", subject: "", from: "", to: "" };
|
||||
|
||||
function EmailsPageContent() {
|
||||
const t = useT();
|
||||
const { tableRef, pageSize } = useFitPageSize();
|
||||
const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS);
|
||||
const [data, setData] = useState<{ items: EmailRow[]; total: number }>({ items: [], total: 0 });
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
|
||||
|
||||
useEffect(() => {
|
||||
if (pageSize == null) return;
|
||||
let cancelled = false;
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error before the filter/page/reloadKey-triggered fetch below, which is the actual synchronization.
|
||||
setLoading(true);
|
||||
setFailed(false);
|
||||
listEmails({
|
||||
recipient: filters.recipient || undefined,
|
||||
subject: filters.subject || undefined,
|
||||
from: filters.from || undefined,
|
||||
to: filters.to || undefined,
|
||||
page,
|
||||
pageSize,
|
||||
})
|
||||
.then((result) => { if (!cancelled) setData(result); })
|
||||
.catch(() => { if (!cancelled) setFailed(true); })
|
||||
.finally(() => { if (!cancelled) setLoading(false); });
|
||||
return () => { cancelled = true; };
|
||||
}, [filters, page, reloadKey, pageSize]);
|
||||
|
||||
const columns = useMemo<ColumnDef<EmailRow, unknown>[]>(
|
||||
() => [
|
||||
{
|
||||
accessorKey: "subject",
|
||||
header: t("EmlSubject"),
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => (
|
||||
<Link href={`/emails/${row.original.id}`} className="font-medium text-primary underline-offset-4 hover:underline focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
|
||||
{row.original.subject}
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
{ id: "recipients", header: t("EmlRecipient"), enableSorting: false, cell: ({ row }) => row.original.recipients.join(", ") },
|
||||
{ id: "datetime", header: t("EmlDate"), enableSorting: false, cell: ({ row }) => formatEmailDate(row.original.datetime) },
|
||||
{ id: "status", header: t("Status"), enableSorting: false, cell: ({ row }) => t(EMAIL_STATUS_KEYS[row.original.status] ?? row.original.status) },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("BO_EMAILS")} />
|
||||
|
||||
{failed && <ErrorState message={t("EmlListLoadFailed")} onRetry={refetch} className="mb-4" />}
|
||||
|
||||
<FilterPanel activeCount={activeCount} onClear={clear}>
|
||||
<FilterField label={t("EmlRecipient")}>
|
||||
<FilterSearch className="w-full" aria-label={t("EmlRecipient")} value={filters.recipient} onChange={(recipient) => set({ recipient })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("EmlSubject")}>
|
||||
<FilterSearch className="w-full" aria-label={t("EmlSubject")} value={filters.subject} onChange={(subject) => set({ subject })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("EmlFrom")}>
|
||||
<DatePicker aria-label={t("EmlFrom")} value={filters.from} onChange={(from) => set({ from })} max={filters.to || undefined} />
|
||||
</FilterField>
|
||||
<FilterField label={t("EmlTo")}>
|
||||
<DatePicker aria-label={t("EmlTo")} value={filters.to} onChange={(to) => set({ to })} min={filters.from || undefined} />
|
||||
</FilterField>
|
||||
</FilterPanel>
|
||||
|
||||
<DataTable
|
||||
label={t("BO_EMAILS")}
|
||||
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.id)}
|
||||
empty={<EmptyState title={activeCount > 0 ? t("EmlNoMatch") : t("EmlNoEmails")} />}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function EmailsPage() {
|
||||
return (
|
||||
<RequireModule pathname="/emails">
|
||||
<EmailsPageContent />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -289,6 +289,24 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
LeadNotFound: "Lead not found",
|
||||
LeadGetFailed: "Failed to load the lead",
|
||||
BO_LEADS: "Leads",
|
||||
BO_EMAILS: "Emails",
|
||||
EmlDate: "Date",
|
||||
EmlRecipient: "Recipient",
|
||||
EmlSubject: "Subject",
|
||||
EmlSender: "Sender",
|
||||
EmlFrom: "From date",
|
||||
EmlTo: "To date",
|
||||
EmlBody: "Email body",
|
||||
EmlStatusPending: "Pending",
|
||||
EmlStatusFailed: "Failed",
|
||||
EmlStatusSuccess: "Success",
|
||||
EmlNoEmails: "No emails found",
|
||||
EmlNoMatch: "No emails match your filters",
|
||||
EmlListLoadFailed: "Failed to load emails",
|
||||
EmlLoadFailed: "Failed to load the email",
|
||||
EmlNotFound: "Email not found",
|
||||
EmlSuperAdminOnly: "Only a super admin can read this email.",
|
||||
EmlBackToEmails: "Back to emails",
|
||||
LeadsSearch: "Search name, mobile or email",
|
||||
LeadsExportTooLarge: "More than 20,000 rows. Narrow the search or filters.",
|
||||
LeadsEvents: "Events",
|
||||
|
||||
@@ -14,7 +14,8 @@ describe("routeModules", () => {
|
||||
it("leaves other routes ungated", () => {
|
||||
expect(requiredModuleFor("/")).toBeUndefined();
|
||||
expect(requiredModulesFor("/members")).toBeUndefined();
|
||||
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/event-leads", "/events", "/interests", "/leads", "/roles", "/users"]);
|
||||
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/emails", "/event-leads", "/events", "/interests", "/leads", "/roles", "/users"]);
|
||||
expect(requiredModuleFor("/emails")).toBe("BO_EMAILS");
|
||||
expect(requiredModuleFor("/leads")).toBe("BO_LEADS");
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,7 @@ export const ROUTE_MODULES: Record<string, string> = {
|
||||
"/interests": "BO_INTERESTS",
|
||||
"/event-leads": "BO_EVENT_LEADS",
|
||||
"/leads": "BO_LEADS",
|
||||
"/emails": "BO_EMAILS",
|
||||
};
|
||||
|
||||
export function requiredModuleFor(pathname: string): string | undefined {
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ apiGet: vi.fn() }));
|
||||
vi.mock("@/app/lib/clientApi", () => ({ apiGet: mocks.apiGet }));
|
||||
|
||||
import { getEmail, listEmails } from "./adminEmails";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.apiGet.mockReset();
|
||||
});
|
||||
|
||||
describe("listEmails", () => {
|
||||
it("sends only the given filters with a 0-based page", async () => {
|
||||
mocks.apiGet.mockResolvedValue({ content: [{ id: 7 }], totalElements: 12 });
|
||||
const out = await listEmails({ recipient: "sales1", from: "2026-11-01", page: 2, pageSize: 10 });
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/emails?recipient=sales1&from=2026-11-01&page=1&size=10");
|
||||
expect(out).toEqual({ items: [{ id: 7 }], total: 12 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("getEmail", () => {
|
||||
it("GETs one email by id", async () => {
|
||||
mocks.apiGet.mockResolvedValue({ id: 7 });
|
||||
await getEmail(7);
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/emails/7");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { apiGet } from "@/app/lib/clientApi";
|
||||
|
||||
/** One saved email in the list; the body is never part of it. */
|
||||
export interface EmailRow {
|
||||
id: number;
|
||||
/** Server-local "yyyy-MM-ddTHH:mm:ss". */
|
||||
datetime: string;
|
||||
recipients: string[];
|
||||
subject: string;
|
||||
/** P pending, N failed, Y success. */
|
||||
status: string;
|
||||
}
|
||||
|
||||
export interface EmailDetail extends Omit<EmailRow, "recipients"> {
|
||||
sender: string;
|
||||
recipients: { recipient: string; type: string | null }[];
|
||||
body: string;
|
||||
}
|
||||
|
||||
export interface EmailListParams {
|
||||
recipient?: string;
|
||||
subject?: string;
|
||||
/** "yyyy-MM-dd". */
|
||||
from?: string;
|
||||
to?: string;
|
||||
/** 1-based. */
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
export async function listEmails(params: EmailListParams): Promise<{ items: EmailRow[]; total: number }> {
|
||||
const qs = new URLSearchParams();
|
||||
for (const key of ["recipient", "subject", "from", "to"] as const) if (params[key]) qs.set(key, params[key]);
|
||||
qs.set("page", String(Math.max(0, params.page - 1)));
|
||||
qs.set("size", String(params.pageSize));
|
||||
const raw = await apiGet<{ content?: EmailRow[]; totalElements?: number } | null>(`/api/emails?${qs}`);
|
||||
const items = Array.isArray(raw?.content) ? raw.content : [];
|
||||
return { items, total: typeof raw?.totalElements === "number" ? raw.totalElements : items.length };
|
||||
}
|
||||
|
||||
export const getEmail = (id: number) => apiGet<EmailDetail>(`/api/emails/${id}`);
|
||||
|
||||
/** "2026-11-30T11:44:26" → "30/11/2026 11:44" (server-local time, shown as is). */
|
||||
export function formatEmailDate(datetime: string): string {
|
||||
const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(datetime ?? "");
|
||||
return m ? `${m[3]}/${m[2]}/${m[1]} ${m[4]}:${m[5]}` : (datetime ?? "");
|
||||
}
|
||||
|
||||
export const EMAIL_STATUS_KEYS: Record<string, string> = { P: "EmlStatusPending", N: "EmlStatusFailed", Y: "EmlStatusSuccess" };
|
||||
Reference in new issue
Block a user