Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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"`,
)
})
})
})
42 changes: 36 additions & 6 deletions build-battle/merchant-console/src/app/api/payments/export/route.ts
Original file line number Diff line number Diff line change
@@ -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}"`,
},
})
}
175 changes: 175 additions & 0 deletions build-battle/merchant-console/src/app/payments/export-dialog.tsx
Original file line number Diff line number Diff line change
@@ -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<ExportColumn, string> = {
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<Scope, number>
}) {
const [selected, setSelected] = useState<Set<ExportColumn>>(
() => new Set(defaultColumns),
)
const [scope, setScope] = useState<Scope>("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 (
<Drawer>
<DrawerTrigger asChild>
<Button variant="secondary" className="w-full gap-2 py-1.5 sm:w-fit">
<Download
className="-ml-0.5 size-4 shrink-0 text-gray-400 dark:text-gray-600"
aria-hidden="true"
/>
Export
</Button>
</DrawerTrigger>
<DrawerContent>
<DrawerHeader>
<DrawerTitle>Export payments</DrawerTitle>
<DrawerDescription>
Choose what goes in the CSV before you download it.
</DrawerDescription>
</DrawerHeader>

<DrawerBody className="space-y-6">
<fieldset>
<legend className="text-sm font-medium text-gray-900 dark:text-gray-50">
Scope
</legend>
<div className="mt-2 space-y-2">
{scopes.map(({ value, label }) => (
<label
key={value}
className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300"
>
<input
type="radio"
name="export-scope"
value={value}
checked={scope === value}
onChange={() => setScope(value)}
className="size-4 accent-blue-500"
/>
<span>
{label}{" "}
<span className="text-gray-500">
({counts[value].toLocaleString()}{" "}
{counts[value] === 1 ? "payment" : "payments"})
</span>
</span>
</label>
))}
</div>
</fieldset>

<fieldset>
<legend className="text-sm font-medium text-gray-900 dark:text-gray-50">
Columns
</legend>
<div className="mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2">
{columns.map((column) => (
<label
key={column}
className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300"
>
<input
type="checkbox"
name="export-columns"
value={column}
checked={selected.has(column)}
onChange={() => toggle(column)}
className="size-4 accent-blue-500"
/>
{COLUMN_LABELS[column]}
</label>
))}
</div>
{chosen.length === 0 && (
<p role="status" className="mt-3 text-sm text-red-600 dark:text-red-500">
Choose at least one column to download.
</p>
)}
</fieldset>
</DrawerBody>

<DrawerFooter className="gap-2 sm:gap-0">
<DrawerClose asChild>
<Button variant="secondary">Cancel</Button>
</DrawerClose>
{chosen.length === 0 ? (
<Button disabled>Download CSV</Button>
) : (
<Button asChild>
<a href={href} download>
Download CSV
</a>
</Button>
)}
</DrawerFooter>
</DrawerContent>
</Drawer>
)
}
Loading