fix(customers): personnummer guard + personal_number on v1 + payment terms from settings (#1724)
* fix(customers): stop personnummer landing unmasked as org_number, persist personal_number on v1, default payment terms from settings
Closes #1707. Closes #1708.
Personnummer (#1707, Discord kalletoxic):
- CreateCustomerSchema rejects an org_number shaped like a Swedish
personal identity number on business customer_types. Only
customer_type=individual rows are masked in lists, so accepting one
stored an unmasked personal identifier (GDPR art. 5.1 c). The shape
check uses the month-position rule (legal-entity orgnr always
carries >= 20), so real orgnr can never false-positive.
- The v1 create, v1 PATCH and bulk-create endpoints accepted
personal_number through the shared schema but silently dropped it.
They now store it encrypted, expose it masked (********-1234) on the
single-customer surfaces, and treat the masked form as unchanged,
mirroring the internal routes.
- Route-level guards on both PATCH routes (new 400
CUSTOMER_ORG_NUMBER_IS_PERSONAL) plus a client-side message in
CustomerForm (sv + en).
Payment terms (#1708, Discord kalletoxic):
- New resolveDefaultPaymentTerms: provided value, else
company_settings.invoice_default_days, else 30. Wired into the UI
new-customer dialog, the internal POST, v1 create (incl. dry-run),
bulk-create and the MCP staged create_customer.
apiskill regenerated; no migrations.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: record what the CI build OOM actually was
main raised the build heap to 8192 in parallel with this branch, so the
fix itself is already in and this keeps it untouched. What was missing
is the diagnosis.
Measured with tsc --noEmit --extendedDiagnostics, type-checking the repo
needs 4 192 550 K at 506d030b and 4 187 096 K on this branch, 5 MB less
and 0.26% more instantiations. So the ceiling is the type-check pass at
steady state against Node 20's ~4 GB default old-space, not bundle
growth and not any single PR. Worth writing down so the next person who
sees "Ineffective mark-compacts near heap limit" does not go looking for
it in their own diff.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
Jakob Wennberg
parent
9fc05c383f
commit
e6c4fe2cf8
@@ -5,6 +5,7 @@ import { validateVatNumber } from '@/lib/vat/vies-client'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { encryptCustomerPersonalNumber, maskCustomerRow } from '@/lib/customers/protect-personal-number'
|
||||
import { looksLikeSwedishPersonalNumber } from '@/lib/customers/personal-number-shape'
|
||||
import { isMaskedPersonalNumber } from '@/lib/customers/mask-personal-number'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
@@ -95,6 +96,17 @@ export const PATCH = withRouteContext(
|
||||
return errorResponseFromCode('CUSTOMER_PERSONAL_NUMBER_NOT_ALLOWED', opLog, { requestId })
|
||||
}
|
||||
|
||||
// GDPR art. 5.1 c: only customer_type='individual' rows get their
|
||||
// identifiers masked, so a personnummer accepted as a business
|
||||
// org_number would be displayed unmasked everywhere.
|
||||
if (
|
||||
body.org_number &&
|
||||
effectiveType !== 'individual' &&
|
||||
looksLikeSwedishPersonalNumber(body.org_number)
|
||||
) {
|
||||
return errorResponseFromCode('CUSTOMER_ORG_NUMBER_IS_PERSONAL', opLog, { requestId })
|
||||
}
|
||||
|
||||
const updateData: Record<string, unknown> = {}
|
||||
if (body.name !== undefined) updateData.name = body.name
|
||||
if (body.customer_type !== undefined) updateData.customer_type = body.customer_type
|
||||
|
||||
@@ -9,6 +9,7 @@ import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structure
|
||||
import type { Customer } from '@/types'
|
||||
import { encryptCustomerPersonalNumber, maskCustomerRow } from '@/lib/customers/protect-personal-number'
|
||||
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
||||
import { resolveDefaultPaymentTerms } from '@/lib/customers/default-payment-terms'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
ensureInitialized()
|
||||
@@ -57,6 +58,13 @@ export const POST = withRouteContext(
|
||||
if (!result.success) return result.response
|
||||
const body = result.data
|
||||
|
||||
// Unset payment terms follow the company's own default, not a hardcoded 30.
|
||||
const defaultPaymentTerms = await resolveDefaultPaymentTerms(
|
||||
supabase,
|
||||
companyId!,
|
||||
body.default_payment_terms,
|
||||
)
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('customers')
|
||||
.insert({
|
||||
@@ -79,7 +87,7 @@ export const POST = withRouteContext(
|
||||
vat_number: body.vat_number,
|
||||
personal_number: encryptCustomerPersonalNumber(body.personal_number),
|
||||
language: body.language || 'sv',
|
||||
default_payment_terms: body.default_payment_terms || 30,
|
||||
default_payment_terms: defaultPaymentTerms,
|
||||
notes: body.notes,
|
||||
})
|
||||
.select()
|
||||
|
||||
@@ -222,6 +222,7 @@ describe('POST /api/pending-operations/:id/commit', () => {
|
||||
enqueueMany([
|
||||
{ data: pendingOp }, // fetch pending op
|
||||
{ data: { id: 'op-1' } }, // CAS claim
|
||||
{ data: null, error: null }, // company_settings read (payment-terms default)
|
||||
{ data: { id: 'cust-1', name: 'Acme AB' } }, // insert customer
|
||||
{ data: null, error: null }, // update pending op status
|
||||
])
|
||||
|
||||
@@ -21,6 +21,12 @@ import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors'
|
||||
import { UpdateCustomerSchema } from '@/lib/api/schemas'
|
||||
import { validateVatNumber } from '@/lib/vat/vies-client'
|
||||
import {
|
||||
encryptCustomerPersonalNumber,
|
||||
maskCustomerRow,
|
||||
} from '@/lib/customers/protect-personal-number'
|
||||
import { isMaskedPersonalNumber } from '@/lib/customers/mask-personal-number'
|
||||
import { looksLikeSwedishPersonalNumber } from '@/lib/customers/personal-number-shape'
|
||||
|
||||
// v1-only extension: allow PATCH to set archived_at back to null to
|
||||
// un-archive a customer. Restricted to literal `null` so the caller can't
|
||||
@@ -47,6 +53,8 @@ const CustomerDetail = z.object({
|
||||
org_number: z.string().nullable(),
|
||||
vat_number: z.string().nullable(),
|
||||
vat_number_validated: z.boolean(),
|
||||
// Always the masked display form ('********-1234'), never the stored value.
|
||||
personal_number: z.string().nullable(),
|
||||
default_payment_terms: z.number(),
|
||||
notes: z.string().nullable(),
|
||||
archived_at: z.string().nullable(),
|
||||
@@ -60,7 +68,7 @@ const OPEN_INVOICE_STATUSES = ['sent', 'partially_paid', 'overdue']
|
||||
// Explicit projection. Excludes user_id, company_id (internal scoping),
|
||||
// and vat_number_validated_at (internal timestamp not in the public schema).
|
||||
const CUSTOMER_DETAIL_COLUMNS =
|
||||
'id, name, customer_type, customer_number, contact_person, email, phone, invoice_email_cc_addresses, invoice_email_bcc_addresses, address_line1, address_line2, postal_code, city, country, org_number, vat_number, vat_number_validated, default_payment_terms, notes, archived_at, created_at, updated_at'
|
||||
'id, name, customer_type, customer_number, contact_person, email, phone, invoice_email_cc_addresses, invoice_email_bcc_addresses, address_line1, address_line2, postal_code, city, country, org_number, vat_number, vat_number_validated, personal_number, default_payment_terms, notes, archived_at, created_at, updated_at'
|
||||
|
||||
const OPEN_INVOICE_COLUMNS =
|
||||
'id, invoice_number, invoice_date, due_date, status, currency, total, remaining_amount'
|
||||
@@ -79,6 +87,7 @@ registerEndpoint({
|
||||
pitfalls: [
|
||||
'archived_at is non-null when the customer has been soft-deleted; the customer is still queryable by id but excluded from default lists.',
|
||||
'vat_number_validated reflects the last successful VIES check; it can become stale if the EU registry revokes a number.',
|
||||
'personal_number is always returned in the masked form ********-1234; the stored value is encrypted and never leaves the API.',
|
||||
],
|
||||
example: {
|
||||
response: {
|
||||
@@ -202,7 +211,9 @@ export const GET = withApiV1<{ params: Promise<{ companyId: string; id: string }
|
||||
}
|
||||
|
||||
return ok(
|
||||
{ ...customer, ...(invoices !== undefined ? { invoices } : {}) },
|
||||
// The selected row carries personal_number ciphertext; mask before it
|
||||
// leaves the server.
|
||||
{ ...maskCustomerRow(customer as { personal_number?: string | null }), ...(invoices !== undefined ? { invoices } : {}) },
|
||||
{
|
||||
requestId: ctx.requestId,
|
||||
partialExpansions: partialExpansions.length > 0 ? partialExpansions : undefined,
|
||||
@@ -230,6 +241,8 @@ registerEndpoint({
|
||||
'Idempotency-Key is mandatory; calls without it return 400.',
|
||||
'org_number uniqueness is enforced at DB level: 23505 → 409 CUSTOMER_DUPLICATE_ORG_NUMBER.',
|
||||
'VIES re-validation is best-effort and runs only on commit. A VIES timeout does not fail the update.',
|
||||
'personal_number: a plaintext value is stored encrypted (individual customers only); the masked form a read returned (********-1234) means "leave unchanged" and is never stored; null clears it. Changing customer_type away from individual clears any stored personal_number.',
|
||||
'An org_number shaped like a Swedish personnummer is rejected for business customer_types (400 CUSTOMER_ORG_NUMBER_IS_PERSONAL).',
|
||||
],
|
||||
example: {
|
||||
request: { default_payment_terms: 14, notes: 'New payment terms agreed 2026-05-12.' },
|
||||
@@ -292,6 +305,51 @@ export const PATCH = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
}
|
||||
const body = parsed.data
|
||||
|
||||
// Mirrors the internal PATCH route: every read path returns the masked
|
||||
// form ('********-1234', or '********-????' when undecryptable), so a
|
||||
// client PATCHing back what it read carries no new value. A mask must
|
||||
// not be validated, stored, or treated as a clear.
|
||||
const personalNumberSubmitted =
|
||||
body.personal_number !== undefined && !isMaskedPersonalNumber(body.personal_number)
|
||||
|
||||
// The individual-only rule for personal_number and the personnummer
|
||||
// guard on org_number both depend on the customer_type the row will
|
||||
// have after the update; read the stored type when the body is silent.
|
||||
let effectiveType: string | undefined = body.customer_type
|
||||
if (
|
||||
effectiveType === undefined &&
|
||||
((personalNumberSubmitted && body.personal_number) || body.org_number)
|
||||
) {
|
||||
const { data: existing } = await ctx.supabase
|
||||
.from('customers')
|
||||
.select('customer_type')
|
||||
.eq('company_id', ctx.companyId!)
|
||||
.eq('id', customerId)
|
||||
.maybeSingle()
|
||||
effectiveType = (existing as { customer_type?: string } | null)?.customer_type
|
||||
}
|
||||
|
||||
if (personalNumberSubmitted && body.personal_number && effectiveType !== 'individual') {
|
||||
return v1ErrorResponseFromCode('CUSTOMER_PERSONAL_NUMBER_NOT_ALLOWED', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { field: 'personal_number' },
|
||||
})
|
||||
}
|
||||
|
||||
// GDPR art. 5.1 c: only customer_type='individual' rows get their
|
||||
// identifiers masked, so a personnummer accepted as a business
|
||||
// org_number would be displayed unmasked everywhere.
|
||||
if (
|
||||
body.org_number &&
|
||||
effectiveType !== 'individual' &&
|
||||
looksLikeSwedishPersonalNumber(body.org_number)
|
||||
) {
|
||||
return v1ErrorResponseFromCode('CUSTOMER_ORG_NUMBER_IS_PERSONAL', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { field: 'org_number' },
|
||||
})
|
||||
}
|
||||
|
||||
// Build the partial update set. Fields explicitly set to undefined in
|
||||
// the body are not in the resulting object (Zod strips undefined). null
|
||||
// IS allowed and means "clear the field" (or, for archived_at, "un-archive").
|
||||
@@ -323,6 +381,15 @@ export const PATCH = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
if (body.customer_number !== undefined) {
|
||||
updateData.customer_number = body.customer_number || null
|
||||
}
|
||||
if (personalNumberSubmitted) {
|
||||
// Stored as ciphertext; customers_personal_number_check accepts that
|
||||
// shape only (20260726110000).
|
||||
updateData.personal_number = encryptCustomerPersonalNumber(body.personal_number)
|
||||
} else if (body.customer_type !== undefined && body.customer_type !== 'individual') {
|
||||
// The row is becoming a business customer: a personnummer may not
|
||||
// remain stored on it (matches the internal PATCH route).
|
||||
updateData.personal_number = null
|
||||
}
|
||||
|
||||
if (Object.keys(updateData).length === 0) {
|
||||
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
@@ -352,7 +419,7 @@ export const PATCH = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
})
|
||||
}
|
||||
|
||||
return dryRunPreview({ ...current, ...updateData }, { requestId: ctx.requestId, log: ctx.log })
|
||||
return dryRunPreview(maskCustomerRow({ ...(current as Record<string, unknown> & { personal_number?: string | null }), ...updateData }), { requestId: ctx.requestId, log: ctx.log })
|
||||
}
|
||||
|
||||
// Best-effort VIES re-validation if vat_number is changing on an
|
||||
@@ -418,7 +485,7 @@ export const PATCH = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
})
|
||||
}
|
||||
|
||||
return ok(data, { requestId: ctx.requestId })
|
||||
return ok(maskCustomerRow(data as Record<string, unknown> & { personal_number?: string | null }), { requestId: ctx.requestId })
|
||||
},
|
||||
{ requireIdempotencyKey: true },
|
||||
)
|
||||
@@ -509,7 +576,7 @@ export const DELETE = withApiV1<{ params: Promise<{ companyId: string; id: strin
|
||||
}
|
||||
|
||||
return dryRunPreview(
|
||||
{ ...current, archived_at: new Date().toISOString() },
|
||||
maskCustomerRow({ ...(current as Record<string, unknown> & { personal_number?: string | null }), archived_at: new Date().toISOString() }),
|
||||
{ requestId: ctx.requestId, log: ctx.log },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@ vi.mock('@/lib/vat/vies-client', () => ({
|
||||
}))
|
||||
|
||||
import { validateApiKey, createServiceClientNoCookies } from '@/lib/auth/api-keys'
|
||||
import { decryptPersonnummer } from '@/lib/salary/personnummer'
|
||||
import { GET as listCustomers, POST as createCustomer } from '../route'
|
||||
import {
|
||||
GET as getCustomer,
|
||||
@@ -947,3 +948,235 @@ describe('DELETE /api/v1/companies/:companyId/customers/:id', () => {
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
})
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
// personal_number handling + company payment-terms default (#1707, #1708)
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
|
||||
// Synthetic personnummer, never a real one.
|
||||
const TEST_PERSONAL_NUMBER = '19900101-1234'
|
||||
const MASKED_PERSONAL_NUMBER = '********-1234'
|
||||
// Ciphertext shape enforced by customers_personal_number_check (20260726110000).
|
||||
const CIPHERTEXT_SHAPE = /^[0-9a-f]{76,255}$/
|
||||
|
||||
describe('personal_number on the v1 customer surface', () => {
|
||||
it('POST rejects a personnummer-shaped org_number on a business customer', async () => {
|
||||
withWriteScope()
|
||||
const supabaseMock = makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
})
|
||||
mockServiceClient.mockReturnValue(supabaseMock)
|
||||
|
||||
const res = await createCustomer(
|
||||
makePostRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/customers`, {
|
||||
name: 'Enskild Firma X',
|
||||
customer_type: 'swedish_business',
|
||||
org_number: TEST_PERSONAL_NUMBER,
|
||||
}),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('VALIDATION_ERROR')
|
||||
expect(JSON.stringify(body.error.details)).toContain('org_number')
|
||||
// The customers table was never touched (idempotency bookkeeping may be).
|
||||
expect(supabaseMock.from.mock.calls.some((c) => c[0] === 'customers')).toBe(false)
|
||||
})
|
||||
|
||||
it('POST stores personal_number encrypted and returns it masked', async () => {
|
||||
withWriteScope()
|
||||
const supabaseMock = makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
customers: {
|
||||
data: {
|
||||
...SAMPLE_CUSTOMER,
|
||||
customer_type: 'individual',
|
||||
org_number: null,
|
||||
vat_number: null,
|
||||
personal_number: TEST_PERSONAL_NUMBER,
|
||||
},
|
||||
error: null,
|
||||
},
|
||||
})
|
||||
mockServiceClient.mockReturnValue(supabaseMock)
|
||||
|
||||
const res = await createCustomer(
|
||||
makePostRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/customers`, {
|
||||
name: 'Anna Andersson',
|
||||
customer_type: 'individual',
|
||||
personal_number: TEST_PERSONAL_NUMBER,
|
||||
}),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(201)
|
||||
const inserted = supabaseMock.captured.insert[0] as { personal_number?: string | null }
|
||||
expect(inserted.personal_number).toMatch(CIPHERTEXT_SHAPE)
|
||||
expect(decryptPersonnummer(inserted.personal_number!)).toBe(TEST_PERSONAL_NUMBER)
|
||||
const body = await res.json()
|
||||
expect(body.data.personal_number).toBe(MASKED_PERSONAL_NUMBER)
|
||||
})
|
||||
|
||||
it('GET returns personal_number masked, never the stored value', async () => {
|
||||
const supabaseMock = makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
customers: {
|
||||
data: { ...SAMPLE_CUSTOMER, customer_type: 'individual', personal_number: TEST_PERSONAL_NUMBER },
|
||||
error: null,
|
||||
},
|
||||
})
|
||||
mockServiceClient.mockReturnValue(supabaseMock)
|
||||
|
||||
const res = await getCustomer(
|
||||
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/customers/${CUSTOMER_ID}`),
|
||||
detailParams(COMPANY_ID, CUSTOMER_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data.personal_number).toBe(MASKED_PERSONAL_NUMBER)
|
||||
})
|
||||
|
||||
it('PATCH stores a plaintext personal_number encrypted and returns it masked', async () => {
|
||||
withWriteScope()
|
||||
const supabaseMock = makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
customers: {
|
||||
data: { ...SAMPLE_CUSTOMER, customer_type: 'individual', personal_number: TEST_PERSONAL_NUMBER },
|
||||
error: null,
|
||||
},
|
||||
})
|
||||
mockServiceClient.mockReturnValue(supabaseMock)
|
||||
|
||||
const res = await updateCustomer(
|
||||
makePatchRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/customers/${CUSTOMER_ID}`, {
|
||||
personal_number: TEST_PERSONAL_NUMBER,
|
||||
}),
|
||||
detailParams(COMPANY_ID, CUSTOMER_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const updated = supabaseMock.captured.update[0] as { personal_number?: string | null }
|
||||
expect(updated.personal_number).toMatch(CIPHERTEXT_SHAPE)
|
||||
expect(decryptPersonnummer(updated.personal_number!)).toBe(TEST_PERSONAL_NUMBER)
|
||||
const body = await res.json()
|
||||
expect(body.data.personal_number).toBe(MASKED_PERSONAL_NUMBER)
|
||||
})
|
||||
|
||||
it('PATCH treats the masked form as "leave unchanged"', async () => {
|
||||
withWriteScope()
|
||||
const supabaseMock = makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
customers: {
|
||||
data: { ...SAMPLE_CUSTOMER, customer_type: 'individual', personal_number: TEST_PERSONAL_NUMBER },
|
||||
error: null,
|
||||
},
|
||||
})
|
||||
mockServiceClient.mockReturnValue(supabaseMock)
|
||||
|
||||
const res = await updateCustomer(
|
||||
makePatchRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/customers/${CUSTOMER_ID}`, {
|
||||
personal_number: MASKED_PERSONAL_NUMBER,
|
||||
notes: 'still here',
|
||||
}),
|
||||
detailParams(COMPANY_ID, CUSTOMER_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const updated = supabaseMock.captured.update[0] as Record<string, unknown>
|
||||
expect('personal_number' in updated).toBe(false)
|
||||
expect(updated.notes).toBe('still here')
|
||||
})
|
||||
|
||||
it('PATCH rejects a personnummer-shaped org_number on a stored business customer', async () => {
|
||||
withWriteScope()
|
||||
const supabaseMock = makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
customers: { data: SAMPLE_CUSTOMER, error: null },
|
||||
})
|
||||
mockServiceClient.mockReturnValue(supabaseMock)
|
||||
|
||||
const res = await updateCustomer(
|
||||
makePatchRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/customers/${CUSTOMER_ID}`, {
|
||||
org_number: TEST_PERSONAL_NUMBER,
|
||||
}),
|
||||
detailParams(COMPANY_ID, CUSTOMER_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('CUSTOMER_ORG_NUMBER_IS_PERSONAL')
|
||||
expect(supabaseMock.captured.update).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('company payment-terms default on create', () => {
|
||||
it('falls back to company_settings.invoice_default_days when default_payment_terms is omitted', async () => {
|
||||
withWriteScope()
|
||||
const supabaseMock = makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
company_settings: { data: { invoice_default_days: 10 }, error: null },
|
||||
customers: { data: { ...SAMPLE_CUSTOMER, default_payment_terms: 10 }, error: null },
|
||||
})
|
||||
mockServiceClient.mockReturnValue(supabaseMock)
|
||||
|
||||
const res = await createCustomer(
|
||||
makePostRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/customers`, {
|
||||
name: 'Terms AB',
|
||||
customer_type: 'swedish_business',
|
||||
}),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(201)
|
||||
const inserted = supabaseMock.captured.insert[0] as { default_payment_terms?: number }
|
||||
expect(inserted.default_payment_terms).toBe(10)
|
||||
})
|
||||
|
||||
it('an explicit default_payment_terms wins over the company setting', async () => {
|
||||
withWriteScope()
|
||||
const supabaseMock = makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
company_settings: { data: { invoice_default_days: 10 }, error: null },
|
||||
customers: { data: { ...SAMPLE_CUSTOMER, default_payment_terms: 45 }, error: null },
|
||||
})
|
||||
mockServiceClient.mockReturnValue(supabaseMock)
|
||||
|
||||
const res = await createCustomer(
|
||||
makePostRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/customers`, {
|
||||
name: 'Terms AB',
|
||||
customer_type: 'swedish_business',
|
||||
default_payment_terms: 45,
|
||||
}),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(201)
|
||||
const inserted = supabaseMock.captured.insert[0] as { default_payment_terms?: number }
|
||||
expect(inserted.default_payment_terms).toBe(45)
|
||||
})
|
||||
|
||||
it('dry-run previews the company default without inserting', async () => {
|
||||
withWriteScope()
|
||||
const supabaseMock = makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
company_settings: { data: { invoice_default_days: 10 }, error: null },
|
||||
})
|
||||
mockServiceClient.mockReturnValue(supabaseMock)
|
||||
|
||||
const res = await createCustomer(
|
||||
makePostRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/customers?dry_run=true`, {
|
||||
name: 'Preview AB',
|
||||
customer_type: 'swedish_business',
|
||||
}),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data.dry_run).toBe(true)
|
||||
expect(body.data.preview.default_payment_terms).toBe(10)
|
||||
expect(supabaseMock.from.mock.calls.some((c) => c[0] === 'customers')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -22,6 +22,8 @@ import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponseFromCode } from '@/lib/api/v1/errors'
|
||||
import { CreateCustomerSchema } from '@/lib/api/schemas'
|
||||
import { validateVatNumber } from '@/lib/vat/vies-client'
|
||||
import { encryptCustomerPersonalNumber } from '@/lib/customers/protect-personal-number'
|
||||
import { resolveDefaultPaymentTerms } from '@/lib/customers/default-payment-terms'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import type { Logger } from '@/lib/logger'
|
||||
import type { Customer } from '@/types'
|
||||
@@ -117,6 +119,7 @@ async function createOneCustomer(
|
||||
input: z.infer<typeof CreateCustomerSchema>,
|
||||
dryRun: boolean,
|
||||
log: Logger,
|
||||
fallbackPaymentTerms: number,
|
||||
): Promise<ResultItem> {
|
||||
if (dryRun) {
|
||||
return {
|
||||
@@ -140,7 +143,7 @@ async function createOneCustomer(
|
||||
org_number: input.org_number ?? null,
|
||||
vat_number: input.vat_number ?? null,
|
||||
vat_number_validated: false,
|
||||
default_payment_terms: input.default_payment_terms ?? 30,
|
||||
default_payment_terms: input.default_payment_terms ?? fallbackPaymentTerms,
|
||||
notes: input.notes ?? null,
|
||||
archived_at: null,
|
||||
created_at: null,
|
||||
@@ -189,7 +192,10 @@ async function createOneCustomer(
|
||||
vat_number: input.vat_number ?? null,
|
||||
vat_number_validated: vatValidated,
|
||||
vat_number_validated_at: vatValidatedAt,
|
||||
default_payment_terms: input.default_payment_terms ?? 30,
|
||||
// Stored as ciphertext (customers_personal_number_check). The response
|
||||
// projection deliberately excludes it; nothing here leaks it.
|
||||
personal_number: encryptCustomerPersonalNumber(input.personal_number),
|
||||
default_payment_terms: input.default_payment_terms ?? fallbackPaymentTerms,
|
||||
notes: input.notes ?? null,
|
||||
})
|
||||
.select(CUSTOMER_RESPONSE_COLUMNS)
|
||||
@@ -296,6 +302,14 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
})
|
||||
}
|
||||
|
||||
// Items without explicit payment terms follow the company's own default,
|
||||
// not a hardcoded 30. Resolved once for the whole batch.
|
||||
const fallbackPaymentTerms = await resolveDefaultPaymentTerms(
|
||||
ctx.supabase,
|
||||
ctx.companyId!,
|
||||
undefined,
|
||||
)
|
||||
|
||||
// Sequential processing: matches /invoices/bulk-create. VIES has its own
|
||||
// upstream throughput limits; running a batch of 50 in parallel can trip
|
||||
// them. The 50-item cap keeps the worst-case latency bounded.
|
||||
@@ -309,6 +323,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
body.customers[i],
|
||||
ctx.dryRun,
|
||||
ctx.log,
|
||||
fallbackPaymentTerms,
|
||||
)
|
||||
results.push(item)
|
||||
}
|
||||
|
||||
@@ -21,6 +21,12 @@ import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors'
|
||||
import { CreateCustomerSchema } from '@/lib/api/schemas'
|
||||
import { validateVatNumber } from '@/lib/vat/vies-client'
|
||||
import {
|
||||
encryptCustomerPersonalNumber,
|
||||
maskCustomerRow,
|
||||
} from '@/lib/customers/protect-personal-number'
|
||||
import { maskCustomerPersonalNumber } from '@/lib/customers/mask-personal-number'
|
||||
import { resolveDefaultPaymentTerms } from '@/lib/customers/default-payment-terms'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import type { Customer } from '@/types'
|
||||
|
||||
@@ -246,6 +252,8 @@ const CustomerCreated = z.object({
|
||||
org_number: z.string().nullable(),
|
||||
vat_number: z.string().nullable(),
|
||||
vat_number_validated: z.boolean(),
|
||||
// Always the masked display form ('********-1234'), never the stored value.
|
||||
personal_number: z.string().nullable(),
|
||||
default_payment_terms: z.number(),
|
||||
notes: z.string().nullable(),
|
||||
archived_at: z.string().nullable(),
|
||||
@@ -256,7 +264,7 @@ const CustomerCreated = z.object({
|
||||
// Drop vat_number_validated_at: declared in neither CustomerCreated nor
|
||||
// CustomerDetail; an internal timestamp with no documented consumer.
|
||||
const CUSTOMER_RESPONSE_COLUMNS =
|
||||
'id, name, customer_type, customer_number, contact_person, email, phone, invoice_email_cc_addresses, invoice_email_bcc_addresses, address_line1, address_line2, postal_code, city, country, org_number, vat_number, vat_number_validated, default_payment_terms, notes, archived_at, created_at, updated_at'
|
||||
'id, name, customer_type, customer_number, contact_person, email, phone, invoice_email_cc_addresses, invoice_email_bcc_addresses, address_line1, address_line2, postal_code, city, country, org_number, vat_number, vat_number_validated, personal_number, default_payment_terms, notes, archived_at, created_at, updated_at'
|
||||
|
||||
registerEndpoint({
|
||||
operation: 'customers.create',
|
||||
@@ -273,6 +281,9 @@ registerEndpoint({
|
||||
'Idempotency-Key is mandatory: calls without it return 400 VALIDATION_ERROR.',
|
||||
'org_number uniqueness is enforced at the database level; duplicate inserts return 409 CUSTOMER_DUPLICATE_ORG_NUMBER.',
|
||||
'For Swedish sole traders (customer_type=individual), org_number IS the personnummer. List responses mask it; the create endpoint accepts it as input.',
|
||||
'An org_number shaped like a Swedish personnummer is rejected for business customer_types: create the customer as customer_type=individual (personal_number or org_number) so the number is masked and protected.',
|
||||
'personal_number is accepted only for customer_type=individual, stored encrypted, and returned in the masked form ********-1234.',
|
||||
'If default_payment_terms is omitted, it defaults to the company setting invoice_default_days, falling back to 30.',
|
||||
'VIES validation runs only on commit. Dry-run skips the external call and leaves vat_number_validated=false in the preview.',
|
||||
],
|
||||
example: {
|
||||
@@ -335,6 +346,15 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
}
|
||||
const body = parsed.data
|
||||
|
||||
// Unset payment terms follow the company's own default, not a hardcoded
|
||||
// 30. Resolved before the dry-run branch so the preview shows the value
|
||||
// a commit would store.
|
||||
const defaultPaymentTerms = await resolveDefaultPaymentTerms(
|
||||
ctx.supabase,
|
||||
ctx.companyId!,
|
||||
body.default_payment_terms,
|
||||
)
|
||||
|
||||
// Dry-run: validate input, return the would-be record. id, timestamps,
|
||||
// and vat_number_validated all populate on commit, not here.
|
||||
if (ctx.dryRun) {
|
||||
@@ -357,7 +377,8 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
org_number: body.org_number ?? null,
|
||||
vat_number: body.vat_number ?? null,
|
||||
vat_number_validated: false,
|
||||
default_payment_terms: body.default_payment_terms ?? 30,
|
||||
personal_number: maskCustomerPersonalNumber(body.personal_number ?? null),
|
||||
default_payment_terms: defaultPaymentTerms,
|
||||
notes: body.notes ?? null,
|
||||
archived_at: null,
|
||||
created_at: null,
|
||||
@@ -408,8 +429,12 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
vat_number: body.vat_number ?? null,
|
||||
vat_number_validated: vatValidated,
|
||||
vat_number_validated_at: vatValidatedAt,
|
||||
// Stored as ciphertext; customers_personal_number_check accepts that
|
||||
// shape only (20260726110000). Validated individual-only upstream by
|
||||
// CreateCustomerSchema.
|
||||
personal_number: encryptCustomerPersonalNumber(body.personal_number),
|
||||
language: body.language ?? 'sv',
|
||||
default_payment_terms: body.default_payment_terms ?? 30,
|
||||
default_payment_terms: defaultPaymentTerms,
|
||||
notes: body.notes ?? null,
|
||||
})
|
||||
.select(CUSTOMER_RESPONSE_COLUMNS)
|
||||
@@ -429,6 +454,10 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
return v1ErrorResponse(error, ctx.log, { requestId: ctx.requestId })
|
||||
}
|
||||
|
||||
// The selected row carries personal_number ciphertext; nothing beyond
|
||||
// this point may see it unmasked.
|
||||
const safeCustomer = maskCustomerRow(data as Record<string, unknown> & { personal_number?: string | null })
|
||||
|
||||
// Emit customer.created so webhooks (Phase 2 PR-C) and downstream
|
||||
// handlers can react. Best-effort: emit failure does not roll back.
|
||||
// Cast through `unknown` because the response projection deliberately
|
||||
@@ -438,7 +467,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
await eventBus.emit({
|
||||
type: 'customer.created',
|
||||
payload: {
|
||||
customer: { ...(data as Record<string, unknown>), user_id: ctx.userId, company_id: ctx.companyId! } as unknown as Customer,
|
||||
customer: { ...safeCustomer, user_id: ctx.userId, company_id: ctx.companyId! } as unknown as Customer,
|
||||
companyId: ctx.companyId!,
|
||||
userId: ctx.userId,
|
||||
},
|
||||
@@ -447,7 +476,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
ctx.log.warn('customer.created emit failed', err as Error)
|
||||
}
|
||||
|
||||
return created(data, { requestId: ctx.requestId })
|
||||
return created(safeCustomer, { requestId: ctx.requestId })
|
||||
},
|
||||
{ requireIdempotencyKey: true },
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user