feat(api): ROT/RUT, articles, and project lifecycle on the v1 API (#904)
* feat(api): ROT/RUT + articles + dimensions on the v1 invoice surface (#895) - v1 invoice POST now routes through buildInvoiceWriteData, the same builder as the dashboard: ROT/RUT deduction lines (server-side compute, personnummer encryption), article_id + revenue_account linkage, accruals, and line_type no longer get silently dropped on the wire. - v1 invoice PATCH accepts default_dimensions so integrations can tag a draft with a project/cost centre after creation. - New PATCH/DELETE /dimensions/:id/values/:valueId: rename, archive, set end_date on project codes; delete unreferenced values (409 with an archive hint when the BFL retention trigger blocks). - New GET /articles: read-only artikelregister list (incl. housework_type) so callers can resolve article_id before composing invoice lines. - Invoice GET/POST projections now expose deduction fields and full item columns; dry-run previews never echo the encrypted personnummer. Closes #895 Co-Authored-By: Claude Opus 4.7 <[email protected]> * refactor(api): address review on #904 - Extract shared v1 invoice projections to lib/api/v1/invoice-columns.ts so create/detail/patch responses can't drift; PATCH now returns deduction_total + deduction_personnummer_last4 like GET/POST. - Narrow the v1 create customer fetch back to the three fields the builder reads instead of select('*'). Co-Authored-By: Claude Opus 4.7 <[email protected]> --------- Co-authored-by: Claude Opus 4.7 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 4.7
parent
31b244acf5
commit
cdac1808c9
@@ -0,0 +1,165 @@
|
||||
/**
|
||||
* 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,
|
||||
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('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)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* 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(),
|
||||
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, 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.',
|
||||
'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,
|
||||
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 })
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,269 @@
|
||||
/**
|
||||
* 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 } from '@/lib/api/v1/errors'
|
||||
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.' },
|
||||
})
|
||||
}
|
||||
|
||||
let rawBody: unknown
|
||||
try {
|
||||
rawBody = await request.json()
|
||||
} catch {
|
||||
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { field: 'body', message: 'Body is not valid JSON.' },
|
||||
})
|
||||
}
|
||||
|
||||
const parsed = UpdateDimensionValueSchema.safeParse(rawBody)
|
||||
if (!parsed.success) {
|
||||
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: {
|
||||
issues: parsed.error.issues.map((i) => ({
|
||||
field: i.path.join('.'),
|
||||
message: i.message,
|
||||
})),
|
||||
},
|
||||
})
|
||||
}
|
||||
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 },
|
||||
)
|
||||
@@ -0,0 +1,349 @@
|
||||
/**
|
||||
* 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')
|
||||
})
|
||||
})
|
||||
@@ -19,6 +19,8 @@ import { parseExpand } from '@/lib/api/v1/expand'
|
||||
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 { INVOICE_FULL_COLUMNS, INVOICE_ITEM_FULL_COLUMNS } from '@/lib/api/v1/invoice-columns'
|
||||
import { DimensionsBagSchema } from '@/lib/bookkeeping/dimension-resolver'
|
||||
|
||||
// Allowed PATCH fields for a draft invoice. Excludes items (separate
|
||||
// workflow), customer_id / currency / document_type (structural: change
|
||||
@@ -31,6 +33,10 @@ const V1PatchDraftInvoiceSchema = z.object({
|
||||
your_reference: z.union([z.string(), z.null()]).optional(),
|
||||
our_reference: z.union([z.string(), z.null()]).optional(),
|
||||
notes: z.union([z.string(), z.null()]).optional(),
|
||||
// Project/cost-centre tagging ({"6":"P001"}): replaces the whole bag.
|
||||
// Send {} to clear all tags. Codes are validated against the dimension
|
||||
// registry when the invoice posts at :send, not here.
|
||||
default_dimensions: DimensionsBagSchema.optional(),
|
||||
})
|
||||
|
||||
// Loose schema: detail responses carry many fields, and pinning the exact
|
||||
@@ -53,17 +59,14 @@ const InvoiceDetail = z.object({
|
||||
|
||||
const ALLOWED_EXPAND = ['items', 'payments'] as const
|
||||
|
||||
// Explicit projections. Detail endpoint is more verbose than list: includes
|
||||
// VAT treatment, conversion, FX, and notes, but still drops user_id and
|
||||
// company_id (internal scoping).
|
||||
const INVOICE_DETAIL_COLUMNS =
|
||||
'id, invoice_number, customer_id, invoice_date, due_date, delivery_date, status, currency, exchange_rate, exchange_rate_date, subtotal, subtotal_sek, vat_amount, vat_amount_sek, total, total_sek, vat_treatment, vat_rate, moms_ruta, your_reference, our_reference, notes, reverse_charge_text, credited_invoice_id, document_type, converted_from_id, paid_at, paid_amount, remaining_amount, default_dimensions, created_at, updated_at'
|
||||
// Explicit projections, shared with the create route so create/detail/patch
|
||||
// responses never drift.
|
||||
const INVOICE_DETAIL_COLUMNS = INVOICE_FULL_COLUMNS
|
||||
|
||||
const CUSTOMER_DETAIL_COLUMNS =
|
||||
'id, name, customer_type, email, phone, 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'
|
||||
|
||||
const INVOICE_ITEM_COLUMNS =
|
||||
'id, sort_order, description, quantity, unit, unit_price, line_total, vat_rate, vat_amount, dimensions, created_at'
|
||||
const INVOICE_ITEM_COLUMNS = INVOICE_ITEM_FULL_COLUMNS
|
||||
|
||||
// Payment projection: drops invoice_id (redundant on the parent), user_id,
|
||||
// company_id (internal scoping).
|
||||
@@ -182,7 +185,7 @@ registerEndpoint({
|
||||
path: '/api/v1/companies/:companyId/invoices/:id',
|
||||
summary: 'Update a draft invoice (metadata fields only).',
|
||||
description:
|
||||
'Partial update for invoices in draft status. Allowed fields: invoice_date, due_date, delivery_date, your_reference, our_reference, notes. customer_id, currency, document_type, items, and computed totals are immutable: replace those by deleting the draft and recreating it. Returns 409 INVOICE_UPDATE_NOT_DRAFT if the invoice is no longer in draft status. Idempotent and dry-runnable.',
|
||||
'Partial update for invoices in draft status. Allowed fields: invoice_date, due_date, delivery_date, your_reference, our_reference, notes, default_dimensions (project/cost-centre tags, e.g. {"6":"P001"}; replaces the whole bag). customer_id, currency, document_type, items, and computed totals are immutable: replace those by deleting the draft and recreating it. Returns 409 INVOICE_UPDATE_NOT_DRAFT if the invoice is no longer in draft status. Idempotent and dry-runnable.',
|
||||
useWhen:
|
||||
'You need to correct a typo, push the due date, or update a customer reference on a draft you have not sent yet. The invoice number stays null until the first :send action.',
|
||||
doNotUseFor:
|
||||
@@ -191,6 +194,7 @@ registerEndpoint({
|
||||
'Idempotency-Key is mandatory.',
|
||||
'A 409 INVOICE_UPDATE_NOT_DRAFT means the invoice has been sent / paid / credited / cancelled. The error code name is shared with the DELETE handler.',
|
||||
'Items are immutable here: to change line items, delete the draft and POST a fresh one.',
|
||||
'default_dimensions replaces the entire bag (no per-key merge): read the current value first if you want to add a tag. Send {} to clear all tags. Codes are validated against the dimension registry at :send, not at PATCH time.',
|
||||
],
|
||||
example: {
|
||||
request: { due_date: '2026-07-15', notes: 'Förlängd förfallotid' },
|
||||
@@ -213,8 +217,7 @@ registerEndpoint({
|
||||
response: { success: dataEnvelope(InvoiceDetail) },
|
||||
})
|
||||
|
||||
const INVOICE_PATCH_RESPONSE_COLUMNS =
|
||||
'id, invoice_number, customer_id, invoice_date, due_date, delivery_date, status, currency, exchange_rate, exchange_rate_date, subtotal, subtotal_sek, vat_amount, vat_amount_sek, total, total_sek, vat_treatment, vat_rate, moms_ruta, your_reference, our_reference, notes, reverse_charge_text, credited_invoice_id, document_type, converted_from_id, paid_at, paid_amount, remaining_amount, created_at, updated_at'
|
||||
const INVOICE_PATCH_RESPONSE_COLUMNS = INVOICE_FULL_COLUMNS
|
||||
|
||||
export const PATCH = withApiV1<{ params: Promise<{ companyId: string; id: string }> }>(
|
||||
'invoices.update',
|
||||
@@ -262,6 +265,7 @@ export const PATCH = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
'your_reference',
|
||||
'our_reference',
|
||||
'notes',
|
||||
'default_dimensions',
|
||||
] as const) {
|
||||
if (body[key] !== undefined) updateData[key] = body[key]
|
||||
}
|
||||
|
||||
@@ -775,6 +775,253 @@ describe('POST /api/v1/companies/:companyId/invoices', () => {
|
||||
expect(body.data.preview.default_dimensions).toEqual({ '6': 'P001' })
|
||||
expect(body.data.preview.items[0].dimensions).toEqual({ '1': 'KS01' })
|
||||
})
|
||||
|
||||
// ── ROT/RUT + article linkage (#895) ────────────────────────────
|
||||
|
||||
// Valid 12-digit personnummer (Luhn-checked); same fixture family as
|
||||
// lib/invoices/__tests__/rot-rut-file.test.ts.
|
||||
const VALID_PNR = '198406012388'
|
||||
|
||||
it('computes ROT deduction server-side and persists deduction fields', async () => {
|
||||
withInvoiceWriteScope()
|
||||
const createdInvoice = { id: 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee', status: 'draft' }
|
||||
let insertedInvoice: Record<string, unknown> | null = null
|
||||
let insertedItems: Array<Record<string, unknown>> | null = null
|
||||
mockServiceClient.mockReturnValue({
|
||||
from: (table: string) => {
|
||||
const handler: ProxyHandler<object> = {
|
||||
get(_t, prop) {
|
||||
if (prop === 'insert') {
|
||||
return (rows: Record<string, unknown> | Array<Record<string, unknown>>) => {
|
||||
if (table === 'invoices') insertedInvoice = rows as Record<string, unknown>
|
||||
if (table === 'invoice_items') insertedItems = rows as Array<Record<string, unknown>>
|
||||
return new Proxy({}, handler)
|
||||
}
|
||||
}
|
||||
if (prop === 'then') {
|
||||
const data =
|
||||
table === 'company_members'
|
||||
? { company_id: COMPANY_ID, role: 'owner' }
|
||||
: table === 'customers'
|
||||
? SWEDISH_BUSINESS_CUSTOMER
|
||||
: table === 'invoices'
|
||||
? createdInvoice
|
||||
: null
|
||||
return (r: (v: unknown) => void) => r({ data, error: null })
|
||||
}
|
||||
return () => new Proxy({}, handler)
|
||||
},
|
||||
}
|
||||
return new Proxy({}, handler)
|
||||
},
|
||||
})
|
||||
|
||||
const res = await createInvoice(
|
||||
makePostInvoice(`https://x.test/api/v1/companies/${COMPANY_ID}/invoices`, {
|
||||
customer_id: CUSTOMER_ID,
|
||||
invoice_date: '2026-05-12',
|
||||
due_date: '2026-06-11',
|
||||
currency: 'SEK',
|
||||
deduction_personnummer: VALID_PNR,
|
||||
deduction_housing_designation: 'Almgren 1:23',
|
||||
items: [
|
||||
{
|
||||
description: 'Takarbete',
|
||||
quantity: 10,
|
||||
unit: 'tim',
|
||||
unit_price: 1000,
|
||||
deduction_type: 'rot',
|
||||
labor_hours: 10,
|
||||
work_type: 'BYGG',
|
||||
},
|
||||
],
|
||||
}),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(201)
|
||||
expect(insertedInvoice).not.toBeNull()
|
||||
// ROT = 30% of 10000 labor.
|
||||
expect(insertedInvoice!.deduction_total).toBe(3000)
|
||||
// Personnummer never stored in plaintext: ciphertext + last4 only.
|
||||
expect(insertedInvoice!.deduction_personnummer_encrypted).toBeTruthy()
|
||||
expect(insertedInvoice!.deduction_personnummer_encrypted).not.toContain(VALID_PNR)
|
||||
expect(insertedInvoice!.deduction_personnummer_last4).toBe('2388')
|
||||
// Customer share: total 12500 minus the 3000 Skatteverket pays via 1513.
|
||||
expect(insertedInvoice!.remaining_amount).toBe(9500)
|
||||
expect(insertedItems).not.toBeNull()
|
||||
expect(insertedItems![0].deduction_type).toBe('rot')
|
||||
expect(insertedItems![0].deduction_amount).toBe(3000)
|
||||
expect(insertedItems![0].work_type).toBe('BYGG')
|
||||
expect(insertedItems![0].labor_hours).toBe(10)
|
||||
// Invoice-level fastighetsbeteckning stamped onto the deduction line.
|
||||
expect(insertedItems![0].housing_designation).toBe('Almgren 1:23')
|
||||
})
|
||||
|
||||
it('rejects a ROT line without personnummer/housing info (400 INVOICE_CREATE_ROT_RUT_VALIDATION)', async () => {
|
||||
withInvoiceWriteScope()
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
customers: { data: SWEDISH_BUSINESS_CUSTOMER, error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await createInvoice(
|
||||
makePostInvoice(`https://x.test/api/v1/companies/${COMPANY_ID}/invoices`, {
|
||||
customer_id: CUSTOMER_ID,
|
||||
invoice_date: '2026-05-12',
|
||||
due_date: '2026-06-11',
|
||||
currency: 'SEK',
|
||||
items: [
|
||||
{
|
||||
description: 'Takarbete',
|
||||
quantity: 10,
|
||||
unit: 'tim',
|
||||
unit_price: 1000,
|
||||
deduction_type: 'rot',
|
||||
labor_hours: 10,
|
||||
work_type: 'BYGG',
|
||||
},
|
||||
],
|
||||
}),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('INVOICE_CREATE_ROT_RUT_VALIDATION')
|
||||
})
|
||||
|
||||
it('dry-run preview computes deduction_total and never echoes the encrypted personnummer', async () => {
|
||||
withInvoiceWriteScope()
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
customers: { data: SWEDISH_BUSINESS_CUSTOMER, error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await createInvoice(
|
||||
makePostInvoice(`https://x.test/api/v1/companies/${COMPANY_ID}/invoices?dry_run=true`, {
|
||||
customer_id: CUSTOMER_ID,
|
||||
invoice_date: '2026-05-12',
|
||||
due_date: '2026-06-11',
|
||||
currency: 'SEK',
|
||||
deduction_personnummer: VALID_PNR,
|
||||
deduction_housing_designation: 'Almgren 1:23',
|
||||
items: [
|
||||
{
|
||||
description: 'Städning',
|
||||
quantity: 4,
|
||||
unit: 'tim',
|
||||
unit_price: 500,
|
||||
deduction_type: 'rut',
|
||||
labor_hours: 4,
|
||||
work_type: 'STAD',
|
||||
},
|
||||
],
|
||||
}),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
// RUT = 50% of 2000 labor.
|
||||
expect(body.data.preview.deduction_total).toBe(1000)
|
||||
expect(body.data.preview.deduction_personnummer_last4).toBe('2388')
|
||||
expect(body.data.preview.deduction_personnummer_encrypted).toBeUndefined()
|
||||
expect(body.data.preview.items[0].deduction_amount).toBe(1000)
|
||||
})
|
||||
|
||||
it('persists article_id + revenue_account on line items (validated against the chart)', async () => {
|
||||
withInvoiceWriteScope()
|
||||
const ARTICLE_ID = 'ffffffff-ffff-4fff-8fff-ffffffffffff'
|
||||
const createdInvoice = { id: 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee', status: 'draft' }
|
||||
let insertedItems: Array<Record<string, unknown>> | null = null
|
||||
mockServiceClient.mockReturnValue({
|
||||
from: (table: string) => {
|
||||
const handler: ProxyHandler<object> = {
|
||||
get(_t, prop) {
|
||||
if (prop === 'insert') {
|
||||
return (rows: Record<string, unknown> | Array<Record<string, unknown>>) => {
|
||||
if (table === 'invoice_items') insertedItems = rows as Array<Record<string, unknown>>
|
||||
return new Proxy({}, handler)
|
||||
}
|
||||
}
|
||||
if (prop === 'then') {
|
||||
const data =
|
||||
table === 'company_members'
|
||||
? { company_id: COMPANY_ID, role: 'owner' }
|
||||
: table === 'customers'
|
||||
? SWEDISH_BUSINESS_CUSTOMER
|
||||
: table === 'chart_of_accounts'
|
||||
? [{ account_number: '3041' }]
|
||||
: table === 'invoices'
|
||||
? createdInvoice
|
||||
: null
|
||||
return (r: (v: unknown) => void) => r({ data, error: null })
|
||||
}
|
||||
return () => new Proxy({}, handler)
|
||||
},
|
||||
}
|
||||
return new Proxy({}, handler)
|
||||
},
|
||||
})
|
||||
|
||||
const res = await createInvoice(
|
||||
makePostInvoice(`https://x.test/api/v1/companies/${COMPANY_ID}/invoices`, {
|
||||
customer_id: CUSTOMER_ID,
|
||||
invoice_date: '2026-05-12',
|
||||
due_date: '2026-06-11',
|
||||
currency: 'SEK',
|
||||
items: [
|
||||
{
|
||||
description: 'Takarbete',
|
||||
quantity: 1,
|
||||
unit: 'st',
|
||||
unit_price: 5000,
|
||||
article_id: ARTICLE_ID,
|
||||
revenue_account: '3041',
|
||||
},
|
||||
],
|
||||
}),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(201)
|
||||
expect(insertedItems).not.toBeNull()
|
||||
expect(insertedItems![0].article_id).toBe(ARTICLE_ID)
|
||||
expect(insertedItems![0].revenue_account).toBe('3041')
|
||||
})
|
||||
|
||||
it('rejects a revenue_account not in the chart of accounts', async () => {
|
||||
withInvoiceWriteScope()
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
customers: { data: SWEDISH_BUSINESS_CUSTOMER, error: null },
|
||||
chart_of_accounts: { data: [], error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await createInvoice(
|
||||
makePostInvoice(`https://x.test/api/v1/companies/${COMPANY_ID}/invoices`, {
|
||||
customer_id: CUSTOMER_ID,
|
||||
invoice_date: '2026-05-12',
|
||||
due_date: '2026-06-11',
|
||||
currency: 'SEK',
|
||||
items: [
|
||||
{ description: 'x', quantity: 1, unit: 'st', unit_price: 100, revenue_account: '3999' },
|
||||
],
|
||||
}),
|
||||
companyParams(COMPANY_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('INVOICE_CREATE_REVENUE_ACCOUNT_INVALID')
|
||||
})
|
||||
})
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────
|
||||
@@ -904,6 +1151,54 @@ describe('PATCH /api/v1/companies/:companyId/invoices/:id', () => {
|
||||
expect(body.data.preview.due_date).toBe('2026-06-11') // unchanged from current
|
||||
})
|
||||
|
||||
it('updates default_dimensions (project tag) on a draft invoice (#895)', async () => {
|
||||
withInvoiceWriteScope()
|
||||
const draftInvoice = {
|
||||
id: INVOICE_ID,
|
||||
status: 'draft',
|
||||
invoice_date: '2026-05-12',
|
||||
due_date: '2026-06-11',
|
||||
default_dimensions: {},
|
||||
}
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
invoices: { data: { ...draftInvoice, default_dimensions: { '6': 'P001' } }, error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await updateInvoice(
|
||||
makePatchInvoice(`https://x.test/api/v1/companies/${COMPANY_ID}/invoices/${INVOICE_ID}`, {
|
||||
default_dimensions: { '6': 'P001' },
|
||||
}),
|
||||
detailParams(COMPANY_ID, INVOICE_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data.default_dimensions).toEqual({ '6': 'P001' })
|
||||
})
|
||||
|
||||
it('rejects a malformed default_dimensions bag', async () => {
|
||||
withInvoiceWriteScope()
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await updateInvoice(
|
||||
makePatchInvoice(`https://x.test/api/v1/companies/${COMPANY_ID}/invoices/${INVOICE_ID}`, {
|
||||
default_dimensions: { 'not-a-number': 'P001' },
|
||||
}),
|
||||
detailParams(COMPANY_ID, INVOICE_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('VALIDATION_ERROR')
|
||||
})
|
||||
|
||||
it('rejects forbidden fields (items / currency / customer_id)', async () => {
|
||||
withInvoiceWriteScope()
|
||||
mockServiceClient.mockReturnValue(
|
||||
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user