From 0904808e81fdbef0595e108d043dcd488d771ac7 Mon Sep 17 00:00:00 2001 From: ngqile Date: Mon, 30 Nov 2026 12:05:21 +0800 Subject: [PATCH] feat(portal): Emails list and detail, with the body in a sandboxed frame Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../app/api/emails/[[...path]]/route.test.ts | 46 +++++++ .../app/api/emails/[[...path]]/route.ts | 18 +++ .../app/design-tokens.test.ts | 2 + .../app/emails/[id]/page.test.tsx | 75 ++++++++++++ solvway-admin-portal/app/emails/[id]/page.tsx | 97 +++++++++++++++ solvway-admin-portal/app/emails/page.test.tsx | 82 +++++++++++++ solvway-admin-portal/app/emails/page.tsx | 114 ++++++++++++++++++ .../app/lib/i18n/defaultMessages.ts | 18 +++ .../app/lib/routeModules.test.ts | 3 +- solvway-admin-portal/app/lib/routeModules.ts | 1 + .../app/lib/services/adminEmails.test.ts | 27 +++++ .../app/lib/services/adminEmails.ts | 49 ++++++++ 12 files changed, 531 insertions(+), 1 deletion(-) create mode 100644 solvway-admin-portal/app/api/emails/[[...path]]/route.test.ts create mode 100644 solvway-admin-portal/app/api/emails/[[...path]]/route.ts create mode 100644 solvway-admin-portal/app/emails/[id]/page.test.tsx create mode 100644 solvway-admin-portal/app/emails/[id]/page.tsx create mode 100644 solvway-admin-portal/app/emails/page.test.tsx create mode 100644 solvway-admin-portal/app/emails/page.tsx create mode 100644 solvway-admin-portal/app/lib/services/adminEmails.test.ts create mode 100644 solvway-admin-portal/app/lib/services/adminEmails.ts diff --git a/solvway-admin-portal/app/api/emails/[[...path]]/route.test.ts b/solvway-admin-portal/app/api/emails/[[...path]]/route.test.ts new file mode 100644 index 0000000..d0f3358 --- /dev/null +++ b/solvway-admin-portal/app/api/emails/[[...path]]/route.test.ts @@ -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[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" }); + }); +}); diff --git a/solvway-admin-portal/app/api/emails/[[...path]]/route.ts b/solvway-admin-portal/app/api/emails/[[...path]]/route.ts new file mode 100644 index 0000000..0e5b4bf --- /dev/null +++ b/solvway-admin-portal/app/api/emails/[[...path]]/route.ts @@ -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(target, { token }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} diff --git a/solvway-admin-portal/app/design-tokens.test.ts b/solvway-admin-portal/app/design-tokens.test.ts index 099f9d3..62c3371 100644 --- a/solvway-admin-portal/app/design-tokens.test.ts +++ b/solvway-admin-portal/app/design-tokens.test.ts @@ -25,6 +25,8 @@ const ALLOW: Record = { // 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"], }; diff --git a/solvway-admin-portal/app/emails/[id]/page.test.tsx b/solvway-admin-portal/app/emails/[id]/page.test.tsx new file mode 100644 index 0000000..e612a90 --- /dev/null +++ b/solvway-admin-portal/app/emails/[id]/page.test.tsx @@ -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()), + 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: "

Hi sales1,

Your temporary password: Xy7kPq2m

", +}; + +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(); + 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(); + 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(); + 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(); + 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(); + expect(await screen.findByText("Email not found")).toBeInTheDocument(); + expect(mocks.getEmail).not.toHaveBeenCalled(); + }); +}); diff --git a/solvway-admin-portal/app/emails/[id]/page.tsx b/solvway-admin-portal/app/emails/[id]/page.tsx new file mode 100644 index 0000000..4085eaa --- /dev/null +++ b/solvway-admin-portal/app/emails/[id]/page.tsx @@ -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