docs(production): standardiserad produktionsberedskap och gap-analys
Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -1,220 +0,0 @@
|
||||
/**
|
||||
* Integration tests for GET /api/v1/companies/:companyId/accounts and
|
||||
* GET .../fiscal-periods.
|
||||
*/
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
beforeAll(() => {
|
||||
if (process.env.NODE_ENV !== 'test') throw new Error('NODE_ENV=test required')
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL ||= 'http://localhost:54321'
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ||= 'test-anon-key'
|
||||
})
|
||||
|
||||
vi.mock('@/lib/auth/api-keys', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/auth/api-keys')>('@/lib/auth/api-keys')
|
||||
return { ...actual, validateApiKey: vi.fn(), createServiceClientNoCookies: vi.fn() }
|
||||
})
|
||||
vi.mock('@supabase/supabase-js', async () => {
|
||||
const actual = await vi.importActual<typeof import('@supabase/supabase-js')>('@supabase/supabase-js')
|
||||
return { ...actual, createClient: vi.fn().mockReturnValue({}) }
|
||||
})
|
||||
|
||||
import { validateApiKey, createServiceClientNoCookies } from '@/lib/auth/api-keys'
|
||||
import { GET as listAccounts } from '../route'
|
||||
import { GET as listPeriods } from '../../fiscal-periods/route'
|
||||
|
||||
const mockValidate = validateApiKey as ReturnType<typeof vi.fn>
|
||||
const mockServiceClient = createServiceClientNoCookies as ReturnType<typeof vi.fn>
|
||||
|
||||
type MockResult = { data?: unknown; error?: unknown }
|
||||
function makeFlexibleSupabase(byTable: Record<string, MockResult | MockResult[]>) {
|
||||
const queues = new Map<string, MockResult[]>()
|
||||
for (const [t, val] of Object.entries(byTable)) {
|
||||
queues.set(t, Array.isArray(val) ? [...val] : [val])
|
||||
}
|
||||
const buildChain = (table: string): unknown => {
|
||||
const handler: ProxyHandler<object> = {
|
||||
get(_target, prop) {
|
||||
if (prop === 'then') {
|
||||
return (resolve: (v: unknown) => void) => {
|
||||
const q = queues.get(table)
|
||||
const next = q && q.length > 1 ? q.shift()! : (q?.[0] ?? { data: null, error: null })
|
||||
resolve(next)
|
||||
}
|
||||
}
|
||||
return (..._args: unknown[]) => buildChain(table)
|
||||
},
|
||||
}
|
||||
return new Proxy({}, handler)
|
||||
}
|
||||
return { from: vi.fn((table: string) => buildChain(table)) }
|
||||
}
|
||||
|
||||
const COMPANY_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
|
||||
|
||||
function makeRequest(url: string): Request {
|
||||
return new Request(url, {
|
||||
method: 'GET',
|
||||
headers: { Authorization: 'Bearer test-fixture-not-a-real-key' },
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: COMPANY_ID,
|
||||
apiKeyId: 'ak_1',
|
||||
scopes: ['reports:read'],
|
||||
mode: 'live',
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /api/v1/companies/:companyId/accounts', () => {
|
||||
it('returns active accounts by default', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
chart_of_accounts: {
|
||||
data: [
|
||||
{
|
||||
account_number: '1930',
|
||||
account_name: 'Företagskonto',
|
||||
account_class: 1,
|
||||
account_group: '19',
|
||||
account_type: 'asset',
|
||||
normal_balance: 'debit',
|
||||
is_system_account: true,
|
||||
is_active: true,
|
||||
description: null,
|
||||
default_vat_code: null,
|
||||
sru_code: null,
|
||||
sort_order: 1930,
|
||||
},
|
||||
],
|
||||
error: null,
|
||||
},
|
||||
}),
|
||||
)
|
||||
const res = await listAccounts(
|
||||
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/accounts`),
|
||||
{ params: Promise.resolve({ companyId: COMPANY_ID }) },
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data.accounts).toHaveLength(1)
|
||||
expect(body.data.accounts[0].account_number).toBe('1930')
|
||||
})
|
||||
|
||||
it('returns all rows when the chart exceeds the 1000-row PostgREST page', async () => {
|
||||
const makeAccount = (n: number, sortOrder: number | null = n) => ({
|
||||
account_number: String(n),
|
||||
account_name: `Konto ${n}`,
|
||||
account_class: Math.floor(n / 1000),
|
||||
account_group: String(n).slice(0, 2),
|
||||
account_type: 'asset',
|
||||
normal_balance: 'debit',
|
||||
is_system_account: false,
|
||||
is_active: true,
|
||||
description: null,
|
||||
default_vat_code: null,
|
||||
sru_code: null,
|
||||
sort_order: sortOrder,
|
||||
})
|
||||
// Page 1: exactly 1000 rows (forces a second range request). Account 1000
|
||||
// gets sort_order 99999 and account 9998 (page 2) a null sort_order, so the
|
||||
// response order proves the sort_order re-sort with nulls last.
|
||||
const page1 = [
|
||||
makeAccount(1000, 99999),
|
||||
...Array.from({ length: 999 }, (_, i) => makeAccount(1001 + i)),
|
||||
]
|
||||
const page2 = [
|
||||
...Array.from({ length: 289 }, (_, i) => makeAccount(2000 + i)),
|
||||
makeAccount(9998, null),
|
||||
]
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
chart_of_accounts: [
|
||||
{ data: page1, error: null },
|
||||
{ data: page2, error: null },
|
||||
],
|
||||
}),
|
||||
)
|
||||
const res = await listAccounts(
|
||||
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/accounts`),
|
||||
{ params: Promise.resolve({ companyId: COMPANY_ID }) },
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data.accounts).toHaveLength(1290)
|
||||
expect(body.data.accounts[0].account_number).toBe('1001')
|
||||
// sort_order 99999 lands second-to-last; null sort_order lands last.
|
||||
expect(body.data.accounts[1288].account_number).toBe('1000')
|
||||
expect(body.data.accounts[1289].account_number).toBe('9998')
|
||||
})
|
||||
|
||||
it('rejects invalid class filter', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
}),
|
||||
)
|
||||
const res = await listAccounts(
|
||||
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/accounts?class=9`),
|
||||
{ params: Promise.resolve({ companyId: COMPANY_ID }) },
|
||||
)
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('rejects keys without reports:read scope', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: COMPANY_ID,
|
||||
scopes: ['invoices:read'],
|
||||
mode: 'live',
|
||||
})
|
||||
mockServiceClient.mockReturnValue(makeFlexibleSupabase({}))
|
||||
const res = await listAccounts(
|
||||
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/accounts`),
|
||||
{ params: Promise.resolve({ companyId: COMPANY_ID }) },
|
||||
)
|
||||
expect(res.status).toBe(403)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /api/v1/companies/:companyId/fiscal-periods', () => {
|
||||
it('returns fiscal periods sorted by period_start desc', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
fiscal_periods: {
|
||||
data: [
|
||||
{
|
||||
id: 'fp-1',
|
||||
name: 'Räkenskapsår 2026',
|
||||
period_start: '2026-01-01',
|
||||
period_end: '2026-12-31',
|
||||
is_closed: false,
|
||||
closed_at: null,
|
||||
locked_at: null,
|
||||
previous_period_id: null,
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
},
|
||||
],
|
||||
error: null,
|
||||
},
|
||||
}),
|
||||
)
|
||||
const res = await listPeriods(
|
||||
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/fiscal-periods`),
|
||||
{ params: Promise.resolve({ companyId: COMPANY_ID }) },
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data.fiscal_periods).toHaveLength(1)
|
||||
// Phase 3 review fix: derived BFL 3 kap fields appear on every row.
|
||||
expect(body.data.fiscal_periods[0].duration_days).toBe(365) // 2026-01-01 → 2026-12-31
|
||||
expect(body.data.fiscal_periods[0].exceeds_18_months).toBe(false)
|
||||
})
|
||||
})
|
||||
File diff suppressed because one or more lines are too long
@@ -1,186 +0,0 @@
|
||||
/**
|
||||
* Tests for GET /api/v1/companies/:companyId/articles (#895).
|
||||
*/
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
beforeAll(() => {
|
||||
if (process.env.NODE_ENV !== 'test') throw new Error('NODE_ENV=test required')
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL ||= 'http://localhost:54321'
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ||= 'test-anon-key'
|
||||
})
|
||||
|
||||
vi.mock('@/lib/auth/api-keys', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/auth/api-keys')>('@/lib/auth/api-keys')
|
||||
return { ...actual, validateApiKey: vi.fn(), createServiceClientNoCookies: vi.fn() }
|
||||
})
|
||||
vi.mock('@supabase/supabase-js', async () => {
|
||||
const actual = await vi.importActual<typeof import('@supabase/supabase-js')>('@supabase/supabase-js')
|
||||
return { ...actual, createClient: vi.fn().mockReturnValue({}) }
|
||||
})
|
||||
|
||||
import { validateApiKey, createServiceClientNoCookies } from '@/lib/auth/api-keys'
|
||||
import { GET as listArticles } from '../route'
|
||||
|
||||
const mockValidate = validateApiKey as ReturnType<typeof vi.fn>
|
||||
const mockServiceClient = createServiceClientNoCookies as ReturnType<typeof vi.fn>
|
||||
|
||||
const COMPANY_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
|
||||
|
||||
const SAMPLE_ARTICLE = {
|
||||
id: 'dddddddd-dddd-4ddd-8ddd-dddddddddddd',
|
||||
article_number: 'A-0001',
|
||||
name: 'Takarbete',
|
||||
name_en: null,
|
||||
type: 'tjanst',
|
||||
unit: 'tim',
|
||||
price_excl_vat: 850,
|
||||
currency: 'SEK',
|
||||
vat_rate: 25,
|
||||
revenue_account: null,
|
||||
cost_price: null,
|
||||
ean: null,
|
||||
housework_type: 'BYGG',
|
||||
notes: null,
|
||||
active: true,
|
||||
created_at: '2026-05-01T09:14:33Z',
|
||||
updated_at: '2026-05-01T09:14:33Z',
|
||||
}
|
||||
|
||||
/** Chainable mock whose terminal await resolves per-table. Records eq() calls. */
|
||||
function makeSupabase(byTable: Record<string, { data?: unknown; error?: unknown }>) {
|
||||
const eqCalls: Array<[string, unknown, unknown]> = []
|
||||
const buildChain = (table: string): unknown => {
|
||||
const handler: ProxyHandler<object> = {
|
||||
get(_target, prop) {
|
||||
if (prop === 'then') {
|
||||
return (resolve: (v: unknown) => void) =>
|
||||
resolve(byTable[table] ?? { data: null, error: null })
|
||||
}
|
||||
return (...args: unknown[]) => {
|
||||
if (prop === 'eq') eqCalls.push([table, args[0], args[1]])
|
||||
return buildChain(table)
|
||||
}
|
||||
},
|
||||
}
|
||||
return new Proxy({}, handler)
|
||||
}
|
||||
return {
|
||||
from: vi.fn((table: string) => buildChain(table)),
|
||||
rpc: vi.fn(() => buildChain('rpc')),
|
||||
eqCalls,
|
||||
}
|
||||
}
|
||||
|
||||
function makeRequest(url: string): Request {
|
||||
return new Request(url, {
|
||||
headers: { Authorization: 'Bearer test-fixture-not-a-real-key' },
|
||||
})
|
||||
}
|
||||
|
||||
const routeParams = { params: Promise.resolve({ companyId: COMPANY_ID }) }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: COMPANY_ID,
|
||||
apiKeyId: 'ak_1',
|
||||
apiKeyName: 'CI key',
|
||||
scopes: ['invoices:read'],
|
||||
mode: 'live',
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /api/v1/companies/:companyId/articles', () => {
|
||||
it('returns active articles with the documented projection', async () => {
|
||||
const client = makeSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
articles: { data: [SAMPLE_ARTICLE], error: null },
|
||||
})
|
||||
mockServiceClient.mockReturnValue(client)
|
||||
|
||||
const res = await listArticles(
|
||||
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/articles`),
|
||||
routeParams,
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data.articles).toHaveLength(1)
|
||||
expect(body.data.articles[0].housework_type).toBe('BYGG')
|
||||
// Default: inactive articles filtered out.
|
||||
expect(client.eqCalls).toContainEqual(['articles', 'active', true])
|
||||
})
|
||||
|
||||
it('exposes the article currency so a caller can tell a non-SEK price apart', async () => {
|
||||
// price_excl_vat alone is ambiguous: without currency an agent copies a EUR
|
||||
// price onto a SEK invoice line with no FX conversion.
|
||||
const client = makeSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
articles: { data: [{ ...SAMPLE_ARTICLE, price_excl_vat: 95, currency: 'EUR' }], error: null },
|
||||
})
|
||||
mockServiceClient.mockReturnValue(client)
|
||||
|
||||
const res = await listArticles(
|
||||
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/articles`),
|
||||
routeParams,
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data.articles[0].currency).toBe('EUR')
|
||||
expect(body.data.articles[0].price_excl_vat).toBe(95)
|
||||
})
|
||||
|
||||
it('includes inactive articles with ?include_inactive=true', async () => {
|
||||
const client = makeSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
articles: { data: [SAMPLE_ARTICLE, { ...SAMPLE_ARTICLE, id: 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee', active: false }], error: null },
|
||||
})
|
||||
mockServiceClient.mockReturnValue(client)
|
||||
|
||||
const res = await listArticles(
|
||||
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/articles?include_inactive=true`),
|
||||
routeParams,
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data.articles).toHaveLength(2)
|
||||
expect(client.eqCalls).not.toContainEqual(['articles', 'active', true])
|
||||
})
|
||||
|
||||
it('rejects a malformed include_inactive with 400 VALIDATION_ERROR', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await listArticles(
|
||||
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/articles?include_inactive=1`),
|
||||
routeParams,
|
||||
)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('VALIDATION_ERROR')
|
||||
})
|
||||
|
||||
it('rejects keys without invoices:read scope (403)', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: COMPANY_ID,
|
||||
scopes: ['reports:read'],
|
||||
mode: 'live',
|
||||
})
|
||||
mockServiceClient.mockReturnValue(makeSupabase({}))
|
||||
|
||||
const res = await listArticles(
|
||||
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/articles`),
|
||||
routeParams,
|
||||
)
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
})
|
||||
})
|
||||
@@ -1,130 +0,0 @@
|
||||
/**
|
||||
* GET /api/v1/companies/{companyId}/articles: list the artikelregister.
|
||||
*
|
||||
* Read-only (#895): exposes the article catalog so API callers can link
|
||||
* invoice items via items[].article_id and copy the article's price,
|
||||
* VAT rate, revenue-account override, and ROT/RUT arbetstypskod
|
||||
* (housework_type) onto the line. Article CRUD stays dashboard-only for
|
||||
* now; the register is small, so this is a plain (non-cursor) list with
|
||||
* an include_inactive toggle, mirroring the internal /api/articles GET.
|
||||
*/
|
||||
import { z } from 'zod'
|
||||
import { ok } from '@/lib/api/v1/response'
|
||||
import { registerEndpoint, dataEnvelope } from '@/lib/api/v1/registry'
|
||||
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors'
|
||||
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
||||
|
||||
const ArticleShape = z.object({
|
||||
id: z.string().uuid(),
|
||||
article_number: z.string().nullable(),
|
||||
name: z.string(),
|
||||
name_en: z.string().nullable(),
|
||||
type: z.enum(['vara', 'tjanst']),
|
||||
unit: z.string(),
|
||||
price_excl_vat: z.number(),
|
||||
currency: z.string(),
|
||||
vat_rate: z.number(),
|
||||
revenue_account: z.string().nullable(),
|
||||
cost_price: z.number().nullable(),
|
||||
ean: z.string().nullable(),
|
||||
housework_type: z.string().nullable(),
|
||||
notes: z.string().nullable(),
|
||||
active: z.boolean(),
|
||||
created_at: z.string(),
|
||||
updated_at: z.string(),
|
||||
})
|
||||
|
||||
// Explicit projection: excludes user_id, company_id (internal scoping).
|
||||
const ARTICLE_COLUMNS =
|
||||
'id, article_number, name, name_en, type, unit, price_excl_vat, currency, vat_rate, revenue_account, cost_price, ean, housework_type, notes, active, created_at, updated_at'
|
||||
|
||||
registerEndpoint({
|
||||
operation: 'articles.list',
|
||||
method: 'GET',
|
||||
path: '/api/v1/companies/:companyId/articles',
|
||||
summary: 'List the article register (artikelregister).',
|
||||
description:
|
||||
'Returns the company\'s articles ordered by name. Pass ?include_inactive=true to include soft-deactivated articles. Use the returned id as items[].article_id when creating invoices; housework_type carries the ROT/RUT arbetstypskod for service articles, and revenue_account the optional BAS class-3 override.',
|
||||
useWhen:
|
||||
'You need the article catalog before composing invoice lines: to resolve an article_id, read its price/VAT defaults, or find ROT/RUT-tagged service articles (housework_type set).',
|
||||
doNotUseFor:
|
||||
'Creating or editing articles (dashboard-only for now). Invoice line creation itself (POST …/invoices with items[].article_id).',
|
||||
pitfalls: [
|
||||
'Linking article_id does NOT auto-fill the invoice line: send description, unit_price, vat_rate etc. explicitly on the item (copy them from this response).',
|
||||
'price_excl_vat always excludes VAT.',
|
||||
'price_excl_vat is denominated in the article\'s own currency, which is NOT always SEK. Check currency before copying the price onto an invoice line: the invoice carries a single currency for all its lines and there is no FX conversion here.',
|
||||
'housework_type is an arbetstypskod hint (e.g. BYGG, STAD); the invoice line still needs deduction_type + labor_hours + work_type set explicitly for ROT/RUT.',
|
||||
'Inactive articles (active=false) are hidden by default but remain linkable for historical reads.',
|
||||
],
|
||||
example: {
|
||||
response: {
|
||||
data: {
|
||||
articles: [
|
||||
{
|
||||
id: '0e9c…',
|
||||
article_number: 'A-0001',
|
||||
name: 'Takarbete',
|
||||
name_en: null,
|
||||
type: 'tjanst',
|
||||
unit: 'tim',
|
||||
price_excl_vat: 850,
|
||||
currency: 'SEK',
|
||||
vat_rate: 25,
|
||||
revenue_account: null,
|
||||
cost_price: null,
|
||||
ean: null,
|
||||
housework_type: 'BYGG',
|
||||
notes: null,
|
||||
active: true,
|
||||
created_at: '2026-05-01T09:14:33Z',
|
||||
updated_at: '2026-05-01T09:14:33Z',
|
||||
},
|
||||
],
|
||||
},
|
||||
meta: { request_id: 'req_…', api_version: '2026-05-12' },
|
||||
},
|
||||
},
|
||||
scope: 'invoices:read',
|
||||
risk: 'low',
|
||||
idempotent: true,
|
||||
reversible: false,
|
||||
dryRunSupported: false,
|
||||
response: { success: dataEnvelope(z.object({ articles: z.array(ArticleShape) })) },
|
||||
})
|
||||
|
||||
export const GET = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
'articles.list',
|
||||
async (request, ctx) => {
|
||||
const url = new URL(request.url)
|
||||
const includeInactiveRaw = url.searchParams.get('include_inactive')
|
||||
if (includeInactiveRaw !== null && !['true', 'false'].includes(includeInactiveRaw)) {
|
||||
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { field: 'include_inactive', message: 'Expected true or false.' },
|
||||
})
|
||||
}
|
||||
const includeInactive = includeInactiveRaw === 'true'
|
||||
|
||||
try {
|
||||
// Imported product catalogs can exceed PostgREST's silent 1000-row cap:
|
||||
// paginate internally, same as the dashboard route. Secondary order on
|
||||
// id gives the stable total order .range() paging requires.
|
||||
const articles = await fetchAllRows(({ from, to }) => {
|
||||
let query = ctx.supabase
|
||||
.from('articles')
|
||||
.select(ARTICLE_COLUMNS)
|
||||
.eq('company_id', ctx.companyId!)
|
||||
if (!includeInactive) query = query.eq('active', true)
|
||||
return query
|
||||
.order('name', { ascending: true })
|
||||
.order('id', { ascending: true })
|
||||
.range(from, to)
|
||||
})
|
||||
|
||||
return ok({ articles }, { requestId: ctx.requestId })
|
||||
} catch (err) {
|
||||
return v1ErrorResponse(err, ctx.log, { requestId: ctx.requestId })
|
||||
}
|
||||
},
|
||||
)
|
||||
-254
@@ -1,254 +0,0 @@
|
||||
/**
|
||||
* Tests for POST /api/v1/companies/{companyId}/bank-connections/{connectionId}/sync.
|
||||
*
|
||||
* Exercises the real withApiV1 wrapper (auth, scope, company membership,
|
||||
* idempotency header) with the Supabase client and the sync runner mocked.
|
||||
*/
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
beforeAll(() => {
|
||||
if (process.env.NODE_ENV !== 'test') throw new Error('NODE_ENV=test required')
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL ||= 'http://localhost:54321'
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ||= 'test-anon-key'
|
||||
})
|
||||
|
||||
vi.mock('@/lib/auth/api-keys', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/auth/api-keys')>('@/lib/auth/api-keys')
|
||||
return { ...actual, validateApiKey: vi.fn(), createServiceClientNoCookies: vi.fn() }
|
||||
})
|
||||
vi.mock('@supabase/supabase-js', async () => {
|
||||
const actual = await vi.importActual<typeof import('@supabase/supabase-js')>('@supabase/supabase-js')
|
||||
return { ...actual, createClient: vi.fn().mockReturnValue({}) }
|
||||
})
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
const { requireCapabilityMock, triggerSyncMock, registryGetMock } = vi.hoisted(() => ({
|
||||
requireCapabilityMock: vi.fn(),
|
||||
triggerSyncMock: vi.fn(),
|
||||
registryGetMock: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/lib/entitlements/has-capability', () => ({
|
||||
requireCapability: requireCapabilityMock,
|
||||
}))
|
||||
// Core cannot import the extension: the route resolves the runner through
|
||||
// the registry's `services` channel, so that is what gets stubbed.
|
||||
vi.mock('@/lib/extensions/registry', () => ({
|
||||
extensionRegistry: { get: registryGetMock },
|
||||
}))
|
||||
|
||||
import { validateApiKey, createServiceClientNoCookies } from '@/lib/auth/api-keys'
|
||||
import { POST } from '../route'
|
||||
|
||||
const mockValidate = validateApiKey as ReturnType<typeof vi.fn>
|
||||
const mockServiceClient = createServiceClientNoCookies as ReturnType<typeof vi.fn>
|
||||
|
||||
type MockResult = { data?: unknown; error?: unknown }
|
||||
function makeFlexibleSupabase(byTable: Record<string, MockResult | MockResult[]>) {
|
||||
const queues = new Map<string, MockResult[]>()
|
||||
for (const [t, val] of Object.entries(byTable)) queues.set(t, Array.isArray(val) ? [...val] : [val])
|
||||
const buildChain = (table: string): unknown => {
|
||||
const handler: ProxyHandler<object> = {
|
||||
get(_target, prop) {
|
||||
if (prop === 'then') {
|
||||
return (resolve: (v: unknown) => void) => {
|
||||
const q = queues.get(table)
|
||||
const next = q && q.length > 1 ? q.shift()! : (q?.[0] ?? { data: null, error: null })
|
||||
resolve(next)
|
||||
}
|
||||
}
|
||||
return (..._args: unknown[]) => buildChain(table)
|
||||
},
|
||||
}
|
||||
return new Proxy({}, handler)
|
||||
}
|
||||
return { from: vi.fn((table: string) => buildChain(table)) }
|
||||
}
|
||||
|
||||
const COMPANY_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
|
||||
const CONNECTION_ID = '11111111-1111-4111-8111-111111111111'
|
||||
const BASE = `http://localhost/api/v1/companies/${COMPANY_ID}/bank-connections/${CONNECTION_ID}/sync`
|
||||
|
||||
function req(opts: { idempotencyKey?: string | null; dryRun?: boolean } = {}): Request {
|
||||
const headers: Record<string, string> = {
|
||||
Authorization: 'Bearer test-fixture-not-a-real-key',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
if (opts.idempotencyKey !== null) headers['Idempotency-Key'] = opts.idempotencyKey ?? 'idem-1'
|
||||
const url = opts.dryRun ? `${BASE}?dry_run=true` : BASE
|
||||
return new Request(url, { method: 'POST', headers, body: '{}' })
|
||||
}
|
||||
|
||||
function authOk(scopes: string[], mode: 'live' | 'test' = 'live') {
|
||||
mockValidate.mockResolvedValue({
|
||||
valid: true,
|
||||
userId: 'user-1',
|
||||
keyId: 'key-1',
|
||||
keyName: 'Test key',
|
||||
scopes,
|
||||
mode,
|
||||
})
|
||||
}
|
||||
|
||||
const params = { params: Promise.resolve({ companyId: COMPANY_ID, connectionId: CONNECTION_ID }) }
|
||||
|
||||
const OK_RESULT = {
|
||||
ok: true,
|
||||
connection_id: CONNECTION_ID,
|
||||
bank: 'Swedbank',
|
||||
imported: 3,
|
||||
duplicates: 12,
|
||||
from_date: '2026-08-26',
|
||||
to_date: '2026-09-02',
|
||||
last_synced_at: '2026-09-02T09:14:03.000Z',
|
||||
}
|
||||
|
||||
describe('v1 bank-connections sync', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
requireCapabilityMock.mockResolvedValue(null)
|
||||
triggerSyncMock.mockResolvedValue(OK_RESULT)
|
||||
registryGetMock.mockImplementation((id: string) =>
|
||||
id === 'enable-banking' ? { services: { triggerConnectionSync: triggerSyncMock } } : undefined,
|
||||
)
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { role: 'owner' } },
|
||||
idempotency_keys: { data: null },
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('401 without a valid key', async () => {
|
||||
mockValidate.mockResolvedValue({ valid: false, error: 'invalid' })
|
||||
const res = await POST(req(), params)
|
||||
expect(res.status).toBe(401)
|
||||
expect(triggerSyncMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('403 INSUFFICIENT_SCOPE when the key lacks transactions:write', async () => {
|
||||
authOk(['transactions:read', 'companies:read'])
|
||||
const res = await POST(req(), params)
|
||||
expect(res.status).toBe(403)
|
||||
expect(triggerSyncMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns the capability-blocked response when bank_sync is not entitled', async () => {
|
||||
authOk(['transactions:write'])
|
||||
requireCapabilityMock.mockResolvedValue(
|
||||
Response.json({ error: { code: 'CAPABILITY_BLOCKED' } }, { status: 403 }),
|
||||
)
|
||||
const res = await POST(req(), params)
|
||||
expect(res.status).toBe(403)
|
||||
expect(requireCapabilityMock).toHaveBeenCalledWith(expect.anything(), COMPANY_ID, 'bank_sync')
|
||||
expect(triggerSyncMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('404 when the key user is not a member of the company', async () => {
|
||||
authOk(['transactions:write'])
|
||||
mockServiceClient.mockReturnValue(makeFlexibleSupabase({ company_members: { data: null } }))
|
||||
const res = await POST(req(), params)
|
||||
expect(res.status).toBe(404)
|
||||
expect(triggerSyncMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('blocks a test key: the bank call cannot be simulated', async () => {
|
||||
authOk(['transactions:write'], 'test')
|
||||
const res = await POST(req(), params)
|
||||
expect(res.status).toBeGreaterThanOrEqual(400)
|
||||
expect(res.status).toBeLessThan(500)
|
||||
expect(triggerSyncMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses ?dry_run=true on a live key with a VALIDATION_ERROR', async () => {
|
||||
authOk(['transactions:write'])
|
||||
const res = await POST(req({ dryRun: true }), params)
|
||||
expect(res.status).toBe(400)
|
||||
const body = (await res.json()) as { error: { code: string; details: { field: string } } }
|
||||
expect(body.error.code).toBe('VALIDATION_ERROR')
|
||||
expect(body.error.details.field).toBe('dry_run')
|
||||
expect(triggerSyncMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('answers EXTENSION_DISABLED when the enable-banking extension is not registered', async () => {
|
||||
authOk(['transactions:write'])
|
||||
registryGetMock.mockReturnValue(undefined)
|
||||
const res = await POST(req(), params)
|
||||
const body = (await res.json()) as { error: { code: string } }
|
||||
expect(body.error.code).toBe('EXTENSION_DISABLED')
|
||||
expect(triggerSyncMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('runs the sync for the path connection and returns the outcome', async () => {
|
||||
authOk(['transactions:write'])
|
||||
const res = await POST(req(), params)
|
||||
expect(res.status).toBe(200)
|
||||
const body = (await res.json()) as {
|
||||
data: Record<string, unknown>
|
||||
meta: { request_id: string }
|
||||
}
|
||||
expect(triggerSyncMock).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({ companyId: COMPANY_ID, userId: 'user-1', connectionId: CONNECTION_ID }),
|
||||
)
|
||||
expect(body.data).toEqual({
|
||||
connection_id: CONNECTION_ID,
|
||||
bank: 'Swedbank',
|
||||
imported: 3,
|
||||
duplicates: 12,
|
||||
from_date: '2026-08-26',
|
||||
to_date: '2026-09-02',
|
||||
last_synced_at: '2026-09-02T09:14:03.000Z',
|
||||
})
|
||||
expect(body.meta.request_id).toMatch(/^req_/)
|
||||
})
|
||||
|
||||
it('429 BANK_SYNC_COOLDOWN with next_allowed_at and Retry-After', async () => {
|
||||
authOk(['transactions:write'])
|
||||
triggerSyncMock.mockResolvedValue({
|
||||
ok: false,
|
||||
code: 'BANK_SYNC_COOLDOWN',
|
||||
connection_id: CONNECTION_ID,
|
||||
next_allowed_at: '2026-09-02T09:29:03.000Z',
|
||||
retry_after_seconds: 600,
|
||||
})
|
||||
const res = await POST(req(), params)
|
||||
expect(res.status).toBe(429)
|
||||
expect(res.headers.get('Retry-After')).toBe('600')
|
||||
const body = (await res.json()) as {
|
||||
error: { code: string; details: { next_allowed_at: string } }
|
||||
}
|
||||
expect(body.error.code).toBe('BANK_SYNC_COOLDOWN')
|
||||
expect(body.error.details.next_allowed_at).toBe('2026-09-02T09:29:03.000Z')
|
||||
})
|
||||
|
||||
it('409 BANK_SESSION_EXPIRED with a recovery hint pointing at the connect link', async () => {
|
||||
authOk(['transactions:write'])
|
||||
triggerSyncMock.mockResolvedValue({
|
||||
ok: false,
|
||||
code: 'BANK_SESSION_EXPIRED',
|
||||
connection_id: CONNECTION_ID,
|
||||
status: 'expired',
|
||||
})
|
||||
const res = await POST(req(), params)
|
||||
expect(res.status).toBe(409)
|
||||
const body = (await res.json()) as { error: { code: string; recovery_hint?: string } }
|
||||
expect(body.error.code).toBe('BANK_SESSION_EXPIRED')
|
||||
expect(body.error.recovery_hint).toContain('connect_url')
|
||||
})
|
||||
|
||||
it('404 NOT_FOUND for a connection outside the company', async () => {
|
||||
authOk(['transactions:write'])
|
||||
triggerSyncMock.mockResolvedValue({ ok: false, code: 'NOT_FOUND', connection_id: CONNECTION_ID })
|
||||
const res = await POST(req(), params)
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('maps a thrown database error into the v1 error envelope', async () => {
|
||||
authOk(['transactions:write'])
|
||||
triggerSyncMock.mockRejectedValue({ message: 'boom', code: '57014' })
|
||||
const res = await POST(req(), params)
|
||||
expect(res.status).toBeGreaterThanOrEqual(500)
|
||||
const body = (await res.json()) as { error: { code: string } }
|
||||
expect(body.error.code).toBeTruthy()
|
||||
})
|
||||
})
|
||||
@@ -1,157 +0,0 @@
|
||||
/**
|
||||
* POST /api/v1/companies/{companyId}/bank-connections/{connectionId}/sync
|
||||
*
|
||||
* Trigger a PSD2 sync of one bank connection now, instead of waiting for
|
||||
* the nightly cron. The window is not caller-controlled: the same gap-aware
|
||||
* incremental lookback the cron uses (7 days, widened to cover any gap since
|
||||
* last_synced_at, capped at 90). A connection synced or attempted within the
|
||||
* last 15 minutes answers 429 BANK_SYNC_COOLDOWN with next_allowed_at (the
|
||||
* attempt guard is a durable lease on the row, claimed atomically), so an
|
||||
* unattended agent can never run up the Enable Banking bill by polling, even
|
||||
* across serverless instances.
|
||||
*
|
||||
* What this cannot do: revive a dead consent. status=expired (or a session
|
||||
* the bank reports dead mid-sync) needs BankID in a browser; the response
|
||||
* says so and points at the connect link.
|
||||
*
|
||||
* The runner lives in the enable-banking extension. Core cannot import it
|
||||
* (CI guard), so it is reached through the registry-resolved `services`
|
||||
* channel declared in lib/bank-sync/trigger-sync-contract.ts, and a
|
||||
* deployment without the extension answers EXTENSION_DISABLED.
|
||||
*/
|
||||
import { z } from 'zod'
|
||||
import { ok } from '@/lib/api/v1/response'
|
||||
import { registerEndpoint, dataEnvelope } from '@/lib/api/v1/registry'
|
||||
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors'
|
||||
import { requireCapability } from '@/lib/entitlements/has-capability'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { extensionRegistry } from '@/lib/extensions/registry'
|
||||
import {
|
||||
SYNC_COOLDOWN_MS,
|
||||
type EnableBankingServices,
|
||||
} from '@/lib/bank-sync/trigger-sync-contract'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
const SyncResponse = z.object({
|
||||
connection_id: z.string().uuid(),
|
||||
bank: z.string().nullable(),
|
||||
imported: z.number().int().nonnegative(),
|
||||
duplicates: z.number().int().nonnegative(),
|
||||
from_date: z.string(),
|
||||
to_date: z.string(),
|
||||
last_synced_at: z.string(),
|
||||
})
|
||||
|
||||
registerEndpoint({
|
||||
operation: 'bank-connections.sync',
|
||||
method: 'POST',
|
||||
path: '/api/v1/companies/:companyId/bank-connections/:connectionId/sync',
|
||||
summary: 'Sync one bank connection now instead of waiting for the nightly run.',
|
||||
description:
|
||||
'Fetches new transactions and balances for one PSD2 bank connection right away. The window is chosen server-side: the last 7 days, widened to cover any gap since last_synced_at, capped at 90 days. Returns how many transactions were imported and the new last_synced_at. A connection synced within the last 15 minutes is refused with 429 BANK_SYNC_COOLDOWN and next_allowed_at: the data is already fresh. Not dry-runnable: the bank call itself is the side effect.',
|
||||
useWhen:
|
||||
'GET /bank-connections shows a stale last_synced_at on an active connection and you need current bank data before building on it (liquidity, reconciliation, a report), or the user asks for the latest transactions now.',
|
||||
doNotUseFor:
|
||||
'Polling. Connections sync every night on their own; call this once when freshness matters, then read /transactions. Fixing a dead connection: status=expired needs BankID in a browser, not a sync.',
|
||||
pitfalls: [
|
||||
'Idempotency-Key is optional here. If you send one, use a fresh key per attempt: a cooldown answer is never cached, but a completed sync is, and replaying it fetches nothing new.',
|
||||
'429 BANK_SYNC_COOLDOWN follows a recent successful sync OR a recent attempt that failed (the 15-minute lease is taken before the bank is called, on every instance). Compare last_synced_at from GET /bank-connections: if it is fresh, use the data you have; if it is still stale, the previous attempt failed, so retry once after next_allowed_at (Retry-After is set).',
|
||||
'409 BANK_SESSION_EXPIRED means the bank reported the consent dead during the sync; the connection is now status=expired. Hand the user the connect link; no API call revives it.',
|
||||
'imported: 0 is normal on a quiet account. Banks report with up to 48 hours of delay, so today\'s transactions often arrive tomorrow.',
|
||||
'Costs one Enable Banking call per enabled account: 403 CAPABILITY_BLOCKED when the company has no bank_sync entitlement.',
|
||||
],
|
||||
example: {
|
||||
response: {
|
||||
data: {
|
||||
connection_id: '4f6c…',
|
||||
bank: 'Swedbank',
|
||||
imported: 3,
|
||||
duplicates: 12,
|
||||
from_date: '2026-08-26',
|
||||
to_date: '2026-09-02',
|
||||
last_synced_at: '2026-09-02T09:14:03Z',
|
||||
},
|
||||
meta: { request_id: 'req_…', api_version: '2026-05-12' },
|
||||
},
|
||||
},
|
||||
scope: 'transactions:write',
|
||||
risk: 'low',
|
||||
idempotent: false,
|
||||
reversible: false,
|
||||
dryRunSupported: false,
|
||||
response: {
|
||||
success: dataEnvelope(SyncResponse),
|
||||
errorCodes: [
|
||||
'BANK_SYNC_COOLDOWN',
|
||||
'BANK_SYNC_NOT_ACTIVE',
|
||||
'BANK_SYNC_NO_ACCOUNTS',
|
||||
'BANK_SESSION_EXPIRED',
|
||||
'BANK_SYNC_FAILED',
|
||||
'CAPABILITY_BLOCKED',
|
||||
'EXTENSION_DISABLED',
|
||||
'NOT_FOUND',
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
export const POST = withApiV1<{ params: Promise<{ companyId: string; connectionId: string }> }>(
|
||||
'bank-connections.sync',
|
||||
async (_request, ctx, params) => {
|
||||
const { connectionId } = await params.params
|
||||
|
||||
const capBlocked = await requireCapability(ctx.supabase, ctx.companyId!, CAPABILITY.bank_sync)
|
||||
if (capBlocked) return capBlocked
|
||||
|
||||
// The bank round-trip IS the side effect, so there is nothing to simulate.
|
||||
// Test keys never reach this line (the wrapper blocks them on endpoints
|
||||
// that cannot dry-run); a live key passing ?dry_run=true is told why.
|
||||
if (ctx.dryRun) {
|
||||
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: {
|
||||
field: 'dry_run',
|
||||
message: 'dry_run is not supported: the bank call is the side effect.',
|
||||
cooldown_ms: SYNC_COOLDOWN_MS,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// The enable-banking extension is opt-in (extensions.config.json) and the
|
||||
// registry is the runtime source of truth: absent registration means the
|
||||
// deployment does not offer PSD2 sync at all.
|
||||
const services = extensionRegistry.get('enable-banking')?.services as
|
||||
| Partial<EnableBankingServices>
|
||||
| undefined
|
||||
if (!services?.triggerConnectionSync) {
|
||||
return v1ErrorResponseFromCode('EXTENSION_DISABLED', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await services.triggerConnectionSync(ctx.supabase, {
|
||||
companyId: ctx.companyId!,
|
||||
userId: ctx.userId,
|
||||
connectionId,
|
||||
log: ctx.log,
|
||||
})
|
||||
|
||||
if (!result.ok) {
|
||||
const { ok: _ok, code, ...details } = result
|
||||
return v1ErrorResponseFromCode(code, ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details,
|
||||
retryAfterSeconds: result.retry_after_seconds,
|
||||
})
|
||||
}
|
||||
|
||||
const { ok: _ok, ...data } = result
|
||||
return ok(data, { requestId: ctx.requestId })
|
||||
} catch (error) {
|
||||
return v1ErrorResponse(error, ctx.log, { requestId: ctx.requestId })
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -1,183 +0,0 @@
|
||||
/**
|
||||
* Tests for GET /api/v1/companies/{companyId}/bank-connections.
|
||||
*
|
||||
* Exercises the real withApiV1 wrapper (auth, scope, company membership)
|
||||
* with the Supabase client mocked.
|
||||
*/
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
beforeAll(() => {
|
||||
if (process.env.NODE_ENV !== 'test') throw new Error('NODE_ENV=test required')
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL ||= 'http://localhost:54321'
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ||= 'test-anon-key'
|
||||
})
|
||||
|
||||
vi.mock('@/lib/auth/api-keys', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/auth/api-keys')>('@/lib/auth/api-keys')
|
||||
return { ...actual, validateApiKey: vi.fn(), createServiceClientNoCookies: vi.fn() }
|
||||
})
|
||||
vi.mock('@supabase/supabase-js', async () => {
|
||||
const actual = await vi.importActual<typeof import('@supabase/supabase-js')>('@supabase/supabase-js')
|
||||
return { ...actual, createClient: vi.fn().mockReturnValue({}) }
|
||||
})
|
||||
|
||||
const { requireCapabilityMock } = vi.hoisted(() => ({ requireCapabilityMock: vi.fn() }))
|
||||
vi.mock('@/lib/entitlements/has-capability', () => ({
|
||||
requireCapability: requireCapabilityMock,
|
||||
}))
|
||||
|
||||
import { validateApiKey, createServiceClientNoCookies } from '@/lib/auth/api-keys'
|
||||
import { GET } from '../route'
|
||||
|
||||
const mockValidate = validateApiKey as ReturnType<typeof vi.fn>
|
||||
const mockServiceClient = createServiceClientNoCookies as ReturnType<typeof vi.fn>
|
||||
|
||||
type MockResult = { data?: unknown; error?: unknown }
|
||||
function makeFlexibleSupabase(byTable: Record<string, MockResult | MockResult[]>) {
|
||||
const queues = new Map<string, MockResult[]>()
|
||||
for (const [t, val] of Object.entries(byTable)) queues.set(t, Array.isArray(val) ? [...val] : [val])
|
||||
const buildChain = (table: string): unknown => {
|
||||
const handler: ProxyHandler<object> = {
|
||||
get(_target, prop) {
|
||||
if (prop === 'then') {
|
||||
return (resolve: (v: unknown) => void) => {
|
||||
const q = queues.get(table)
|
||||
const next = q && q.length > 1 ? q.shift()! : (q?.[0] ?? { data: null, error: null })
|
||||
resolve(next)
|
||||
}
|
||||
}
|
||||
return (..._args: unknown[]) => buildChain(table)
|
||||
},
|
||||
}
|
||||
return new Proxy({}, handler)
|
||||
}
|
||||
return { from: vi.fn((table: string) => buildChain(table)) }
|
||||
}
|
||||
|
||||
const COMPANY_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
|
||||
const BASE = `http://localhost/api/v1/companies/${COMPANY_ID}/bank-connections`
|
||||
|
||||
const CONNECTION_ROW = {
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
bank_name: 'Swedbank',
|
||||
status: 'active',
|
||||
created_at: '2026-08-01T00:00:00Z',
|
||||
last_synced_at: '2026-08-31T05:04:12Z',
|
||||
consent_expires: '2026-11-01T00:00:00Z',
|
||||
error_message: null,
|
||||
}
|
||||
|
||||
function req(): Request {
|
||||
return new Request(BASE, {
|
||||
headers: { Authorization: 'Bearer test-fixture-not-a-real-key' },
|
||||
})
|
||||
}
|
||||
|
||||
function authOk(scopes: string[]) {
|
||||
mockValidate.mockResolvedValue({
|
||||
valid: true,
|
||||
userId: 'user-1',
|
||||
keyId: 'key-1',
|
||||
keyName: 'Test key',
|
||||
scopes,
|
||||
mode: 'live',
|
||||
})
|
||||
}
|
||||
|
||||
const params = { params: Promise.resolve({ companyId: COMPANY_ID }) }
|
||||
|
||||
describe('v1 bank-connections list', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
requireCapabilityMock.mockResolvedValue(null)
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { role: 'owner' } },
|
||||
bank_connections: { data: [CONNECTION_ROW] },
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('401 without a valid key', async () => {
|
||||
mockValidate.mockResolvedValue({ valid: false, error: 'invalid' })
|
||||
const res = await GET(req(), params)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('403 INSUFFICIENT_SCOPE when the key lacks companies:read', async () => {
|
||||
authOk(['transactions:read'])
|
||||
const res = await GET(req(), params)
|
||||
expect(res.status).toBe(403)
|
||||
})
|
||||
|
||||
it('returns the capability-blocked response when bank_sync is not entitled', async () => {
|
||||
authOk(['companies:read'])
|
||||
requireCapabilityMock.mockResolvedValue(
|
||||
Response.json({ error: { code: 'CAPABILITY_BLOCKED' } }, { status: 403 }),
|
||||
)
|
||||
const res = await GET(req(), params)
|
||||
expect(res.status).toBe(403)
|
||||
expect(requireCapabilityMock).toHaveBeenCalledWith(expect.anything(), COMPANY_ID, 'bank_sync')
|
||||
})
|
||||
|
||||
it('404 when the key user is not a member of the company', async () => {
|
||||
authOk(['companies:read'])
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: null },
|
||||
}),
|
||||
)
|
||||
const res = await GET(req(), params)
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('returns connections with freshness fields under qualified names', async () => {
|
||||
authOk(['companies:read'])
|
||||
const res = await GET(req(), params)
|
||||
expect(res.status).toBe(200)
|
||||
const body = (await res.json()) as {
|
||||
data: { bank_connections: Array<Record<string, unknown>> }
|
||||
meta: { request_id: string }
|
||||
}
|
||||
expect(body.data.bank_connections).toEqual([
|
||||
{
|
||||
connection_id: '11111111-1111-4111-8111-111111111111',
|
||||
bank: 'Swedbank',
|
||||
status: 'active',
|
||||
since: '2026-08-01T00:00:00Z',
|
||||
last_synced_at: '2026-08-31T05:04:12Z',
|
||||
consent_expires: '2026-11-01T00:00:00Z',
|
||||
error_message: null,
|
||||
},
|
||||
])
|
||||
expect(body.meta.request_id).toMatch(/^req_/)
|
||||
})
|
||||
|
||||
it('returns an empty list when the company has no connections', async () => {
|
||||
authOk(['companies:read'])
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { role: 'owner' } },
|
||||
bank_connections: { data: [] },
|
||||
}),
|
||||
)
|
||||
const res = await GET(req(), params)
|
||||
expect(res.status).toBe(200)
|
||||
const body = (await res.json()) as { data: { bank_connections: unknown[] } }
|
||||
expect(body.data.bank_connections).toEqual([])
|
||||
})
|
||||
|
||||
it('maps a database error into the v1 error envelope', async () => {
|
||||
authOk(['companies:read'])
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { role: 'owner' } },
|
||||
bank_connections: { data: null, error: { message: 'boom' } },
|
||||
}),
|
||||
)
|
||||
const res = await GET(req(), params)
|
||||
expect(res.status).toBeGreaterThanOrEqual(500)
|
||||
const body = (await res.json()) as { error: { code: string } }
|
||||
expect(body.error.code).toBeTruthy()
|
||||
})
|
||||
})
|
||||
@@ -1,118 +0,0 @@
|
||||
/**
|
||||
* GET /api/v1/companies/{companyId}/bank-connections
|
||||
*
|
||||
* List PSD2 bank connections with freshness metadata: last_synced_at,
|
||||
* consent_expires, status, error_message. This is the API-key surface's
|
||||
* answer to "is my bank data current?": a connection whose last_synced_at
|
||||
* is stale, or whose status is expired/error, means the transaction and
|
||||
* balance data downstream is old even though it looks complete.
|
||||
*/
|
||||
import { z } from 'zod'
|
||||
import { ok } from '@/lib/api/v1/response'
|
||||
import { registerEndpoint, dataEnvelope } from '@/lib/api/v1/registry'
|
||||
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponse } from '@/lib/api/v1/errors'
|
||||
import { requireCapability } from '@/lib/entitlements/has-capability'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
|
||||
const BankConnection = z.object({
|
||||
connection_id: z.string(),
|
||||
bank: z.string().nullable(),
|
||||
status: z.enum(['pending', 'pending_selection', 'active', 'expired', 'error']),
|
||||
since: z.string(),
|
||||
last_synced_at: z.string().nullable(),
|
||||
consent_expires: z.string().nullable(),
|
||||
error_message: z.string().nullable(),
|
||||
})
|
||||
|
||||
const BankConnectionsResponse = dataEnvelope(
|
||||
z.object({ bank_connections: z.array(BankConnection) }),
|
||||
)
|
||||
|
||||
registerEndpoint({
|
||||
operation: 'bank-connections.list',
|
||||
method: 'GET',
|
||||
path: '/api/v1/companies/:companyId/bank-connections',
|
||||
summary: 'List PSD2 bank connections with sync freshness and consent expiry.',
|
||||
description:
|
||||
'Returns every bank connection for the company with its status, last successful sync (last_synced_at), consent expiry (consent_expires) and any user-facing error message. Connections sync automatically once a day server-side; this endpoint tells you whether that is still happening.',
|
||||
useWhen:
|
||||
'You need to verify bank data is current before building on it (liquidity, reconciliation, reports), or to detect a dead connection that needs BankID re-authorisation.',
|
||||
doNotUseFor:
|
||||
'Fetching transactions (use /transactions) or account balances (use /cash-accounts). Triggering a sync: not available on this surface; syncing is automatic.',
|
||||
pitfalls: [
|
||||
'last_synced_at is null until the first sync completes (about a minute after connecting); it does NOT mean the connection is broken.',
|
||||
'A connection can hold status=active with a stale last_synced_at (older than ~36 hours): treat the data as suspect, but do NOT assume re-authorisation fixes it. Common causes are a lapsed subscription (this endpoint then answers with a capability error) or every account deselected in settings.',
|
||||
'status=expired means the PSD2 consent is dead: only the user can fix it, with BankID in a browser.',
|
||||
'error_message is Swedish and user-facing: show it verbatim rather than translating.',
|
||||
],
|
||||
example: {
|
||||
response: {
|
||||
data: {
|
||||
bank_connections: [
|
||||
{
|
||||
connection_id: '4f6c…',
|
||||
bank: 'Swedbank',
|
||||
status: 'active',
|
||||
since: '2026-08-01T00:00:00Z',
|
||||
last_synced_at: '2026-08-31T05:04:12Z',
|
||||
consent_expires: '2026-11-01T00:00:00Z',
|
||||
error_message: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
meta: { request_id: 'req_…', api_version: '2026-05-12' },
|
||||
},
|
||||
},
|
||||
scope: 'companies:read',
|
||||
risk: 'low',
|
||||
idempotent: true,
|
||||
reversible: false,
|
||||
dryRunSupported: false,
|
||||
response: { success: BankConnectionsResponse },
|
||||
})
|
||||
|
||||
export const GET = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
'bank-connections.list',
|
||||
async (_request, ctx) => {
|
||||
// Mirror the MCP twin (gnubok_connect_bank is gated on bank_sync via
|
||||
// MCP_TOOL_CAPABILITY_MAP): without this, a company whose entitlement
|
||||
// lapsed reads status=active with a frozen last_synced_at and the docs
|
||||
// steer the agent toward a needless BankID re-auth. The capability error
|
||||
// names the real cause instead.
|
||||
const capBlocked = await requireCapability(ctx.supabase, ctx.companyId!, CAPABILITY.bank_sync)
|
||||
if (capBlocked) return capBlocked
|
||||
|
||||
try {
|
||||
const { data, error } = await ctx.supabase
|
||||
.from('bank_connections')
|
||||
.select('id, bank_name, status, created_at, last_synced_at, consent_expires, error_message')
|
||||
.eq('company_id', ctx.companyId!)
|
||||
.in('status', ['pending', 'pending_selection', 'active', 'expired', 'error'])
|
||||
.order('created_at', { ascending: false })
|
||||
if (error) throw error
|
||||
|
||||
type Row = {
|
||||
id: string
|
||||
bank_name: string | null
|
||||
status: string
|
||||
created_at: string
|
||||
last_synced_at: string | null
|
||||
consent_expires: string | null
|
||||
error_message: string | null
|
||||
}
|
||||
const bank_connections = ((data ?? []) as Row[]).map((c) => ({
|
||||
connection_id: c.id,
|
||||
bank: c.bank_name,
|
||||
status: c.status,
|
||||
since: c.created_at,
|
||||
last_synced_at: c.last_synced_at,
|
||||
consent_expires: c.consent_expires,
|
||||
error_message: c.error_message,
|
||||
}))
|
||||
return ok({ bank_connections }, { requestId: ctx.requestId })
|
||||
} catch (error) {
|
||||
return v1ErrorResponse(error, ctx.log, { requestId: ctx.requestId })
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -1,176 +0,0 @@
|
||||
/**
|
||||
* Integration tests for GET .../cash-accounts (bank/cash accounts with the
|
||||
* bank-reported balance).
|
||||
*/
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
beforeAll(() => {
|
||||
if (process.env.NODE_ENV !== 'test') throw new Error('NODE_ENV=test required')
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL ||= 'http://localhost:54321'
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ||= 'test-anon-key'
|
||||
})
|
||||
|
||||
vi.mock('@/lib/auth/api-keys', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/auth/api-keys')>('@/lib/auth/api-keys')
|
||||
return { ...actual, validateApiKey: vi.fn(), createServiceClientNoCookies: vi.fn() }
|
||||
})
|
||||
vi.mock('@supabase/supabase-js', async () => {
|
||||
const actual = await vi.importActual<typeof import('@supabase/supabase-js')>('@supabase/supabase-js')
|
||||
return { ...actual, createClient: vi.fn().mockReturnValue({}) }
|
||||
})
|
||||
vi.mock('@/lib/cash-accounts/service', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/cash-accounts/service')>('@/lib/cash-accounts/service')
|
||||
return { ...actual, listForCompany: vi.fn() }
|
||||
})
|
||||
|
||||
import { validateApiKey, createServiceClientNoCookies } from '@/lib/auth/api-keys'
|
||||
import { listForCompany } from '@/lib/cash-accounts/service'
|
||||
import { GET } from '../route'
|
||||
|
||||
const mockValidate = validateApiKey as ReturnType<typeof vi.fn>
|
||||
const mockServiceClient = createServiceClientNoCookies as ReturnType<typeof vi.fn>
|
||||
|
||||
const COMPANY_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
|
||||
|
||||
function getRequest(url: string, withAuth = true): Request {
|
||||
return new Request(url, {
|
||||
method: 'GET',
|
||||
headers: withAuth ? { Authorization: 'Bearer test-fixture-not-a-real-key' } : {},
|
||||
})
|
||||
}
|
||||
|
||||
type MockResult = { data?: unknown; error?: unknown }
|
||||
function makeFlexibleSupabase(byTable: Record<string, MockResult | MockResult[]>) {
|
||||
const queues = new Map<string, MockResult[]>()
|
||||
for (const [t, val] of Object.entries(byTable)) {
|
||||
queues.set(t, Array.isArray(val) ? [...val] : [val])
|
||||
}
|
||||
const buildChain = (table: string): unknown => {
|
||||
const handler: ProxyHandler<object> = {
|
||||
get(_target, prop) {
|
||||
if (prop === 'then') {
|
||||
return (resolve: (v: unknown) => void) => {
|
||||
const q = queues.get(table)
|
||||
const next = q && q.length > 1 ? q.shift()! : (q?.[0] ?? { data: null, error: null })
|
||||
resolve(next)
|
||||
}
|
||||
}
|
||||
return (..._args: unknown[]) => buildChain(table)
|
||||
},
|
||||
}
|
||||
return new Proxy({}, handler)
|
||||
}
|
||||
return { from: vi.fn((table: string) => buildChain(table)) }
|
||||
}
|
||||
|
||||
function makeMemberSupabase() {
|
||||
return makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockServiceClient.mockReturnValue(makeMemberSupabase())
|
||||
})
|
||||
|
||||
describe('GET /api/v1/companies/{companyId}/cash-accounts', () => {
|
||||
beforeEach(() => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: COMPANY_ID,
|
||||
apiKeyId: 'ak_1',
|
||||
scopes: ['transactions:read'],
|
||||
mode: 'live',
|
||||
})
|
||||
})
|
||||
|
||||
it('returns 401 without an API key', async () => {
|
||||
mockValidate.mockResolvedValue(null)
|
||||
const res = await GET(
|
||||
getRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/cash-accounts`, false),
|
||||
{ params: Promise.resolve({ companyId: COMPANY_ID }) },
|
||||
)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 on an invalid enabled_only value', async () => {
|
||||
const res = await GET(
|
||||
getRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/cash-accounts?enabled_only=banana`),
|
||||
{ params: Promise.resolve({ companyId: COMPANY_ID }) },
|
||||
)
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('VALIDATION_ERROR')
|
||||
})
|
||||
|
||||
it('returns the accounts with bank-reported balance fields', async () => {
|
||||
vi.mocked(listForCompany).mockResolvedValue([
|
||||
{
|
||||
id: 'ca-1',
|
||||
company_id: COMPANY_ID,
|
||||
ledger_account: '1930',
|
||||
name: 'Företagskonto',
|
||||
currency: 'SEK',
|
||||
iban: 'SE4550000000058398257466',
|
||||
is_primary: true,
|
||||
enabled: true,
|
||||
source: 'enable_banking',
|
||||
balance: 125430.5,
|
||||
available_balance: 123930.5,
|
||||
balance_updated_at: '2026-09-01T05:12:44.000Z',
|
||||
},
|
||||
{
|
||||
id: 'ca-2',
|
||||
company_id: COMPANY_ID,
|
||||
ledger_account: '1940',
|
||||
name: null,
|
||||
currency: 'SEK',
|
||||
iban: null,
|
||||
is_primary: false,
|
||||
enabled: true,
|
||||
source: 'manual',
|
||||
},
|
||||
] as never)
|
||||
|
||||
const res = await GET(
|
||||
getRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/cash-accounts`),
|
||||
{ params: Promise.resolve({ companyId: COMPANY_ID }) },
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data.cash_accounts).toHaveLength(2)
|
||||
expect(body.data.cash_accounts[0]).toEqual({
|
||||
cash_account_id: 'ca-1',
|
||||
ledger_account: '1930',
|
||||
name: 'Företagskonto',
|
||||
currency: 'SEK',
|
||||
iban: 'SE4550000000058398257466',
|
||||
is_primary: true,
|
||||
enabled: true,
|
||||
source: 'enable_banking',
|
||||
balance: 125430.5,
|
||||
available_balance: 123930.5,
|
||||
balance_updated_at: '2026-09-01T05:12:44.000Z',
|
||||
})
|
||||
// Manual account: explicit nulls for the bank-reported fields.
|
||||
expect(body.data.cash_accounts[1]).toMatchObject({
|
||||
cash_account_id: 'ca-2',
|
||||
balance: null,
|
||||
available_balance: null,
|
||||
balance_updated_at: null,
|
||||
})
|
||||
// Qualified ids only: no bare `id` on the wire.
|
||||
expect(body.data.cash_accounts[0]).not.toHaveProperty('id')
|
||||
})
|
||||
|
||||
it('passes enabled_only=true through to the service', async () => {
|
||||
vi.mocked(listForCompany).mockResolvedValue([])
|
||||
const res = await GET(
|
||||
getRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/cash-accounts?enabled_only=true`),
|
||||
{ params: Promise.resolve({ companyId: COMPANY_ID }) },
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
expect(listForCompany).toHaveBeenCalledWith(expect.anything(), COMPANY_ID, { enabledOnly: true })
|
||||
})
|
||||
})
|
||||
@@ -1,111 +0,0 @@
|
||||
/**
|
||||
* GET /api/v1/companies/{companyId}/cash-accounts
|
||||
*
|
||||
* List the company's bank/cash accounts (cash_accounts) including the
|
||||
* bank-reported balance (booked + available) and when it was fetched.
|
||||
* The balance figures come from the PSD2 provider, not from the ledger.
|
||||
*/
|
||||
import { z } from 'zod'
|
||||
import { ok } from '@/lib/api/v1/response'
|
||||
import { registerEndpoint, dataEnvelope } from '@/lib/api/v1/registry'
|
||||
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponse, v1ValidationError } from '@/lib/api/v1/errors'
|
||||
import { listForCompany } from '@/lib/cash-accounts/service'
|
||||
|
||||
const CashAccount = z.object({
|
||||
cash_account_id: z.string(),
|
||||
ledger_account: z.string(),
|
||||
name: z.string().nullable(),
|
||||
currency: z.string(),
|
||||
iban: z.string().nullable(),
|
||||
is_primary: z.boolean(),
|
||||
enabled: z.boolean(),
|
||||
source: z.enum(['enable_banking', 'manual', 'sie_import']),
|
||||
balance: z.number().nullable(),
|
||||
available_balance: z.number().nullable(),
|
||||
balance_updated_at: z.string().nullable(),
|
||||
})
|
||||
|
||||
const CashAccountsResponse = dataEnvelope(
|
||||
z.object({ cash_accounts: z.array(CashAccount) }),
|
||||
)
|
||||
|
||||
registerEndpoint({
|
||||
operation: 'cash-accounts.list',
|
||||
method: 'GET',
|
||||
path: '/api/v1/companies/:companyId/cash-accounts',
|
||||
summary: 'List bank/cash accounts with the bank-reported balance.',
|
||||
description:
|
||||
'Returns the company\'s cash accounts (bank accounts, kassa) with their BAS ledger mapping and, for PSD2-connected accounts, the balance the bank itself reported at the last sync: balance (booked), available_balance, and balance_updated_at (when it was fetched). Pass ?enabled_only=true to return only accounts that sync.',
|
||||
useWhen:
|
||||
'You need the current bank balance per account (e.g. a covering decision before a payment run), or cash_account_id values to filter transaction listings.',
|
||||
doNotUseFor:
|
||||
'The bookkept 19xx balance: use the trial-balance or balance-sheet reports. The two legitimately differ (pending bookings, timing).',
|
||||
pitfalls: [
|
||||
'balance/available_balance are what the BANK reported, refreshed at most every 12h (PSD2 quota): check balance_updated_at before treating them as current.',
|
||||
'balance is null for manual and SIE-imported accounts, and for PSD2 accounts that have not completed a sync since connecting.',
|
||||
'available_balance is null when the bank reports no available balance type; that does not mean 0.',
|
||||
],
|
||||
example: {
|
||||
response: {
|
||||
data: {
|
||||
cash_accounts: [
|
||||
{
|
||||
cash_account_id: 'ca_…',
|
||||
ledger_account: '1930',
|
||||
name: 'Företagskonto',
|
||||
currency: 'SEK',
|
||||
iban: 'SE4550000000058398257466',
|
||||
is_primary: true,
|
||||
enabled: true,
|
||||
source: 'enable_banking',
|
||||
balance: 125430.5,
|
||||
available_balance: 123930.5,
|
||||
balance_updated_at: '2026-09-01T05:12:44.000Z',
|
||||
},
|
||||
],
|
||||
},
|
||||
meta: { request_id: 'req_…', api_version: '2026-05-12' },
|
||||
},
|
||||
},
|
||||
scope: 'transactions:read',
|
||||
risk: 'low',
|
||||
idempotent: true,
|
||||
reversible: false,
|
||||
dryRunSupported: false,
|
||||
response: { success: CashAccountsResponse },
|
||||
})
|
||||
|
||||
export const GET = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
'cash-accounts.list',
|
||||
async (request, ctx) => {
|
||||
const url = new URL(request.url)
|
||||
const Filters = z.object({ enabled_only: z.enum(['true', 'false']).optional() })
|
||||
const parsed = Filters.safeParse({
|
||||
enabled_only: url.searchParams.get('enabled_only') ?? undefined,
|
||||
})
|
||||
if (!parsed.success) return v1ValidationError(ctx, parsed.error)
|
||||
|
||||
try {
|
||||
const rows = await listForCompany(ctx.supabase, ctx.companyId!, {
|
||||
enabledOnly: parsed.data.enabled_only === 'true',
|
||||
})
|
||||
const cashAccounts = rows.map((row) => ({
|
||||
cash_account_id: row.id,
|
||||
ledger_account: row.ledger_account,
|
||||
name: row.name ?? null,
|
||||
currency: row.currency,
|
||||
iban: row.iban ?? null,
|
||||
is_primary: row.is_primary === true,
|
||||
enabled: row.enabled !== false,
|
||||
source: row.source,
|
||||
balance: row.balance ?? null,
|
||||
available_balance: row.available_balance ?? null,
|
||||
balance_updated_at: row.balance_updated_at ?? null,
|
||||
}))
|
||||
return ok({ cash_accounts: cashAccounts }, { requestId: ctx.requestId })
|
||||
} catch (error) {
|
||||
return v1ErrorResponse(error, ctx.log, { requestId: ctx.requestId })
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -1,239 +0,0 @@
|
||||
/**
|
||||
* Integration tests for GET /api/v1/companies/:companyId/compliance/check.
|
||||
*
|
||||
* Focus: the voucher_gaps runner must check EVERY voucher series registered
|
||||
* for the period (BFNAR 2013:2 kap 8 §: the verifikationsnummerserie must be
|
||||
* unbroken per series, and a gap must be documented). Checking only series
|
||||
* 'A' reports "clean" books that are not clean.
|
||||
*/
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
beforeAll(() => {
|
||||
if (process.env.NODE_ENV !== 'test') throw new Error('NODE_ENV=test required')
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL ||= 'http://localhost:54321'
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ||= 'test-anon-key'
|
||||
})
|
||||
|
||||
vi.mock('@/lib/auth/api-keys', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/auth/api-keys')>('@/lib/auth/api-keys')
|
||||
return { ...actual, validateApiKey: vi.fn(), createServiceClientNoCookies: vi.fn() }
|
||||
})
|
||||
vi.mock('@supabase/supabase-js', async () => {
|
||||
const actual = await vi.importActual<typeof import('@supabase/supabase-js')>('@supabase/supabase-js')
|
||||
return { ...actual, createClient: vi.fn().mockReturnValue({}) }
|
||||
})
|
||||
|
||||
import { validateApiKey, createServiceClientNoCookies } from '@/lib/auth/api-keys'
|
||||
import { GET as complianceCheck } from '../route'
|
||||
|
||||
const mockValidate = validateApiKey as ReturnType<typeof vi.fn>
|
||||
const mockServiceClient = createServiceClientNoCookies as ReturnType<typeof vi.fn>
|
||||
|
||||
const COMPANY_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
|
||||
const PERIOD_ID = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'
|
||||
|
||||
type MockResult = { data?: unknown; error?: unknown }
|
||||
type Gap = { gap_start: number; gap_end: number }
|
||||
|
||||
/** Per-table result queues + a `detect_voucher_gaps` stub keyed by p_series. */
|
||||
function makeSupabase(opts: {
|
||||
tables?: Record<string, MockResult>
|
||||
gapsBySeries?: Record<string, Gap[]>
|
||||
rpcError?: unknown
|
||||
}) {
|
||||
const tables = opts.tables ?? {}
|
||||
const buildChain = (table: string): unknown => {
|
||||
const handler: ProxyHandler<object> = {
|
||||
get(_target, prop) {
|
||||
if (prop === 'then') {
|
||||
return (resolve: (v: unknown) => void) =>
|
||||
resolve(tables[table] ?? { data: null, error: null })
|
||||
}
|
||||
return (..._args: unknown[]) => buildChain(table)
|
||||
},
|
||||
}
|
||||
return new Proxy({}, handler)
|
||||
}
|
||||
const rpc = vi.fn(async (_name: string, args: Record<string, unknown>) => {
|
||||
if (opts.rpcError) return { data: null, error: opts.rpcError }
|
||||
const series = args.p_series as string
|
||||
return { data: opts.gapsBySeries?.[series] ?? [], error: null }
|
||||
})
|
||||
return { from: vi.fn((table: string) => buildChain(table)), rpc }
|
||||
}
|
||||
|
||||
const MEMBERSHIP: MockResult = { data: { company_id: COMPANY_ID, role: 'owner' }, error: null }
|
||||
const PERIOD: MockResult = { data: { id: PERIOD_ID }, error: null }
|
||||
|
||||
function makeRequest(query: string, opts: { auth?: boolean } = {}): Request {
|
||||
return new Request(`https://x.test/api/v1/companies/${COMPANY_ID}/compliance/check${query}`, {
|
||||
method: 'GET',
|
||||
headers: opts.auth === false ? {} : { Authorization: 'Bearer test-fixture-not-a-real-key' },
|
||||
})
|
||||
}
|
||||
|
||||
function call(request: Request) {
|
||||
return complianceCheck(request, { params: Promise.resolve({ companyId: COMPANY_ID }) })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: COMPANY_ID,
|
||||
apiKeyId: 'ak_1',
|
||||
scopes: ['compliance:read'],
|
||||
mode: 'live',
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /api/v1/companies/:companyId/compliance/check', () => {
|
||||
it('returns 401 without a bearer token', async () => {
|
||||
mockServiceClient.mockReturnValue(makeSupabase({}))
|
||||
const res = await call(makeRequest(`?type=voucher_gaps&fiscal_period_id=${PERIOD_ID}`, { auth: false }))
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 for an unsupported check type', async () => {
|
||||
mockServiceClient.mockReturnValue(makeSupabase({ tables: { company_members: MEMBERSHIP } }))
|
||||
const res = await call(makeRequest('?type=not_a_check'))
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 400 when voucher_gaps is called without fiscal_period_id', async () => {
|
||||
mockServiceClient.mockReturnValue(makeSupabase({ tables: { company_members: MEMBERSHIP } }))
|
||||
const res = await call(makeRequest('?type=voucher_gaps'))
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 when the caller is not a member of the company', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeSupabase({ tables: { company_members: { data: null, error: null } } }),
|
||||
)
|
||||
const res = await call(makeRequest(`?type=voucher_gaps&fiscal_period_id=${PERIOD_ID}`))
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('reports clean when every series is continuous', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeSupabase({
|
||||
tables: {
|
||||
company_members: MEMBERSHIP,
|
||||
fiscal_periods: PERIOD,
|
||||
voucher_sequences: { data: [{ voucher_series: 'A' }, { voucher_series: 'F' }], error: null },
|
||||
},
|
||||
gapsBySeries: {},
|
||||
}),
|
||||
)
|
||||
const res = await call(makeRequest(`?type=voucher_gaps&fiscal_period_id=${PERIOD_ID}`))
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data.ready).toBe(true)
|
||||
expect(body.data.findings).toHaveLength(0)
|
||||
expect(body.data.details.total_gaps).toBe(0)
|
||||
expect(body.data.details.series_checked).toEqual(['A', 'F'])
|
||||
})
|
||||
|
||||
it('reports a gap that sits in a non-A series (series F: 33 → 37)', async () => {
|
||||
const supabase = makeSupabase({
|
||||
tables: {
|
||||
company_members: MEMBERSHIP,
|
||||
fiscal_periods: PERIOD,
|
||||
voucher_sequences: { data: [{ voucher_series: 'A' }, { voucher_series: 'F' }], error: null },
|
||||
voucher_gap_explanations: { data: [], error: null },
|
||||
},
|
||||
gapsBySeries: { F: [{ gap_start: 34, gap_end: 36 }] },
|
||||
})
|
||||
mockServiceClient.mockReturnValue(supabase)
|
||||
|
||||
const res = await call(makeRequest(`?type=voucher_gaps&fiscal_period_id=${PERIOD_ID}`))
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
|
||||
// Every registered series is checked, not only the RPC's 'A' default.
|
||||
const seriesArgs = supabase.rpc.mock.calls.map((c) => (c[1] as { p_series: string }).p_series)
|
||||
expect(seriesArgs).toEqual(['A', 'F'])
|
||||
|
||||
expect(body.data.ready).toBe(false)
|
||||
expect(body.data.findings).toHaveLength(1)
|
||||
const finding = body.data.findings[0]
|
||||
expect(finding.severity).toBe('blocker')
|
||||
expect(finding.code).toBe('VOUCHER_GAP_UNEXPLAINED')
|
||||
// The RPC returns only (gap_start, gap_end): the series must still be real.
|
||||
expect(finding.message).toContain('Series F')
|
||||
expect(finding.message).not.toContain('undefined')
|
||||
expect(finding.details).toMatchObject({
|
||||
voucher_series: 'F',
|
||||
gap_start: 34,
|
||||
gap_end: 36,
|
||||
has_explanation: false,
|
||||
})
|
||||
expect(body.data.details.unexplained_count).toBe(1)
|
||||
})
|
||||
|
||||
it('downgrades a gap to info only when voucher_gap_explanations documents it', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeSupabase({
|
||||
tables: {
|
||||
company_members: MEMBERSHIP,
|
||||
fiscal_periods: PERIOD,
|
||||
voucher_sequences: { data: [{ voucher_series: 'F' }], error: null },
|
||||
voucher_gap_explanations: {
|
||||
data: [{ voucher_series: 'F', gap_start: 34, gap_end: 36 }],
|
||||
error: null,
|
||||
},
|
||||
},
|
||||
gapsBySeries: { F: [{ gap_start: 34, gap_end: 36 }] },
|
||||
}),
|
||||
)
|
||||
const res = await call(makeRequest(`?type=voucher_gaps&fiscal_period_id=${PERIOD_ID}`))
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data.ready).toBe(true)
|
||||
expect(body.data.findings[0].severity).toBe('info')
|
||||
expect(body.data.findings[0].code).toBe('VOUCHER_GAP_EXPLAINED')
|
||||
expect(body.data.findings[0].details.voucher_series).toBe('F')
|
||||
})
|
||||
|
||||
it('falls back to series A when the period has no voucher_sequences rows', async () => {
|
||||
const supabase = makeSupabase({
|
||||
tables: {
|
||||
company_members: MEMBERSHIP,
|
||||
fiscal_periods: PERIOD,
|
||||
voucher_sequences: { data: [], error: null },
|
||||
},
|
||||
gapsBySeries: {},
|
||||
})
|
||||
mockServiceClient.mockReturnValue(supabase)
|
||||
const res = await call(makeRequest(`?type=voucher_gaps&fiscal_period_id=${PERIOD_ID}`))
|
||||
expect(res.status).toBe(200)
|
||||
expect(supabase.rpc.mock.calls.map((c) => (c[1] as { p_series: string }).p_series)).toEqual(['A'])
|
||||
})
|
||||
|
||||
it('surfaces a failing detection instead of reporting "no gaps"', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeSupabase({
|
||||
tables: {
|
||||
company_members: MEMBERSHIP,
|
||||
fiscal_periods: PERIOD,
|
||||
voucher_sequences: { data: [{ voucher_series: 'F' }], error: null },
|
||||
},
|
||||
rpcError: { message: 'boom', code: 'XX000' },
|
||||
}),
|
||||
)
|
||||
const res = await call(makeRequest(`?type=voucher_gaps&fiscal_period_id=${PERIOD_ID}`))
|
||||
expect(res.status).toBeGreaterThanOrEqual(400)
|
||||
const body = await res.json()
|
||||
expect(body.data).toBeUndefined()
|
||||
})
|
||||
|
||||
it('returns 400 when fiscal_period_id belongs to another company', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeSupabase({
|
||||
tables: { company_members: MEMBERSHIP, fiscal_periods: { data: null, error: null } },
|
||||
}),
|
||||
)
|
||||
const res = await call(makeRequest(`?type=voucher_gaps&fiscal_period_id=${PERIOD_ID}`))
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
})
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,247 +0,0 @@
|
||||
/**
|
||||
* Integration tests for POST /api/v1/companies/:companyId/customers/bulk-create.
|
||||
*/
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
beforeAll(() => {
|
||||
if (process.env.NODE_ENV !== 'test') {
|
||||
throw new Error(
|
||||
`customer bulk-create tests require NODE_ENV=test (got ${process.env.NODE_ENV ?? 'undefined'})`,
|
||||
)
|
||||
}
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL ||= 'http://localhost:54321'
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ||= 'test-anon-key'
|
||||
})
|
||||
|
||||
vi.mock('@/lib/auth/api-keys', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/auth/api-keys')>('@/lib/auth/api-keys')
|
||||
return {
|
||||
...actual,
|
||||
validateApiKey: vi.fn(),
|
||||
createServiceClientNoCookies: vi.fn(),
|
||||
}
|
||||
})
|
||||
vi.mock('@supabase/supabase-js', async () => {
|
||||
const actual = await vi.importActual<typeof import('@supabase/supabase-js')>('@supabase/supabase-js')
|
||||
return { ...actual, createClient: vi.fn().mockReturnValue({}) }
|
||||
})
|
||||
vi.mock('@/lib/vat/vies-client', () => ({
|
||||
validateVatNumber: vi.fn().mockResolvedValue({ valid: false }),
|
||||
}))
|
||||
|
||||
import { validateApiKey, createServiceClientNoCookies } from '@/lib/auth/api-keys'
|
||||
import { POST as bulkCreate } from '../route'
|
||||
|
||||
const mockValidate = validateApiKey as ReturnType<typeof vi.fn>
|
||||
const mockServiceClient = createServiceClientNoCookies as ReturnType<typeof vi.fn>
|
||||
|
||||
type MockResult = { data?: unknown; error?: unknown }
|
||||
function makeFlexibleSupabase(byTable: Record<string, MockResult | MockResult[]>) {
|
||||
const queues = new Map<string, MockResult[]>()
|
||||
for (const [t, val] of Object.entries(byTable)) {
|
||||
queues.set(t, Array.isArray(val) ? [...val] : [val])
|
||||
}
|
||||
const buildChain = (table: string): unknown => {
|
||||
const handler: ProxyHandler<object> = {
|
||||
get(_target, prop) {
|
||||
if (prop === 'then') {
|
||||
return (resolve: (v: unknown) => void) => {
|
||||
const q = queues.get(table)
|
||||
const next = q && q.length > 1 ? q.shift()! : (q?.[0] ?? { data: null, error: null })
|
||||
resolve(next)
|
||||
}
|
||||
}
|
||||
return (..._args: unknown[]) => buildChain(table)
|
||||
},
|
||||
}
|
||||
return new Proxy({}, handler)
|
||||
}
|
||||
return { from: vi.fn((table: string) => buildChain(table)) }
|
||||
}
|
||||
|
||||
const COMPANY_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
|
||||
const USER_ID = 'user-1'
|
||||
|
||||
function makeRequest(url: string, body: unknown): Request {
|
||||
return new Request(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'Bearer test-fixture-not-a-real-key',
|
||||
'Content-Type': 'application/json',
|
||||
'Idempotency-Key': 'idem1234-5050-4abc-8def-1234567890ab',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
function companyParams(companyId: string) {
|
||||
return { params: Promise.resolve({ companyId }) }
|
||||
}
|
||||
|
||||
const SAMPLE = (name = 'Acme AB') => ({
|
||||
name,
|
||||
customer_type: 'swedish_business' as const,
|
||||
org_number: '556677-8899',
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: USER_ID,
|
||||
companyId: COMPANY_ID,
|
||||
apiKeyId: 'ak_1',
|
||||
scopes: ['customers:write'],
|
||||
mode: 'live',
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/v1/companies/:companyId/customers/bulk-create', () => {
|
||||
it('creates two customers and returns a 200 with summary', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
customers: [
|
||||
{ data: { id: 'c1', name: 'Acme', customer_type: 'swedish_business' }, error: null },
|
||||
{ data: { id: 'c2', name: 'Beta', customer_type: 'swedish_business' }, error: null },
|
||||
],
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await bulkCreate(
|
||||
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/customers/bulk-create`, {
|
||||
customers: [SAMPLE('Acme AB'), SAMPLE('Beta AB')],
|
||||
}),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data.summary).toEqual({ total: 2, succeeded: 2, failed: 0 })
|
||||
expect(body.data.results[0]).toMatchObject({ ok: true, request_index: 0 })
|
||||
expect(body.data.results[1]).toMatchObject({ ok: true, request_index: 1 })
|
||||
})
|
||||
|
||||
it('returns per-item failure for org_number duplicate', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
customers: { data: null, error: { code: '23505', message: 'duplicate' } },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await bulkCreate(
|
||||
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/customers/bulk-create`, {
|
||||
customers: [SAMPLE('Acme AB')],
|
||||
}),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data.summary.failed).toBe(1)
|
||||
expect(body.data.results[0].error.code).toBe('CUSTOMER_DUPLICATE_ORG_NUMBER')
|
||||
// Ensure org_number value is NOT echoed (GDPR Art.5(1)(c)).
|
||||
expect(JSON.stringify(body.data.results[0].error.details)).not.toContain('556677-8899')
|
||||
})
|
||||
|
||||
it('rejects more than 50 customers per request', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
}),
|
||||
)
|
||||
const customers = Array.from({ length: 51 }, () => SAMPLE())
|
||||
|
||||
const res = await bulkCreate(
|
||||
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/customers/bulk-create`, {
|
||||
customers,
|
||||
}),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('VALIDATION_ERROR')
|
||||
})
|
||||
|
||||
it('rejects all_or_nothing: true with 501 NOT_IMPLEMENTED', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await bulkCreate(
|
||||
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/customers/bulk-create`, {
|
||||
all_or_nothing: true,
|
||||
customers: [SAMPLE()],
|
||||
}),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(501)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('NOT_IMPLEMENTED')
|
||||
})
|
||||
|
||||
it('dry-run returns previews without inserting', async () => {
|
||||
const supabaseMock = makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
})
|
||||
mockServiceClient.mockReturnValue(supabaseMock)
|
||||
|
||||
const res = await bulkCreate(
|
||||
makeRequest(
|
||||
`https://x.test/api/v1/companies/${COMPANY_ID}/customers/bulk-create?dry_run=true`,
|
||||
{ customers: [SAMPLE()] },
|
||||
),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('X-Dry-Run')).toBe('true')
|
||||
const body = await res.json()
|
||||
expect(body.data.dry_run).toBe(true)
|
||||
expect(body.data.preview.summary.succeeded).toBe(1)
|
||||
// No `customers` insert was attempted.
|
||||
const insertedCustomer = supabaseMock.from.mock.calls.some((c) => c[0] === 'customers')
|
||||
expect(insertedCustomer).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects empty customers array', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await bulkCreate(
|
||||
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/customers/bulk-create`, {
|
||||
customers: [],
|
||||
}),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('VALIDATION_ERROR')
|
||||
})
|
||||
|
||||
it('rejects keys without customers:write scope', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: USER_ID,
|
||||
companyId: COMPANY_ID,
|
||||
scopes: ['customers:read'],
|
||||
mode: 'live',
|
||||
})
|
||||
mockServiceClient.mockReturnValue(makeFlexibleSupabase({}))
|
||||
|
||||
const res = await bulkCreate(
|
||||
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/customers/bulk-create`, {
|
||||
customers: [SAMPLE()],
|
||||
}),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
})
|
||||
})
|
||||
@@ -1,335 +0,0 @@
|
||||
/**
|
||||
* POST /api/v1/companies/{companyId}/customers/bulk-create
|
||||
*
|
||||
* Bulk-create up to 50 customers in one call. Each item is validated and
|
||||
* inserted independently: per-item failures don't roll back successes.
|
||||
* Mirrors the shape of /invoices/bulk-create exactly so agents only need
|
||||
* to learn one bulk pattern.
|
||||
*
|
||||
* Response: `{ results: [{ ok, request_index, data?, error? }], summary }`.
|
||||
* Idempotent over the whole batch. Dry-runnable.
|
||||
*
|
||||
* VIES validation for eu_business customers is best-effort PER ITEM. A VIES
|
||||
* timeout does NOT fail the item: it just leaves vat_number_validated=false.
|
||||
*/
|
||||
|
||||
import { z } from 'zod'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { ok } from '@/lib/api/v1/response'
|
||||
import { dryRunPreview } from '@/lib/api/v1/dry-run'
|
||||
import { registerEndpoint, dataEnvelope } from '@/lib/api/v1/registry'
|
||||
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponseFromCode, v1ValidationError } from '@/lib/api/v1/errors'
|
||||
import { readV1JsonBody } from '@/lib/api/v1/body'
|
||||
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'
|
||||
|
||||
const BulkCreateRequest = z.object({
|
||||
customers: z.array(CreateCustomerSchema).min(1).max(50),
|
||||
all_or_nothing: z.boolean().optional().default(false),
|
||||
})
|
||||
|
||||
const BulkResultItem = z.object({
|
||||
ok: z.boolean(),
|
||||
request_index: z.number().int().nonnegative(),
|
||||
data: z.unknown().optional(),
|
||||
error: z
|
||||
.object({
|
||||
code: z.string(),
|
||||
message: z.string(),
|
||||
details: z.unknown().optional(),
|
||||
})
|
||||
.optional(),
|
||||
})
|
||||
|
||||
const BulkCreateResponse = z.object({
|
||||
results: z.array(BulkResultItem),
|
||||
summary: z.object({
|
||||
total: z.number().int(),
|
||||
succeeded: z.number().int(),
|
||||
failed: z.number().int(),
|
||||
}),
|
||||
})
|
||||
|
||||
// Same projection as the single-create endpoint: keeps response shapes
|
||||
// identical so callers can union the two surfaces transparently.
|
||||
const CUSTOMER_RESPONSE_COLUMNS =
|
||||
'id, name, customer_type, 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'
|
||||
|
||||
registerEndpoint({
|
||||
operation: 'customers.bulk-create',
|
||||
method: 'POST',
|
||||
path: '/api/v1/companies/:companyId/customers/bulk-create',
|
||||
summary: 'Create up to 50 customers in one call (partial-success).',
|
||||
description:
|
||||
'Bulk-create endpoint mirroring /invoices/bulk-create. Each customer is validated and inserted independently: per-item failures do not roll back items that succeeded. Returns a results array plus a summary. Idempotent over the whole batch. Dry-runnable.',
|
||||
useWhen:
|
||||
'You\'re importing a roster of customers from another CRM, or seeding a fresh company with its existing client list. Use dry-run first to validate the batch.',
|
||||
doNotUseFor:
|
||||
'Updating existing customers: PATCH /customers/{id} once per customer. Bulk uploads of > 50 customers: split into pages of 50. Transactional all-or-nothing imports: passing all_or_nothing: true returns 501 NOT_IMPLEMENTED.',
|
||||
pitfalls: [
|
||||
'Idempotency-Key is mandatory and covers the WHOLE batch. A retried bulk-create returns the cached full response: it does not retry only the failed items.',
|
||||
'Passing all_or_nothing: true returns 501 NOT_IMPLEMENTED. Today only partial-success batches exist; omit the flag or pass false.',
|
||||
'org_number uniqueness is enforced at the DB level: items with duplicates fail individually with CUSTOMER_DUPLICATE_ORG_NUMBER.',
|
||||
'VIES validation for eu_business customers is best-effort per item; a VIES timeout leaves vat_number_validated=false but does NOT fail the item.',
|
||||
],
|
||||
example: {
|
||||
request: {
|
||||
customers: [
|
||||
{ name: 'Acme AB', customer_type: 'swedish_business', org_number: '556677-8899' },
|
||||
{ name: 'Foo OY', customer_type: 'eu_business', vat_number: 'FI12345678' },
|
||||
],
|
||||
},
|
||||
response: {
|
||||
data: {
|
||||
results: [
|
||||
{ ok: true, request_index: 0, data: { id: '0e9c…', name: 'Acme AB' } },
|
||||
{ ok: true, request_index: 1, data: { id: '4d2a…', name: 'Foo OY' } },
|
||||
],
|
||||
summary: { total: 2, succeeded: 2, failed: 0 },
|
||||
},
|
||||
meta: { request_id: 'req_…', api_version: '2026-05-12' },
|
||||
},
|
||||
},
|
||||
scope: 'customers:write',
|
||||
risk: 'low',
|
||||
idempotent: true,
|
||||
reversible: true,
|
||||
dryRunSupported: true,
|
||||
request: { body: BulkCreateRequest },
|
||||
response: { success: dataEnvelope(BulkCreateResponse) },
|
||||
})
|
||||
|
||||
interface ResultItem {
|
||||
ok: boolean
|
||||
request_index: number
|
||||
data?: unknown
|
||||
error?: { code: string; message: string; details?: unknown }
|
||||
}
|
||||
|
||||
async function createOneCustomer(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
userId: string,
|
||||
index: number,
|
||||
input: z.infer<typeof CreateCustomerSchema>,
|
||||
dryRun: boolean,
|
||||
log: Logger,
|
||||
fallbackPaymentTerms: number,
|
||||
): Promise<ResultItem> {
|
||||
if (dryRun) {
|
||||
return {
|
||||
ok: true,
|
||||
request_index: index,
|
||||
data: {
|
||||
preview: {
|
||||
id: null,
|
||||
name: input.name,
|
||||
customer_type: input.customer_type,
|
||||
contact_person: input.contact_person ?? null,
|
||||
email: input.email ?? null,
|
||||
phone: input.phone ?? null,
|
||||
invoice_email_cc_addresses: input.invoice_email_cc_addresses ?? null,
|
||||
invoice_email_bcc_addresses: input.invoice_email_bcc_addresses ?? null,
|
||||
address_line1: input.address_line1 ?? null,
|
||||
address_line2: input.address_line2 ?? null,
|
||||
postal_code: input.postal_code ?? null,
|
||||
city: input.city ?? null,
|
||||
country: input.country ?? 'SE',
|
||||
org_number: input.org_number ?? null,
|
||||
vat_number: input.vat_number ?? null,
|
||||
vat_number_validated: false,
|
||||
default_payment_terms: input.default_payment_terms ?? fallbackPaymentTerms,
|
||||
notes: input.notes ?? null,
|
||||
archived_at: null,
|
||||
created_at: null,
|
||||
updated_at: null,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Best-effort VIES validation. Resolve BEFORE the insert so the row
|
||||
// reflects validation state atomically.
|
||||
let vatValidated = false
|
||||
let vatValidatedAt: string | null = null
|
||||
if (input.customer_type === 'eu_business' && input.vat_number) {
|
||||
try {
|
||||
const vatResult = await validateVatNumber(input.vat_number)
|
||||
if (vatResult.valid) {
|
||||
vatValidated = true
|
||||
vatValidatedAt = new Date().toISOString()
|
||||
}
|
||||
} catch (err) {
|
||||
log.warn('bulk-create: VIES validation failed for item', err as Error, {
|
||||
request_index: index,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('customers')
|
||||
.insert({
|
||||
user_id: userId,
|
||||
company_id: companyId,
|
||||
name: input.name,
|
||||
customer_type: input.customer_type,
|
||||
contact_person: input.contact_person ?? null,
|
||||
email: input.email ?? null,
|
||||
phone: input.phone ?? null,
|
||||
invoice_email_cc_addresses: input.invoice_email_cc_addresses ?? null,
|
||||
invoice_email_bcc_addresses: input.invoice_email_bcc_addresses ?? null,
|
||||
address_line1: input.address_line1 ?? null,
|
||||
address_line2: input.address_line2 ?? null,
|
||||
postal_code: input.postal_code ?? null,
|
||||
city: input.city ?? null,
|
||||
country: input.country ?? 'SE',
|
||||
org_number: input.org_number ?? null,
|
||||
vat_number: input.vat_number ?? null,
|
||||
vat_number_validated: vatValidated,
|
||||
vat_number_validated_at: vatValidatedAt,
|
||||
// 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)
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
if (error.code === '23505') {
|
||||
// GDPR Art.5(1)(c): do NOT echo input.org_number; for sole traders
|
||||
// it IS the personnummer. The error code + field is enough: the
|
||||
// caller knows the value they submitted.
|
||||
return {
|
||||
ok: false,
|
||||
request_index: index,
|
||||
error: {
|
||||
code: 'CUSTOMER_DUPLICATE_ORG_NUMBER',
|
||||
message: 'A customer with this org_number already exists in this company.',
|
||||
details: { field: 'org_number' },
|
||||
},
|
||||
}
|
||||
}
|
||||
log.error('bulk-create: customer insert failed', error, {
|
||||
request_index: index,
|
||||
companyId,
|
||||
pgCode: error.code,
|
||||
})
|
||||
return {
|
||||
ok: false,
|
||||
request_index: index,
|
||||
error: {
|
||||
code: 'CUSTOMER_CREATE_FAILED',
|
||||
message: 'Customer insert failed.',
|
||||
details: { pg_code: error.code },
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Emit customer.created per success. Same cast pattern as the single
|
||||
// POST: projection omits internal scoping fields we re-inject here.
|
||||
try {
|
||||
await eventBus.emit({
|
||||
type: 'customer.created',
|
||||
payload: {
|
||||
customer: {
|
||||
...(data as Record<string, unknown>),
|
||||
user_id: userId,
|
||||
company_id: companyId,
|
||||
} as unknown as Customer,
|
||||
companyId,
|
||||
userId,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
log.warn('bulk-create: customer.created emit failed', err as Error, {
|
||||
request_index: index,
|
||||
})
|
||||
}
|
||||
|
||||
return { ok: true, request_index: index, data }
|
||||
}
|
||||
|
||||
export const POST = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
'customers.bulk-create',
|
||||
async (request, ctx) => {
|
||||
if (!z.string().uuid().safeParse(ctx.companyId).success) {
|
||||
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { field: 'companyId', message: 'companyId must be a UUID.' },
|
||||
})
|
||||
}
|
||||
|
||||
const rawBodyResult = await readV1JsonBody(request, ctx)
|
||||
if (!rawBodyResult.ok) return rawBodyResult.response
|
||||
const rawBody = rawBodyResult.body
|
||||
|
||||
const parsed = BulkCreateRequest.safeParse(rawBody)
|
||||
if (!parsed.success) return v1ValidationError(ctx, parsed.error)
|
||||
const body = parsed.data
|
||||
|
||||
// Reject all_or_nothing: true loudly. Same contract as invoices/bulk-create.
|
||||
if (body.all_or_nothing) {
|
||||
return v1ErrorResponseFromCode('NOT_IMPLEMENTED', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: {
|
||||
field: 'all_or_nothing',
|
||||
message:
|
||||
'all_or_nothing: true is not yet implemented. Omit the flag (or pass false) to use partial-success semantics.',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// 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.
|
||||
const results: ResultItem[] = []
|
||||
for (let i = 0; i < body.customers.length; i++) {
|
||||
const item = await createOneCustomer(
|
||||
ctx.supabase,
|
||||
ctx.companyId!,
|
||||
ctx.userId,
|
||||
i,
|
||||
body.customers[i],
|
||||
ctx.dryRun,
|
||||
ctx.log,
|
||||
fallbackPaymentTerms,
|
||||
)
|
||||
results.push(item)
|
||||
}
|
||||
|
||||
const summary = {
|
||||
total: results.length,
|
||||
succeeded: results.filter((r) => r.ok).length,
|
||||
failed: results.filter((r) => !r.ok).length,
|
||||
}
|
||||
|
||||
ctx.log.info('customers.bulk-create completed', {
|
||||
companyId: ctx.companyId,
|
||||
userId: ctx.userId,
|
||||
...summary,
|
||||
dryRun: ctx.dryRun,
|
||||
})
|
||||
|
||||
if (ctx.dryRun) {
|
||||
return dryRunPreview({ results, summary }, { requestId: ctx.requestId, log: ctx.log })
|
||||
}
|
||||
return ok({ results, summary }, { requestId: ctx.requestId })
|
||||
},
|
||||
{ requireIdempotencyKey: true },
|
||||
)
|
||||
@@ -1,462 +0,0 @@
|
||||
/**
|
||||
* /api/v1/companies/{companyId}/customers: list + create customer endpoints.
|
||||
*
|
||||
* GET : list with filters (customer_type, search, include_archived).
|
||||
* Cursor pagination on (created_at ASC, id ASC).
|
||||
* POST : create. Idempotent (mandatory Idempotency-Key). Dry-runnable
|
||||
* (?dry_run=true returns validated would-be record without
|
||||
* committing). VIES validation runs only on commit.
|
||||
*/
|
||||
|
||||
import { z } from 'zod'
|
||||
import { created, paginated } from '@/lib/api/v1/response'
|
||||
import { dryRunPreview } from '@/lib/api/v1/dry-run'
|
||||
import {
|
||||
decodeDefaultCursor,
|
||||
encodeDefaultCursor,
|
||||
parsePaginationParams,
|
||||
} from '@/lib/api/v1/pagination'
|
||||
import { registerEndpoint, listEnvelope, dataEnvelope } from '@/lib/api/v1/registry'
|
||||
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponse, v1ErrorResponseFromCode, v1ValidationError } from '@/lib/api/v1/errors'
|
||||
import { readV1JsonBody } from '@/lib/api/v1/body'
|
||||
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'
|
||||
|
||||
// Mirror the canonical CustomerTypeSchema from lib/api/schemas.ts. Only
|
||||
// 'individual' refers to a natural person (Swedish sole trader / enskild
|
||||
// firma); the three *_business variants are legal entities.
|
||||
const CustomerType = z.enum([
|
||||
'individual',
|
||||
'swedish_business',
|
||||
'eu_business',
|
||||
'non_eu_business',
|
||||
])
|
||||
|
||||
const CustomerSummary = z.object({
|
||||
id: z.string().uuid(),
|
||||
name: z.string(),
|
||||
customer_type: CustomerType,
|
||||
email: z.string().nullable(),
|
||||
org_number: z.string().nullable(),
|
||||
vat_number: z.string().nullable(),
|
||||
default_payment_terms: z.number(),
|
||||
/** The party (motpart) behind the row; fetch it with GET .../{id}?expand=party or the MCP tool get_party. */
|
||||
party_id: z.string().uuid().nullable().optional(),
|
||||
archived_at: z.string().nullable(),
|
||||
created_at: z.string(),
|
||||
})
|
||||
|
||||
const CustomersListResponse = listEnvelope(CustomerSummary)
|
||||
|
||||
// Explicit projection: never SELECT *. Schema migrations adding columns
|
||||
// must update this list before the field becomes visible on the public API.
|
||||
const CUSTOMER_SUMMARY_COLUMNS =
|
||||
'id, name, customer_type, email, org_number, vat_number, default_payment_terms, party_id, archived_at, created_at'
|
||||
|
||||
registerEndpoint({
|
||||
operation: 'customers.list',
|
||||
method: 'GET',
|
||||
path: '/api/v1/companies/:companyId/customers',
|
||||
summary: 'List customers for a company.',
|
||||
description:
|
||||
'Returns active customers in created-first order. Pass ?include_archived=true to include archived rows. Use ?search to match against name or org_number.',
|
||||
useWhen:
|
||||
'You need a customer roster: for building a UI picker, syncing a CRM, or resolving a customer_id before creating an invoice.',
|
||||
doNotUseFor:
|
||||
'Fetching a single customer you already know the id of: use GET /api/v1/companies/{companyId}/customers/{id}. Suppliers are a separate resource.',
|
||||
pitfalls: [
|
||||
'Archived customers are hidden by default; the dashboard makes the same choice.',
|
||||
'org_number is included so callers can match against external CRM identifiers; for sole traders (enskild firma) it equals the personnummer.',
|
||||
],
|
||||
example: {
|
||||
response: {
|
||||
data: [
|
||||
{
|
||||
id: 'a8f1…',
|
||||
name: 'Acme AB',
|
||||
customer_type: 'business',
|
||||
email: '[email protected]',
|
||||
org_number: '556677-8899',
|
||||
vat_number: 'SE556677889901',
|
||||
default_payment_terms: 30,
|
||||
archived_at: null,
|
||||
created_at: '2025-04-12T08:30:00Z',
|
||||
},
|
||||
],
|
||||
meta: { request_id: 'req_…', api_version: '2026-05-12', next_cursor: null },
|
||||
},
|
||||
},
|
||||
scope: 'customers:read',
|
||||
risk: 'low',
|
||||
idempotent: true,
|
||||
reversible: false,
|
||||
dryRunSupported: false,
|
||||
response: { success: CustomersListResponse },
|
||||
})
|
||||
|
||||
export const GET = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
'customers.list',
|
||||
async (request, ctx) => {
|
||||
const url = new URL(request.url)
|
||||
const { limit, cursor } = parsePaginationParams(url)
|
||||
const decoded = decodeDefaultCursor(cursor)
|
||||
|
||||
const FiltersSchema = z.object({
|
||||
customer_type: CustomerType.optional(),
|
||||
search: z.string().min(1).max(200).optional(),
|
||||
include_archived: z.enum(['true', 'false']).optional(),
|
||||
})
|
||||
const filtersResult = FiltersSchema.safeParse({
|
||||
customer_type: url.searchParams.get('customer_type') ?? undefined,
|
||||
search: url.searchParams.get('search') ?? undefined,
|
||||
include_archived: url.searchParams.get('include_archived') ?? undefined,
|
||||
})
|
||||
if (!filtersResult.success) {
|
||||
return v1ValidationError(ctx, filtersResult.error)
|
||||
}
|
||||
const filters = filtersResult.data
|
||||
const includeArchived = filters.include_archived === 'true'
|
||||
|
||||
let query = ctx.supabase
|
||||
.from('customers')
|
||||
.select(CUSTOMER_SUMMARY_COLUMNS)
|
||||
.eq('company_id', ctx.companyId!)
|
||||
.order('created_at', { ascending: true })
|
||||
.order('id', { ascending: true })
|
||||
.limit(limit + 1)
|
||||
|
||||
if (!includeArchived) {
|
||||
query = query.is('archived_at', null)
|
||||
}
|
||||
if (filters.customer_type) {
|
||||
query = query.eq('customer_type', filters.customer_type)
|
||||
}
|
||||
if (filters.search) {
|
||||
// Build a safe ilike pattern. Two layers of escaping:
|
||||
// 1. PostgREST `.or()` filter syntax uses commas + parens as
|
||||
// delimiters; strip them from the user-supplied term.
|
||||
// 2. SQL LIKE treats `%` and `_` (and `\` as the default escape) as
|
||||
// wildcards; escape them so '100%' searches for the literal
|
||||
// string '100%' rather than 'anything containing 100'.
|
||||
const term = filters.search
|
||||
.replace(/[,()]/g, '') // PostgREST delimiters
|
||||
.replace(/[%_\\]/g, '\\$&') // LIKE wildcards
|
||||
query = query.or(`name.ilike.%${term}%,org_number.ilike.${term}%`)
|
||||
}
|
||||
|
||||
if (decoded) {
|
||||
query = query.or(
|
||||
`created_at.gt.${decoded.ts},and(created_at.eq.${decoded.ts},id.gt.${decoded.id})`,
|
||||
)
|
||||
}
|
||||
|
||||
const { data, error } = await query
|
||||
|
||||
if (error) {
|
||||
return v1ErrorResponse(error, ctx.log, { requestId: ctx.requestId })
|
||||
}
|
||||
|
||||
type Row = {
|
||||
id: string
|
||||
name: string
|
||||
customer_type: string
|
||||
email: string | null
|
||||
org_number: string | null
|
||||
vat_number: string | null
|
||||
default_payment_terms: number
|
||||
archived_at: string | null
|
||||
created_at: string
|
||||
} & Record<string, unknown>
|
||||
|
||||
const rows = ((data ?? []) as unknown) as Row[]
|
||||
const trimmed = rows.slice(0, limit)
|
||||
const hasMore = rows.length > limit
|
||||
|
||||
// GDPR Art.5(1)(c) data minimisation: for sole traders (enskild firma,
|
||||
// customer_type='individual'), org_number IS the personnummer: a
|
||||
// directly identifying special-category identifier. Mask both
|
||||
// org_number and vat_number in the LIST response so bulk fetches don't
|
||||
// expose personal IDs. The DETAIL endpoint (deliberate drill-in to one
|
||||
// record) still returns them. Business customers' org_numbers are
|
||||
// Bolagsverket public-record data and stay visible.
|
||||
//
|
||||
// 'eu_individual' is retained as defense-in-depth: it's not a valid
|
||||
// value in the canonical CustomerTypeSchema (so newly created customers
|
||||
// can never have it), but the `customer_type` DB column has no CHECK
|
||||
// constraint, so legacy rows from prior schema iterations could in
|
||||
// principle carry it. Masking is free when the value never appears and
|
||||
// protective if it ever does. Adding 'eu_individual' as a first-class
|
||||
// customer_type for EU natural persons is a separate product decision.
|
||||
const INDIVIDUAL_TYPES = new Set(['individual', 'eu_individual'])
|
||||
|
||||
const customers = trimmed.map((r) => {
|
||||
const isIndividual = INDIVIDUAL_TYPES.has(r.customer_type)
|
||||
return {
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
customer_type: r.customer_type,
|
||||
email: r.email,
|
||||
org_number: isIndividual ? null : r.org_number,
|
||||
vat_number: isIndividual ? null : r.vat_number,
|
||||
default_payment_terms: r.default_payment_terms,
|
||||
archived_at: r.archived_at,
|
||||
created_at: r.created_at,
|
||||
}
|
||||
})
|
||||
|
||||
const last = trimmed[trimmed.length - 1]
|
||||
const nextCursor = hasMore && last
|
||||
? encodeDefaultCursor({ id: last.id, created_at: last.created_at })
|
||||
: null
|
||||
|
||||
return paginated(customers, {
|
||||
requestId: ctx.requestId,
|
||||
nextCursor: nextCursor ?? undefined,
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
// POST: create customer
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
|
||||
const CustomerCreated = z.object({
|
||||
id: z.string().uuid().nullable(),
|
||||
name: z.string(),
|
||||
customer_type: CustomerType,
|
||||
customer_number: z.string().nullable(),
|
||||
contact_person: z.string().nullable(),
|
||||
email: z.string().nullable(),
|
||||
phone: z.string().nullable(),
|
||||
invoice_email_cc_addresses: z.array(z.string()).nullable(),
|
||||
invoice_email_bcc_addresses: z.array(z.string()).nullable(),
|
||||
address_line1: z.string().nullable(),
|
||||
address_line2: z.string().nullable(),
|
||||
postal_code: z.string().nullable(),
|
||||
city: z.string().nullable(),
|
||||
country: z.string(),
|
||||
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(),
|
||||
created_at: z.string().nullable(),
|
||||
updated_at: z.string().nullable(),
|
||||
})
|
||||
|
||||
// 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, personal_number, default_payment_terms, notes, archived_at, created_at, updated_at'
|
||||
|
||||
registerEndpoint({
|
||||
operation: 'customers.create',
|
||||
method: 'POST',
|
||||
path: '/api/v1/companies/:companyId/customers',
|
||||
summary: 'Create a customer.',
|
||||
description:
|
||||
'Creates a new customer for the company. Requires Idempotency-Key (UUID). Supports ?dry_run=true for input validation without committing: the dry-run response shows the would-be record minus id and timestamps. EU-business customers with a VAT number are auto-validated against VIES on commit.',
|
||||
useWhen:
|
||||
'You need to register a new customer before invoicing them. Use dry-run first to catch validation errors before committing.',
|
||||
doNotUseFor:
|
||||
'Updating an existing customer (PATCH instead). Creating suppliers (different resource).',
|
||||
pitfalls: [
|
||||
'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.',
|
||||
'A personnummer-shaped org_number on customer_type=individual is treated as the personnummer submitted in the wrong field: it is stored encrypted as personal_number, returned masked (********-1234), and org_number is left empty. Prefer passing it as personal_number. Next to a different personal_number in the same body it is a 400.',
|
||||
'An org_number shaped like a Swedish personnummer is rejected for business customer_types: create the customer as customer_type=individual with personal_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: {
|
||||
request: {
|
||||
name: 'Acme AB',
|
||||
customer_type: 'swedish_business',
|
||||
email: '[email protected]',
|
||||
org_number: '556677-8899',
|
||||
default_payment_terms: 30,
|
||||
},
|
||||
response: {
|
||||
data: {
|
||||
id: '0e9c…',
|
||||
name: 'Acme AB',
|
||||
customer_type: 'swedish_business',
|
||||
email: '[email protected]',
|
||||
org_number: '556677-8899',
|
||||
vat_number_validated: false,
|
||||
default_payment_terms: 30,
|
||||
archived_at: null,
|
||||
created_at: '2026-05-12T16:00:00Z',
|
||||
updated_at: '2026-05-12T16:00:00Z',
|
||||
},
|
||||
meta: { request_id: 'req_…', api_version: '2026-05-12' },
|
||||
},
|
||||
},
|
||||
scope: 'customers:write',
|
||||
risk: 'low',
|
||||
idempotent: true,
|
||||
reversible: true,
|
||||
dryRunSupported: true,
|
||||
request: { body: CreateCustomerSchema },
|
||||
response: { success: dataEnvelope(CustomerCreated) },
|
||||
})
|
||||
|
||||
export const POST = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
'customers.create',
|
||||
async (request, ctx) => {
|
||||
const raw = await readV1JsonBody(request, ctx)
|
||||
if (!raw.ok) return raw.response
|
||||
|
||||
const parsed = CreateCustomerSchema.safeParse(raw.body)
|
||||
if (!parsed.success) {
|
||||
return v1ValidationError(ctx, parsed.error)
|
||||
}
|
||||
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) {
|
||||
return dryRunPreview(
|
||||
{
|
||||
id: null,
|
||||
name: body.name,
|
||||
customer_type: body.customer_type,
|
||||
customer_number: body.customer_number || null,
|
||||
contact_person: body.contact_person ?? null,
|
||||
email: body.email ?? null,
|
||||
phone: body.phone ?? null,
|
||||
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 ?? null,
|
||||
address_line2: body.address_line2 ?? null,
|
||||
postal_code: body.postal_code ?? null,
|
||||
city: body.city ?? null,
|
||||
country: body.country ?? 'SE',
|
||||
org_number: body.org_number ?? null,
|
||||
vat_number: body.vat_number ?? null,
|
||||
vat_number_validated: false,
|
||||
personal_number: maskCustomerPersonalNumber(body.personal_number ?? null),
|
||||
default_payment_terms: defaultPaymentTerms,
|
||||
notes: body.notes ?? null,
|
||||
archived_at: null,
|
||||
created_at: null,
|
||||
updated_at: null,
|
||||
},
|
||||
{ requestId: ctx.requestId, log: ctx.log },
|
||||
)
|
||||
}
|
||||
|
||||
// Best-effort VIES validation. Resolve BEFORE the insert so the
|
||||
// resulting row reflects the validation state atomically and the
|
||||
// API response can't expose stale vat_number_validated.
|
||||
let vatValidated = false
|
||||
let vatValidatedAt: string | null = null
|
||||
if (body.customer_type === 'eu_business' && body.vat_number) {
|
||||
try {
|
||||
const vatResult = await validateVatNumber(body.vat_number)
|
||||
if (vatResult.valid) {
|
||||
vatValidated = true
|
||||
vatValidatedAt = new Date().toISOString()
|
||||
}
|
||||
} catch (err) {
|
||||
ctx.log.warn('auto-VIES validation failed on customer create', err as Error)
|
||||
}
|
||||
}
|
||||
|
||||
const { data, error } = await ctx.supabase
|
||||
.from('customers')
|
||||
.insert({
|
||||
user_id: ctx.userId,
|
||||
company_id: ctx.companyId!,
|
||||
name: body.name,
|
||||
customer_type: body.customer_type,
|
||||
// Empty string clears the customer number, same as an explicit null
|
||||
// (matches the internal /api/customers route).
|
||||
customer_number: body.customer_number || null,
|
||||
contact_person: body.contact_person ?? null,
|
||||
email: body.email ?? null,
|
||||
phone: body.phone ?? null,
|
||||
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 ?? null,
|
||||
address_line2: body.address_line2 ?? null,
|
||||
postal_code: body.postal_code ?? null,
|
||||
city: body.city ?? null,
|
||||
country: body.country ?? 'SE',
|
||||
org_number: body.org_number ?? null,
|
||||
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: defaultPaymentTerms,
|
||||
notes: body.notes ?? null,
|
||||
})
|
||||
.select(CUSTOMER_RESPONSE_COLUMNS)
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
if (error.code === '23505') {
|
||||
// GDPR Art.5(1)(c): do NOT echo body.org_number in the response:
|
||||
// for customer_type='individual' it IS the personnummer.
|
||||
// The error code alone tells the caller which field conflicted;
|
||||
// they already know the value they submitted.
|
||||
return v1ErrorResponseFromCode('CUSTOMER_DUPLICATE_ORG_NUMBER', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { field: 'org_number' },
|
||||
})
|
||||
}
|
||||
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
|
||||
// omits internal scoping fields (user_id, company_id) the Customer type
|
||||
// requires; we re-inject them on the payload from ctx.
|
||||
try {
|
||||
await eventBus.emit({
|
||||
type: 'customer.created',
|
||||
payload: {
|
||||
customer: { ...safeCustomer, user_id: ctx.userId, company_id: ctx.companyId! } as unknown as Customer,
|
||||
companyId: ctx.companyId!,
|
||||
userId: ctx.userId,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
ctx.log.warn('customer.created emit failed', err as Error)
|
||||
}
|
||||
|
||||
return created(safeCustomer, { requestId: ctx.requestId })
|
||||
},
|
||||
{ requireIdempotencyKey: true },
|
||||
)
|
||||
@@ -1,254 +0,0 @@
|
||||
/**
|
||||
* PATCH /api/v1/companies/{companyId}/dimensions/{id}/values/{valueId}:
|
||||
* update a dimension value (name / is_active / start_date / end_date;
|
||||
* `code` is immutable). Archiving (is_active=false) and setting an
|
||||
* end_date on a project code both go through here.
|
||||
* DELETE /api/v1/companies/{companyId}/dimensions/{id}/values/{valueId}:
|
||||
* delete an UNREFERENCED value. Values referenced by posted/reversed
|
||||
* journal lines are protected by the DB retention trigger
|
||||
* (enforce_dimension_value_retention, BFL 7-year philosophy) and
|
||||
* return 409 DIMENSION_VALUE_REFERENCED: archive instead.
|
||||
*
|
||||
* Mirrors the internal /api/dimensions/[id]/values/[valueId] semantics so
|
||||
* dashboard and API behave identically.
|
||||
*/
|
||||
import { z } from 'zod'
|
||||
import { ok } from '@/lib/api/v1/response'
|
||||
import { dryRunPreview } from '@/lib/api/v1/dry-run'
|
||||
import { registerEndpoint, dataEnvelope } from '@/lib/api/v1/registry'
|
||||
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponse, v1ErrorResponseFromCode, v1ValidationError } from '@/lib/api/v1/errors'
|
||||
import { readV1JsonBody } from '@/lib/api/v1/body'
|
||||
import { UpdateDimensionValueSchema } from '@/lib/api/schemas'
|
||||
|
||||
const DimensionValueShape = z.object({
|
||||
id: z.string().uuid(),
|
||||
dimension_id: z.string().uuid(),
|
||||
code: z.string(),
|
||||
name: z.string(),
|
||||
is_active: z.boolean(),
|
||||
start_date: z.string().nullable(),
|
||||
end_date: z.string().nullable(),
|
||||
})
|
||||
|
||||
const VALUE_COLUMNS = 'id, dimension_id, code, name, is_active, start_date, end_date'
|
||||
|
||||
registerEndpoint({
|
||||
operation: 'dimensions.values.update',
|
||||
method: 'PATCH',
|
||||
path: '/api/v1/companies/:companyId/dimensions/:id/values/:valueId',
|
||||
summary: 'Update a dimension value (rename, archive, set start/end date).',
|
||||
description:
|
||||
'Sparse update of a dimension value (SIE #OBJEKT): name, is_active (false = archive), start_date, end_date. `code` is immutable: renaming a code would orphan every journal line tagged with it; create a new value and archive the old one instead. Dates are only allowed on accumulating dimensions (resets_annually=false, e.g. dim 6 Projekt): use end_date to close a finished project. Idempotent (mandatory Idempotency-Key) and dry-runnable.',
|
||||
useWhen:
|
||||
'You need to rename a project/cost-centre, mark a finished project with an end date, or archive (is_active=false) a value that should no longer be used on new lines.',
|
||||
doNotUseFor:
|
||||
'Changing the code (immutable: create + archive instead). Removing an unused value entirely (use DELETE). Tagging lines (pass dimensions on the journal-entry line or invoice).',
|
||||
pitfalls: [
|
||||
'Idempotency-Key is mandatory.',
|
||||
'The :id segment is the dimension UUID and :valueId the value UUID (both from GET …/dimensions), not SIE numbers or codes.',
|
||||
'start_date/end_date return 400 DIMENSION_VALUE_DATES_NOT_ALLOWED on resets_annually dimensions (dim 1 Kostnadsställe).',
|
||||
'Archived values (is_active=false) still appear in GET …/dimensions and remain valid on historical lines; they are only blocked for NEW tags.',
|
||||
],
|
||||
example: {
|
||||
request: { end_date: '2026-08-31', is_active: false },
|
||||
response: {
|
||||
data: {
|
||||
id: '0e9c…',
|
||||
dimension_id: 'a8f1…',
|
||||
code: 'P001',
|
||||
name: 'Villa Almgren tak',
|
||||
is_active: false,
|
||||
start_date: null,
|
||||
end_date: '2026-08-31',
|
||||
},
|
||||
meta: { request_id: 'req_…', api_version: '2026-05-12' },
|
||||
},
|
||||
},
|
||||
scope: 'bookkeeping:write',
|
||||
risk: 'low',
|
||||
idempotent: true,
|
||||
reversible: true,
|
||||
dryRunSupported: true,
|
||||
request: { body: UpdateDimensionValueSchema },
|
||||
response: { success: dataEnvelope(DimensionValueShape) },
|
||||
})
|
||||
|
||||
registerEndpoint({
|
||||
operation: 'dimensions.values.delete',
|
||||
method: 'DELETE',
|
||||
path: '/api/v1/companies/:companyId/dimensions/:id/values/:valueId',
|
||||
summary: 'Delete an unreferenced dimension value.',
|
||||
description:
|
||||
'Hard-deletes a dimension value (SIE #OBJEKT) that no journal line references. Values used on posted or reversed verifikat are retained for the BFL 7-year archive and cannot be deleted: the DB trigger blocks it and this endpoint returns 409 DIMENSION_VALUE_REFERENCED. Archive those instead (PATCH is_active=false). Requires Idempotency-Key.',
|
||||
useWhen:
|
||||
'A project/cost-centre code was created by mistake (typo, duplicate) and has never been used on any booking.',
|
||||
doNotUseFor:
|
||||
'Retiring a project that has bookings: PATCH is_active=false (and optionally end_date) instead. Deleting a whole dimension (not supported).',
|
||||
pitfalls: [
|
||||
'Idempotency-Key is mandatory.',
|
||||
'409 DIMENSION_VALUE_REFERENCED means the value is used on booked verifikat: it can never be deleted, only archived.',
|
||||
'Deletion is permanent: the code can be re-created afterwards, but the old row id is gone.',
|
||||
],
|
||||
example: {
|
||||
response: {
|
||||
data: { deleted: true, id: '0e9c…' },
|
||||
meta: { request_id: 'req_…', api_version: '2026-05-12' },
|
||||
},
|
||||
},
|
||||
scope: 'bookkeeping:write',
|
||||
risk: 'medium',
|
||||
idempotent: true,
|
||||
reversible: false,
|
||||
dryRunSupported: false,
|
||||
response: { success: dataEnvelope(z.object({ deleted: z.literal(true), id: z.string().uuid() })) },
|
||||
})
|
||||
|
||||
type ValueRouteParams = { params: Promise<{ companyId: string; id: string; valueId: string }> }
|
||||
|
||||
async function resolveIds(params: ValueRouteParams['params']) {
|
||||
const { id, valueId } = await params
|
||||
const parsed = z
|
||||
.object({ id: z.string().uuid(), valueId: z.string().uuid() })
|
||||
.safeParse({ id, valueId })
|
||||
return parsed.success ? parsed.data : null
|
||||
}
|
||||
|
||||
export const PATCH = withApiV1<ValueRouteParams>(
|
||||
'dimensions.values.update',
|
||||
async (request, ctx, { params }) => {
|
||||
const ids = await resolveIds(params)
|
||||
if (!ids) {
|
||||
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { field: 'id', message: 'Dimension id and value id must be UUIDs.' },
|
||||
})
|
||||
}
|
||||
|
||||
const rawBodyResult = await readV1JsonBody(request, ctx)
|
||||
if (!rawBodyResult.ok) return rawBodyResult.response
|
||||
const rawBody = rawBodyResult.body
|
||||
|
||||
const parsed = UpdateDimensionValueSchema.safeParse(rawBody)
|
||||
if (!parsed.success) return v1ValidationError(ctx, parsed.error)
|
||||
const body = parsed.data
|
||||
|
||||
// Value dates only make sense on accumulating dimensions (projekt-style
|
||||
// ranges). When the request carries an actual date (explicit null = clear,
|
||||
// always allowed), check the parent dimension's resets_annually flag.
|
||||
// Mirrors the internal route exactly.
|
||||
if (body.start_date != null || body.end_date != null) {
|
||||
const { data: dimension, error: dimError } = await ctx.supabase
|
||||
.from('dimensions')
|
||||
.select('id, resets_annually')
|
||||
.eq('id', ids.id)
|
||||
.eq('company_id', ctx.companyId!)
|
||||
.maybeSingle()
|
||||
|
||||
if (dimError) {
|
||||
return v1ErrorResponse(dimError, ctx.log, { requestId: ctx.requestId })
|
||||
}
|
||||
if (!dimension) {
|
||||
return v1ErrorResponseFromCode('DIMENSION_NOT_FOUND', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { dimension_id: ids.id },
|
||||
})
|
||||
}
|
||||
if (dimension.resets_annually) {
|
||||
return v1ErrorResponseFromCode('DIMENSION_VALUE_DATES_NOT_ALLOWED', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const updateData: Record<string, unknown> = {}
|
||||
for (const key of ['name', 'is_active', 'start_date', 'end_date'] as const) {
|
||||
if (body[key] !== undefined) updateData[key] = body[key]
|
||||
}
|
||||
|
||||
// Pre-flight fetch: needed for a faithful dry-run preview and a clean 404
|
||||
// before the write.
|
||||
const { data: current, error: fetchErr } = await ctx.supabase
|
||||
.from('dimension_values')
|
||||
.select(VALUE_COLUMNS)
|
||||
.eq('id', ids.valueId)
|
||||
.eq('dimension_id', ids.id)
|
||||
.eq('company_id', ctx.companyId!)
|
||||
.maybeSingle()
|
||||
|
||||
if (fetchErr) {
|
||||
return v1ErrorResponse(fetchErr, ctx.log, { requestId: ctx.requestId })
|
||||
}
|
||||
if (!current) {
|
||||
return v1ErrorResponseFromCode('DIMENSION_VALUE_NOT_FOUND', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
})
|
||||
}
|
||||
|
||||
if (ctx.dryRun) {
|
||||
return dryRunPreview({ ...current, ...updateData }, { requestId: ctx.requestId, log: ctx.log })
|
||||
}
|
||||
|
||||
const { data, error } = await ctx.supabase
|
||||
.from('dimension_values')
|
||||
.update(updateData)
|
||||
.eq('id', ids.valueId)
|
||||
.eq('dimension_id', ids.id)
|
||||
.eq('company_id', ctx.companyId!)
|
||||
.select(VALUE_COLUMNS)
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
return v1ErrorResponse(error, ctx.log, { requestId: ctx.requestId })
|
||||
}
|
||||
|
||||
return ok(data, { requestId: ctx.requestId })
|
||||
},
|
||||
{ requireIdempotencyKey: true },
|
||||
)
|
||||
|
||||
export const DELETE = withApiV1<ValueRouteParams>(
|
||||
'dimensions.values.delete',
|
||||
async (_request, ctx, { params }) => {
|
||||
const ids = await resolveIds(params)
|
||||
if (!ids) {
|
||||
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { field: 'id', message: 'Dimension id and value id must be UUIDs.' },
|
||||
})
|
||||
}
|
||||
|
||||
const { data, error } = await ctx.supabase
|
||||
.from('dimension_values')
|
||||
.delete()
|
||||
.eq('id', ids.valueId)
|
||||
.eq('dimension_id', ids.id)
|
||||
.eq('company_id', ctx.companyId!)
|
||||
.select('id')
|
||||
|
||||
if (error) {
|
||||
// P0001 = plpgsql RAISE EXCEPTION: the retention trigger refusing the
|
||||
// delete because posted/reversed lines reference the value.
|
||||
if (error.code === 'P0001') {
|
||||
return v1ErrorResponseFromCode('DIMENSION_VALUE_REFERENCED', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { value_id: ids.valueId },
|
||||
validAlternatives: {
|
||||
archive_endpoint: `/api/v1/companies/${ctx.companyId}/dimensions/${ids.id}/values/${ids.valueId}`,
|
||||
archive_body: { is_active: false },
|
||||
},
|
||||
})
|
||||
}
|
||||
return v1ErrorResponse(error, ctx.log, { requestId: ctx.requestId })
|
||||
}
|
||||
|
||||
if (!data || data.length === 0) {
|
||||
return v1ErrorResponseFromCode('DIMENSION_VALUE_NOT_FOUND', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
})
|
||||
}
|
||||
|
||||
return ok({ deleted: true, id: ids.valueId }, { requestId: ctx.requestId })
|
||||
},
|
||||
{ requireIdempotencyKey: true },
|
||||
)
|
||||
@@ -1,151 +0,0 @@
|
||||
/**
|
||||
* POST /api/v1/companies/{companyId}/dimensions/{id}/values
|
||||
*
|
||||
* Create a dimension value (SIE #OBJEKT). Idempotent (mandatory
|
||||
* Idempotency-Key), dry-runnable. Codes follow the strict Fortnox format
|
||||
* (^[A-Za-z0-9ÅÄÖåäö_+\-]{1,20}$) for user-created values; the DB CHECK is
|
||||
* looser by design so legacy free-text codes survive imports. `code` is
|
||||
* immutable after creation.
|
||||
*/
|
||||
import { z } from 'zod'
|
||||
import { created } from '@/lib/api/v1/response'
|
||||
import { dryRunPreview } from '@/lib/api/v1/dry-run'
|
||||
import { registerEndpoint, dataEnvelope } from '@/lib/api/v1/registry'
|
||||
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponse, v1ErrorResponseFromCode, v1ValidationError } from '@/lib/api/v1/errors'
|
||||
import { readV1JsonBody } from '@/lib/api/v1/body'
|
||||
import { CreateDimensionValueSchema } from '@/lib/api/schemas'
|
||||
|
||||
const DimensionValueCreated = z.object({
|
||||
id: z.string().uuid().nullable(),
|
||||
dimension_id: z.string().uuid(),
|
||||
code: z.string(),
|
||||
name: z.string(),
|
||||
is_active: z.boolean(),
|
||||
start_date: z.string().nullable(),
|
||||
end_date: z.string().nullable(),
|
||||
created_at: z.string().nullable(),
|
||||
})
|
||||
|
||||
registerEndpoint({
|
||||
operation: 'dimensions.values.create',
|
||||
method: 'POST',
|
||||
path: '/api/v1/companies/:companyId/dimensions/:id/values',
|
||||
summary: 'Create a dimension value (kostnadsställe/projekt code).',
|
||||
description:
|
||||
'Registers a new value (SIE #OBJEKT) under a dimension: e.g. a new project code under dimension 6. Requires Idempotency-Key (UUID). Supports ?dry_run=true to validate the code format without committing. The `:id` path segment is the dimension row id (from GET …/dimensions), not the sie_dim_no. Duplicate codes within the dimension return 409 DIMENSION_VALUE_DUPLICATE_CODE.',
|
||||
useWhen:
|
||||
'A voucher or invoice references a cost centre / project code that does not exist yet and the user has confirmed it should be created.',
|
||||
doNotUseFor:
|
||||
'Renaming or archiving an existing value (dashboard register in v1). Tagging lines: pass the dimensions map on the journal-entry line instead.',
|
||||
pitfalls: [
|
||||
'Idempotency-Key is mandatory: calls without it return 400 VALIDATION_ERROR.',
|
||||
'The :id segment is the dimension UUID, not the SIE dimension number.',
|
||||
'Codes are limited to the strict Fortnox charset (A-Ö, digits, _, +, -; max 20 chars) even though historical imported codes may be looser.',
|
||||
'code is immutable after creation: there is no rename in v1; create the correct code and archive the wrong one.',
|
||||
],
|
||||
example: {
|
||||
request: { code: 'P001', name: 'Villa Almgren tak' },
|
||||
response: {
|
||||
data: {
|
||||
id: '0e9c…',
|
||||
dimension_id: 'a8f1…',
|
||||
code: 'P001',
|
||||
name: 'Villa Almgren tak',
|
||||
is_active: true,
|
||||
start_date: null,
|
||||
end_date: null,
|
||||
created_at: '2026-07-02T12:00:00Z',
|
||||
},
|
||||
meta: { request_id: 'req_…', api_version: '2026-05-12' },
|
||||
},
|
||||
},
|
||||
scope: 'bookkeeping:write',
|
||||
risk: 'low',
|
||||
idempotent: true,
|
||||
reversible: true,
|
||||
dryRunSupported: true,
|
||||
request: { body: CreateDimensionValueSchema },
|
||||
response: { success: dataEnvelope(DimensionValueCreated) },
|
||||
})
|
||||
|
||||
export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string }> }>(
|
||||
'dimensions.values.create',
|
||||
async (request, ctx, { params }) => {
|
||||
const { id } = await params
|
||||
|
||||
if (!z.string().uuid().safeParse(id).success) {
|
||||
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { field: 'id', message: 'Dimension id must be a UUID.' },
|
||||
})
|
||||
}
|
||||
|
||||
const rawBodyResult = await readV1JsonBody(request, ctx)
|
||||
if (!rawBodyResult.ok) return rawBodyResult.response
|
||||
const rawBody = rawBodyResult.body
|
||||
|
||||
const parsed = CreateDimensionValueSchema.safeParse(rawBody)
|
||||
if (!parsed.success) return v1ValidationError(ctx, parsed.error)
|
||||
const body = parsed.data
|
||||
|
||||
// The dimension must exist and belong to the company in the URL.
|
||||
const { data: dimension, error: dimError } = await ctx.supabase
|
||||
.from('dimensions')
|
||||
.select('id')
|
||||
.eq('id', id)
|
||||
.eq('company_id', ctx.companyId!)
|
||||
.maybeSingle()
|
||||
if (dimError) {
|
||||
return v1ErrorResponse(dimError, ctx.log, { requestId: ctx.requestId })
|
||||
}
|
||||
if (!dimension) {
|
||||
return v1ErrorResponseFromCode('DIMENSION_NOT_FOUND', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { dimension_id: id },
|
||||
})
|
||||
}
|
||||
|
||||
if (ctx.dryRun) {
|
||||
return dryRunPreview(
|
||||
{
|
||||
id: null,
|
||||
dimension_id: id,
|
||||
code: body.code,
|
||||
name: body.name,
|
||||
is_active: true,
|
||||
start_date: body.start_date ?? null,
|
||||
end_date: body.end_date ?? null,
|
||||
created_at: null,
|
||||
},
|
||||
{ requestId: ctx.requestId, log: ctx.log },
|
||||
)
|
||||
}
|
||||
|
||||
const { data, error } = await ctx.supabase
|
||||
.from('dimension_values')
|
||||
.insert({
|
||||
company_id: ctx.companyId!,
|
||||
dimension_id: id,
|
||||
code: body.code,
|
||||
name: body.name,
|
||||
start_date: body.start_date ?? null,
|
||||
end_date: body.end_date ?? null,
|
||||
})
|
||||
.select('id, dimension_id, code, name, is_active, start_date, end_date, created_at')
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
if (error.code === '23505') {
|
||||
return v1ErrorResponseFromCode('DIMENSION_VALUE_DUPLICATE_CODE', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { code: body.code },
|
||||
})
|
||||
}
|
||||
return v1ErrorResponse(error, ctx.log, { requestId: ctx.requestId })
|
||||
}
|
||||
|
||||
return created(data, { requestId: ctx.requestId })
|
||||
},
|
||||
{ requireIdempotencyKey: true },
|
||||
)
|
||||
@@ -1,327 +0,0 @@
|
||||
/**
|
||||
* Integration tests for the v1 dimensions surface (dimensions PR2):
|
||||
* GET /api/v1/companies/:companyId/dimensions
|
||||
* POST /api/v1/companies/:companyId/dimensions/:id/values
|
||||
*
|
||||
* Mirrors the suppliers/accounts test pattern: a Proxy-backed Supabase mock
|
||||
* returns whatever the route awaits, keyed by table name (plus an `rpc` key
|
||||
* for ensure_company_dimensions).
|
||||
*/
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
beforeAll(() => {
|
||||
if (process.env.NODE_ENV !== 'test') throw new Error('NODE_ENV=test required')
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL ||= 'http://localhost:54321'
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ||= 'test-anon-key'
|
||||
})
|
||||
|
||||
vi.mock('@/lib/auth/api-keys', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/auth/api-keys')>('@/lib/auth/api-keys')
|
||||
return { ...actual, validateApiKey: vi.fn(), createServiceClientNoCookies: vi.fn() }
|
||||
})
|
||||
vi.mock('@supabase/supabase-js', async () => {
|
||||
const actual = await vi.importActual<typeof import('@supabase/supabase-js')>('@supabase/supabase-js')
|
||||
return { ...actual, createClient: vi.fn().mockReturnValue({}) }
|
||||
})
|
||||
|
||||
import { validateApiKey, createServiceClientNoCookies } from '@/lib/auth/api-keys'
|
||||
import { GET as listDimensions } from '../route'
|
||||
import { POST as createValue } from '../[id]/values/route'
|
||||
|
||||
const mockValidate = validateApiKey as ReturnType<typeof vi.fn>
|
||||
const mockServiceClient = createServiceClientNoCookies as ReturnType<typeof vi.fn>
|
||||
|
||||
interface TableResp {
|
||||
data?: unknown
|
||||
error?: unknown
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-table queue mock: TableResp[] consumes one entry per await, then sticks
|
||||
* on the last entry. The special key `rpc` answers `supabase.rpc(...)` calls.
|
||||
*/
|
||||
function makeFlexibleSupabase(byTable: Record<string, TableResp | TableResp[]>) {
|
||||
const queues = new Map<string, TableResp[]>()
|
||||
for (const [t, val] of Object.entries(byTable)) {
|
||||
queues.set(t, Array.isArray(val) ? [...val] : [val])
|
||||
}
|
||||
const buildChain = (key: string): unknown => {
|
||||
const handler: ProxyHandler<object> = {
|
||||
get(_target, prop) {
|
||||
if (prop === 'then') {
|
||||
return (resolve: (v: unknown) => void) => {
|
||||
const q = queues.get(key)
|
||||
const next = q && q.length > 1 ? q.shift()! : (q?.[0] ?? { data: null, error: null })
|
||||
resolve(next)
|
||||
}
|
||||
}
|
||||
return (..._args: unknown[]) => buildChain(key)
|
||||
},
|
||||
}
|
||||
return new Proxy({}, handler)
|
||||
}
|
||||
return {
|
||||
from: vi.fn((table: string) => buildChain(table)),
|
||||
rpc: vi.fn(() => buildChain('rpc')),
|
||||
}
|
||||
}
|
||||
|
||||
const COMPANY_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
|
||||
const DIMENSION_ID = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'
|
||||
|
||||
function makeRequest(url: string, init?: RequestInit): Request {
|
||||
return new Request(url, {
|
||||
...init,
|
||||
headers: {
|
||||
Authorization: 'Bearer test-fixture-not-a-real-key',
|
||||
'Idempotency-Key': 'c1aaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
|
||||
...(init?.headers ?? {}),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const SAMPLE_DIMS = [
|
||||
{
|
||||
id: DIMENSION_ID,
|
||||
sie_dim_no: 1,
|
||||
name: 'Kostnadsställe',
|
||||
resets_annually: true,
|
||||
is_system: true,
|
||||
is_active: true,
|
||||
sort_order: 10,
|
||||
},
|
||||
{
|
||||
id: 'cccccccc-cccc-4ccc-8ccc-cccccccccccc',
|
||||
sie_dim_no: 6,
|
||||
name: 'Projekt',
|
||||
resets_annually: false,
|
||||
is_system: true,
|
||||
is_active: true,
|
||||
sort_order: 20,
|
||||
},
|
||||
]
|
||||
|
||||
const SAMPLE_VALUE = {
|
||||
id: 'dddddddd-dddd-4ddd-8ddd-dddddddddddd',
|
||||
dimension_id: DIMENSION_ID,
|
||||
code: 'BUTIK',
|
||||
name: 'Butiken',
|
||||
is_active: true,
|
||||
start_date: null,
|
||||
end_date: null,
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: COMPANY_ID,
|
||||
apiKeyId: 'ak_1',
|
||||
apiKeyName: 'CI key',
|
||||
scopes: ['reports:read', 'bookkeeping:write'],
|
||||
mode: 'live',
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /api/v1/companies/:companyId/dimensions', () => {
|
||||
it('ensures system dims and returns the registry with nested values', async () => {
|
||||
const client = makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
rpc: { data: null, error: null },
|
||||
dimensions: { data: SAMPLE_DIMS, error: null },
|
||||
dimension_values: { data: [SAMPLE_VALUE], error: null },
|
||||
})
|
||||
mockServiceClient.mockReturnValue(client)
|
||||
|
||||
const res = await listDimensions(
|
||||
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/dimensions`),
|
||||
{ params: Promise.resolve({ companyId: COMPANY_ID }) },
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(client.rpc).toHaveBeenCalledWith('ensure_company_dimensions', {
|
||||
p_company_id: COMPANY_ID,
|
||||
})
|
||||
const body = await res.json()
|
||||
expect(body.data.dimensions).toHaveLength(2)
|
||||
expect(body.data.dimensions[0].sie_dim_no).toBe(1)
|
||||
expect(body.data.dimensions[0].values).toEqual([
|
||||
{
|
||||
id: SAMPLE_VALUE.id,
|
||||
code: 'BUTIK',
|
||||
name: 'Butiken',
|
||||
is_active: true,
|
||||
start_date: null,
|
||||
end_date: null,
|
||||
},
|
||||
])
|
||||
expect(body.data.dimensions[1].values).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects keys without reports:read scope (403)', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: COMPANY_ID,
|
||||
scopes: ['invoices:read'],
|
||||
mode: 'live',
|
||||
})
|
||||
mockServiceClient.mockReturnValue(makeFlexibleSupabase({}))
|
||||
|
||||
const res = await listDimensions(
|
||||
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/dimensions`),
|
||||
{ params: Promise.resolve({ companyId: COMPANY_ID }) },
|
||||
)
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/v1/companies/:companyId/dimensions/:id/values', () => {
|
||||
const url = `https://x.test/api/v1/companies/${COMPANY_ID}/dimensions/${DIMENSION_ID}/values`
|
||||
const detailParams = { params: Promise.resolve({ companyId: COMPANY_ID, id: DIMENSION_ID }) }
|
||||
|
||||
it('creates a value (201, happy path)', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
dimensions: { data: { id: DIMENSION_ID }, error: null },
|
||||
dimension_values: { data: { ...SAMPLE_VALUE, created_at: '2026-07-02T12:00:00Z' }, error: null },
|
||||
idempotency_keys: { data: null, error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await createValue(
|
||||
makeRequest(url, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ code: 'BUTIK', name: 'Butiken' }),
|
||||
}),
|
||||
detailParams,
|
||||
)
|
||||
|
||||
expect(res.status).toBe(201)
|
||||
const body = await res.json()
|
||||
expect(body.data.code).toBe('BUTIK')
|
||||
})
|
||||
|
||||
it('returns 400 when Idempotency-Key is missing', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const req = new Request(url, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({ code: 'BUTIK', name: 'Butiken' }),
|
||||
})
|
||||
const res = await createValue(req, detailParams)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('rejects a non-Fortnox code with 400 VALIDATION_ERROR', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
idempotency_keys: { data: null, error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await createValue(
|
||||
makeRequest(url, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ code: 'BAD CODE!', name: 'x' }),
|
||||
}),
|
||||
detailParams,
|
||||
)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('VALIDATION_ERROR')
|
||||
})
|
||||
|
||||
it('returns 404 DIMENSION_NOT_FOUND for a dimension outside the company', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
dimensions: { data: null, error: null },
|
||||
idempotency_keys: { data: null, error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await createValue(
|
||||
makeRequest(url, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ code: 'BUTIK', name: 'Butiken' }),
|
||||
}),
|
||||
detailParams,
|
||||
)
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('DIMENSION_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('returns 409 DIMENSION_VALUE_DUPLICATE_CODE on a 23505', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
dimensions: { data: { id: DIMENSION_ID }, error: null },
|
||||
dimension_values: { data: null, error: { code: '23505', message: 'duplicate' } },
|
||||
idempotency_keys: { data: null, error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await createValue(
|
||||
makeRequest(url, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ code: 'BUTIK', name: 'Butiken' }),
|
||||
}),
|
||||
detailParams,
|
||||
)
|
||||
|
||||
expect(res.status).toBe(409)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('DIMENSION_VALUE_DUPLICATE_CODE')
|
||||
})
|
||||
|
||||
it('returns a dry-run preview without inserting when ?dry_run=true', async () => {
|
||||
const fromSpy = vi.fn()
|
||||
mockServiceClient.mockReturnValue({
|
||||
from: (table: string) => {
|
||||
fromSpy(table)
|
||||
return new Proxy({}, {
|
||||
get(_t, prop) {
|
||||
if (prop === 'then') {
|
||||
const data =
|
||||
table === 'company_members'
|
||||
? { company_id: COMPANY_ID, role: 'owner' }
|
||||
: table === 'dimensions'
|
||||
? { id: DIMENSION_ID }
|
||||
: null
|
||||
return (resolve: (v: unknown) => void) => resolve({ data, error: null })
|
||||
}
|
||||
return () => new Proxy({}, this!)
|
||||
},
|
||||
})
|
||||
},
|
||||
rpc: vi.fn(),
|
||||
})
|
||||
|
||||
const res = await createValue(
|
||||
makeRequest(`${url}?dry_run=true`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ code: 'P001', name: 'Villa Almgren tak' }),
|
||||
}),
|
||||
detailParams,
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('X-Dry-Run')).toBe('true')
|
||||
expect(fromSpy).not.toHaveBeenCalledWith('dimension_values')
|
||||
const body = await res.json()
|
||||
expect(body.data.dry_run).toBe(true)
|
||||
expect(body.data.preview.code).toBe('P001')
|
||||
})
|
||||
})
|
||||
@@ -1,349 +0,0 @@
|
||||
/**
|
||||
* Tests for the v1 dimension value lifecycle endpoints (#895):
|
||||
* PATCH /api/v1/companies/:companyId/dimensions/:id/values/:valueId
|
||||
* DELETE /api/v1/companies/:companyId/dimensions/:id/values/:valueId
|
||||
*
|
||||
* Same Proxy-backed Supabase mock pattern as ./route.test.ts.
|
||||
*/
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
beforeAll(() => {
|
||||
if (process.env.NODE_ENV !== 'test') throw new Error('NODE_ENV=test required')
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL ||= 'http://localhost:54321'
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ||= 'test-anon-key'
|
||||
})
|
||||
|
||||
vi.mock('@/lib/auth/api-keys', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/auth/api-keys')>('@/lib/auth/api-keys')
|
||||
return { ...actual, validateApiKey: vi.fn(), createServiceClientNoCookies: vi.fn() }
|
||||
})
|
||||
vi.mock('@supabase/supabase-js', async () => {
|
||||
const actual = await vi.importActual<typeof import('@supabase/supabase-js')>('@supabase/supabase-js')
|
||||
return { ...actual, createClient: vi.fn().mockReturnValue({}) }
|
||||
})
|
||||
|
||||
import { validateApiKey, createServiceClientNoCookies } from '@/lib/auth/api-keys'
|
||||
import { PATCH as patchValue, DELETE as deleteValue } from '../[id]/values/[valueId]/route'
|
||||
|
||||
const mockValidate = validateApiKey as ReturnType<typeof vi.fn>
|
||||
const mockServiceClient = createServiceClientNoCookies as ReturnType<typeof vi.fn>
|
||||
|
||||
interface TableResp {
|
||||
data?: unknown
|
||||
error?: unknown
|
||||
}
|
||||
|
||||
function makeFlexibleSupabase(byTable: Record<string, TableResp | TableResp[]>) {
|
||||
const queues = new Map<string, TableResp[]>()
|
||||
for (const [t, val] of Object.entries(byTable)) {
|
||||
queues.set(t, Array.isArray(val) ? [...val] : [val])
|
||||
}
|
||||
const buildChain = (key: string): unknown => {
|
||||
const handler: ProxyHandler<object> = {
|
||||
get(_target, prop) {
|
||||
if (prop === 'then') {
|
||||
return (resolve: (v: unknown) => void) => {
|
||||
const q = queues.get(key)
|
||||
const next = q && q.length > 1 ? q.shift()! : (q?.[0] ?? { data: null, error: null })
|
||||
resolve(next)
|
||||
}
|
||||
}
|
||||
return (..._args: unknown[]) => buildChain(key)
|
||||
},
|
||||
}
|
||||
return new Proxy({}, handler)
|
||||
}
|
||||
return {
|
||||
from: vi.fn((table: string) => buildChain(table)),
|
||||
rpc: vi.fn(() => buildChain('rpc')),
|
||||
}
|
||||
}
|
||||
|
||||
const COMPANY_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
|
||||
const DIMENSION_ID = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'
|
||||
const VALUE_ID = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd'
|
||||
|
||||
const URL_BASE = `https://x.test/api/v1/companies/${COMPANY_ID}/dimensions/${DIMENSION_ID}/values/${VALUE_ID}`
|
||||
const routeParams = {
|
||||
params: Promise.resolve({ companyId: COMPANY_ID, id: DIMENSION_ID, valueId: VALUE_ID }),
|
||||
}
|
||||
|
||||
const SAMPLE_VALUE = {
|
||||
id: VALUE_ID,
|
||||
dimension_id: DIMENSION_ID,
|
||||
code: 'P001',
|
||||
name: 'Villa Almgren tak',
|
||||
is_active: true,
|
||||
start_date: null,
|
||||
end_date: null,
|
||||
}
|
||||
|
||||
function makeRequest(url: string, init?: RequestInit): Request {
|
||||
return new Request(url, {
|
||||
...init,
|
||||
headers: {
|
||||
Authorization: 'Bearer test-fixture-not-a-real-key',
|
||||
'Idempotency-Key': 'c1aaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
|
||||
...(init?.headers ?? {}),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: COMPANY_ID,
|
||||
apiKeyId: 'ak_1',
|
||||
apiKeyName: 'CI key',
|
||||
scopes: ['bookkeeping:write'],
|
||||
mode: 'live',
|
||||
})
|
||||
})
|
||||
|
||||
describe('PATCH /api/v1/companies/:companyId/dimensions/:id/values/:valueId', () => {
|
||||
it('updates name + is_active (archive) on the value', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
dimension_values: [
|
||||
{ data: SAMPLE_VALUE, error: null },
|
||||
{ data: { ...SAMPLE_VALUE, name: 'Nytt namn', is_active: false }, error: null },
|
||||
],
|
||||
idempotency_keys: { data: null, error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await patchValue(
|
||||
makeRequest(URL_BASE, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ name: 'Nytt namn', is_active: false }),
|
||||
}),
|
||||
routeParams,
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data.name).toBe('Nytt namn')
|
||||
expect(body.data.is_active).toBe(false)
|
||||
})
|
||||
|
||||
it('sets an end_date on a project value (accumulating dimension)', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
dimensions: { data: { id: DIMENSION_ID, resets_annually: false }, error: null },
|
||||
dimension_values: [
|
||||
{ data: SAMPLE_VALUE, error: null },
|
||||
{ data: { ...SAMPLE_VALUE, end_date: '2026-08-31' }, error: null },
|
||||
],
|
||||
idempotency_keys: { data: null, error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await patchValue(
|
||||
makeRequest(URL_BASE, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ end_date: '2026-08-31' }),
|
||||
}),
|
||||
routeParams,
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data.end_date).toBe('2026-08-31')
|
||||
})
|
||||
|
||||
it('rejects dates on a resets_annually dimension (kostnadsställe)', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
dimensions: { data: { id: DIMENSION_ID, resets_annually: true }, error: null },
|
||||
idempotency_keys: { data: null, error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await patchValue(
|
||||
makeRequest(URL_BASE, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ end_date: '2026-08-31' }),
|
||||
}),
|
||||
routeParams,
|
||||
)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('DIMENSION_VALUE_DATES_NOT_ALLOWED')
|
||||
})
|
||||
|
||||
it('returns 404 DIMENSION_VALUE_NOT_FOUND when the value is not in the company', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
dimension_values: { data: null, error: null },
|
||||
idempotency_keys: { data: null, error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await patchValue(
|
||||
makeRequest(URL_BASE, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ name: 'x' }),
|
||||
}),
|
||||
routeParams,
|
||||
)
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('DIMENSION_VALUE_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('rejects an empty body (schema refine)', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
idempotency_keys: { data: null, error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await patchValue(
|
||||
makeRequest(URL_BASE, { method: 'PATCH', body: JSON.stringify({}) }),
|
||||
routeParams,
|
||||
)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('VALIDATION_ERROR')
|
||||
})
|
||||
|
||||
it('dry-run previews the merged value without writing', async () => {
|
||||
const fromSpy = vi.fn()
|
||||
mockServiceClient.mockReturnValue({
|
||||
from: (table: string) => {
|
||||
fromSpy(table)
|
||||
const handler: ProxyHandler<object> = {
|
||||
get(_t, prop) {
|
||||
if (prop === 'then') {
|
||||
const data =
|
||||
table === 'company_members'
|
||||
? { company_id: COMPANY_ID, role: 'owner' }
|
||||
: table === 'dimension_values'
|
||||
? SAMPLE_VALUE
|
||||
: null
|
||||
return (resolve: (v: unknown) => void) => resolve({ data, error: null })
|
||||
}
|
||||
return () => new Proxy({}, handler)
|
||||
},
|
||||
}
|
||||
return new Proxy({}, handler)
|
||||
},
|
||||
rpc: vi.fn(),
|
||||
})
|
||||
|
||||
const res = await patchValue(
|
||||
makeRequest(`${URL_BASE}?dry_run=true`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ is_active: false }),
|
||||
}),
|
||||
routeParams,
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('X-Dry-Run')).toBe('true')
|
||||
const body = await res.json()
|
||||
expect(body.data.dry_run).toBe(true)
|
||||
expect(body.data.preview.is_active).toBe(false)
|
||||
// Only one read (the pre-flight fetch): no second dimension_values await
|
||||
// means no UPDATE was issued through the queue.
|
||||
expect(fromSpy.mock.calls.filter(([t]) => t === 'dimension_values')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('rejects keys without bookkeeping:write scope (403)', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: COMPANY_ID,
|
||||
scopes: ['reports:read'],
|
||||
mode: 'live',
|
||||
})
|
||||
mockServiceClient.mockReturnValue(makeFlexibleSupabase({}))
|
||||
|
||||
const res = await patchValue(
|
||||
makeRequest(URL_BASE, { method: 'PATCH', body: JSON.stringify({ name: 'x' }) }),
|
||||
routeParams,
|
||||
)
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /api/v1/companies/:companyId/dimensions/:id/values/:valueId', () => {
|
||||
it('deletes an unreferenced value', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
dimension_values: { data: [{ id: VALUE_ID }], error: null },
|
||||
idempotency_keys: { data: null, error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await deleteValue(makeRequest(URL_BASE, { method: 'DELETE' }), routeParams)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data).toEqual({ deleted: true, id: VALUE_ID })
|
||||
})
|
||||
|
||||
it('returns 409 DIMENSION_VALUE_REFERENCED with an archive hint when the retention trigger blocks', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
dimension_values: {
|
||||
data: null,
|
||||
error: { code: 'P0001', message: 'Värdet "P001" används på bokförda verifikat' },
|
||||
},
|
||||
idempotency_keys: { data: null, error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await deleteValue(makeRequest(URL_BASE, { method: 'DELETE' }), routeParams)
|
||||
|
||||
expect(res.status).toBe(409)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('DIMENSION_VALUE_REFERENCED')
|
||||
expect(body.error.valid_alternatives.archive_body).toEqual({ is_active: false })
|
||||
})
|
||||
|
||||
it('returns 404 DIMENSION_VALUE_NOT_FOUND when nothing was deleted', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
dimension_values: { data: [], error: null },
|
||||
idempotency_keys: { data: null, error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await deleteValue(makeRequest(URL_BASE, { method: 'DELETE' }), routeParams)
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('DIMENSION_VALUE_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('returns 400 VALIDATION_ERROR for a non-UUID valueId', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
idempotency_keys: { data: null, error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await deleteValue(
|
||||
makeRequest(URL_BASE, { method: 'DELETE' }),
|
||||
{ params: Promise.resolve({ companyId: COMPANY_ID, id: DIMENSION_ID, valueId: 'not-a-uuid' }) },
|
||||
)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('VALIDATION_ERROR')
|
||||
})
|
||||
})
|
||||
@@ -1,149 +0,0 @@
|
||||
/**
|
||||
* GET /api/v1/companies/{companyId}/dimensions
|
||||
*
|
||||
* List the dimension registry (SIE #DIM) with nested values (#OBJEKT).
|
||||
* Ensures the system dims (1 = Kostnadsställe, 6 = Projekt) exist via the
|
||||
* ensure_company_dimensions RPC before reading: lazy seeding, so the list is
|
||||
* never empty even for companies that have not touched dimensions.
|
||||
*/
|
||||
import { z } from 'zod'
|
||||
import { ok } from '@/lib/api/v1/response'
|
||||
import { registerEndpoint, dataEnvelope } from '@/lib/api/v1/registry'
|
||||
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponse } from '@/lib/api/v1/errors'
|
||||
|
||||
const DimensionValue = z.object({
|
||||
id: z.string().uuid(),
|
||||
code: z.string(),
|
||||
name: z.string(),
|
||||
is_active: z.boolean(),
|
||||
start_date: z.string().nullable(),
|
||||
end_date: z.string().nullable(),
|
||||
})
|
||||
|
||||
const Dimension = z.object({
|
||||
id: z.string().uuid(),
|
||||
sie_dim_no: z.number().int().min(1),
|
||||
name: z.string(),
|
||||
resets_annually: z.boolean(),
|
||||
is_system: z.boolean(),
|
||||
is_active: z.boolean(),
|
||||
sort_order: z.number().int(),
|
||||
values: z.array(DimensionValue),
|
||||
})
|
||||
|
||||
const DimensionsResponse = dataEnvelope(z.object({ dimensions: z.array(Dimension) }))
|
||||
|
||||
registerEndpoint({
|
||||
operation: 'dimensions.list',
|
||||
method: 'GET',
|
||||
path: '/api/v1/companies/:companyId/dimensions',
|
||||
summary: 'List dimensions (kostnadsställe/projekt) with their values.',
|
||||
description:
|
||||
'Returns the company\'s dimension registry: SIE #DIM entries keyed by sie_dim_no (1 = Kostnadsställe, 6 = Projekt; both always exist): with the registered values (#OBJEKT) nested under each dimension. Dimensions are ordered by sort_order, values by code. Line-level tags on journal entries reference these values as {"<sie_dim_no>":"<code>"} in the `dimensions` map.',
|
||||
useWhen:
|
||||
'You need the valid dimension value codes before tagging journal-entry lines with a cost centre or project, or you are rendering a dimension picker.',
|
||||
doNotUseFor:
|
||||
'Filtering reports (pass the dimension filter to the report endpoints once available) or reading which lines carry a tag (read the journal entries themselves).',
|
||||
pitfalls: [
|
||||
'Dimension value codes are STRINGS and case-sensitive: "P001", not 1.',
|
||||
'sie_dim_no is the key used in journal_entry_lines.dimensions, NOT the dimension row id.',
|
||||
'is_active=false values are historical (archived): do not tag new lines with them.',
|
||||
'resets_annually=true (dim 1) means balances reset each fiscal year; dim 6 (projekt) accumulates across years.',
|
||||
],
|
||||
example: {
|
||||
response: {
|
||||
data: {
|
||||
dimensions: [
|
||||
{
|
||||
id: '0e9c…',
|
||||
sie_dim_no: 1,
|
||||
name: 'Kostnadsställe',
|
||||
resets_annually: true,
|
||||
is_system: true,
|
||||
is_active: true,
|
||||
sort_order: 10,
|
||||
values: [
|
||||
{
|
||||
id: 'a8f1…',
|
||||
code: 'BUTIK',
|
||||
name: 'Butiken',
|
||||
is_active: true,
|
||||
start_date: null,
|
||||
end_date: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
meta: { request_id: 'req_…', api_version: '2026-05-12' },
|
||||
},
|
||||
},
|
||||
scope: 'reports:read',
|
||||
risk: 'low',
|
||||
idempotent: true,
|
||||
reversible: false,
|
||||
dryRunSupported: false,
|
||||
response: { success: DimensionsResponse },
|
||||
})
|
||||
|
||||
interface DimensionValueRow {
|
||||
id: string
|
||||
dimension_id: string
|
||||
code: string
|
||||
name: string
|
||||
is_active: boolean
|
||||
start_date: string | null
|
||||
end_date: string | null
|
||||
}
|
||||
|
||||
export const GET = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
'dimensions.list',
|
||||
async (_request, ctx) => {
|
||||
const { error: ensureError } = await ctx.supabase.rpc('ensure_company_dimensions', {
|
||||
p_company_id: ctx.companyId!,
|
||||
})
|
||||
if (ensureError) {
|
||||
return v1ErrorResponse(ensureError, ctx.log, { requestId: ctx.requestId })
|
||||
}
|
||||
|
||||
const { data: dims, error: dimsError } = await ctx.supabase
|
||||
.from('dimensions')
|
||||
.select('id, sie_dim_no, name, resets_annually, is_system, is_active, sort_order')
|
||||
.eq('company_id', ctx.companyId!)
|
||||
.order('sort_order', { ascending: true })
|
||||
.order('sie_dim_no', { ascending: true })
|
||||
if (dimsError) {
|
||||
return v1ErrorResponse(dimsError, ctx.log, { requestId: ctx.requestId })
|
||||
}
|
||||
|
||||
const { data: values, error: valuesError } = await ctx.supabase
|
||||
.from('dimension_values')
|
||||
.select('id, dimension_id, code, name, is_active, start_date, end_date')
|
||||
.eq('company_id', ctx.companyId!)
|
||||
.order('code', { ascending: true })
|
||||
if (valuesError) {
|
||||
return v1ErrorResponse(valuesError, ctx.log, { requestId: ctx.requestId })
|
||||
}
|
||||
|
||||
const valuesByDimension = new Map<string, Omit<DimensionValueRow, 'dimension_id'>[]>()
|
||||
for (const v of ((values ?? []) as DimensionValueRow[])) {
|
||||
const bucket = valuesByDimension.get(v.dimension_id) ?? []
|
||||
bucket.push({
|
||||
id: v.id,
|
||||
code: v.code,
|
||||
name: v.name,
|
||||
is_active: v.is_active,
|
||||
start_date: v.start_date,
|
||||
end_date: v.end_date,
|
||||
})
|
||||
valuesByDimension.set(v.dimension_id, bucket)
|
||||
}
|
||||
|
||||
const dimensions = ((dims ?? []) as Array<Record<string, unknown> & { id: string }>).map(
|
||||
(d) => ({ ...d, values: valuesByDimension.get(d.id) ?? [] }),
|
||||
)
|
||||
|
||||
return ok({ dimensions }, { requestId: ctx.requestId })
|
||||
},
|
||||
)
|
||||
@@ -1,156 +0,0 @@
|
||||
/**
|
||||
* GET /api/v1/companies/{companyId}/documents/{id}/download
|
||||
*
|
||||
* Returns a signed Supabase Storage URL (15-minute expiry) for the
|
||||
* document's current version. The signed URL is a direct-download link
|
||||
* the caller can fetch from any HTTP client without re-presenting an
|
||||
* API key: keep it server-side and don't surface to end-users beyond
|
||||
* the immediate transaction.
|
||||
*
|
||||
* The endpoint emits a `document.accessed` event (best-effort) so the
|
||||
* audit trail records every download.
|
||||
*/
|
||||
|
||||
import { z } from 'zod'
|
||||
import { ok } from '@/lib/api/v1/response'
|
||||
import { registerEndpoint, dataEnvelope } from '@/lib/api/v1/registry'
|
||||
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
const DocumentDownloadResponse = z.object({
|
||||
id: z.string().uuid(),
|
||||
file_name: z.string(),
|
||||
mime_type: z.string().nullable(),
|
||||
sha256_hash: z.string(),
|
||||
/**
|
||||
* False when the requested id is a SUPERSEDED version (a newer version
|
||||
* exists). The signed URL is still issued: old versions are retained
|
||||
* for BFL 7 kap audit, but agents should treat the response as
|
||||
* historical and re-resolve the current version via GET /documents
|
||||
* if they need the latest bytes.
|
||||
*/
|
||||
is_current_version: z.boolean(),
|
||||
download_url: z.string().url(),
|
||||
expires_in_seconds: z.number().int(),
|
||||
})
|
||||
|
||||
// 15 minutes. Three bots converged on this (SOC 2 CC6.1, GDPR Art. 5(1)(f),
|
||||
// ISO 27001 A.8.12) when the original 60-minute window was flagged as a
|
||||
// bearer-token-equivalent with too wide an exposure window. The dashboard
|
||||
// internal route still issues 60min URLs because it's gated by an active
|
||||
// session; the v1 surface has no session, only the URL itself: so the
|
||||
// shorter window applies. A caller that needs longer than 15 minutes for
|
||||
// a single download should re-request the URL.
|
||||
const SIGNED_URL_TTL_SECONDS = 15 * 60
|
||||
|
||||
registerEndpoint({
|
||||
operation: 'documents.download',
|
||||
method: 'GET',
|
||||
path: '/api/v1/companies/:companyId/documents/:id/download',
|
||||
summary: 'Get a time-limited signed download URL for a document.',
|
||||
description: `Returns a Supabase Storage signed URL valid for ${SIGNED_URL_TTL_SECONDS / 60} minutes. The URL itself is the canonical download: fetch it with any HTTP client; no API key needed on the storage host. Verify file integrity client-side against the returned sha256_hash if your workflow requires it.`,
|
||||
useWhen:
|
||||
'You need the bytes of an archived document (e.g. for OCR, attachment to an email, regulatory export). Always re-fetch the URL before each download: old URLs expire.',
|
||||
doNotUseFor:
|
||||
'Persisting the URL anywhere: it expires. Storing the URL in a webhook payload or audit log makes the audit trail dependent on URL state.',
|
||||
pitfalls: [
|
||||
`The signed URL expires after ${SIGNED_URL_TTL_SECONDS / 60} minutes. Don't cache it beyond the immediate transaction.`,
|
||||
'The URL leaks the Supabase Storage origin; this is benign (the signature alone authorizes the read) but rate-limit any forwarding so you don\'t reveal the storage layout to untrusted callers.',
|
||||
'Each call emits a document.accessed event. Polling this endpoint produces audit noise; cache the URL for its full TTL.',
|
||||
],
|
||||
example: {
|
||||
response: {
|
||||
data: {
|
||||
id: '0e9c…',
|
||||
file_name: 'kvitto-2026-05-12.pdf',
|
||||
mime_type: 'application/pdf',
|
||||
sha256_hash: '8a7f…',
|
||||
download_url: 'https://…supabase.co/storage/v1/object/sign/…',
|
||||
expires_in_seconds: 900,
|
||||
},
|
||||
meta: { request_id: 'req_…', api_version: '2026-05-12' },
|
||||
},
|
||||
},
|
||||
scope: 'documents:read',
|
||||
risk: 'low',
|
||||
idempotent: true,
|
||||
reversible: false,
|
||||
dryRunSupported: false,
|
||||
response: { success: dataEnvelope(DocumentDownloadResponse) },
|
||||
})
|
||||
|
||||
export const GET = withApiV1<{ params: Promise<{ companyId: string; id: string }> }>(
|
||||
'documents.download',
|
||||
async (_request, ctx, params) => {
|
||||
const { id } = await params.params
|
||||
const idParse = z.string().uuid().safeParse(id)
|
||||
if (!idParse.success) {
|
||||
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { field: 'id', message: 'document id must be a UUID.' },
|
||||
})
|
||||
}
|
||||
const documentId = idParse.data
|
||||
|
||||
const { data: doc, error: docErr } = await ctx.supabase
|
||||
.from('document_attachments')
|
||||
.select('id, file_name, mime_type, sha256_hash, storage_path, is_current_version')
|
||||
.eq('id', documentId)
|
||||
.eq('company_id', ctx.companyId!)
|
||||
.maybeSingle()
|
||||
|
||||
if (docErr) return v1ErrorResponse(docErr, ctx.log, { requestId: ctx.requestId })
|
||||
if (!doc) {
|
||||
// Enumeration hardening: wrong id and cross-tenant id are
|
||||
// indistinguishable from outside.
|
||||
return v1ErrorResponseFromCode('NOT_FOUND', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { resource: 'document' },
|
||||
})
|
||||
}
|
||||
const typed = doc as {
|
||||
id: string; file_name: string; mime_type: string | null; sha256_hash: string;
|
||||
storage_path: string; is_current_version: boolean;
|
||||
}
|
||||
|
||||
const { data: signed, error: signErr } = await ctx.supabase.storage
|
||||
.from('documents')
|
||||
.createSignedUrl(typed.storage_path, SIGNED_URL_TTL_SECONDS)
|
||||
|
||||
if (signErr || !signed?.signedUrl) {
|
||||
ctx.log.error('createSignedUrl failed', signErr as Error, { documentId })
|
||||
return v1ErrorResponseFromCode('DOC_DOWNLOAD_FAILED', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { reason: getUserErrorMessage(signErr) ?? 'unknown' },
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
await eventBus.emit({
|
||||
type: 'document.accessed',
|
||||
payload: {
|
||||
document: { id: typed.id, file_name: typed.file_name },
|
||||
userId: ctx.userId,
|
||||
companyId: ctx.companyId!,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
ctx.log.warn('document.accessed emit failed', err as Error)
|
||||
}
|
||||
|
||||
return ok(
|
||||
{
|
||||
id: typed.id,
|
||||
file_name: typed.file_name,
|
||||
mime_type: typed.mime_type,
|
||||
sha256_hash: typed.sha256_hash,
|
||||
is_current_version: typed.is_current_version,
|
||||
download_url: signed.signedUrl,
|
||||
expires_in_seconds: SIGNED_URL_TTL_SECONDS,
|
||||
},
|
||||
{ requestId: ctx.requestId },
|
||||
)
|
||||
},
|
||||
)
|
||||
@@ -1,255 +0,0 @@
|
||||
/**
|
||||
* POST /api/v1/companies/{companyId}/documents/{id}/link
|
||||
*
|
||||
* Link an already-uploaded document to a journal entry (and optionally a
|
||||
* specific line). Wraps lib/core/documents/document-service.linkToJournalEntry.
|
||||
*
|
||||
* Body: `{ journal_entry_id: UUID, journal_entry_line_id?: UUID, inbox_item_id?: UUID }`.
|
||||
*
|
||||
* When `inbox_item_id` is supplied the matching invoice_inbox_items row is
|
||||
* stamped with `created_journal_entry_id` so it drops out of the active inbox
|
||||
* into the resolved state. The stamp is best-effort: a failure is logged but
|
||||
* does not fail the request (the document link is the legally-relevant write).
|
||||
*
|
||||
* The link is REVERSIBLE: set journal_entry_id back via the dashboard if
|
||||
* needed (no unlink endpoint in v1 yet to keep the WORM contract tight).
|
||||
* Once the journal entry it points at is committed (status='posted'), the
|
||||
* document row is effectively immutable per BFL 7 kap.
|
||||
*
|
||||
* Idempotent (mandatory Idempotency-Key). Dry-runnable: confirms the JE
|
||||
* and document both exist + belong to the company without persisting.
|
||||
*/
|
||||
|
||||
import { z } from 'zod'
|
||||
import { ok } from '@/lib/api/v1/response'
|
||||
import { dryRunPreview } from '@/lib/api/v1/dry-run'
|
||||
import { registerEndpoint, dataEnvelope } from '@/lib/api/v1/registry'
|
||||
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponse, v1ErrorResponseFromCode, v1ValidationError } from '@/lib/api/v1/errors'
|
||||
import { readV1JsonBody } from '@/lib/api/v1/body'
|
||||
import { linkToJournalEntry } from '@/lib/core/documents/document-service'
|
||||
|
||||
const Body = z
|
||||
.object({
|
||||
journal_entry_id: z.string().uuid(),
|
||||
journal_entry_line_id: z.string().uuid().optional(),
|
||||
inbox_item_id: z.string().uuid().optional(),
|
||||
})
|
||||
.strict()
|
||||
|
||||
const DocumentLinkedResponse = z.object({
|
||||
id: z.string().uuid(),
|
||||
journal_entry_id: z.string().uuid(),
|
||||
journal_entry_line_id: z.string().uuid().nullable(),
|
||||
file_name: z.string(),
|
||||
})
|
||||
|
||||
registerEndpoint({
|
||||
operation: 'documents.link',
|
||||
method: 'POST',
|
||||
path: '/api/v1/companies/:companyId/documents/:id/link',
|
||||
summary: 'Link a document to a journal entry.',
|
||||
description:
|
||||
'Sets journal_entry_id (and optionally journal_entry_line_id) on an existing document. Optionally stamps the originating invoice_inbox_items row as consumed via inbox_item_id. Use this after /documents upload when the link target was unknown at upload time, or to re-link a stray document. Once the target JE is posted, the document row is effectively immutable per BFL 7 kap retention.',
|
||||
useWhen:
|
||||
'A document was uploaded without a journal_entry_id (e.g. bulk import) and you now want to attach it to a posted verifikation. Pass inbox_item_id when the document came from the invoice inbox so the item is marked resolved in one call.',
|
||||
doNotUseFor:
|
||||
'Unlinking: no v1 unlink endpoint. The dashboard exposes a manual override; v1 keeps the WORM contract by refusing to revert posted-JE links.',
|
||||
pitfalls: [
|
||||
'Idempotency-Key is mandatory.',
|
||||
'Both the document and the journal_entry_id must belong to the caller\'s company. NOT_FOUND on mismatch (enumeration hardening).',
|
||||
'Re-linking an already-linked document overwrites the previous journal_entry_id: confirm the old target is what you intend to break.',
|
||||
'inbox_item_id stamping is best-effort: if the stamp fails the document link still succeeds. Use POST /api/v1/companies/:companyId/inbox-items/:id/stamp to stamp independently.',
|
||||
],
|
||||
example: {
|
||||
request: { journal_entry_id: 'a8f1…' },
|
||||
response: {
|
||||
data: {
|
||||
id: '0e9c…',
|
||||
journal_entry_id: 'a8f1…',
|
||||
journal_entry_line_id: null,
|
||||
file_name: 'kvitto-2026-05-12.pdf',
|
||||
},
|
||||
meta: { request_id: 'req_…', api_version: '2026-05-12' },
|
||||
},
|
||||
},
|
||||
scope: 'documents:write',
|
||||
risk: 'medium',
|
||||
idempotent: true,
|
||||
reversible: false,
|
||||
dryRunSupported: true,
|
||||
request: { body: Body },
|
||||
response: { success: dataEnvelope(DocumentLinkedResponse) },
|
||||
})
|
||||
|
||||
export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string }> }>(
|
||||
'documents.link',
|
||||
async (request, ctx, params) => {
|
||||
const { id } = await params.params
|
||||
const idParse = z.string().uuid().safeParse(id)
|
||||
if (!idParse.success) {
|
||||
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { field: 'id', message: 'document id must be a UUID.' },
|
||||
})
|
||||
}
|
||||
const documentId = idParse.data
|
||||
|
||||
const rawBodyResult = await readV1JsonBody(request, ctx)
|
||||
if (!rawBodyResult.ok) return rawBodyResult.response
|
||||
const rawBody = rawBodyResult.body
|
||||
const parsed = Body.safeParse(rawBody)
|
||||
if (!parsed.success) return v1ValidationError(ctx, parsed.error)
|
||||
const body = parsed.data
|
||||
|
||||
// Ownership pre-check: document AND target JE must both belong to the
|
||||
// caller's company before the link write. Otherwise the row could
|
||||
// persist with a cross-tenant journal_entry_id pointer. Capture
|
||||
// `.error` on both: a DB fault must not silently masquerade as a
|
||||
// NOT_FOUND (round-1 finding).
|
||||
const [docRes, jeRes] = await Promise.all([
|
||||
ctx.supabase
|
||||
.from('document_attachments')
|
||||
.select('id, file_name, journal_entry_id')
|
||||
.eq('id', documentId)
|
||||
.eq('company_id', ctx.companyId!)
|
||||
.maybeSingle(),
|
||||
ctx.supabase
|
||||
.from('journal_entries')
|
||||
.select('id')
|
||||
.eq('id', body.journal_entry_id)
|
||||
.eq('company_id', ctx.companyId!)
|
||||
.maybeSingle(),
|
||||
])
|
||||
|
||||
if (docRes.error) {
|
||||
ctx.log.error('documents.link doc pre-check DB error', docRes.error as Error, { documentId })
|
||||
return v1ErrorResponseFromCode('INTERNAL_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId, details: { step: 'doc_ownership_check' },
|
||||
})
|
||||
}
|
||||
if (jeRes.error) {
|
||||
ctx.log.error('documents.link JE pre-check DB error', jeRes.error as Error, { journalEntryId: body.journal_entry_id })
|
||||
return v1ErrorResponseFromCode('INTERNAL_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId, details: { step: 'je_ownership_check' },
|
||||
})
|
||||
}
|
||||
|
||||
const doc = docRes.data as { id: string; file_name: string; journal_entry_id: string | null } | null
|
||||
const je = jeRes.data
|
||||
|
||||
if (!doc) {
|
||||
return v1ErrorResponseFromCode('NOT_FOUND', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { resource: 'document' },
|
||||
})
|
||||
}
|
||||
if (!je) {
|
||||
return v1ErrorResponseFromCode('NOT_FOUND', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { resource: 'journal_entry', field: 'journal_entry_id' },
|
||||
})
|
||||
}
|
||||
|
||||
// WORM guard: if this document is ALREADY linked to a posted JE, refuse
|
||||
// the overwrite. BFL 5 kap 5 § + 7 kap require posted räkenskaps-
|
||||
// information (incl. the link to underlying documents) to remain
|
||||
// immutable. The pre-check confirms the new target: without this
|
||||
// additional check the caller could silently break the link to an
|
||||
// already-posted verifikation.
|
||||
if (doc.journal_entry_id && doc.journal_entry_id !== body.journal_entry_id) {
|
||||
const { data: existingJe } = await ctx.supabase
|
||||
.from('journal_entries')
|
||||
.select('id, status')
|
||||
.eq('id', doc.journal_entry_id)
|
||||
.eq('company_id', ctx.companyId!)
|
||||
.maybeSingle()
|
||||
if (existingJe && (existingJe as { status: string }).status === 'posted') {
|
||||
return v1ErrorResponseFromCode('CONFLICT', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: {
|
||||
reason: 'document_already_linked_to_posted_entry',
|
||||
current_journal_entry_id: doc.journal_entry_id,
|
||||
remediation:
|
||||
'Documents linked to posted verifikationer cannot be re-linked (BFL 5 kap 5 §). Upload a new document and link the new one to the new target.',
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// journal_entry_line_id ownership: must belong to the target JE.
|
||||
// Skipped above (only document + JE) because the line ownership is
|
||||
// transitively bound through journal_entry_id (which we just verified).
|
||||
if (body.journal_entry_line_id) {
|
||||
const { data: lineRow, error: lineErr } = await ctx.supabase
|
||||
.from('journal_entry_lines')
|
||||
.select('id')
|
||||
.eq('id', body.journal_entry_line_id)
|
||||
.eq('journal_entry_id', body.journal_entry_id)
|
||||
.maybeSingle()
|
||||
if (lineErr) {
|
||||
ctx.log.error('documents.link line pre-check DB error', lineErr as Error)
|
||||
return v1ErrorResponseFromCode('INTERNAL_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId, details: { step: 'je_line_ownership_check' },
|
||||
})
|
||||
}
|
||||
if (!lineRow) {
|
||||
return v1ErrorResponseFromCode('NOT_FOUND', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { resource: 'journal_entry_line', field: 'journal_entry_line_id' },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (ctx.dryRun) {
|
||||
return dryRunPreview(
|
||||
{
|
||||
id: documentId,
|
||||
journal_entry_id: body.journal_entry_id,
|
||||
journal_entry_line_id: body.journal_entry_line_id ?? null,
|
||||
file_name: doc.file_name,
|
||||
},
|
||||
{ requestId: ctx.requestId, log: ctx.log },
|
||||
)
|
||||
}
|
||||
|
||||
try {
|
||||
const updated = await linkToJournalEntry(
|
||||
ctx.supabase,
|
||||
ctx.companyId!,
|
||||
documentId,
|
||||
body.journal_entry_id,
|
||||
body.journal_entry_line_id,
|
||||
)
|
||||
|
||||
if (body.inbox_item_id) {
|
||||
const { error: stampErr } = await ctx.supabase
|
||||
.from('invoice_inbox_items')
|
||||
.update({ created_journal_entry_id: body.journal_entry_id })
|
||||
.eq('id', body.inbox_item_id)
|
||||
.eq('company_id', ctx.companyId!)
|
||||
.is('created_journal_entry_id', null)
|
||||
if (stampErr) {
|
||||
ctx.log.error('documents.link inbox stamp failed (best-effort)', stampErr as Error, {
|
||||
inboxItemId: body.inbox_item_id,
|
||||
journalEntryId: body.journal_entry_id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return ok(
|
||||
{
|
||||
id: updated.id,
|
||||
journal_entry_id: updated.journal_entry_id!,
|
||||
journal_entry_line_id: updated.journal_entry_line_id,
|
||||
file_name: updated.file_name,
|
||||
},
|
||||
{ requestId: ctx.requestId },
|
||||
)
|
||||
} catch (err) {
|
||||
ctx.log.error('documents.link failed', err as Error, { documentId, journalEntryId: body.journal_entry_id })
|
||||
return v1ErrorResponse(err, ctx.log, { requestId: ctx.requestId })
|
||||
}
|
||||
},
|
||||
{ requireIdempotencyKey: true },
|
||||
)
|
||||
@@ -1,313 +0,0 @@
|
||||
/**
|
||||
* POST /api/v1/companies/{companyId}/documents
|
||||
*
|
||||
* Multipart upload of a document into the WORM archive. Wraps
|
||||
* lib/core/documents/document-service.uploadDocument: hashes the bytes
|
||||
* (SHA-256), writes to Supabase Storage under documents/{userId}/...,
|
||||
* inserts an immutable row into document_attachments (version=1,
|
||||
* is_current_version=true).
|
||||
*
|
||||
* multipart/form-data parts:
|
||||
* file (required, binary): the document; MIME validated
|
||||
* upload_source (optional) : 'file_upload' (default) | 'camera' | 'email' | 'api'
|
||||
* journal_entry_id (optional UUID) : link the document to a JE at upload time
|
||||
* journal_entry_line_id (optional UUID): link to a specific JE line
|
||||
*
|
||||
* Idempotent (mandatory Idempotency-Key: the SHA-256 of the bytes is the
|
||||
* deduplication anchor on retry inside the engine's `upsert: false` storage
|
||||
* write).
|
||||
*
|
||||
* Dry-run is NOT supported on this endpoint: the engine hashes + stores +
|
||||
* inserts atomically; the "dry-run" equivalent is a client-side
|
||||
* size+MIME check before submitting. Future iteration may add a header-only
|
||||
* preflight; held back to keep the multipart contract minimal.
|
||||
*
|
||||
* WORM (BFL 7 kap): once inserted, the row cannot be modified or deleted
|
||||
* if it is linked to a posted journal entry: the DB trigger blocks both.
|
||||
* Updating a document means uploading a new VERSION via the dashboard
|
||||
* (no v1 endpoint today; bypassing through the dashboard is intentional
|
||||
* until the contract is hardened with audit-trail tests).
|
||||
*/
|
||||
|
||||
import { z } from 'zod'
|
||||
import { created } from '@/lib/api/v1/response'
|
||||
import { registerEndpoint, dataEnvelope } from '@/lib/api/v1/registry'
|
||||
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponseFromCode } from '@/lib/api/v1/errors'
|
||||
import {
|
||||
uploadDocument,
|
||||
validateDocumentFile,
|
||||
MAX_DOCUMENT_SIZE,
|
||||
ALLOWED_DOCUMENT_TYPES,
|
||||
} from '@/lib/core/documents/document-service'
|
||||
import type { DocumentUploadSource } from '@/types'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
const DocumentUploaded = z.object({
|
||||
id: z.string().uuid(),
|
||||
file_name: z.string(),
|
||||
mime_type: z.string().nullable(),
|
||||
file_size_bytes: z.number(),
|
||||
sha256_hash: z.string(),
|
||||
version: z.number().int(),
|
||||
is_current_version: z.boolean(),
|
||||
upload_source: z.string().nullable(),
|
||||
journal_entry_id: z.string().uuid().nullable(),
|
||||
journal_entry_line_id: z.string().uuid().nullable(),
|
||||
created_at: z.string(),
|
||||
})
|
||||
|
||||
// For the registry, the Zod body is a metadata-only shape (everything the
|
||||
// caller MIGHT supply in the multipart envelope besides the file itself).
|
||||
// The actual multipart parsing happens in-route via request.formData().
|
||||
const MultipartBodySchema = z.object({
|
||||
file: z.unknown(), // OpenAPI generator renders this as { type: 'string', format: 'binary' }
|
||||
upload_source: z.enum(['file_upload', 'camera', 'email', 'api']).optional(),
|
||||
journal_entry_id: z.string().uuid().optional(),
|
||||
journal_entry_line_id: z.string().uuid().optional(),
|
||||
})
|
||||
|
||||
registerEndpoint({
|
||||
operation: 'documents.upload',
|
||||
method: 'POST',
|
||||
path: '/api/v1/companies/:companyId/documents',
|
||||
summary: 'Upload a document to the WORM archive.',
|
||||
description: `Multipart upload of a document (PDF / image) under the BFL 7 kap retention regime. The bytes are hashed (SHA-256), written to Supabase Storage, and recorded in document_attachments at version=1. Allowed MIME types: ${ALLOWED_DOCUMENT_TYPES.join(', ')}. Max size: ${MAX_DOCUMENT_SIZE / 1024 / 1024} MB.`,
|
||||
useWhen:
|
||||
'You have a receipt, invoice scan, or supporting document for a posted verifikation and want it archived for the 7-year BFL retention period. Optionally link to a journal entry at upload time via journal_entry_id.',
|
||||
doNotUseFor:
|
||||
'Updating an existing document (no v1 update endpoint; new versions go through the dashboard). Bulk uploads: call once per file.',
|
||||
pitfalls: [
|
||||
'Idempotency-Key is mandatory; multipart retries with the same key replay the cached response.',
|
||||
`Max size ${MAX_DOCUMENT_SIZE / 1024 / 1024} MB enforced server-side: DOC_UPLOAD_TOO_LARGE on overrun.`,
|
||||
`Only ${ALLOWED_DOCUMENT_TYPES.join(' / ')} accepted: DOC_UPLOAD_UNSUPPORTED_TYPE otherwise.`,
|
||||
'WORM: once linked to a posted journal entry, the document row cannot be modified or deleted (DB trigger). Upload-then-link is reversible (the document exists with journal_entry_id=null until linked); once linked, treat as immutable.',
|
||||
'Dry-run is not supported on this endpoint: the engine hashes + stores + inserts in one atomic flow.',
|
||||
],
|
||||
example: {
|
||||
request: {
|
||||
// OpenAPI generator renders these as multipart parts.
|
||||
file: '<binary>',
|
||||
upload_source: 'api',
|
||||
journal_entry_id: 'a8f1…',
|
||||
},
|
||||
response: {
|
||||
data: {
|
||||
id: '0e9c…',
|
||||
file_name: 'kvitto-2026-05-12.pdf',
|
||||
mime_type: 'application/pdf',
|
||||
file_size_bytes: 184320,
|
||||
sha256_hash: '8a7f…',
|
||||
version: 1,
|
||||
is_current_version: true,
|
||||
journal_entry_id: 'a8f1…',
|
||||
},
|
||||
meta: { request_id: 'req_…', api_version: '2026-05-12' },
|
||||
},
|
||||
},
|
||||
scope: 'documents:write',
|
||||
risk: 'medium',
|
||||
idempotent: true,
|
||||
reversible: false,
|
||||
dryRunSupported: false,
|
||||
request: { body: MultipartBodySchema, contentType: 'multipart/form-data' },
|
||||
response: { success: dataEnvelope(DocumentUploaded) },
|
||||
})
|
||||
|
||||
export const POST = withApiV1<{ params: Promise<{ companyId: string }> }>(
|
||||
'documents.upload',
|
||||
async (request, ctx) => {
|
||||
let formData: FormData
|
||||
try {
|
||||
formData = await request.formData()
|
||||
} catch {
|
||||
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: {
|
||||
field: 'body',
|
||||
message:
|
||||
'Body must be multipart/form-data with a `file` part. Set Content-Type accordingly.',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const file = formData.get('file')
|
||||
if (!file || !(file instanceof File)) {
|
||||
return v1ErrorResponseFromCode('DOC_UPLOAD_NO_FILE', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
})
|
||||
}
|
||||
|
||||
const validationError = validateDocumentFile({ size: file.size, type: file.type })
|
||||
if (validationError) {
|
||||
// The validator returns a Swedish string. Bucket by error category
|
||||
// so the agent receives a stable code.
|
||||
const code = /storlek|stor|MB|tom/i.test(validationError)
|
||||
? 'DOC_UPLOAD_TOO_LARGE'
|
||||
: 'DOC_UPLOAD_UNSUPPORTED_TYPE'
|
||||
return v1ErrorResponseFromCode(code, ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: {
|
||||
reason: validationError,
|
||||
file_size_bytes: file.size,
|
||||
mime_type: file.type,
|
||||
max_size_bytes: MAX_DOCUMENT_SIZE,
|
||||
allowed_types: ALLOWED_DOCUMENT_TYPES,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Optional metadata fields. upload_source is enum-validated at runtime
|
||||
// (the column has no CHECK constraint, so an unrecognised value would
|
||||
// persist as-is otherwise).
|
||||
const uploadSourceRaw = formData.get('upload_source')
|
||||
const UploadSourceSchema = z.enum(['file_upload', 'camera', 'email', 'api'])
|
||||
let uploadSource: DocumentUploadSource = 'file_upload'
|
||||
if (typeof uploadSourceRaw === 'string') {
|
||||
const parsed = UploadSourceSchema.safeParse(uploadSourceRaw)
|
||||
if (!parsed.success) {
|
||||
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: {
|
||||
field: 'upload_source',
|
||||
message: `upload_source must be one of: ${UploadSourceSchema.options.join(', ')}.`,
|
||||
attempted: uploadSourceRaw,
|
||||
},
|
||||
})
|
||||
}
|
||||
uploadSource = parsed.data
|
||||
}
|
||||
|
||||
const journalEntryIdRaw = formData.get('journal_entry_id')
|
||||
const journalEntryId = typeof journalEntryIdRaw === 'string' ? journalEntryIdRaw : undefined
|
||||
if (journalEntryId && !z.string().uuid().safeParse(journalEntryId).success) {
|
||||
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { field: 'journal_entry_id', message: 'must be a UUID' },
|
||||
})
|
||||
}
|
||||
const journalEntryLineIdRaw = formData.get('journal_entry_line_id')
|
||||
const journalEntryLineId = typeof journalEntryLineIdRaw === 'string' ? journalEntryLineIdRaw : undefined
|
||||
if (journalEntryLineId && !z.string().uuid().safeParse(journalEntryLineId).success) {
|
||||
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { field: 'journal_entry_line_id', message: 'must be a UUID' },
|
||||
})
|
||||
}
|
||||
|
||||
// If the caller supplied journal_entry_id, verify it belongs to the
|
||||
// caller's company before the upload commits. Otherwise we'd persist a
|
||||
// document whose `journal_entry_id` points at another company's JE:
|
||||
// the DB has no FK enforcing cross-table tenancy.
|
||||
if (journalEntryId) {
|
||||
const { data: jeRow, error: jeErr } = await ctx.supabase
|
||||
.from('journal_entries')
|
||||
.select('id')
|
||||
.eq('id', journalEntryId)
|
||||
.eq('company_id', ctx.companyId!)
|
||||
.maybeSingle()
|
||||
if (jeErr) {
|
||||
ctx.log.error('documents.upload JE pre-check DB error', jeErr as Error, { journalEntryId })
|
||||
return v1ErrorResponseFromCode('INTERNAL_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId, details: { step: 'je_ownership_check' },
|
||||
})
|
||||
}
|
||||
if (!jeRow) {
|
||||
return v1ErrorResponseFromCode('NOT_FOUND', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { resource: 'journal_entry', field: 'journal_entry_id' },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// If the caller supplied journal_entry_line_id, verify the line belongs
|
||||
// to the supplied JE (and transitively to the company we already
|
||||
// validated). Without this guard the row would persist with a
|
||||
// line-level pointer to another company's JE line.
|
||||
if (journalEntryLineId) {
|
||||
if (!journalEntryId) {
|
||||
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: {
|
||||
field: 'journal_entry_line_id',
|
||||
message: 'journal_entry_line_id requires journal_entry_id.',
|
||||
},
|
||||
})
|
||||
}
|
||||
const { data: lineRow, error: lineErr } = await ctx.supabase
|
||||
.from('journal_entry_lines')
|
||||
.select('id')
|
||||
.eq('id', journalEntryLineId)
|
||||
.eq('journal_entry_id', journalEntryId)
|
||||
.maybeSingle()
|
||||
if (lineErr) {
|
||||
ctx.log.error('documents.upload JE-line pre-check DB error', lineErr as Error, { journalEntryLineId })
|
||||
return v1ErrorResponseFromCode('INTERNAL_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId, details: { step: 'je_line_ownership_check' },
|
||||
})
|
||||
}
|
||||
if (!lineRow) {
|
||||
return v1ErrorResponseFromCode('NOT_FOUND', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { resource: 'journal_entry_line', field: 'journal_entry_line_id' },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const opLog = ctx.log.child({ filename: file.name, sizeBytes: file.size })
|
||||
|
||||
try {
|
||||
const buffer = await file.arrayBuffer()
|
||||
const document = await uploadDocument(
|
||||
ctx.supabase,
|
||||
ctx.userId,
|
||||
ctx.companyId!,
|
||||
{ name: file.name, buffer, type: file.type },
|
||||
{
|
||||
upload_source: uploadSource,
|
||||
journal_entry_id: journalEntryId,
|
||||
journal_entry_line_id: journalEntryLineId,
|
||||
},
|
||||
)
|
||||
// `storage_path` is deliberately omitted from the public response:
|
||||
// the path encodes internal layout (userId prefix + timestamp) which
|
||||
// /download deliberately keeps hidden. Use /download/{id} to fetch
|
||||
// the actual bytes via a short-lived signed URL.
|
||||
return created(
|
||||
{
|
||||
id: document.id,
|
||||
file_name: document.file_name,
|
||||
mime_type: document.mime_type,
|
||||
file_size_bytes: document.file_size_bytes,
|
||||
sha256_hash: document.sha256_hash,
|
||||
version: document.version,
|
||||
is_current_version: document.is_current_version,
|
||||
upload_source: document.upload_source,
|
||||
journal_entry_id: document.journal_entry_id,
|
||||
journal_entry_line_id: document.journal_entry_line_id,
|
||||
created_at: document.created_at,
|
||||
},
|
||||
{ requestId: ctx.requestId },
|
||||
)
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'unknown'
|
||||
// Magic-byte validation rejections (validateDocumentMagicBytes) are a
|
||||
// client problem, not a storage failure: surface as 400 with an
|
||||
// accurate message instead of the misleading "kunde inte sparas".
|
||||
if (/kunde inte verifieras|matchar inte den angivna filtypen/i.test(message)) {
|
||||
opLog.warn('document upload rejected by content validation', { reason: message })
|
||||
return v1ErrorResponseFromCode('DOC_UPLOAD_INVALID_CONTENT', opLog, {
|
||||
requestId: ctx.requestId,
|
||||
details: { reason: getErrorMessage(err) },
|
||||
})
|
||||
}
|
||||
// Full error is logged above; the raw message can leak storage-layer
|
||||
// internals, so the client only gets the generic code + requestId.
|
||||
opLog.error('document upload failed', err as Error)
|
||||
return v1ErrorResponseFromCode('DOC_UPLOAD_STORAGE_FAILED', opLog, {
|
||||
requestId: ctx.requestId,
|
||||
})
|
||||
}
|
||||
},
|
||||
{ requireIdempotencyKey: true },
|
||||
)
|
||||
@@ -1,405 +0,0 @@
|
||||
/**
|
||||
* Tests for the v1 absence endpoints (payroll gap-closure 1.4).
|
||||
*
|
||||
* GET/PUT/DELETE /employees/{id}/absence. PUT is the first PUT route on v1:
|
||||
* the wrapper's REQUIRES_IDEMPOTENCY set was extended to include it, and the
|
||||
* test-key case below is the regression test for that hole (a test key on a
|
||||
* PUT must be forced into dry-run, never write through).
|
||||
*/
|
||||
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
beforeAll(() => {
|
||||
if (process.env.NODE_ENV !== 'test') {
|
||||
throw new Error(
|
||||
`absence route tests require NODE_ENV=test (got ${process.env.NODE_ENV ?? 'undefined'})`,
|
||||
)
|
||||
}
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL ||= 'http://localhost:54321'
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ||= 'test-anon-key'
|
||||
})
|
||||
|
||||
vi.mock('@/lib/auth/api-keys', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/auth/api-keys')>('@/lib/auth/api-keys')
|
||||
return {
|
||||
...actual,
|
||||
validateApiKey: vi.fn(),
|
||||
createServiceClientNoCookies: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@supabase/supabase-js', async () => {
|
||||
const actual = await vi.importActual<typeof import('@supabase/supabase-js')>('@supabase/supabase-js')
|
||||
return { ...actual, createClient: vi.fn().mockReturnValue({}) }
|
||||
})
|
||||
|
||||
import { validateApiKey, createServiceClientNoCookies } from '@/lib/auth/api-keys'
|
||||
import { GET as listAbsence, PUT as putAbsence, DELETE as deleteAbsence } from '../route'
|
||||
|
||||
const mockValidate = validateApiKey as ReturnType<typeof vi.fn>
|
||||
const mockServiceClient = createServiceClientNoCookies as ReturnType<typeof vi.fn>
|
||||
|
||||
interface TableResp {
|
||||
data?: unknown
|
||||
error?: unknown
|
||||
count?: number | null
|
||||
}
|
||||
|
||||
function makeFlexibleSupabase(byTable: Record<string, TableResp | TableResp[]>) {
|
||||
const queues = new Map<string, TableResp[]>()
|
||||
for (const [t, val] of Object.entries(byTable)) {
|
||||
queues.set(t, Array.isArray(val) ? [...val] : [val])
|
||||
}
|
||||
const tableCalls: string[] = []
|
||||
const buildChain = (table: string): unknown => {
|
||||
const handler: ProxyHandler<object> = {
|
||||
get(_target, prop) {
|
||||
if (prop === 'then') {
|
||||
return (resolve: (v: unknown) => void) => {
|
||||
const q = queues.get(table)
|
||||
const next = q && q.length > 1 ? q.shift()! : (q?.[0] ?? { data: null, error: null, count: null })
|
||||
resolve({ count: null, ...next })
|
||||
}
|
||||
}
|
||||
return (..._args: unknown[]) => buildChain(table)
|
||||
},
|
||||
}
|
||||
return new Proxy({}, handler)
|
||||
}
|
||||
return {
|
||||
tableCalls,
|
||||
from: vi.fn((table: string) => {
|
||||
tableCalls.push(table)
|
||||
return buildChain(table)
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
const COMPANY_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
|
||||
const EMPLOYEE_ID = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'
|
||||
const USER_ID = 'user-1'
|
||||
|
||||
const SAMPLE_DAY = {
|
||||
id: 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee',
|
||||
absence_date: '2026-03-03',
|
||||
absence_type: 'sick',
|
||||
hours: 8,
|
||||
notes: null,
|
||||
salary_run_employee_id: null,
|
||||
created_at: '2026-03-03T08:00:00Z',
|
||||
updated_at: '2026-03-03T08:00:00Z',
|
||||
}
|
||||
|
||||
function makeRequest(url: string, init?: RequestInit): Request {
|
||||
return new Request(url, {
|
||||
...init,
|
||||
headers: {
|
||||
Authorization: 'Bearer test-fixture-not-a-real-key',
|
||||
...(init?.headers ?? {}),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function absenceParams(companyId: string, id: string) {
|
||||
return { params: Promise.resolve({ companyId, id }) }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: USER_ID,
|
||||
companyId: COMPANY_ID,
|
||||
apiKeyId: 'ak_1',
|
||||
apiKeyName: 'CI key',
|
||||
scopes: ['payroll:read', 'payroll:write'],
|
||||
mode: 'live',
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /api/v1/companies/:companyId/employees/:id/absence', () => {
|
||||
it('lists absence days with qualified ids', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
employees: { data: { id: EMPLOYEE_ID }, error: null },
|
||||
salary_absence_days: { data: [SAMPLE_DAY], error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await listAbsence(
|
||||
makeRequest(
|
||||
`https://x.test/api/v1/companies/${COMPANY_ID}/employees/${EMPLOYEE_ID}/absence?from=2026-03-01&to=2026-03-31`,
|
||||
),
|
||||
absenceParams(COMPANY_ID, EMPLOYEE_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data).toHaveLength(1)
|
||||
expect(body.data[0].salary_absence_day_id).toBe(SAMPLE_DAY.id)
|
||||
expect(body.data[0].id).toBeUndefined()
|
||||
})
|
||||
|
||||
it('rejects a missing from/to with 400', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
}),
|
||||
)
|
||||
const res = await listAbsence(
|
||||
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/employees/${EMPLOYEE_ID}/absence`),
|
||||
absenceParams(COMPANY_ID, EMPLOYEE_ID),
|
||||
)
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('rejects a reversed range (from > to) with VALIDATION_ERROR', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
}),
|
||||
)
|
||||
const res = await listAbsence(
|
||||
makeRequest(
|
||||
`https://x.test/api/v1/companies/${COMPANY_ID}/employees/${EMPLOYEE_ID}/absence?from=2026-03-31&to=2026-03-01`,
|
||||
),
|
||||
absenceParams(COMPANY_ID, EMPLOYEE_ID),
|
||||
)
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('VALIDATION_ERROR')
|
||||
})
|
||||
|
||||
it('rejects a range beyond 92 days with ABSENCE_RANGE_TOO_LARGE', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
}),
|
||||
)
|
||||
const res = await listAbsence(
|
||||
makeRequest(
|
||||
`https://x.test/api/v1/companies/${COMPANY_ID}/employees/${EMPLOYEE_ID}/absence?from=2026-01-01&to=2026-12-31`,
|
||||
),
|
||||
absenceParams(COMPANY_ID, EMPLOYEE_ID),
|
||||
)
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('ABSENCE_RANGE_TOO_LARGE')
|
||||
})
|
||||
|
||||
it('returns 404 EMPLOYEE_NOT_FOUND for an unknown employee', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
employees: { data: null, error: null },
|
||||
}),
|
||||
)
|
||||
const res = await listAbsence(
|
||||
makeRequest(
|
||||
`https://x.test/api/v1/companies/${COMPANY_ID}/employees/${EMPLOYEE_ID}/absence?from=2026-03-01&to=2026-03-31`,
|
||||
),
|
||||
absenceParams(COMPANY_ID, EMPLOYEE_ID),
|
||||
)
|
||||
expect(res.status).toBe(404)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('EMPLOYEE_NOT_FOUND')
|
||||
})
|
||||
})
|
||||
|
||||
describe('PUT /api/v1/companies/:companyId/employees/:id/absence', () => {
|
||||
const validBody = { from: '2026-03-02', to: '2026-03-06', absence_type: 'sick' }
|
||||
|
||||
it('upserts the expanded range (happy path)', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
employees: { data: { id: EMPLOYEE_ID }, error: null },
|
||||
salary_absence_days: [
|
||||
{ data: [SAMPLE_DAY, { ...SAMPLE_DAY, id: 'ffffffff-ffff-4fff-8fff-ffffffffffff', absence_date: '2026-03-04' }], error: null }, // bulk upsert
|
||||
],
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await putAbsence(
|
||||
makeRequest(
|
||||
`https://x.test/api/v1/companies/${COMPANY_ID}/employees/${EMPLOYEE_ID}/absence`,
|
||||
{ method: 'PUT', body: JSON.stringify(validBody) },
|
||||
),
|
||||
absenceParams(COMPANY_ID, EMPLOYEE_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data.count).toBe(2)
|
||||
expect(body.data.days[0].salary_absence_day_id).toBeTruthy()
|
||||
})
|
||||
|
||||
it('rejects from > to with 400', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
}),
|
||||
)
|
||||
const res = await putAbsence(
|
||||
makeRequest(
|
||||
`https://x.test/api/v1/companies/${COMPANY_ID}/employees/${EMPLOYEE_ID}/absence`,
|
||||
{ method: 'PUT', body: JSON.stringify({ ...validBody, from: '2026-03-10' }) },
|
||||
),
|
||||
absenceParams(COMPANY_ID, EMPLOYEE_ID),
|
||||
)
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('maps the 24h trigger to 409 ABSENCE_HOURS_CONFLICT', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
employees: { data: { id: EMPLOYEE_ID }, error: null },
|
||||
salary_absence_days: [
|
||||
{ data: null, error: { code: '23514', message: 'Total tid över 24h' } },
|
||||
],
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await putAbsence(
|
||||
makeRequest(
|
||||
`https://x.test/api/v1/companies/${COMPANY_ID}/employees/${EMPLOYEE_ID}/absence`,
|
||||
{ method: 'PUT', body: JSON.stringify(validBody) },
|
||||
),
|
||||
absenceParams(COMPANY_ID, EMPLOYEE_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(409)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('ABSENCE_HOURS_CONFLICT')
|
||||
})
|
||||
|
||||
it('returns a dry-run preview without writing', async () => {
|
||||
const supabaseMock = makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
employees: { data: { id: EMPLOYEE_ID }, error: null },
|
||||
})
|
||||
mockServiceClient.mockReturnValue(supabaseMock)
|
||||
|
||||
const res = await putAbsence(
|
||||
makeRequest(
|
||||
`https://x.test/api/v1/companies/${COMPANY_ID}/employees/${EMPLOYEE_ID}/absence?dry_run=true`,
|
||||
{ method: 'PUT', body: JSON.stringify(validBody) },
|
||||
),
|
||||
absenceParams(COMPANY_ID, EMPLOYEE_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('X-Dry-Run')).toBe('true')
|
||||
const body = await res.json()
|
||||
expect(body.data.preview.count).toBe(5)
|
||||
expect(supabaseMock.tableCalls).not.toContain('salary_absence_days')
|
||||
})
|
||||
|
||||
it('forces TEST KEYS into dry-run on PUT (wrapper REQUIRES_IDEMPOTENCY regression)', async () => {
|
||||
// Before the wrapper hardening, PUT was missing from REQUIRES_IDEMPOTENCY:
|
||||
// a test key would have written through. This test locks the fix in.
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: USER_ID,
|
||||
companyId: COMPANY_ID,
|
||||
apiKeyId: 'ak_test',
|
||||
apiKeyName: 'test key',
|
||||
scopes: ['payroll:read', 'payroll:write'],
|
||||
mode: 'test',
|
||||
})
|
||||
const supabaseMock = makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
employees: { data: { id: EMPLOYEE_ID }, error: null },
|
||||
})
|
||||
mockServiceClient.mockReturnValue(supabaseMock)
|
||||
|
||||
const res = await putAbsence(
|
||||
makeRequest(
|
||||
`https://x.test/api/v1/companies/${COMPANY_ID}/employees/${EMPLOYEE_ID}/absence`,
|
||||
{ method: 'PUT', body: JSON.stringify(validBody) },
|
||||
),
|
||||
absenceParams(COMPANY_ID, EMPLOYEE_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('X-Dry-Run')).toBe('true')
|
||||
expect(res.headers.get('X-Gnubok-Mode')).toBe('test')
|
||||
// The write table was never touched.
|
||||
expect(supabaseMock.tableCalls).not.toContain('salary_absence_days')
|
||||
})
|
||||
|
||||
it('rejects keys without payroll:write scope', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: USER_ID,
|
||||
companyId: COMPANY_ID,
|
||||
apiKeyId: 'ak_1',
|
||||
apiKeyName: 'read-only',
|
||||
scopes: ['payroll:read'],
|
||||
mode: 'live',
|
||||
})
|
||||
mockServiceClient.mockReturnValue(makeFlexibleSupabase({}))
|
||||
|
||||
const res = await putAbsence(
|
||||
makeRequest(
|
||||
`https://x.test/api/v1/companies/${COMPANY_ID}/employees/${EMPLOYEE_ID}/absence`,
|
||||
{ method: 'PUT', body: JSON.stringify(validBody) },
|
||||
),
|
||||
absenceParams(COMPANY_ID, EMPLOYEE_ID),
|
||||
)
|
||||
expect(res.status).toBe(403)
|
||||
})
|
||||
|
||||
it('returns 401 without a bearer token', async () => {
|
||||
mockValidate.mockResolvedValue(null)
|
||||
mockServiceClient.mockReturnValue(makeFlexibleSupabase({}))
|
||||
|
||||
const res = await putAbsence(
|
||||
new Request(
|
||||
`https://x.test/api/v1/companies/${COMPANY_ID}/employees/${EMPLOYEE_ID}/absence`,
|
||||
{ method: 'PUT', body: JSON.stringify(validBody) },
|
||||
),
|
||||
absenceParams(COMPANY_ID, EMPLOYEE_ID),
|
||||
)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /api/v1/companies/:companyId/employees/:id/absence', () => {
|
||||
it('deletes the range and returns deleted_count', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
employees: { data: { id: EMPLOYEE_ID }, error: null },
|
||||
salary_absence_days: { data: null, error: null, count: 3 },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await deleteAbsence(
|
||||
makeRequest(
|
||||
`https://x.test/api/v1/companies/${COMPANY_ID}/employees/${EMPLOYEE_ID}/absence?from=2026-03-01&to=2026-03-31&type=sick`,
|
||||
{ method: 'DELETE' },
|
||||
),
|
||||
absenceParams(COMPANY_ID, EMPLOYEE_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data.deleted_count).toBe(3)
|
||||
})
|
||||
|
||||
it('requires from and to', async () => {
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
}),
|
||||
)
|
||||
const res = await deleteAbsence(
|
||||
makeRequest(
|
||||
`https://x.test/api/v1/companies/${COMPANY_ID}/employees/${EMPLOYEE_ID}/absence`,
|
||||
{ method: 'DELETE' },
|
||||
),
|
||||
absenceParams(COMPANY_ID, EMPLOYEE_ID),
|
||||
)
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
})
|
||||
@@ -1,327 +0,0 @@
|
||||
/**
|
||||
* /api/v1/companies/{companyId}/employees/{id}/absence
|
||||
*
|
||||
* GET : list absence days in a date range (max 92 days: the range IS the
|
||||
* pagination, no cursor).
|
||||
* PUT : range upsert. Expands [from, to] to per-day rows on the natural
|
||||
* key (employee, date, type). Truly idempotent: retries converge.
|
||||
* DELETE : range delete (optional type filter). Returns deleted_count.
|
||||
*
|
||||
* Storage is per-day (sjuklönelagen karens/day-14 boundaries and AGI 2025+
|
||||
* per-event Frånvarouppgift derive from day rows); the range payload is API
|
||||
* ergonomics only. Pre-cutover backfill is legal at any date: imported
|
||||
* history feeds the sick-segment lookback in the calculation engine.
|
||||
*/
|
||||
|
||||
import { z } from 'zod'
|
||||
import { ok } from '@/lib/api/v1/response'
|
||||
import { dryRunPreview } from '@/lib/api/v1/dry-run'
|
||||
import { registerEndpoint, dataEnvelope, listEnvelope } from '@/lib/api/v1/registry'
|
||||
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponseFromCode, v1ValidationError } from '@/lib/api/v1/errors'
|
||||
import { readV1JsonBody } from '@/lib/api/v1/body'
|
||||
import { AbsenceTypeSchema } from '@/lib/api/schemas'
|
||||
import {
|
||||
ABSENCE_RANGE_MAX_DAYS,
|
||||
deleteAbsenceRange,
|
||||
listAbsenceDays,
|
||||
upsertAbsenceRange,
|
||||
} from '@/lib/salary/absence'
|
||||
|
||||
const isoDate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Expected YYYY-MM-DD date format')
|
||||
|
||||
const AbsenceDay = z.object({
|
||||
salary_absence_day_id: z.string().uuid(),
|
||||
absence_date: z.string(),
|
||||
absence_type: AbsenceTypeSchema,
|
||||
hours: z.number(),
|
||||
notes: z.string().nullable(),
|
||||
salary_run_employee_id: z.string().uuid().nullable(),
|
||||
created_at: z.string(),
|
||||
updated_at: z.string(),
|
||||
})
|
||||
|
||||
const RangeQuery = z
|
||||
.object({
|
||||
from: isoDate,
|
||||
to: isoDate,
|
||||
type: AbsenceTypeSchema.optional(),
|
||||
})
|
||||
.refine((v) => v.from <= v.to, { message: 'from must be <= to', path: ['from'] })
|
||||
|
||||
registerEndpoint({
|
||||
operation: 'employees.absence.list',
|
||||
method: 'GET',
|
||||
path: '/api/v1/companies/:companyId/employees/:id/absence',
|
||||
summary: 'List absence days for an employee in a date range.',
|
||||
description:
|
||||
'Returns per-day absence rows (sick, vab, parental, ...) between ?from and ?to (inclusive, max 92 days). No cursor pagination: the bounded range is the page. Optional ?type filter.',
|
||||
useWhen:
|
||||
'You need an employee\'s registered absence: to reconcile with an external time-tracking system, to verify what the salary engine will derive, or to display a calendar.',
|
||||
doNotUseFor:
|
||||
'The derived pay impact (karensavdrag, sjuklön lines): that lives on the payslip detail after :calculate. Worked hours for hourly staff: separate register, not on v1 yet.',
|
||||
pitfalls: [
|
||||
'Ranges over 92 days return 400 ABSENCE_RANGE_TOO_LARGE: iterate quarters instead.',
|
||||
'A day can carry multiple rows with different absence_type values (e.g. half-day sick + half-day vab).',
|
||||
'Rows may reference the salary run that consumed them via salary_run_employee_id.',
|
||||
],
|
||||
example: {
|
||||
response: {
|
||||
data: [
|
||||
{
|
||||
salary_absence_day_id: 'abs_91d2…',
|
||||
absence_date: '2026-03-03',
|
||||
absence_type: 'sick',
|
||||
hours: 8,
|
||||
notes: null,
|
||||
},
|
||||
],
|
||||
meta: { request_id: 'req_…', api_version: '2026-05-12' },
|
||||
},
|
||||
},
|
||||
scope: 'payroll:read',
|
||||
risk: 'low',
|
||||
idempotent: true,
|
||||
reversible: false,
|
||||
dryRunSupported: false,
|
||||
response: { success: listEnvelope(AbsenceDay) },
|
||||
})
|
||||
|
||||
export const GET = withApiV1<{ params: Promise<{ companyId: string; id: string }> }>(
|
||||
'employees.absence.list',
|
||||
async (request, ctx, params) => {
|
||||
const { id } = await params.params
|
||||
const idParse = z.string().uuid().safeParse(id)
|
||||
if (!idParse.success) {
|
||||
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { field: 'id', message: 'Employee id must be a UUID.' },
|
||||
})
|
||||
}
|
||||
|
||||
const url = new URL(request.url)
|
||||
const parsed = RangeQuery.safeParse({
|
||||
from: url.searchParams.get('from') ?? undefined,
|
||||
to: url.searchParams.get('to') ?? undefined,
|
||||
type: url.searchParams.get('type') ?? undefined,
|
||||
})
|
||||
if (!parsed.success) return v1ValidationError(ctx, parsed.error)
|
||||
const { from, to, type } = parsed.data
|
||||
|
||||
// Same cap as writes: the bounded range is the pagination contract.
|
||||
const spanMs = Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)
|
||||
if (spanMs < 0 || spanMs / 86_400_000 + 1 > ABSENCE_RANGE_MAX_DAYS) {
|
||||
return v1ErrorResponseFromCode('ABSENCE_RANGE_TOO_LARGE', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { from, to, max_days: ABSENCE_RANGE_MAX_DAYS },
|
||||
})
|
||||
}
|
||||
|
||||
const result = await listAbsenceDays(ctx.supabase, {
|
||||
companyId: ctx.companyId!,
|
||||
employeeId: idParse.data,
|
||||
from,
|
||||
to,
|
||||
absenceType: type,
|
||||
})
|
||||
|
||||
if (!result.ok) {
|
||||
return v1ErrorResponseFromCode(result.code, ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: result.details,
|
||||
})
|
||||
}
|
||||
|
||||
return ok(
|
||||
result.data.map(({ id: rowId, ...rest }) => ({ salary_absence_day_id: rowId, ...rest })),
|
||||
{ requestId: ctx.requestId },
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
// PUT: range upsert
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
|
||||
const UpsertRangeBody = z
|
||||
.object({
|
||||
from: isoDate,
|
||||
to: isoDate,
|
||||
absence_type: AbsenceTypeSchema,
|
||||
hours_per_day: z.number().positive().max(24).default(8),
|
||||
notes: z.string().max(2000).optional(),
|
||||
include_weekends: z.boolean().default(false),
|
||||
})
|
||||
.refine((v) => v.from <= v.to, { message: 'from must be <= to', path: ['from'] })
|
||||
|
||||
const UpsertRangeResponse = z.object({
|
||||
count: z.number().int(),
|
||||
days: z.array(AbsenceDay.partial({ salary_absence_day_id: true, notes: true, salary_run_employee_id: true, created_at: true, updated_at: true })),
|
||||
})
|
||||
|
||||
registerEndpoint({
|
||||
operation: 'employees.absence.upsert',
|
||||
method: 'PUT',
|
||||
path: '/api/v1/companies/:companyId/employees/:id/absence',
|
||||
summary: 'Register absence for an employee over a date range.',
|
||||
description:
|
||||
'Expands [from, to] (max 92 days) to per-day rows and upserts them on the natural key (employee, date, type). Weekends are skipped unless include_weekends=true. Single day = from == to. Idempotent by construction: replaying the same PUT converges on the same rows.',
|
||||
useWhen:
|
||||
'"Anna was sick 3-7 March": one call registers the whole event. Also for pre-cutover history backfill when migrating from another payroll system (any past date is legal; imported sick days feed the karensavdrag lookback).',
|
||||
doNotUseFor:
|
||||
'Vacation day REQUESTS/approval workflows (out of scope). Editing hours on one existing day inside a range: PUT the single day (from == to) with the new hours.',
|
||||
pitfalls: [
|
||||
'Weekends are skipped by default: pass include_weekends=true for schedules that span them.',
|
||||
'Upsert REPLACES the (date, type) rows in the range: hours/notes are overwritten, not merged.',
|
||||
'A day whose combined absence + worked hours exceed 24h returns 409 ABSENCE_HOURS_CONFLICT and the whole range is rejected (atomic).',
|
||||
'Registering absence does not recompute an open salary run: call POST /salary-runs/{id}/calculate afterwards.',
|
||||
],
|
||||
example: {
|
||||
request: { from: '2026-03-03', to: '2026-03-07', absence_type: 'sick' },
|
||||
response: {
|
||||
data: { count: 5, days: [{ absence_date: '2026-03-03', absence_type: 'sick', hours: 8 }] },
|
||||
meta: { request_id: 'req_…', api_version: '2026-05-12' },
|
||||
},
|
||||
},
|
||||
scope: 'payroll:write',
|
||||
risk: 'low',
|
||||
idempotent: true,
|
||||
reversible: true,
|
||||
dryRunSupported: true,
|
||||
request: { body: UpsertRangeBody },
|
||||
response: { success: dataEnvelope(UpsertRangeResponse) },
|
||||
})
|
||||
|
||||
export const PUT = withApiV1<{ params: Promise<{ companyId: string; id: string }> }>(
|
||||
'employees.absence.upsert',
|
||||
async (request, ctx, params) => {
|
||||
const { id } = await params.params
|
||||
const idParse = z.string().uuid().safeParse(id)
|
||||
if (!idParse.success) {
|
||||
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { field: 'id', message: 'Employee id must be a UUID.' },
|
||||
})
|
||||
}
|
||||
|
||||
const rawBodyResult = await readV1JsonBody(request, ctx)
|
||||
if (!rawBodyResult.ok) return rawBodyResult.response
|
||||
const rawBody = rawBodyResult.body
|
||||
|
||||
const parsed = UpsertRangeBody.safeParse(rawBody)
|
||||
if (!parsed.success) return v1ValidationError(ctx, parsed.error)
|
||||
const body = parsed.data
|
||||
|
||||
const result = await upsertAbsenceRange(ctx.supabase, {
|
||||
companyId: ctx.companyId!,
|
||||
employeeId: idParse.data,
|
||||
from: body.from,
|
||||
to: body.to,
|
||||
absenceType: body.absence_type,
|
||||
hoursPerDay: body.hours_per_day,
|
||||
notes: body.notes ?? null,
|
||||
includeWeekends: body.include_weekends,
|
||||
dryRun: ctx.dryRun,
|
||||
})
|
||||
|
||||
if (!result.ok) {
|
||||
return v1ErrorResponseFromCode(result.code, ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: result.details,
|
||||
})
|
||||
}
|
||||
|
||||
const payload = {
|
||||
count: result.data.count,
|
||||
days: result.data.days.map((d) => {
|
||||
const { id: rowId, ...rest } = d as { id?: string } & Record<string, unknown>
|
||||
return rowId ? { salary_absence_day_id: rowId, ...rest } : rest
|
||||
}),
|
||||
}
|
||||
|
||||
if (ctx.dryRun) {
|
||||
return dryRunPreview(payload, { requestId: ctx.requestId, log: ctx.log })
|
||||
}
|
||||
return ok(payload, { requestId: ctx.requestId })
|
||||
},
|
||||
{ requireIdempotencyKey: false },
|
||||
)
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
// DELETE: range delete
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
|
||||
const DeleteRangeResponse = z.object({ deleted_count: z.number().int() })
|
||||
|
||||
registerEndpoint({
|
||||
operation: 'employees.absence.delete',
|
||||
method: 'DELETE',
|
||||
path: '/api/v1/companies/:companyId/employees/:id/absence',
|
||||
summary: 'Delete absence days for an employee in a date range.',
|
||||
description:
|
||||
'Deletes per-day absence rows between ?from and ?to (inclusive), optionally filtered by ?type. Returns deleted_count (200, not 204) so callers can verify how many rows went.',
|
||||
useWhen:
|
||||
'An absence event was registered by mistake or ended early: "Anna came back Thursday, delete Thu-Fri sick days".',
|
||||
doNotUseFor:
|
||||
'Correcting hours on a day: PUT the day again instead. Rows already consumed by a BOOKED run: deleting them does not un-book the run; use the run correction flow.',
|
||||
pitfalls: [
|
||||
'Without ?type, ALL absence types in the range are deleted.',
|
||||
'deleted_count: 0 with a 200 means nothing matched: not an error.',
|
||||
],
|
||||
example: {
|
||||
response: {
|
||||
data: { deleted_count: 2 },
|
||||
meta: { request_id: 'req_…', api_version: '2026-05-12' },
|
||||
},
|
||||
},
|
||||
scope: 'payroll:write',
|
||||
risk: 'low',
|
||||
idempotent: true,
|
||||
reversible: false,
|
||||
dryRunSupported: true,
|
||||
response: { success: dataEnvelope(DeleteRangeResponse) },
|
||||
})
|
||||
|
||||
export const DELETE = withApiV1<{ params: Promise<{ companyId: string; id: string }> }>(
|
||||
'employees.absence.delete',
|
||||
async (request, ctx, params) => {
|
||||
const { id } = await params.params
|
||||
const idParse = z.string().uuid().safeParse(id)
|
||||
if (!idParse.success) {
|
||||
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { field: 'id', message: 'Employee id must be a UUID.' },
|
||||
})
|
||||
}
|
||||
|
||||
const url = new URL(request.url)
|
||||
const parsed = RangeQuery.safeParse({
|
||||
from: url.searchParams.get('from') ?? undefined,
|
||||
to: url.searchParams.get('to') ?? undefined,
|
||||
type: url.searchParams.get('type') ?? undefined,
|
||||
})
|
||||
if (!parsed.success) return v1ValidationError(ctx, parsed.error)
|
||||
const { from, to, type } = parsed.data
|
||||
|
||||
const result = await deleteAbsenceRange(ctx.supabase, {
|
||||
companyId: ctx.companyId!,
|
||||
employeeId: idParse.data,
|
||||
from,
|
||||
to,
|
||||
absenceType: type,
|
||||
dryRun: ctx.dryRun,
|
||||
})
|
||||
|
||||
if (!result.ok) {
|
||||
return v1ErrorResponseFromCode(result.code, ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: result.details,
|
||||
})
|
||||
}
|
||||
|
||||
if (ctx.dryRun) {
|
||||
return dryRunPreview(result.data, { requestId: ctx.requestId, log: ctx.log })
|
||||
}
|
||||
return ok(result.data, { requestId: ctx.requestId })
|
||||
},
|
||||
)
|
||||
-553
File diff suppressed because it is too large
Load Diff
@@ -1,200 +0,0 @@
|
||||
/**
|
||||
* /api/v1/companies/{companyId}/employees/{id}/opening-balances
|
||||
*
|
||||
* GET : the employee's cutover opening balances + lock state.
|
||||
* PUT : full-replace upsert (naturally idempotent). Editable until the
|
||||
* employee appears in a BOOKED salary run; then 409
|
||||
* OPENING_BALANCES_LOCKED (self-unlocks if that run is corrected).
|
||||
*
|
||||
* This is the payroll cutover surface for mid-year migrations from another
|
||||
* payroll system: YTD accumulators (payslip continuity), vacation balances
|
||||
* incl. sparade dagar by origin year, the opening semesterlöneskuld SEK
|
||||
* (report-only: the 2920/2940 balance arrived via SIE opening balances),
|
||||
* and the högriskskydd karens-count adjustment. Ongoing sick cases need no
|
||||
* fields here: import pre-cutover days via PUT /employees/{id}/absence and
|
||||
* the engine reconstructs segments, återinsjuknande, and karens state.
|
||||
*/
|
||||
|
||||
import { z } from 'zod'
|
||||
import { ok } from '@/lib/api/v1/response'
|
||||
import { dryRunPreview } from '@/lib/api/v1/dry-run'
|
||||
import { registerEndpoint, dataEnvelope } from '@/lib/api/v1/registry'
|
||||
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponseFromCode, v1ValidationError } from '@/lib/api/v1/errors'
|
||||
import { readV1JsonBody } from '@/lib/api/v1/body'
|
||||
import { OpeningBalancesFieldsSchema } from '@/lib/api/schemas'
|
||||
import { getOpeningBalances, setOpeningBalancesBulk } from '@/lib/salary/opening-balances'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
const OpeningBalancesResponse = z.object({
|
||||
employee_opening_balances_id: z.string().uuid().nullable(),
|
||||
employee_id: z.string().uuid(),
|
||||
cutover_date: z.string(),
|
||||
ytd_gross: z.number(),
|
||||
ytd_tax: z.number(),
|
||||
ytd_net: z.number(),
|
||||
vacation_paid_days_remaining: z.number(),
|
||||
vacation_days_taken_this_year: z.number(),
|
||||
vacation_saved_days_by_year: z.record(z.string(), z.number()),
|
||||
opening_semester_liability: z.number(),
|
||||
opening_semester_liability_avgifter: z.number(),
|
||||
karens_periods_adjustment: z.number(),
|
||||
locked: z.boolean(),
|
||||
locked_by_run_id: z.string().uuid().nullable(),
|
||||
})
|
||||
|
||||
registerEndpoint({
|
||||
operation: 'employees.opening-balances.get',
|
||||
method: 'GET',
|
||||
path: '/api/v1/companies/:companyId/employees/:id/opening-balances',
|
||||
summary: 'Get an employee\'s payroll cutover opening balances.',
|
||||
description:
|
||||
'Returns the opening balances set for a mid-year migration (YTD gross/tax/net, vacation balances, opening semesterlöneskuld, karens adjustment) plus the lock state: locked=true once the employee has a booked salary run.',
|
||||
useWhen:
|
||||
'Verifying cutover state before the first calculated run, or checking whether balances can still be edited (locked=false).',
|
||||
doNotUseFor:
|
||||
'The live vacation liability (GET /reports/vacation-liability includes the opening terms). Pre-cutover absence history: GET /employees/{id}/absence.',
|
||||
pitfalls: [
|
||||
'404 NOT_FOUND when no opening balances have been set: distinct from an all-zeros row.',
|
||||
'locked_by_run_id names the booked run that froze the row; correcting that run unlocks it.',
|
||||
],
|
||||
example: {
|
||||
response: {
|
||||
data: {
|
||||
employee_id: 'emp_77b2…',
|
||||
cutover_date: '2026-07-01',
|
||||
ytd_gross: 210000,
|
||||
vacation_paid_days_remaining: 12.5,
|
||||
locked: false,
|
||||
},
|
||||
meta: { request_id: 'req_…', api_version: '2026-05-12' },
|
||||
},
|
||||
},
|
||||
scope: 'payroll:read',
|
||||
risk: 'low',
|
||||
idempotent: true,
|
||||
reversible: false,
|
||||
dryRunSupported: false,
|
||||
response: { success: dataEnvelope(OpeningBalancesResponse) },
|
||||
})
|
||||
|
||||
export const GET = withApiV1<{ params: Promise<{ companyId: string; id: string }> }>(
|
||||
'employees.opening-balances.get',
|
||||
async (_request, ctx, params) => {
|
||||
const { id } = await params.params
|
||||
const idParse = z.string().uuid().safeParse(id)
|
||||
if (!idParse.success) {
|
||||
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { field: 'id', message: 'Employee id must be a UUID.' },
|
||||
})
|
||||
}
|
||||
|
||||
const result = await getOpeningBalances(ctx.supabase, {
|
||||
companyId: ctx.companyId!,
|
||||
employeeId: idParse.data,
|
||||
})
|
||||
if (!result.ok) {
|
||||
return v1ErrorResponseFromCode(result.code, ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: result.details,
|
||||
})
|
||||
}
|
||||
if (result.data === null) {
|
||||
return v1ErrorResponseFromCode('NOT_FOUND', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { resource: 'employee_opening_balances', employee_id: idParse.data },
|
||||
})
|
||||
}
|
||||
return ok(result.data, { requestId: ctx.requestId })
|
||||
},
|
||||
)
|
||||
|
||||
registerEndpoint({
|
||||
operation: 'employees.opening-balances.set',
|
||||
method: 'PUT',
|
||||
path: '/api/v1/companies/:companyId/employees/:id/opening-balances',
|
||||
summary: 'Set an employee\'s payroll cutover opening balances.',
|
||||
description:
|
||||
'Full-replace upsert of the cutover state: YTD gross/tax/net for the cutover year, paid vacation days remaining, paid days already taken this vacation year, sparade dagar keyed by origin year (5-year rule), opening semesterlöneskuld SEK (+avgifter), and karens periods not covered by imported absence rows. cutover_date must be the first of a month in the current or previous year, on/after employment_start.',
|
||||
useWhen:
|
||||
'Onboarding one employee during a mid-year migration from Fortnox/Visma/etc. For whole-company onboarding, prefer the bulk PUT /employees/opening-balances.',
|
||||
doNotUseFor:
|
||||
'SIE opening balances on the LEDGER (2920/2940 arrive via the SIE import). Ongoing sick cases: import pre-cutover days via PUT /employees/{id}/absence instead.',
|
||||
pitfalls: [
|
||||
'Full replace: omitted numeric fields reset to 0 (their defaults). Send the complete state every time.',
|
||||
'409 OPENING_BALANCES_LOCKED once the employee has a booked run; correcting that run unlocks.',
|
||||
'The opening liability is NOT booked by Accounted: it only feeds the vacation-liability report.',
|
||||
'YTD affects payslip display and reports only; per-month tax and avgifter caps never read it.',
|
||||
],
|
||||
example: {
|
||||
request: {
|
||||
cutover_date: '2026-07-01',
|
||||
ytd_gross: 210000,
|
||||
ytd_tax: 48000,
|
||||
ytd_net: 162000,
|
||||
vacation_paid_days_remaining: 12.5,
|
||||
vacation_saved_days_by_year: { '2025': 5 },
|
||||
opening_semester_liability: 42000,
|
||||
opening_semester_liability_avgifter: 13196.4,
|
||||
karens_periods_adjustment: 1,
|
||||
},
|
||||
response: {
|
||||
data: { employee_id: 'emp_77b2…', cutover_date: '2026-07-01', locked: false },
|
||||
meta: { request_id: 'req_…', api_version: '2026-05-12' },
|
||||
},
|
||||
},
|
||||
scope: 'payroll:write',
|
||||
risk: 'medium',
|
||||
idempotent: true,
|
||||
reversible: true,
|
||||
dryRunSupported: true,
|
||||
request: { body: OpeningBalancesFieldsSchema },
|
||||
response: { success: dataEnvelope(OpeningBalancesResponse) },
|
||||
})
|
||||
|
||||
export const PUT = withApiV1<{ params: Promise<{ companyId: string; id: string }> }>(
|
||||
'employees.opening-balances.set',
|
||||
async (request, ctx, params) => {
|
||||
const { id } = await params.params
|
||||
const idParse = z.string().uuid().safeParse(id)
|
||||
if (!idParse.success) {
|
||||
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { field: 'id', message: 'Employee id must be a UUID.' },
|
||||
})
|
||||
}
|
||||
|
||||
const rawBodyResult = await readV1JsonBody(request, ctx)
|
||||
if (!rawBodyResult.ok) return rawBodyResult.response
|
||||
const rawBody = rawBodyResult.body
|
||||
|
||||
const parsed = OpeningBalancesFieldsSchema.safeParse(rawBody)
|
||||
if (!parsed.success) return v1ValidationError(ctx, parsed.error)
|
||||
|
||||
// The per-employee PUT is the bulk handler with one item: one validation
|
||||
// and one upsert path to maintain.
|
||||
const result = await setOpeningBalancesBulk(ctx.supabase, {
|
||||
companyId: ctx.companyId!,
|
||||
userId: ctx.userId,
|
||||
items: [{ employee_id: idParse.data, ...parsed.data }],
|
||||
dryRun: ctx.dryRun,
|
||||
})
|
||||
|
||||
if (!result.ok) {
|
||||
// Single-item calls surface the item's own error code directly (a
|
||||
// one-element 422 list would just be indirection).
|
||||
const itemError = result.itemErrors?.[0]
|
||||
return v1ErrorResponseFromCode(itemError?.code ?? result.code, ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: itemError ? { message: getUserErrorMessage(itemError) } : result.details,
|
||||
})
|
||||
}
|
||||
|
||||
const row = result.data.rows[0]
|
||||
if (ctx.dryRun) {
|
||||
return dryRunPreview(row, { requestId: ctx.requestId, log: ctx.log })
|
||||
}
|
||||
return ok(row, { requestId: ctx.requestId })
|
||||
},
|
||||
)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user