Files
accounted/app/api/payslip/[token]/pdf/route.ts
T
f266c386f3 chore: repo-wide bloat sweep, remove dead code and fold duplicate helpers (#2150)
* chore: repo-wide bloat sweep, remove dead code and fold duplicate helpers

Remove 33 dead files, ~270 unreferenced exports/types, 13 dead i18n
namespaces and 4 unused dependencies; fold byte-identical helper copies
into one canonical home each (lib/utils chunk/sleep/utcDateStamp,
lib/dates/iso, lib/invariants/uuid, lib/xml/escape, lib/reports/sru/format,
lib/pdf/number-text, lib/browser/panel-request, lib/api/v1/body +
v1ValidationError rolled out to ~55 v1 routes, booking-template schemas).

No behaviour change: v1 bodies and status codes, MCP tool schemas, DB
writes and money math are untouched. Naive ore rounding was deliberately
not swapped for roundOre; see DECISIONS.md 2026-09-02 for the full list
of things left alone on purpose.

tsc, lint, 19588 unit tests and check:guards green; antipattern baseline
ratcheted (naive-ore-round 622 -> 620, hand-rolled-invariant 115 -> 113).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test(transactions): import RawTransaction from @/types after the ingest re-export removal

CI's type ratchet (check:types, full tsconfig) caught the one test file
that still imported the type through lib/transactions/ingest.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-02 11:51:16 +02:00

111 lines
3.8 KiB
TypeScript

import { NextResponse } from 'next/server'
import { renderToBuffer } from '@react-pdf/renderer'
import { createServiceClientNoCookies } from '@/lib/auth/api-keys'
import { resolvePayslipToken, isValidPayslipTokenFormat } from '@/lib/salary/payslips/links'
import { buildPayslipData, payslipFileName } from '@/lib/salary/payslips/build-payslip-data'
import { PayslipPDF } from '@/lib/salary/pdf/payslip-template'
import { contentDisposition } from '@/lib/api/content-disposition'
import { createTokenRateLimiter } from '@/lib/api/token-rate-limit'
// 20 requests per minute per token, process-local (same limiter as /api/calendar/feed).
const rateLimiter = createTokenRateLimiter({ max: 20, windowMs: 60_000 })
/**
* GET /api/payslip/[token]/pdf
*
* Public payslip PDF download. The token IS the authentication — the code
* path is the only guard (strict hash equality, revocation/expiry checks,
* per-token rate limit). Salary PII: masked personnummer only, no-store,
* and the raw token is never logged.
*/
export async function GET(
_request: Request,
{ params }: { params: Promise<{ token: string }> },
) {
const { token } = await params
if (!isValidPayslipTokenFormat(token)) {
return new NextResponse('Invalid token', { status: 400 })
}
if (!rateLimiter.allow(token)) {
return new NextResponse('Too many requests', { status: 429 })
}
const serviceClient = createServiceClientNoCookies()
const resolved = await resolvePayslipToken(serviceClient, token)
if (!resolved.ok) {
if (resolved.reason === 'expired' || resolved.reason === 'revoked') {
return new NextResponse('Link no longer valid', { status: 410 })
}
return new NextResponse('Not found', { status: 404 })
}
const { link } = resolved
const [{ data: run }, { data: sre }, { data: company }, { data: settings }] = await Promise.all([
serviceClient
.from('salary_runs')
.select('*')
.eq('id', link.salary_run_id)
.eq('company_id', link.company_id)
.single(),
serviceClient
.from('salary_run_employees')
.select('*, employee:employees(first_name, last_name, personnummer, employment_type, tax_table_number, tax_column, clearing_number, bank_account_number), line_items:salary_line_items(*)')
.eq('salary_run_id', link.salary_run_id)
.eq('employee_id', link.employee_id)
.single(),
serviceClient
.from('companies')
.select('name, org_number')
.eq('id', link.company_id)
.single(),
serviceClient
.from('company_settings')
.select('company_name')
.eq('company_id', link.company_id)
.maybeSingle(),
])
if (!run || !sre || !company) {
return new NextResponse('Not found', { status: 404 })
}
const emp = sre.employee as unknown as {
first_name: string
last_name: string
personnummer: string
employment_type: string
tax_table_number: number | null
tax_column: number
clearing_number: string | null
bank_account_number: string | null
}
// Employer name follows the current company_settings.company_name, falling
// back to the frozen onboarding companies.name.
const data = buildPayslipData({
run,
sre,
employee: emp,
company: { name: settings?.company_name || company.name, org_number: company.org_number },
})
const fileName = payslipFileName(run, emp)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const buffer = await renderToBuffer(PayslipPDF({ data }) as any)
return new Response(buffer as unknown as BodyInit, {
headers: {
'Content-Type': 'application/pdf',
// RFC 5987 dual form: employee names with non-Latin-1 characters
// (e.g. NFD combining marks) would otherwise make undici reject
// the header value and crash the response.
'Content-Disposition': contentDisposition('attachment', fileName),
'Cache-Control': 'no-store',
},
})
}