fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* GET /api/customers/{id}/personal-number
|
||||
*
|
||||
* The deliberate drill-in behind the mask: returns the full personnummer for
|
||||
* one individual customer.
|
||||
*
|
||||
* Every other customer read surface (list, detail, export) returns
|
||||
* '********-1234'. Without this endpoint the value was write-only by
|
||||
* construction: a user could store a personnummer and then never verify what
|
||||
* had actually been stored, which is the failure this exists to close. It
|
||||
* mirrors the employee convention, where the list masks and the master GET
|
||||
* returns all 12 digits (app/api/v1/companies/[companyId]/employees/[id]).
|
||||
*
|
||||
* Gated on the write role even though it only reads. .compliance/ropa.yaml
|
||||
* listed `no_full_value_read_endpoint` among the safeguards for
|
||||
* customers.personal_number; this endpoint retires that measure, so it keeps
|
||||
* the exposure as narrow as the purpose allows. The person who needs to verify
|
||||
* a stored personnummer is the one who typed it and can correct it, which is
|
||||
* exactly the non-viewer role. A viewer (typically an external consultant with
|
||||
* read-only access) keeps seeing the mask.
|
||||
*
|
||||
* The read is logged with the actor, never with the value, so a reveal is
|
||||
* attributable. audit_log is written by DB triggers only, so this is a
|
||||
* structured application log rather than an audit row.
|
||||
*/
|
||||
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { revealStoredCustomerPersonalNumber } from '@/lib/customers/protect-personal-number'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
export const GET = withRouteContext(
|
||||
'customer.personal_number.reveal',
|
||||
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params
|
||||
const { supabase, companyId, user, log, requestId } = ctx
|
||||
const opLog = log.child({ customerId: id })
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('customers')
|
||||
.select('id, personal_number')
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
if (error.code === 'PGRST116') {
|
||||
return errorResponseFromCode('CUSTOMER_NOT_FOUND', opLog, { requestId })
|
||||
}
|
||||
opLog.error('customer fetch before personal number reveal failed', error)
|
||||
return errorResponseFromCode('INTERNAL_ERROR', opLog, {
|
||||
requestId,
|
||||
details: { reason: getUserErrorMessage(error) },
|
||||
})
|
||||
}
|
||||
|
||||
if (!data.personal_number) {
|
||||
return errorResponseFromCode('CUSTOMER_NO_PERSONAL_NUMBER', opLog, { requestId })
|
||||
}
|
||||
|
||||
let personalNumber: string | null
|
||||
try {
|
||||
personalNumber = revealStoredCustomerPersonalNumber(data.personal_number)
|
||||
} catch (err) {
|
||||
// Same row state the mask renders as '********-????'. Answer with the
|
||||
// specific code so the UI can tell the user to retype it, rather than
|
||||
// with a 500 that reads as "try again later".
|
||||
opLog.error('customer personal_number decrypt failed on reveal', {
|
||||
reason: err instanceof Error ? err.message : String(err),
|
||||
})
|
||||
return errorResponseFromCode('CUSTOMER_PERSONAL_NUMBER_UNREADABLE', opLog, { requestId })
|
||||
}
|
||||
|
||||
// Attributable without being a leak: who revealed which customer, never
|
||||
// the number itself.
|
||||
opLog.info('customer personal number revealed', { userId: user.id })
|
||||
|
||||
return NextResponse.json({ data: { personal_number: personalNumber } })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -0,0 +1,285 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { UpdateCustomerSchema } from '@/lib/api/schemas'
|
||||
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,
|
||||
normalizeReroutedPersonalNumber,
|
||||
orgNumberHoldsPersonalNumber,
|
||||
personalNumberDigits,
|
||||
} from '@/lib/customers/personal-number-shape'
|
||||
import { isMaskedPersonalNumber } from '@/lib/customers/mask-personal-number'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { COUNTRY_CONSISTENCY_MESSAGES, checkCountryConsistency } from '@/lib/vat/country-codes'
|
||||
|
||||
export const GET = withRouteContext(
|
||||
'customer.get',
|
||||
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
const opLog = log.child({ customerId: id })
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('customers')
|
||||
.select('*')
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
if (error.code === 'PGRST116') {
|
||||
return errorResponseFromCode('CUSTOMER_NOT_FOUND', opLog, { requestId })
|
||||
}
|
||||
opLog.error('customer fetch failed', error)
|
||||
return errorResponseFromCode('INTERNAL_ERROR', opLog, {
|
||||
requestId,
|
||||
details: { reason: getUserErrorMessage(error) },
|
||||
})
|
||||
}
|
||||
|
||||
const { data: invoices } = await supabase
|
||||
.from('invoices')
|
||||
.select('id, invoice_number, invoice_date, due_date, status, total, currency')
|
||||
.eq('customer_id', id)
|
||||
.eq('company_id', companyId)
|
||||
.order('invoice_date', { ascending: false })
|
||||
|
||||
return NextResponse.json({ data: { ...maskCustomerRow(data), invoices: invoices || [] } })
|
||||
},
|
||||
)
|
||||
|
||||
export const PATCH = withRouteContext(
|
||||
'customer.update',
|
||||
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
const opLog = log.child({ customerId: id })
|
||||
|
||||
const result = await validateBody(request, UpdateCustomerSchema, {
|
||||
log: opLog,
|
||||
operation: 'customer.update',
|
||||
})
|
||||
if (!result.success) return result.response
|
||||
const body = result.data
|
||||
|
||||
const { data: existing, error: existingError } = await supabase
|
||||
.from('customers')
|
||||
.select('id, customer_type, country, vat_number')
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
if (existingError || !existing) {
|
||||
if (existingError?.code === 'PGRST116') {
|
||||
return errorResponseFromCode('CUSTOMER_NOT_FOUND', opLog, { requestId })
|
||||
}
|
||||
opLog.error('customer lookup before update failed', existingError)
|
||||
return errorResponseFromCode('CUSTOMER_UPDATE_FAILED', opLog, { requestId })
|
||||
}
|
||||
|
||||
// No ordinary read returns the stored personnummer, only '********-1234',
|
||||
// or '********-????' when the stored value could not be decrypted. A
|
||||
// client that PATCHes back a customer it just read therefore submits one
|
||||
// of those, and it counts as "field not supplied": it carries no new
|
||||
// value, so it must not be validated, stored or treated as a clear.
|
||||
// CustomerForm strips it before sending, but the guard belongs here too:
|
||||
// any other client (script, agent, future UI) that skips it would
|
||||
// otherwise destroy the value.
|
||||
//
|
||||
// Both forms are recognized via lib/customers/mask-personal-number.ts so
|
||||
// this route, UpdateCustomerSchema and the form cannot disagree about what
|
||||
// counts as a mask. They previously each carried their own '-1234'-only
|
||||
// copy, which made an undecryptable row uneditable in every field, not
|
||||
// just this one.
|
||||
const personalNumberSubmitted =
|
||||
body.personal_number !== undefined && !isMaskedPersonalNumber(body.personal_number)
|
||||
|
||||
const effectiveType = body.customer_type ?? existing.customer_type
|
||||
if (personalNumberSubmitted && body.personal_number && effectiveType !== 'individual') {
|
||||
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 })
|
||||
}
|
||||
|
||||
// The mirror image for individuals: a personnummer submitted as
|
||||
// org_number is the personnummer in the wrong field. It is stored
|
||||
// encrypted in personal_number and org_number is cleared, same as
|
||||
// CreateCustomerSchema does on create. Next to a DIFFERENT plaintext
|
||||
// personal_number in the same body the two conflict.
|
||||
const reroutedPersonalNumber = orgNumberHoldsPersonalNumber(effectiveType, body.org_number)
|
||||
? normalizeReroutedPersonalNumber(body.org_number!)
|
||||
: null
|
||||
if (
|
||||
reroutedPersonalNumber
|
||||
&& personalNumberSubmitted
|
||||
&& body.personal_number
|
||||
&& personalNumberDigits(body.personal_number) !== personalNumberDigits(reroutedPersonalNumber)
|
||||
) {
|
||||
return errorResponseFromCode('CUSTOMER_PERSONAL_NUMBER_CONFLICT', opLog, { requestId })
|
||||
}
|
||||
|
||||
// Country vs type vs VAT prefix on the row as it will END UP (#2025): a
|
||||
// type change alone can make the stored country wrong, and a country
|
||||
// change alone can contradict the stored VAT number. Judged only when
|
||||
// one of the three is in the body: a legacy row that is already
|
||||
// contradictory must still be able to change its email.
|
||||
const countryRuleTouched =
|
||||
body.customer_type !== undefined || body.country !== undefined || body.vat_number !== undefined
|
||||
const countryIssue = countryRuleTouched
|
||||
? checkCountryConsistency({
|
||||
partyType: effectiveType,
|
||||
country: body.country ?? existing.country,
|
||||
vatNumber: body.vat_number ?? existing.vat_number,
|
||||
})
|
||||
: null
|
||||
if (countryIssue) {
|
||||
return errorResponseFromCode('CUSTOMER_COUNTRY_MISMATCH', opLog, {
|
||||
requestId,
|
||||
messageSv: COUNTRY_CONSISTENCY_MESSAGES[countryIssue].sv,
|
||||
messageEn: COUNTRY_CONSISTENCY_MESSAGES[countryIssue].en,
|
||||
details: { issue: countryIssue, field: 'country' },
|
||||
})
|
||||
}
|
||||
|
||||
const updateData: Record<string, unknown> = {}
|
||||
if (body.name !== undefined) updateData.name = body.name
|
||||
if (body.customer_type !== undefined) updateData.customer_type = body.customer_type
|
||||
// Empty string clears the customer number, same as an explicit null.
|
||||
if (body.customer_number !== undefined) updateData.customer_number = body.customer_number || null
|
||||
if (body.contact_person !== undefined) updateData.contact_person = body.contact_person
|
||||
if (body.email !== undefined) updateData.email = body.email
|
||||
if (body.phone !== undefined) updateData.phone = body.phone
|
||||
if (body.invoice_email_cc_addresses !== undefined) {
|
||||
updateData.invoice_email_cc_addresses = body.invoice_email_cc_addresses
|
||||
}
|
||||
if (body.invoice_email_bcc_addresses !== undefined) {
|
||||
updateData.invoice_email_bcc_addresses = body.invoice_email_bcc_addresses
|
||||
}
|
||||
if (body.address_line1 !== undefined) updateData.address_line1 = body.address_line1
|
||||
if (body.address_line2 !== undefined) updateData.address_line2 = body.address_line2
|
||||
if (body.postal_code !== undefined) updateData.postal_code = body.postal_code
|
||||
if (body.city !== undefined) updateData.city = body.city
|
||||
if (body.country !== undefined) updateData.country = body.country
|
||||
if (body.org_number !== undefined) {
|
||||
updateData.org_number = reroutedPersonalNumber ? null : body.org_number
|
||||
}
|
||||
if (body.vat_number !== undefined) updateData.vat_number = body.vat_number
|
||||
if (reroutedPersonalNumber && !(personalNumberSubmitted && body.personal_number)) {
|
||||
updateData.personal_number = encryptCustomerPersonalNumber(reroutedPersonalNumber)
|
||||
} else 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 && effectiveType !== 'individual') {
|
||||
updateData.personal_number = null
|
||||
}
|
||||
if (body.language !== undefined) updateData.language = body.language
|
||||
if (body.default_payment_terms !== undefined) updateData.default_payment_terms = body.default_payment_terms
|
||||
if (body.notes !== undefined) updateData.notes = body.notes
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('customers')
|
||||
.update(updateData)
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.select()
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
if (error.code === 'PGRST116') {
|
||||
return errorResponseFromCode('CUSTOMER_NOT_FOUND', opLog, { requestId })
|
||||
}
|
||||
if (error.code === '23505') {
|
||||
return errorResponseFromCode('CUSTOMER_DUPLICATE_ORG_NUMBER', opLog, {
|
||||
requestId,
|
||||
details: { orgNumber: body.org_number },
|
||||
})
|
||||
}
|
||||
opLog.error('customer update failed', error)
|
||||
return errorResponseFromCode('CUSTOMER_UPDATE_FAILED', opLog, {
|
||||
requestId,
|
||||
details: { reason: getUserErrorMessage(error) },
|
||||
})
|
||||
}
|
||||
|
||||
// Re-run VIES validation when the VAT number changes on an EU business
|
||||
// customer (non-blocking).
|
||||
const isEuBusiness = (body.customer_type || data.customer_type) === 'eu_business'
|
||||
if (body.vat_number !== undefined && isEuBusiness) {
|
||||
try {
|
||||
if (body.vat_number) {
|
||||
const vatResult = await validateVatNumber(body.vat_number)
|
||||
const validatedAt = vatResult.valid ? new Date().toISOString() : null
|
||||
await supabase
|
||||
.from('customers')
|
||||
.update({
|
||||
vat_number_validated: vatResult.valid,
|
||||
vat_number_validated_at: validatedAt,
|
||||
})
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
data.vat_number_validated = vatResult.valid
|
||||
data.vat_number_validated_at = validatedAt
|
||||
} else {
|
||||
await supabase
|
||||
.from('customers')
|
||||
.update({ vat_number_validated: false, vat_number_validated_at: null })
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
data.vat_number_validated = false
|
||||
data.vat_number_validated_at = null
|
||||
}
|
||||
} catch (err) {
|
||||
opLog.warn('auto-VIES validation failed on customer update', err as Error)
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: maskCustomerRow(data) })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
|
||||
export const DELETE = withRouteContext(
|
||||
'customer.delete',
|
||||
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
const opLog = log.child({ customerId: id })
|
||||
|
||||
const { error, count } = await supabase
|
||||
.from('customers')
|
||||
.delete({ count: 'exact' })
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
|
||||
if (error) {
|
||||
if (error.code === '23503') {
|
||||
return errorResponseFromCode('CUSTOMER_HAS_INVOICES', opLog, { requestId })
|
||||
}
|
||||
opLog.error('customer delete failed', error)
|
||||
return errorResponseFromCode('CUSTOMER_DELETE_FAILED', opLog, {
|
||||
requestId,
|
||||
details: { reason: getUserErrorMessage(error) },
|
||||
})
|
||||
}
|
||||
|
||||
if (count === 0) {
|
||||
return errorResponseFromCode('CUSTOMER_NOT_FOUND', opLog, { requestId })
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -0,0 +1,244 @@
|
||||
/**
|
||||
* customers.country is ISO 3166-1 alpha-2 and must agree with the customer
|
||||
* type and the VAT prefix (#2025, #2028) on POST /api/customers and
|
||||
* PATCH /api/customers/[id].
|
||||
*
|
||||
* Same harness as customer-number.test.ts: the routes run through the real
|
||||
* withRouteContext wrapper with a hand-rolled Supabase mock that records
|
||||
* insert/update payloads and answers every query with `queryResult`.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
import { eventBus } from '@/lib/events'
|
||||
|
||||
const captured: { insert: unknown[]; update: unknown[] } = { insert: [], update: [] }
|
||||
let queryResult: { data: unknown; error: unknown } = { data: null, error: null }
|
||||
|
||||
const buildChain = (): unknown =>
|
||||
new Proxy(
|
||||
{},
|
||||
{
|
||||
get(_target, prop) {
|
||||
if (prop === 'then') {
|
||||
return (resolve: (v: unknown) => void) => resolve(queryResult)
|
||||
}
|
||||
return (...args: unknown[]) => {
|
||||
if (prop === 'insert') captured.insert.push(args[0])
|
||||
if (prop === 'update') captured.update.push(args[0])
|
||||
return buildChain()
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
const supabase = {
|
||||
from: vi.fn(() => buildChain()),
|
||||
rpc: vi.fn(() => buildChain()),
|
||||
}
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const requireWriteMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
// Never reach VIES from a unit test.
|
||||
vi.mock('@/lib/vat/vies-client', () => ({
|
||||
validateVatNumber: vi.fn().mockResolvedValue({ valid: false }),
|
||||
}))
|
||||
|
||||
import { POST } from '../route'
|
||||
import { PATCH } from '../[id]/route'
|
||||
|
||||
type CustomerRow = { country?: string }
|
||||
|
||||
const CUSTOMER_ID = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
captured.insert.length = 0
|
||||
captured.update.length = 0
|
||||
queryResult = { data: null, error: null }
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
describe('country on POST /api/customers', () => {
|
||||
it('stores a country name as its ISO code (#2028)', async () => {
|
||||
queryResult = { data: { id: CUSTOMER_ID, name: 'Muster Handels GmbH', country: 'DE' }, error: null }
|
||||
const request = createMockRequest('/api/customers', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
name: 'Muster Handels GmbH',
|
||||
customer_type: 'eu_business',
|
||||
country: 'Germany',
|
||||
vat_number: 'DE811234567',
|
||||
},
|
||||
})
|
||||
|
||||
const response = await POST(request, { params: Promise.resolve({}) })
|
||||
expect(response.status).toBe(200)
|
||||
expect((captured.insert[0] as CustomerRow).country).toBe('DE')
|
||||
})
|
||||
|
||||
it('derives the EU country from the VAT prefix when none is given', async () => {
|
||||
queryResult = { data: { id: CUSTOMER_ID, name: 'Muster Handels GmbH', country: 'DE' }, error: null }
|
||||
const request = createMockRequest('/api/customers', {
|
||||
method: 'POST',
|
||||
body: { name: 'Muster Handels GmbH', customer_type: 'eu_business', vat_number: 'DE811234567' },
|
||||
})
|
||||
|
||||
const response = await POST(request, { params: Promise.resolve({}) })
|
||||
expect(response.status).toBe(200)
|
||||
expect((captured.insert[0] as CustomerRow).country).toBe('DE')
|
||||
})
|
||||
|
||||
it('defaults a Swedish business to SE, never to the name Sweden', async () => {
|
||||
queryResult = { data: { id: CUSTOMER_ID, name: 'Acme AB', country: 'SE' }, error: null }
|
||||
const request = createMockRequest('/api/customers', {
|
||||
method: 'POST',
|
||||
body: { name: 'Acme AB', customer_type: 'swedish_business' },
|
||||
})
|
||||
|
||||
const response = await POST(request, { params: Promise.resolve({}) })
|
||||
expect(response.status).toBe(200)
|
||||
expect((captured.insert[0] as CustomerRow).country).toBe('SE')
|
||||
})
|
||||
|
||||
it('rejects an EU business with land Sverige (#2025)', async () => {
|
||||
const request = createMockRequest('/api/customers', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
name: 'Muster Handels GmbH',
|
||||
customer_type: 'eu_business',
|
||||
country: 'Sverige',
|
||||
vat_number: 'DE811234567',
|
||||
},
|
||||
})
|
||||
|
||||
const response = await POST(request, { params: Promise.resolve({}) })
|
||||
expect(response.status).toBe(400)
|
||||
const { body } = await parseJsonResponse<{ error: unknown }>(response)
|
||||
expect(JSON.stringify(body.error)).toMatch(/country/)
|
||||
expect(captured.insert).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('rejects a VAT prefix that names another country than the row', async () => {
|
||||
const request = createMockRequest('/api/customers', {
|
||||
method: 'POST',
|
||||
body: { name: 'Muster', customer_type: 'eu_business', country: 'FR', vat_number: 'DE811234567' },
|
||||
})
|
||||
|
||||
const response = await POST(request, { params: Promise.resolve({}) })
|
||||
expect(response.status).toBe(400)
|
||||
expect(captured.insert).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('rejects a country it cannot read as a code', async () => {
|
||||
const request = createMockRequest('/api/customers', {
|
||||
method: 'POST',
|
||||
body: { name: 'Acme AB', customer_type: 'swedish_business', country: 'Atlantis' },
|
||||
})
|
||||
|
||||
const response = await POST(request, { params: Promise.resolve({}) })
|
||||
expect(response.status).toBe(400)
|
||||
expect(captured.insert).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('country on PATCH /api/customers/[id]', () => {
|
||||
const params = { params: Promise.resolve({ id: CUSTOMER_ID }) }
|
||||
|
||||
it('normalises a country name before writing it', async () => {
|
||||
queryResult = {
|
||||
data: { id: CUSTOMER_ID, customer_type: 'swedish_business', country: 'SE', vat_number: null },
|
||||
error: null,
|
||||
}
|
||||
const request = createMockRequest(`/api/customers/${CUSTOMER_ID}`, {
|
||||
method: 'PATCH',
|
||||
body: { country: 'Sweden' },
|
||||
})
|
||||
|
||||
const response = await PATCH(request, params)
|
||||
expect(response.status).toBe(200)
|
||||
expect((captured.update[0] as CustomerRow).country).toBe('SE')
|
||||
})
|
||||
|
||||
it('refuses a type change that contradicts the stored country', async () => {
|
||||
queryResult = {
|
||||
data: { id: CUSTOMER_ID, customer_type: 'swedish_business', country: 'SE', vat_number: null },
|
||||
error: null,
|
||||
}
|
||||
const request = createMockRequest(`/api/customers/${CUSTOMER_ID}`, {
|
||||
method: 'PATCH',
|
||||
body: { customer_type: 'eu_business' },
|
||||
})
|
||||
|
||||
const response = await PATCH(request, params)
|
||||
expect(response.status).toBe(400)
|
||||
const { body } = await parseJsonResponse<{ error: { code: string; details?: { issue?: string } } }>(response)
|
||||
expect(body.error.code).toBe('CUSTOMER_COUNTRY_MISMATCH')
|
||||
expect(body.error.details?.issue).toBe('EU_BUSINESS_COUNTRY_IS_SE')
|
||||
expect(captured.update).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('refuses a country change that contradicts the stored VAT prefix', async () => {
|
||||
queryResult = {
|
||||
data: { id: CUSTOMER_ID, customer_type: 'eu_business', country: 'DE', vat_number: 'DE811234567' },
|
||||
error: null,
|
||||
}
|
||||
const request = createMockRequest(`/api/customers/${CUSTOMER_ID}`, {
|
||||
method: 'PATCH',
|
||||
body: { country: 'Frankrike' },
|
||||
})
|
||||
|
||||
const response = await PATCH(request, params)
|
||||
expect(response.status).toBe(400)
|
||||
const { body } = await parseJsonResponse<{ error: { code: string; details?: { issue?: string } } }>(response)
|
||||
expect(body.error.code).toBe('CUSTOMER_COUNTRY_MISMATCH')
|
||||
expect(body.error.details?.issue).toBe('VAT_PREFIX_COUNTRY_MISMATCH')
|
||||
expect(captured.update).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('lets a contradictory legacy row change unrelated fields', async () => {
|
||||
queryResult = {
|
||||
data: { id: CUSTOMER_ID, customer_type: 'eu_business', country: 'SE', vat_number: 'DE811234567' },
|
||||
error: null,
|
||||
}
|
||||
const request = createMockRequest(`/api/customers/${CUSTOMER_ID}`, {
|
||||
method: 'PATCH',
|
||||
body: { email: '[email protected]' },
|
||||
})
|
||||
|
||||
const response = await PATCH(request, params)
|
||||
expect(response.status).toBe(200)
|
||||
expect(captured.update).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('accepts a country and type changed together into a consistent row', async () => {
|
||||
queryResult = {
|
||||
data: { id: CUSTOMER_ID, customer_type: 'swedish_business', country: 'SE', vat_number: null },
|
||||
error: null,
|
||||
}
|
||||
const request = createMockRequest(`/api/customers/${CUSTOMER_ID}`, {
|
||||
method: 'PATCH',
|
||||
body: { customer_type: 'eu_business', country: 'de', vat_number: 'DE811234567' },
|
||||
})
|
||||
|
||||
const response = await PATCH(request, params)
|
||||
expect(response.status).toBe(200)
|
||||
expect((captured.update[0] as CustomerRow).country).toBe('DE')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,297 @@
|
||||
/**
|
||||
* Tests for the customer_number field (kundnummer, issue #914) on
|
||||
* POST /api/customers and PATCH /api/customers/[id].
|
||||
*
|
||||
* Exercises the routes through the real withRouteContext wrapper, mocking its
|
||||
* auth/company/write dependencies. Uses a hand-rolled Supabase mock that
|
||||
* records insert/update payloads so the tests can assert the route-level
|
||||
* normalization: the value is trimmed by the Zod schema, and empty string or
|
||||
* null clears the column to null.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
import { eventBus } from '@/lib/events'
|
||||
|
||||
const captured: { insert: unknown[]; update: unknown[] } = { insert: [], update: [] }
|
||||
let queryResult: { data: unknown; error: unknown } = { data: null, error: null }
|
||||
|
||||
const buildChain = (): unknown =>
|
||||
new Proxy(
|
||||
{},
|
||||
{
|
||||
get(_target, prop) {
|
||||
if (prop === 'then') {
|
||||
return (resolve: (v: unknown) => void) => resolve(queryResult)
|
||||
}
|
||||
return (...args: unknown[]) => {
|
||||
if (prop === 'insert') captured.insert.push(args[0])
|
||||
if (prop === 'update') captured.update.push(args[0])
|
||||
return buildChain()
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
const supabase = {
|
||||
from: vi.fn(() => buildChain()),
|
||||
rpc: vi.fn(() => buildChain()),
|
||||
}
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const requireWriteMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
import { POST } from '../route'
|
||||
import { PATCH } from '../[id]/route'
|
||||
|
||||
type CustomerRow = {
|
||||
customer_number?: string | null
|
||||
contact_person?: string | null
|
||||
invoice_email_cc_addresses?: string[] | null
|
||||
invoice_email_bcc_addresses?: string[] | null
|
||||
}
|
||||
|
||||
describe('customer_number on POST /api/customers', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
captured.insert.length = 0
|
||||
captured.update.length = 0
|
||||
queryResult = { data: null, error: null }
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
it('rejects a customer_number longer than 32 characters with 400', async () => {
|
||||
const request = createMockRequest('/api/customers', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
name: 'Test AB',
|
||||
customer_type: 'swedish_business',
|
||||
customer_number: 'X'.repeat(33),
|
||||
},
|
||||
})
|
||||
|
||||
const response = await POST(request, { params: Promise.resolve({}) })
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(captured.insert).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('stores a trimmed customer_number on create', async () => {
|
||||
queryResult = {
|
||||
data: { id: 'cust-1', name: 'Test AB', customer_type: 'swedish_business', customer_number: '1001' },
|
||||
error: null,
|
||||
}
|
||||
|
||||
const request = createMockRequest('/api/customers', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
name: 'Test AB',
|
||||
customer_type: 'swedish_business',
|
||||
customer_number: ' 1001 ',
|
||||
},
|
||||
})
|
||||
|
||||
const response = await POST(request, { params: Promise.resolve({}) })
|
||||
const { status, body } = await parseJsonResponse<{ data: CustomerRow }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect((captured.insert[0] as CustomerRow).customer_number).toBe('1001')
|
||||
expect(body.data.customer_number).toBe('1001')
|
||||
})
|
||||
|
||||
it('normalizes an empty customer_number to null on create', async () => {
|
||||
queryResult = {
|
||||
data: { id: 'cust-1', name: 'Test AB', customer_type: 'swedish_business', customer_number: null },
|
||||
error: null,
|
||||
}
|
||||
|
||||
const request = createMockRequest('/api/customers', {
|
||||
method: 'POST',
|
||||
body: { name: 'Test AB', customer_type: 'swedish_business', customer_number: '' },
|
||||
})
|
||||
|
||||
const response = await POST(request, { params: Promise.resolve({}) })
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect((captured.insert[0] as CustomerRow).customer_number).toBeNull()
|
||||
})
|
||||
|
||||
it('defaults customer_number to null when omitted', async () => {
|
||||
queryResult = {
|
||||
data: { id: 'cust-1', name: 'Test AB', customer_type: 'swedish_business', customer_number: null },
|
||||
error: null,
|
||||
}
|
||||
|
||||
const request = createMockRequest('/api/customers', {
|
||||
method: 'POST',
|
||||
body: { name: 'Test AB', customer_type: 'swedish_business' },
|
||||
})
|
||||
|
||||
const response = await POST(request, { params: Promise.resolve({}) })
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect((captured.insert[0] as CustomerRow).customer_number).toBeNull()
|
||||
})
|
||||
|
||||
it('stores customer invoice contact metadata on create', async () => {
|
||||
queryResult = {
|
||||
data: { id: 'cust-1', name: 'Test AB', customer_type: 'swedish_business' },
|
||||
error: null,
|
||||
}
|
||||
const request = createMockRequest('/api/customers', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
name: 'Test AB',
|
||||
customer_type: 'swedish_business',
|
||||
contact_person: 'Anna Andersson',
|
||||
invoice_email_cc_addresses: ['[email protected]'],
|
||||
invoice_email_bcc_addresses: ['[email protected]'],
|
||||
},
|
||||
})
|
||||
|
||||
const response = await POST(request, { params: Promise.resolve({}) })
|
||||
expect((await parseJsonResponse(response)).status).toBe(200)
|
||||
expect(captured.insert[0]).toMatchObject({
|
||||
contact_person: 'Anna Andersson',
|
||||
invoice_email_cc_addresses: ['[email protected]'],
|
||||
invoice_email_bcc_addresses: ['[email protected]'],
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects more than 19 customer invoice copy recipients', async () => {
|
||||
const request = createMockRequest('/api/customers', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
name: 'Test AB',
|
||||
customer_type: 'swedish_business',
|
||||
invoice_email_cc_addresses: Array.from(
|
||||
{ length: 20 },
|
||||
(_, index) => `copy-${index}@example.test`,
|
||||
),
|
||||
},
|
||||
})
|
||||
|
||||
const response = await POST(request, { params: Promise.resolve({}) })
|
||||
expect((await parseJsonResponse(response)).status).toBe(400)
|
||||
expect(captured.insert).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('customer_number on PATCH /api/customers/[id]', () => {
|
||||
const routeParams = { params: Promise.resolve({ id: 'cust-1' }) }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
captured.insert.length = 0
|
||||
captured.update.length = 0
|
||||
queryResult = {
|
||||
data: { id: 'cust-1', customer_type: 'swedish_business' },
|
||||
error: null,
|
||||
}
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
it('rejects a customer_number longer than 32 characters with 400', async () => {
|
||||
const request = createMockRequest('/api/customers/cust-1', {
|
||||
method: 'PATCH',
|
||||
body: { customer_number: 'X'.repeat(33) },
|
||||
})
|
||||
|
||||
const response = await PATCH(request, routeParams)
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(captured.update).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('updates the customer_number', async () => {
|
||||
const request = createMockRequest('/api/customers/cust-1', {
|
||||
method: 'PATCH',
|
||||
body: { customer_number: 'K-42' },
|
||||
})
|
||||
|
||||
const response = await PATCH(request, routeParams)
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect((captured.update[0] as CustomerRow).customer_number).toBe('K-42')
|
||||
})
|
||||
|
||||
it('clears the customer_number when null is sent', async () => {
|
||||
const request = createMockRequest('/api/customers/cust-1', {
|
||||
method: 'PATCH',
|
||||
body: { customer_number: null },
|
||||
})
|
||||
|
||||
const response = await PATCH(request, routeParams)
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect((captured.update[0] as CustomerRow).customer_number).toBeNull()
|
||||
})
|
||||
|
||||
it('clears the customer_number when an empty string is sent', async () => {
|
||||
const request = createMockRequest('/api/customers/cust-1', {
|
||||
method: 'PATCH',
|
||||
body: { customer_number: '' },
|
||||
})
|
||||
|
||||
const response = await PATCH(request, routeParams)
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect((captured.update[0] as CustomerRow).customer_number).toBeNull()
|
||||
})
|
||||
|
||||
it('leaves the customer_number untouched when the field is omitted', async () => {
|
||||
const request = createMockRequest('/api/customers/cust-1', {
|
||||
method: 'PATCH',
|
||||
body: { name: 'New Name AB' },
|
||||
})
|
||||
|
||||
const response = await PATCH(request, routeParams)
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(captured.update[0]).not.toHaveProperty('customer_number')
|
||||
})
|
||||
|
||||
it('updates customer invoice contact metadata', async () => {
|
||||
const request = createMockRequest('/api/customers/cust-1', {
|
||||
method: 'PATCH',
|
||||
body: {
|
||||
contact_person: '',
|
||||
invoice_email_cc_addresses: [],
|
||||
invoice_email_bcc_addresses: ['[email protected]'],
|
||||
},
|
||||
})
|
||||
|
||||
const response = await PATCH(request, routeParams)
|
||||
expect((await parseJsonResponse(response)).status).toBe(200)
|
||||
expect(captured.update[0]).toMatchObject({
|
||||
contact_person: '',
|
||||
invoice_email_cc_addresses: [],
|
||||
invoice_email_bcc_addresses: ['[email protected]'],
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* GET /api/customers: the roster hides customers archived through the v1 API
|
||||
* (archived_at set). Archived rows stay in the table for BFL retention, so the
|
||||
* filter is the only thing keeping them out of the dashboard list.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import {
|
||||
createMockRequest,
|
||||
parseJsonResponse,
|
||||
createQueuedMockSupabase,
|
||||
makeCustomer,
|
||||
} from '@/tests/helpers'
|
||||
import { eventBus } from '@/lib/events'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset, findCall } = createQueuedMockSupabase()
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => Promise.resolve(mockSupabase),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({
|
||||
ensureInitialized: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
import { GET } from '../route'
|
||||
|
||||
describe('GET /api/customers: archived rows', () => {
|
||||
const mockUser = { id: 'user-1', email: '[email protected]' }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
eventBus.clear()
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
||||
|
||||
const response = await GET(createMockRequest('/api/customers'), { params: Promise.resolve({}) })
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('filters on archived_at IS NULL and still returns the active roster', async () => {
|
||||
const customers = [makeCustomer({ name: 'Beta AB' }), makeCustomer({ name: 'Alfa AB' })]
|
||||
enqueue({ data: customers, error: null })
|
||||
|
||||
const response = await GET(createMockRequest('/api/customers'), { params: Promise.resolve({}) })
|
||||
const { status, body } = await parseJsonResponse<{ data: Array<{ name: string }> }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.map((c) => c.name)).toEqual(['Alfa AB', 'Beta AB'])
|
||||
expect(findCall('customers', 'eq')).toEqual(['company_id', 'company-1'])
|
||||
expect(findCall('customers', 'is')).toEqual(['archived_at', null])
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,171 @@
|
||||
/**
|
||||
* GET /api/customers/[id]/personal-number: the drill-in behind the mask.
|
||||
*
|
||||
* Every other customer read surface returns '********-1234'. Without this
|
||||
* endpoint the field was write-only by construction: a user could store a
|
||||
* personnummer and had no way to check what had actually been stored, which is
|
||||
* what made an unreadable value indistinguishable from a rendering fault.
|
||||
*
|
||||
* What these tests pin:
|
||||
* - auth and tenancy run before anything is decrypted
|
||||
* - a stored ciphertext comes back as the full personnummer
|
||||
* - an undecryptable row answers with its own code, not a 500, because the
|
||||
* user can fix it in one step by typing the number in again
|
||||
*/
|
||||
import { NextResponse } from 'next/server'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
import { encryptPersonnummer } from '@/lib/salary/personnummer'
|
||||
|
||||
let queryResult: { data: unknown; error: unknown } = { data: null, error: null }
|
||||
|
||||
const buildChain = (): unknown =>
|
||||
new Proxy(
|
||||
{},
|
||||
{
|
||||
get(_target, prop) {
|
||||
if (prop === 'then') {
|
||||
return (resolve: (value: unknown) => void) => resolve(queryResult)
|
||||
}
|
||||
return () => buildChain()
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
const supabase = { from: vi.fn(() => buildChain()) }
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const requireWriteMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
import { GET } from '../[id]/personal-number/route'
|
||||
|
||||
// Synthetic personnummer, never a real one.
|
||||
const PERSONAL_NUMBER = '19900101-1234'
|
||||
|
||||
// Hex of the shape customers_personal_number_check accepts that is NOT valid
|
||||
// ciphertext: the GCM auth tag can never verify.
|
||||
const GARBAGE_HEX = 'ab'.repeat(40)
|
||||
|
||||
describe('GET /api/customers/[id]/personal-number', () => {
|
||||
const routeParams = { params: Promise.resolve({ id: 'customer-1' }) }
|
||||
const request = () => createMockRequest('/api/customers/customer-1/personal-number')
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
queryResult = { data: null, error: null }
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
it('returns 403 for a viewer, who keeps seeing the mask', async () => {
|
||||
// The drill-in retires the `no_full_value_read_endpoint` safeguard in
|
||||
// .compliance/ropa.yaml, so it stays as narrow as the purpose allows: the
|
||||
// person who needs to verify a personnummer is the one who can correct it.
|
||||
requireWriteMock.mockResolvedValue({
|
||||
ok: false,
|
||||
response: NextResponse.json(
|
||||
{ error: 'Du har endast läsbehörighet i detta företag.' },
|
||||
{ status: 403 },
|
||||
),
|
||||
})
|
||||
queryResult = {
|
||||
data: { id: 'customer-1', personal_number: encryptPersonnummer(PERSONAL_NUMBER) },
|
||||
error: null,
|
||||
}
|
||||
|
||||
const response = await GET(request(), routeParams)
|
||||
|
||||
expect(response.status).toBe(403)
|
||||
expect(await response.text()).not.toContain(PERSONAL_NUMBER)
|
||||
})
|
||||
|
||||
it('returns 401 when unauthenticated, before touching the row', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const response = await GET(request(), routeParams)
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
expect(supabase.from).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns the full personnummer for a stored ciphertext', async () => {
|
||||
queryResult = {
|
||||
data: { id: 'customer-1', personal_number: encryptPersonnummer(PERSONAL_NUMBER) },
|
||||
error: null,
|
||||
}
|
||||
|
||||
const response = await GET(request(), routeParams)
|
||||
const { status, body } = await parseJsonResponse<{ data: { personal_number: string } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.personal_number).toBe(PERSONAL_NUMBER)
|
||||
})
|
||||
|
||||
it('returns a legacy plaintext value unchanged', async () => {
|
||||
queryResult = { data: { id: 'customer-1', personal_number: '900101-1234' }, error: null }
|
||||
|
||||
const { status, body } = await parseJsonResponse<{ data: { personal_number: string } }>(
|
||||
await GET(request(), routeParams),
|
||||
)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.personal_number).toBe('900101-1234')
|
||||
})
|
||||
|
||||
it('returns 404 when the customer does not exist in the active company', async () => {
|
||||
queryResult = { data: null, error: { code: 'PGRST116', message: 'No rows returned' } }
|
||||
|
||||
const response = await GET(request(), { params: Promise.resolve({ id: 'missing' }) })
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
})
|
||||
|
||||
it('returns 404 when the customer has no stored personnummer', async () => {
|
||||
queryResult = { data: { id: 'customer-1', personal_number: null }, error: null }
|
||||
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await GET(request(), routeParams),
|
||||
)
|
||||
|
||||
expect(status).toBe(404)
|
||||
expect(body.error.code).toBe('CUSTOMER_NO_PERSONAL_NUMBER')
|
||||
})
|
||||
|
||||
it('answers with a specific code, not a 500, when the value cannot be decrypted', async () => {
|
||||
// The row that renders as '********-????'. Retrying never helps, so this
|
||||
// must not look transient: the UI turns this code into "type it in again".
|
||||
queryResult = { data: { id: 'customer-1', personal_number: GARBAGE_HEX }, error: null }
|
||||
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await GET(request(), routeParams),
|
||||
)
|
||||
|
||||
expect(status).toBe(422)
|
||||
expect(body.error.code).toBe('CUSTOMER_PERSONAL_NUMBER_UNREADABLE')
|
||||
})
|
||||
|
||||
it('never leaks the stored ciphertext, whatever the outcome', async () => {
|
||||
const stored = encryptPersonnummer(PERSONAL_NUMBER)
|
||||
queryResult = { data: { id: 'customer-1', personal_number: stored }, error: null }
|
||||
|
||||
const raw = await (await GET(request(), routeParams)).text()
|
||||
|
||||
expect(raw).not.toContain(stored)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* Representative viewer-403 test.
|
||||
*
|
||||
* Verifies that POST /api/customers returns 403 when the caller's
|
||||
* requireWritePermission check returns an error response. This is a
|
||||
* canary test: if it breaks, the wiring between mutating routes and
|
||||
* requireWritePermission has drifted.
|
||||
*
|
||||
* The full per-role behavior of requireWritePermission itself is
|
||||
* covered in lib/auth/__tests__/require-write.test.ts.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const mockAuthGetUser = vi.fn()
|
||||
const mockFrom = vi.fn()
|
||||
const mockSupabase = {
|
||||
auth: { getUser: mockAuthGetUser },
|
||||
from: mockFrom,
|
||||
}
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => Promise.resolve(mockSupabase),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({
|
||||
ensureInitialized: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const requireWritePermissionMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWritePermissionMock(...args),
|
||||
}))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
describe('POST /api/customers: viewer role gate', () => {
|
||||
const mockUser = { id: 'user-1', email: '[email protected]' }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockAuthGetUser.mockResolvedValue({ data: { user: mockUser } })
|
||||
})
|
||||
|
||||
it('returns 403 with Swedish message when requireWritePermission rejects', async () => {
|
||||
requireWritePermissionMock.mockResolvedValue({
|
||||
ok: false,
|
||||
response: NextResponse.json(
|
||||
{ error: 'Du har endast läsbehörighet i detta företag.' },
|
||||
{ status: 403 },
|
||||
),
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/customers', {
|
||||
method: 'POST',
|
||||
body: { name: 'Test customer', customer_type: 'company' },
|
||||
})
|
||||
|
||||
const response = await POST(request)
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(403)
|
||||
expect(body.error).toContain('läsbehörighet')
|
||||
})
|
||||
|
||||
it('calls requireWritePermission with the authenticated user id', async () => {
|
||||
requireWritePermissionMock.mockResolvedValue({
|
||||
ok: false,
|
||||
response: NextResponse.json({ error: 'blocked' }, { status: 403 }),
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/customers', {
|
||||
method: 'POST',
|
||||
body: { name: 'Test customer', customer_type: 'company' },
|
||||
})
|
||||
|
||||
await POST(request)
|
||||
|
||||
// The wrapper hands over the company it already resolved so the guard
|
||||
// does not repeat the resolve_active_company round trip.
|
||||
expect(requireWritePermissionMock).toHaveBeenCalledWith(mockSupabase, 'user-1', {
|
||||
companyId: 'company-1',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,148 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { CreateCustomerSchema } from '@/lib/api/schemas'
|
||||
import { validateVatNumber } from '@/lib/vat/vies-client'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
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()
|
||||
|
||||
export const GET = withRouteContext(
|
||||
'customer.list',
|
||||
async (_request, ctx) => {
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
|
||||
// Paginated: PostgREST caps an unranged select at 1000 rows, which would
|
||||
// hand the roster page a silently truncated customer list. Ordered on the
|
||||
// PK because paging is only stable under a unique total order; the
|
||||
// name sort callers expect is re-applied below.
|
||||
//
|
||||
// Archived rows (soft-deleted via the v1 API) stay in the table for BFL
|
||||
// retention but are not part of the roster: same canonical
|
||||
// `archived_at IS NULL` filter as the v1 list route.
|
||||
let rows: Customer[]
|
||||
try {
|
||||
rows = await fetchAllRows<Customer>(
|
||||
({ from, to }) =>
|
||||
supabase
|
||||
.from('customers')
|
||||
.select('*')
|
||||
.eq('company_id', companyId)
|
||||
.is('archived_at', null)
|
||||
.order('id', { ascending: true })
|
||||
.range(from, to),
|
||||
{ dedupeBy: (row) => row.id },
|
||||
)
|
||||
} catch (error) {
|
||||
log.error('customer list failed', error as Error)
|
||||
return errorResponse(error, log, { requestId })
|
||||
}
|
||||
|
||||
rows.sort((a, b) => (a.name ?? '').localeCompare(b.name ?? '', 'sv'))
|
||||
|
||||
return NextResponse.json({ data: rows.map(maskCustomerRow) })
|
||||
},
|
||||
)
|
||||
|
||||
export const POST = withRouteContext(
|
||||
'customer.create',
|
||||
async (request, ctx) => {
|
||||
const { user, supabase, companyId, log, requestId } = ctx
|
||||
|
||||
const result = await validateBody(request, CreateCustomerSchema, {
|
||||
log,
|
||||
operation: 'customer.create',
|
||||
})
|
||||
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({
|
||||
user_id: user.id,
|
||||
company_id: companyId,
|
||||
name: body.name,
|
||||
customer_type: body.customer_type,
|
||||
customer_number: body.customer_number || null,
|
||||
contact_person: body.contact_person ?? null,
|
||||
email: body.email,
|
||||
phone: body.phone,
|
||||
invoice_email_cc_addresses: body.invoice_email_cc_addresses ?? null,
|
||||
invoice_email_bcc_addresses: body.invoice_email_bcc_addresses ?? null,
|
||||
address_line1: body.address_line1,
|
||||
address_line2: body.address_line2,
|
||||
postal_code: body.postal_code,
|
||||
city: body.city,
|
||||
country: body.country ?? 'SE',
|
||||
org_number: body.org_number,
|
||||
vat_number: body.vat_number,
|
||||
personal_number: encryptCustomerPersonalNumber(body.personal_number),
|
||||
language: body.language || 'sv',
|
||||
default_payment_terms: defaultPaymentTerms,
|
||||
notes: body.notes,
|
||||
})
|
||||
.select()
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
if (error.code === '23505') {
|
||||
return errorResponseFromCode('CUSTOMER_DUPLICATE_ORG_NUMBER', log, {
|
||||
requestId,
|
||||
details: { orgNumber: body.org_number },
|
||||
})
|
||||
}
|
||||
log.error('customer insert failed', error)
|
||||
return errorResponseFromCode('CUSTOMER_CREATE_FAILED', log, {
|
||||
requestId,
|
||||
details: { reason: getUserErrorMessage(error) },
|
||||
})
|
||||
}
|
||||
|
||||
// Auto-validate VAT number for EU business customers (non-blocking).
|
||||
if (body.customer_type === 'eu_business' && body.vat_number) {
|
||||
try {
|
||||
const vatResult = await validateVatNumber(body.vat_number)
|
||||
if (vatResult.valid) {
|
||||
await supabase
|
||||
.from('customers')
|
||||
.update({
|
||||
vat_number_validated: true,
|
||||
vat_number_validated_at: new Date().toISOString(),
|
||||
})
|
||||
.eq('id', data.id)
|
||||
.eq('company_id', companyId)
|
||||
|
||||
data.vat_number_validated = true
|
||||
data.vat_number_validated_at = new Date().toISOString()
|
||||
}
|
||||
} catch (err) {
|
||||
log.warn('auto-VIES validation failed on customer create', err as Error, {
|
||||
customerId: data.id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const safeCustomer = maskCustomerRow(data)
|
||||
await eventBus.emit({
|
||||
type: 'customer.created',
|
||||
payload: { customer: safeCustomer as Customer, companyId: companyId!, userId: user.id },
|
||||
})
|
||||
|
||||
return NextResponse.json({ data: safeCustomer })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
Reference in New Issue
Block a user