diff --git a/build-battle/merchant-console/src/app/api/payments/export/route.test.ts b/build-battle/merchant-console/src/app/api/payments/export/route.test.ts new file mode 100644 index 00000000..b9d6a9aa --- /dev/null +++ b/build-battle/merchant-console/src/app/api/payments/export/route.test.ts @@ -0,0 +1,122 @@ +import { describe, expect, it } from "vitest" +import { NextRequest } from "next/server" +import { filterPayments, parseFilters } from "@/data/queries" +import { EXPORT_COLUMNS } from "@/lib/csv" +import { GET } from "./route" + +/** + * The export route is the boundary where client input meets the file ops + * hands to a merchant, so the validation and the defaults are pinned here. + */ + +const call = (query = "") => + GET(new NextRequest(`http://localhost/api/payments/export${query}`)) + +const header = (csv: string) => csv.split("\n")[0].split(",") + +/** Payment ids in the file. Ids carry no commas or newlines, so lines are safe to split. */ +const ids = (csv: string) => csv.split("\n").slice(1) + +const expectedIds = (query: string) => + filterPayments(parseFilters(new URLSearchParams(query))).map((p) => p.id) + +describe("GET /api/payments/export", () => { + it("leaves out card last four when no columns are requested", async () => { + const res = await call() + expect(res.status).toBe(200) + expect(res.headers.get("content-type")).toBe("text/csv; charset=utf-8") + + const csv = await res.text() + expect(header(csv)).toEqual(EXPORT_COLUMNS.filter((c) => c !== "last4")) + }) + + it("includes last four only when it is asked for by name", async () => { + const csv = await (await call("?columns=id,last4")).text() + expect(header(csv)).toEqual(["id", "last4"]) + }) + + it("exports only the requested columns, in file order", async () => { + const csv = await (await call("?columns=amount,id")).text() + expect(header(csv)).toEqual(["id", "amount"]) + }) + + it.each([ + ["an unknown column", "?columns=pan"], + ["one unknown among known columns", "?columns=id,evil"], + ["a column in the wrong case", "?columns=ID"], + ["an empty selection", "?columns="], + ["only separators", "?columns=,,"], + ])("returns 400 with a message for %s", async (_label, query) => { + const res = await call(query) + expect(res.status).toBe(400) + const body = await res.json() + expect(typeof body.error).toBe("string") + expect(body.error.length).toBeGreaterThan(0) + }) + + it("returns 400 for a scope that is not allowlisted", async () => { + const res = await call("?scope=everything") + expect(res.status).toBe(400) + expect(typeof (await res.json()).error).toBe("string") + }) + + it("honors the filters when the scope is filtered, which is the default", async () => { + const query = "status=disputed" + const expected = expectedIds(query) + expect(expected.length).toBeGreaterThan(0) + + for (const suffix of ["", "&scope=filtered"]) { + const csv = await (await call(`?columns=id&${query}${suffix}`)).text() + expect(ids(csv)).toHaveLength(expected.length) + expect(new Set(ids(csv))).toEqual(new Set(expected)) + } + }) + + it("exports every payment when the scope is all, ignoring the filters", async () => { + const everything = expectedIds("") + const filtered = expectedIds("status=disputed") + expect(everything.length).toBeGreaterThan(filtered.length) + + const csv = await ( + await call("?columns=id&scope=all&status=disputed&merchantId=mch_01") + ).text() + expect(ids(csv)).toHaveLength(everything.length) + expect(new Set(ids(csv))).toEqual(new Set(everything)) + }) + + it("does not paginate the file", async () => { + const csv = await (await call("?columns=id&page=2")).text() + expect(ids(csv)).toHaveLength(expectedIds("").length) + }) + + describe("filename", () => { + const disposition = async (query: string) => + (await call(query)).headers.get("content-disposition") + const today = new Date().toISOString().slice(0, 10) + + it("names an all-payments export as such", async () => { + expect(await disposition("?scope=all&status=disputed")).toBe( + `attachment; filename="payments-all-${today}.csv"`, + ) + }) + + it("puts the validated status in the name", async () => { + expect(await disposition("?status=disputed")).toBe( + `attachment; filename="payments-disputed-${today}.csv"`, + ) + }) + + it("never puts a client-supplied merchant id or search text in the name", async () => { + const value = await disposition( + `?status=captured&merchantId=${encodeURIComponent('x"; evil.exe')}&search=secret`, + ) + expect(value).toBe(`attachment; filename="payments-captured-${today}.csv"`) + }) + + it("falls back to 'filtered' when only a search is active", async () => { + expect(await disposition("?search=refund")).toBe( + `attachment; filename="payments-filtered-${today}.csv"`, + ) + }) + }) +}) diff --git a/build-battle/merchant-console/src/app/api/payments/export/route.ts b/build-battle/merchant-console/src/app/api/payments/export/route.ts index 1869bbca..dce55cce 100644 --- a/build-battle/merchant-console/src/app/api/payments/export/route.ts +++ b/build-battle/merchant-console/src/app/api/payments/export/route.ts @@ -1,25 +1,55 @@ import { filterPayments, parseFilters, sortPayments } from "@/data/queries" -import { exportFilename, toCsv } from "@/lib/csv" +import { exportFilename, parseExportColumns, toCsv } from "@/lib/csv" import { NextRequest } from "next/server" +const SCOPES = ["filtered", "all"] as const +type Scope = (typeof SCOPES)[number] + +function badRequest(message: string) { + return Response.json({ error: message }, { status: 400 }) +} + /** * Exports the payments table as CSV. * - * Honors the active filters and reuses the query builder, but the column set - * and the scope are fixed. Giving ops control over both is NWP-101. + * Query params, on top of the usual filters: + * - `columns`: comma-separated, checked against EXPORT_COLUMNS. Absent means + * every column except last four; empty or unknown names are a 400. + * - `scope`: `filtered` (default) uses the request's filters; `all` ignores + * them and exports every payment, newest first. + * + * Rows always come from the shared query builder, unpaginated. */ export function GET(request: NextRequest) { - const filters = parseFilters(request.nextUrl.searchParams) + const params = request.nextUrl.searchParams + + const columns = parseExportColumns(params.get("columns")) + if (!columns.ok) return badRequest(columns.error) + + const rawScope = params.get("scope") ?? "filtered" + if (!SCOPES.includes(rawScope as Scope)) { + return badRequest("Scope must be \"filtered\" or \"all\".") + } + const scope = rawScope as Scope + + const filters = parseFilters(scope === "all" ? new URLSearchParams() : params) const rows = sortPayments( filterPayments(filters), filters.sort, filters.direction, ) - return new Response(toCsv(rows), { + const filename = exportFilename( + new Date(), + scope === "all" + ? { scope: "all" } + : { scope: "filtered", status: filters.status, merchantId: filters.merchantId }, + ) + + return new Response(toCsv(rows, columns.columns), { headers: { "content-type": "text/csv; charset=utf-8", - "content-disposition": `attachment; filename="${exportFilename()}"`, + "content-disposition": `attachment; filename="${filename}"`, }, }) } diff --git a/build-battle/merchant-console/src/app/payments/export-dialog.tsx b/build-battle/merchant-console/src/app/payments/export-dialog.tsx new file mode 100644 index 00000000..343fe671 --- /dev/null +++ b/build-battle/merchant-console/src/app/payments/export-dialog.tsx @@ -0,0 +1,175 @@ +"use client" + +import { Button } from "@/components/Button" +import { + Drawer, + DrawerBody, + DrawerClose, + DrawerContent, + DrawerDescription, + DrawerFooter, + DrawerHeader, + DrawerTitle, + DrawerTrigger, +} from "@/components/Drawer" +import type { ExportColumn } from "@/lib/csv" +import { Download } from "lucide-react" +import { useState } from "react" + +const COLUMN_LABELS: Record = { + id: "Payment ID", + created_at: "Created (UTC)", + merchant: "Merchant", + description: "Description", + status: "Status", + method: "Method", + card_brand: "Card brand", + last4: "Card last four", + amount: "Amount", + currency: "Currency", +} + +type Scope = "filtered" | "all" + +/** + * Options for the payments CSV export: which columns, and whether to export + * the current filter or every payment. The file itself is built by + * `GET /api/payments/export`, which validates both choices again. + */ +export function ExportDialog({ + query, + columns, + defaultColumns, + counts, +}: { + /** The page's current filter params, without `page`. */ + query: string + /** Every exportable column, in file order. */ + columns: readonly ExportColumn[] + /** The columns checked when the dialog opens. */ + defaultColumns: readonly ExportColumn[] + /** Rows each scope will export. */ + counts: Record +}) { + const [selected, setSelected] = useState>( + () => new Set(defaultColumns), + ) + const [scope, setScope] = useState("filtered") + + const toggle = (column: ExportColumn) => + setSelected((current) => { + const next = new Set(current) + if (next.has(column)) next.delete(column) + else next.add(column) + return next + }) + + const chosen = columns.filter((column) => selected.has(column)) + const params = new URLSearchParams(scope === "filtered" ? query : "") + params.set("columns", chosen.join(",")) + params.set("scope", scope) + const href = `/api/payments/export?${params.toString()}` + + const scopes: { value: Scope; label: string }[] = [ + { value: "filtered", label: "Current filter" }, + { value: "all", label: "All payments" }, + ] + + return ( + + + + + + + Export payments + + Choose what goes in the CSV before you download it. + + + + +
+ + Scope + +
+ {scopes.map(({ value, label }) => ( + + ))} +
+
+ +
+ + Columns + +
+ {columns.map((column) => ( + + ))} +
+ {chosen.length === 0 && ( +

+ Choose at least one column to download. +

+ )} +
+
+ + + + + + {chosen.length === 0 ? ( + + ) : ( + + )} + +
+
+ ) +} diff --git a/build-battle/merchant-console/src/app/payments/page.tsx b/build-battle/merchant-console/src/app/payments/page.tsx index f97f4896..6e6d8ec9 100644 --- a/build-battle/merchant-console/src/app/payments/page.tsx +++ b/build-battle/merchant-console/src/app/payments/page.tsx @@ -10,12 +10,13 @@ import { } from "@/components/Table" import { StatusBadge } from "@/components/ui/payments/StatusBadge" import { merchantById, merchants } from "@/data/merchants" -import { queryPayments } from "@/data/queries" +import { parseFilters, queryPayments } from "@/data/queries" import { PaymentFilters, PaymentStatus } from "@/data/types" +import { DEFAULT_EXPORT_COLUMNS, EXPORT_COLUMNS } from "@/lib/csv" import { formatDate } from "@/lib/dates" import { formatMoney } from "@/lib/money" -import { Download } from "lucide-react" import Link from "next/link" +import { ExportDialog } from "./export-dialog" import { PaymentsFilterBar } from "./filter-bar" const STATUSES: (PaymentStatus | "all")[] = [ @@ -47,6 +48,15 @@ export default async function PaymentsPage({ Object.entries(params).filter(([, v]) => Boolean(v)) as [string, string][], ) + // The export reads its filters with parseFilters, so the counts shown in the + // dialog do too: the number on screen is the number of rows in the file. + const exportQuery = new URLSearchParams(query) + exportQuery.delete("page") + const exportCounts = { + filtered: queryPayments(parseFilters(exportQuery)).total, + all: queryPayments(parseFilters(new URLSearchParams())).total, + } + const pageHref = (next: number) => { const q = new URLSearchParams(query) q.set("page", String(next)) @@ -65,15 +75,12 @@ export default async function PaymentsPage({ search: filters.search ?? "", }} /> - + diff --git a/build-battle/merchant-console/src/components/Drawer.tsx b/build-battle/merchant-console/src/components/Drawer.tsx index fc9a5539..85114676 100644 --- a/build-battle/merchant-console/src/components/Drawer.tsx +++ b/build-battle/merchant-console/src/components/Drawer.tsx @@ -112,6 +112,7 @@ const DrawerHeader = React.forwardRef<