feat(api): v1 invoice PDF + customer bulk-create (Phase 2 PR-B-3) (#460)

Closes out the Phase 2 invoices+customers vertical. After this PR, every
write/read the dashboard does on these two resources is reachable via the
public API.

GET /api/v1/companies/{companyId}/invoices/{id}/pdf
  Read-only application/pdf endpoint. Mirrors the dashboard's internal
  /api/invoices/[id]/pdf so a downloaded PDF is byte-equivalent across
  surfaces. Drafts render with the "faktura-utkast-<id-slice>.pdf"
  filename (preview before send is a legitimate workflow); sent invoices
  use "faktura-<number>.pdf"; credit notes use "kreditfaktura-<number>.pdf"
  and embed the original invoice's löpnummer per ML 17 kap 22–23§
  back-reference; proforma + delivery notes get their own prefixes.

  Error codes: INVOICE_PDF_RENDER_FAILED (500, new),
  INVOICE_SEND_COMPANY_SETTINGS_MISSING (404, reused — same condition,
  same remediation).

POST /api/v1/companies/{companyId}/customers/bulk-create
  Mirrors /invoices/bulk-create exactly: same `{ results, summary }`
  shape, same all_or_nothing: true → 501 NOT_IMPLEMENTED contract, same
  50-item cap, same sequential processing. Per-item rollback isn't
  needed (customer insert is a single row), but per-item 23505 →
  CUSTOMER_DUPLICATE_ORG_NUMBER failure surfaces in the results array
  without echoing org_number (GDPR Art.5(1)(c): for sole traders
  org_number IS the personnummer). VIES validation runs per item,
  best-effort — a timeout leaves vat_number_validated=false but does
  NOT fail the item.

Registry: extended EndpointDefinition.response with an optional
  `contentType` field so the OpenAPI generator can emit
  `format: binary` schemas for non-JSON responses. The PDF endpoint is
  the first consumer; future binary endpoints (SIE export, ICS feeds)
  use the same hook.

Scope catalogue: added GET .../pdf → invoices:read,
  POST .../customers/bulk-create → customers:write.

Tests: 14 new integration cases (7 for PDF: sent / draft / credit-note
filename, 404, render-error 500, non-UUID 400, scope rejection; 7 for
customer bulk-create: happy path, dup-org error masking, max-50 cap,
all_or_nothing 501, dry-run preview, empty array, scope rejection).
Suite green: 3232 passing. Build + lint clean.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-05-13 10:53:51 +02:00
committed by GitHub
co-authored by Claude Opus 4.7
parent 64e6aa67a7
commit 01e99d3220
8 changed files with 1070 additions and 2 deletions
+3
View File
@@ -26,5 +26,8 @@ import '@/app/api/v1/companies/[companyId]/invoices/[id]/mark-paid/route'
import '@/app/api/v1/companies/[companyId]/invoices/[id]/credit/route'
import '@/app/api/v1/companies/[companyId]/invoices/[id]/send/route'
import '@/app/api/v1/companies/[companyId]/invoices/bulk-create/route'
// Phase 2 PR-B-3 — invoice PDF + customer bulk-create.
import '@/app/api/v1/companies/[companyId]/invoices/[id]/pdf/route'
import '@/app/api/v1/companies/[companyId]/customers/bulk-create/route'
export {}
+16 -2
View File
@@ -80,6 +80,15 @@ export interface EndpointDefinition {
success: ZodTypeAny
/** Stable error codes this endpoint can emit (cross-referenced with the docs). */
errorCodes?: string[]
/**
* Override the default 'application/json' content type for non-JSON
* responses (e.g. binary downloads). When set to 'application/pdf', the
* OpenAPI generator emits a `{ type: 'string', format: 'binary' }` schema
* instead of deriving from `success`. The `success` schema is still
* required (use `z.unknown()` as a marker) so existing registry consumers
* don't need to handle a missing field.
*/
contentType?: string
}
}
@@ -238,7 +247,12 @@ export function generateOpenApiSpec(serverUrl: string): OpenApiSpec {
// OpenAPI path syntax: {param} instead of :param.
const openApiPath = def.path.replace(/:([^/]+)/g, '{$1}')
const responseSchema = zodToJsonSchema(def.response.success)
// Binary responses (e.g. application/pdf) declare a `format: binary`
// schema rather than deriving from the Zod success type.
const successContent = def.response.contentType && def.response.contentType !== 'application/json'
? { [def.response.contentType]: { schema: { type: 'string', format: 'binary' } } }
: { 'application/json': { schema: zodToJsonSchema(def.response.success) } }
const operationDef: Record<string, unknown> = {
operationId: def.operation,
summary: def.summary,
@@ -257,7 +271,7 @@ export function generateOpenApiSpec(serverUrl: string): OpenApiSpec {
responses: {
'200': {
description: 'Success',
content: { 'application/json': { schema: responseSchema } },
content: successContent,
},
'400': { description: 'Validation error', $ref: '#/components/responses/Error' },
'401': { description: 'Unauthorized', $ref: '#/components/responses/Error' },
+3
View File
@@ -65,6 +65,9 @@ export const V1_ENDPOINT_SCOPES: Record<string, ApiKeyScope> = {
'POST /api/v1/companies/:companyId/invoices/:id/credit': 'invoices:write',
'POST /api/v1/companies/:companyId/invoices/:id/send': 'invoices:write',
'POST /api/v1/companies/:companyId/invoices/bulk-create': 'invoices:write',
// Phase 2 PR-B-3 — invoice PDF + customer bulk-create.
'GET /api/v1/companies/:companyId/invoices/:id/pdf': 'invoices:read',
'POST /api/v1/companies/:companyId/customers/bulk-create': 'customers:write',
// Webhooks (Phase 6 — placeholder so the catalogue is complete)
'GET /api/v1/companies/:companyId/webhooks': 'webhooks:manage',
+5
View File
@@ -461,6 +461,11 @@ const INVOICE: Record<string, StructuredErrorEntry> = {
'Fakturans PDF kunde inte skapas. Kontrollera fakturarader och kunduppgifter och försök igen.',
message_en: 'Failed to render invoice PDF before send; no invoice number was consumed.',
},
INVOICE_PDF_RENDER_FAILED: {
httpStatus: 500,
message_sv: 'Fakturans PDF kunde inte skapas.',
message_en: 'Invoice PDF rendering failed.',
},
INVOICE_SEND_PARTIAL: {
httpStatus: 200,
message_sv: