feat(dimensions): PR2 registry — CRUD API, register UI, settings toggle, SIE export on the new registry (#858)
* feat(dimensions): PR2 registry — CRUD API, register UI, settings toggle, SIE export on the new registry
Phase 2 of dev_docs/dimensions_implementation_plan.md. Companies with
dimensions_enabled=false (default) see zero change.
API:
- Dashboard CRUD: GET /api/dimensions (lazy-seeds system dims 1/6 via the
ensure_company_dimensions RPC), PATCH /api/dimensions/[id] (is_system
rename blocked), POST/PATCH/DELETE values (code immutable after creation;
strict Fortnox code format ^[A-Za-z0-9ÅÄÖåäö_+\-]{1,20}$ at the API layer;
retention-trigger deletes surface the Swedish "arkivera istället" message
as 409 DIMENSION_VALUE_REFERENCED).
- POST /api/dimensions/import-existing — scans journal_entry_lines.dimensions
for unregistered codes and mints inactive placeholder registry rows.
- v1 public API: GET dimensions + POST values (Idempotency-Key, dry-run),
registered in the OpenAPI spec (102→104 endpoints).
- dimensions_enabled boolean on company_settings (new migration,
UI-visibility only, never correctness-bearing) exposed through the
existing settings read/update path.
SIE export (lib/reports/sie-export.ts):
- Reads the new dimensions/dimension_values registry; legacy
cost_centers/projects tables now have zero readers (drop migration next).
- Fixes the latent Visma-rejection bug: #OBJEKT now declared for INACTIVE
values referenced by lines.
- Generic-N: #DIM/#UNDERDIM loop sorted by sie_dim_no; #TRANS object lists
serialize from the line JSONB map (sorted, '01'→'1' collapse); orphan
codes/dims synthesize declarations from the SIE reserved-number seed —
every referenced (dim, code) pair is guaranteed declared.
UI:
- /dimensions register (Register-recipe): tabs per dimension, search,
sortable table, value dialog (code immutable on edit, projekt dates on
dim 6), archive-not-delete affordances.
- DimensionCombobox shipped (mounts in the tagging PR).
- Settings toggle "Aktivera kostnadsställen & projekt" — toggle-on runs the
import-existing scan and links to the register.
- Nav row in redovisning, rendered only when dimensions_enabled (same
mechanism as pays_salaries).
- dimensions.* i18n namespace (51 keys, sv/en parity).
- Sandbox seed: demo dims + values, revenue line tagged {"1":"BUTIK","6":"P001"}.
Verified: 6328/6328 unit tests, guard + coverage gate green, tsc parity with
main (210=210), production build passes.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(dimensions): PR2 review round — atomic archived-create, UNDERDIM ordering, import robustness, date semantics
- POST values accepts is_active so "create as archived" is atomic; the UI's
fragile create-then-PATCH fallback is deleted (PR Agent finding 1).
- DimensionCombobox blur revert reads the committed value/values through refs
so a selection landing inside the 150ms window always wins (finding 2).
- import-existing sanitizes candidate codes like the PR1 backfill and upserts
with ignoreDuplicates — one bad/duplicate code can no longer abort the
batch; created counted from returned rows (finding 3).
- SIE export emits all root #DIM before any #UNDERDIM so a parent always
precedes a lower-numbered child (SIE4 declaration order — Swedish review);
synthesized placeholder declarations now log one structured warning
(BFNAR 2013:2 behandlingshistorik) + defence-in-depth comment.
- Value dates rejected (400 DIMENSION_VALUE_DATES_NOT_ALLOWED) when the
parent dimension is flow-period (resets_annually=true); explicit null
still clears (Swedish review).
- Sandbox seed logs seeded dimension codes; GET /api/dimensions documents
the deliberate absence of dimensions_enabled gating (UI-visibility flag,
not a security boundary — compliance-swarm V8.2.1 rejected by design).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
8cc2efb083
commit
8bb49c07a2
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* PATCH /api/dimensions/[id] — update a dimension (name / is_active / sort_order).
|
||||
*
|
||||
* Guard rails:
|
||||
* - Renaming an is_system dimension (1 = Kostnadsställe, 6 = Projekt) is
|
||||
* rejected with 400 DIMENSION_SYSTEM_RENAME ("Systemdimensioner kan inte
|
||||
* döpas om"). Archiving (is_active=false) and reordering remain allowed.
|
||||
* - sie_dim_no / is_system are immutable at the DB level
|
||||
* (enforce_dimension_registry_guards) and not accepted here at all.
|
||||
*/
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { UpdateDimensionSchema } from '@/lib/api/schemas'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
export const PATCH = withRouteContext(
|
||||
'dimension.update',
|
||||
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
const opLog = log.child({ dimensionId: id })
|
||||
|
||||
const result = await validateBody(request, UpdateDimensionSchema, {
|
||||
log: opLog,
|
||||
operation: 'dimension.update',
|
||||
})
|
||||
if (!result.success) return result.response
|
||||
const body = result.data
|
||||
|
||||
const { data: existing, error: fetchError } = await supabase
|
||||
.from('dimensions')
|
||||
.select('id, name, is_system')
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
|
||||
if (fetchError) {
|
||||
opLog.error('dimension fetch failed', fetchError)
|
||||
return errorResponse(fetchError, opLog, { requestId })
|
||||
}
|
||||
if (!existing) {
|
||||
return errorResponseFromCode('DIMENSION_NOT_FOUND', opLog, { requestId })
|
||||
}
|
||||
|
||||
if (existing.is_system && body.name !== undefined && body.name !== existing.name) {
|
||||
return errorResponseFromCode('DIMENSION_SYSTEM_RENAME', opLog, { requestId })
|
||||
}
|
||||
|
||||
// Sparse update — only the fields the caller actually sent.
|
||||
const updateData: Record<string, unknown> = {}
|
||||
for (const key of ['name', 'is_active', 'sort_order'] as const) {
|
||||
if (body[key] !== undefined) updateData[key] = body[key]
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('dimensions')
|
||||
.update(updateData)
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.select('id, sie_dim_no, name, resets_annually, is_system, is_active, sort_order')
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
opLog.error('dimension update failed', error)
|
||||
return errorResponseFromCode('DIMENSION_UPDATE_FAILED', opLog, {
|
||||
requestId,
|
||||
details: { reason: error.message },
|
||||
})
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* PATCH /api/dimensions/[id]/values/[valueId] — update a dimension value
|
||||
* (name / is_active / start_date / end_date; `code` is immutable in v1).
|
||||
* DELETE /api/dimensions/[id]/values/[valueId] — delete an UNREFERENCED value.
|
||||
*
|
||||
* Deleting a value referenced by posted/reversed lines is blocked by the DB
|
||||
* retention trigger (enforce_dimension_value_retention, BFL 7-year
|
||||
* philosophy). Its Swedish message ("Värdet "X" används på bokförda verifikat
|
||||
* och kan inte tas bort — arkivera det istället.") is surfaced verbatim as a
|
||||
* 409 DIMENSION_VALUE_REFERENCED so the register UI can toast it and offer
|
||||
* archive instead.
|
||||
*/
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { UpdateDimensionValueSchema } from '@/lib/api/schemas'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
type ValueParams = { params: Promise<{ id: string; valueId: string }> }
|
||||
|
||||
export const PATCH = withRouteContext(
|
||||
'dimension.value.update',
|
||||
async (request, ctx, { params }: ValueParams) => {
|
||||
const { id, valueId } = await params
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
const opLog = log.child({ dimensionId: id, valueId })
|
||||
|
||||
const result = await validateBody(request, UpdateDimensionValueSchema, {
|
||||
log: opLog,
|
||||
operation: 'dimension.value.update',
|
||||
})
|
||||
if (!result.success) return result.response
|
||||
const body = result.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.
|
||||
if (body.start_date != null || body.end_date != null) {
|
||||
const { data: dimension, error: dimError } = await supabase
|
||||
.from('dimensions')
|
||||
.select('id, resets_annually')
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
|
||||
if (dimError) {
|
||||
opLog.error('dimension fetch failed', dimError)
|
||||
return errorResponse(dimError, opLog, { requestId })
|
||||
}
|
||||
if (!dimension) {
|
||||
return errorResponseFromCode('DIMENSION_NOT_FOUND', opLog, { requestId })
|
||||
}
|
||||
if (dimension.resets_annually) {
|
||||
return errorResponseFromCode('DIMENSION_VALUE_DATES_NOT_ALLOWED', opLog, { requestId })
|
||||
}
|
||||
}
|
||||
|
||||
// Sparse update — only the fields the caller actually sent. `code` is
|
||||
// deliberately absent from the schema: renaming a code would silently
|
||||
// orphan every line tagged with it.
|
||||
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]
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('dimension_values')
|
||||
.update(updateData)
|
||||
.eq('id', valueId)
|
||||
.eq('dimension_id', id)
|
||||
.eq('company_id', companyId)
|
||||
.select('id, dimension_id, code, name, is_active, start_date, end_date')
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
if (error.code === 'PGRST116') {
|
||||
return errorResponseFromCode('DIMENSION_VALUE_NOT_FOUND', opLog, { requestId })
|
||||
}
|
||||
opLog.error('dimension value update failed', error)
|
||||
return errorResponseFromCode('DIMENSION_VALUE_UPDATE_FAILED', opLog, {
|
||||
requestId,
|
||||
details: { reason: error.message },
|
||||
})
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
|
||||
export const DELETE = withRouteContext(
|
||||
'dimension.value.delete',
|
||||
async (_request, ctx, { params }: ValueParams) => {
|
||||
const { id, valueId } = await params
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
const opLog = log.child({ dimensionId: id, valueId })
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('dimension_values')
|
||||
.delete()
|
||||
.eq('id', valueId)
|
||||
.eq('dimension_id', id)
|
||||
.eq('company_id', companyId)
|
||||
.select('id')
|
||||
|
||||
if (error) {
|
||||
// P0001 = plpgsql RAISE EXCEPTION — the retention trigger refusing the
|
||||
// delete. Surface its Swedish message verbatim (it names the code).
|
||||
if (error.code === 'P0001') {
|
||||
return errorResponseFromCode('DIMENSION_VALUE_REFERENCED', opLog, {
|
||||
requestId,
|
||||
messageSv: error.message,
|
||||
})
|
||||
}
|
||||
opLog.error('dimension value delete failed', error)
|
||||
return errorResponseFromCode('DIMENSION_VALUE_DELETE_FAILED', opLog, {
|
||||
requestId,
|
||||
details: { reason: error.message },
|
||||
})
|
||||
}
|
||||
|
||||
if (!data || data.length === 0) {
|
||||
return errorResponseFromCode('DIMENSION_VALUE_NOT_FOUND', opLog, { requestId })
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* POST /api/dimensions/[id]/values — create a dimension value (SIE #OBJEKT).
|
||||
*
|
||||
* Codes are validated against 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 the backfill/SIE import,
|
||||
* but new registry codes minted here stay portable. Duplicate codes within the
|
||||
* dimension return 409 DIMENSION_VALUE_DUPLICATE_CODE with a Swedish message.
|
||||
* `code` is immutable after creation (v1: no rename — retag instead).
|
||||
*/
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { CreateDimensionValueSchema } from '@/lib/api/schemas'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
export const POST = withRouteContext(
|
||||
'dimension.value.create',
|
||||
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
const opLog = log.child({ dimensionId: id })
|
||||
|
||||
const result = await validateBody(request, CreateDimensionValueSchema, {
|
||||
log: opLog,
|
||||
operation: 'dimension.value.create',
|
||||
})
|
||||
if (!result.success) return result.response
|
||||
const body = result.data
|
||||
|
||||
// The dimension must exist and belong to the active company (defense in
|
||||
// depth alongside the composite FK — a foreign dimension id 404s here).
|
||||
const { data: dimension, error: dimError } = await supabase
|
||||
.from('dimensions')
|
||||
.select('id, resets_annually')
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
|
||||
if (dimError) {
|
||||
opLog.error('dimension fetch failed', dimError)
|
||||
return errorResponse(dimError, opLog, { requestId })
|
||||
}
|
||||
if (!dimension) {
|
||||
return errorResponseFromCode('DIMENSION_NOT_FOUND', opLog, { requestId })
|
||||
}
|
||||
|
||||
// Value dates only make sense on accumulating dimensions (projekt-style
|
||||
// ranges). A resets-annually dimension (e.g. kostnadsställe) rejects any
|
||||
// request carrying an actual date (explicit null is a harmless no-op).
|
||||
if (dimension.resets_annually && (body.start_date != null || body.end_date != null)) {
|
||||
return errorResponseFromCode('DIMENSION_VALUE_DATES_NOT_ALLOWED', opLog, { requestId })
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('dimension_values')
|
||||
.insert({
|
||||
company_id: companyId,
|
||||
dimension_id: id,
|
||||
code: body.code,
|
||||
name: body.name,
|
||||
// Default true; is_active=false makes "create as archived" atomic
|
||||
// (no follow-up PATCH from the register UI).
|
||||
is_active: body.is_active ?? true,
|
||||
start_date: body.start_date ?? null,
|
||||
end_date: body.end_date ?? null,
|
||||
})
|
||||
.select('id, dimension_id, code, name, is_active, start_date, end_date')
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
if (error.code === '23505') {
|
||||
return errorResponseFromCode('DIMENSION_VALUE_DUPLICATE_CODE', opLog, {
|
||||
requestId,
|
||||
details: { code: body.code },
|
||||
})
|
||||
}
|
||||
opLog.error('dimension value insert failed', error)
|
||||
return errorResponseFromCode('DIMENSION_VALUE_CREATE_FAILED', opLog, {
|
||||
requestId,
|
||||
details: { reason: error.message },
|
||||
})
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* Tests for PATCH /api/dimensions/[id] (update dimension).
|
||||
*
|
||||
* Covers: 401, empty-body validation (400), 404, the is_system name-lock
|
||||
* ("Systemdimensioner kan inte döpas om" — 400 DIMENSION_SYSTEM_RENAME),
|
||||
* archiving a system dimension (allowed), and the happy rename of a custom
|
||||
* dimension.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
createQueuedMockSupabase,
|
||||
createMockRequest,
|
||||
createMockRouteParams,
|
||||
parseJsonResponse,
|
||||
} from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const requireWriteMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
import { PATCH } from '../[id]/route'
|
||||
|
||||
const params = () => createMockRouteParams({ id: 'dim-1' })
|
||||
|
||||
describe('PATCH /api/dimensions/[id]', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/dimensions/dim-1', {
|
||||
method: 'PATCH',
|
||||
body: { name: 'Avdelning' },
|
||||
})
|
||||
const response = await PATCH(request, params())
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('rejects an empty body with 400', async () => {
|
||||
const request = createMockRequest('/api/dimensions/dim-1', { method: 'PATCH', body: {} })
|
||||
const response = await PATCH(request, params())
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 when the dimension does not belong to the company', async () => {
|
||||
enqueue({ data: null }) // maybeSingle fetch
|
||||
|
||||
const request = createMockRequest('/api/dimensions/dim-1', {
|
||||
method: 'PATCH',
|
||||
body: { name: 'Avdelning' },
|
||||
})
|
||||
const response = await PATCH(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
|
||||
|
||||
expect(status).toBe(404)
|
||||
expect(body.error.code).toBe('DIMENSION_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('rejects renaming a system dimension with 400 DIMENSION_SYSTEM_RENAME', async () => {
|
||||
enqueue({ data: { id: 'dim-1', name: 'Kostnadsställe', is_system: true } })
|
||||
|
||||
const request = createMockRequest('/api/dimensions/dim-1', {
|
||||
method: 'PATCH',
|
||||
body: { name: 'Avdelning' },
|
||||
})
|
||||
const response = await PATCH(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string; message: string } }>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('DIMENSION_SYSTEM_RENAME')
|
||||
expect(body.error.message).toBe('Systemdimensioner kan inte döpas om.')
|
||||
})
|
||||
|
||||
it('allows archiving a system dimension (is_active only, no rename)', async () => {
|
||||
enqueue({ data: { id: 'dim-1', name: 'Kostnadsställe', is_system: true } })
|
||||
enqueue({
|
||||
data: {
|
||||
id: 'dim-1', sie_dim_no: 1, name: 'Kostnadsställe',
|
||||
resets_annually: true, is_system: true, is_active: false, sort_order: 10,
|
||||
},
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/dimensions/dim-1', {
|
||||
method: 'PATCH',
|
||||
body: { is_active: false },
|
||||
})
|
||||
const response = await PATCH(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ data: { is_active: boolean } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.is_active).toBe(false)
|
||||
})
|
||||
|
||||
it('renames a non-system dimension (happy path)', async () => {
|
||||
enqueue({ data: { id: 'dim-1', name: 'Dimension 7', is_system: false } })
|
||||
enqueue({
|
||||
data: {
|
||||
id: 'dim-1', sie_dim_no: 7, name: 'Avdelning',
|
||||
resets_annually: true, is_system: false, is_active: true, sort_order: 30,
|
||||
},
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/dimensions/dim-1', {
|
||||
method: 'PATCH',
|
||||
body: { name: 'Avdelning', sort_order: 30 },
|
||||
})
|
||||
const response = await PATCH(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ data: { name: string; sort_order: number } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.name).toBe('Avdelning')
|
||||
expect(body.data.sort_order).toBe(30)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,172 @@
|
||||
/**
|
||||
* Tests for POST /api/dimensions/import-existing (backfill scan).
|
||||
*
|
||||
* Covers: 401, the empty-company early exit, the happy path where codes
|
||||
* found on journal lines but missing from the registry are created as
|
||||
* inactive placeholder values ({ created: n }), code sanitization (PR1
|
||||
* backfill parity), and duplicate-tolerant upserts.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
import { POST } from '../import-existing/route'
|
||||
|
||||
const request = () => createMockRequest('/api/dimensions/import-existing', { method: 'POST' })
|
||||
const noParams = { params: Promise.resolve({}) }
|
||||
|
||||
describe('POST /api/dimensions/import-existing', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const response = await POST(request(), noParams)
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns { created: 0 } when no line carries dimensions', async () => {
|
||||
enqueue({ data: null }) // ensure RPC
|
||||
enqueue({ data: [] }) // journal_entry_lines scan
|
||||
|
||||
const response = await POST(request(), noParams)
|
||||
const { status, body } = await parseJsonResponse<{ created: number }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.created).toBe(0)
|
||||
})
|
||||
|
||||
it('creates inactive placeholder values for codes missing from the registry', async () => {
|
||||
enqueue({ data: null }) // ensure RPC
|
||||
// Lines: KS01 (dim 1) appears twice, P001 (dim 6) once, BUTIK already registered.
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'l1', dimensions: { '1': 'KS01' } },
|
||||
{ id: 'l2', dimensions: { '1': 'KS01', '6': 'P001' } },
|
||||
{ id: 'l3', dimensions: { '1': 'BUTIK' } },
|
||||
],
|
||||
})
|
||||
// Registry dims 1 & 6 exist (system dims).
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'dim-1', sie_dim_no: 1 },
|
||||
{ id: 'dim-6', sie_dim_no: 6 },
|
||||
],
|
||||
})
|
||||
// Existing values: BUTIK is already registered under dim 1.
|
||||
enqueue({ data: [{ dimension_id: 'dim-1', code: 'BUTIK' }] })
|
||||
// Upsert of the two missing values succeeds — created counts returned rows.
|
||||
enqueue({ data: [{ id: 'nv1' }, { id: 'nv2' }] })
|
||||
|
||||
const response = await POST(request(), noParams)
|
||||
const { status, body } = await parseJsonResponse<{ created: number }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.created).toBe(2) // KS01 + P001; BUTIK skipped (already registered)
|
||||
})
|
||||
|
||||
it('sanitizes candidate codes like the PR1 backfill and de-duplicates after sanitization', async () => {
|
||||
enqueue({ data: null }) // ensure RPC
|
||||
// 'KS"01"' and 'KS{01}' both sanitize to KS01 (one candidate); a 50-char
|
||||
// code is capped at 40; '"{}"' sanitizes to empty and is dropped entirely.
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'l1', dimensions: { '1': 'KS"01"' } },
|
||||
{ id: 'l2', dimensions: { '1': 'KS{01}' } },
|
||||
{ id: 'l3', dimensions: { '1': 'X'.repeat(50) } },
|
||||
{ id: 'l4', dimensions: { '1': '"{}"' } },
|
||||
],
|
||||
})
|
||||
enqueue({ data: [{ id: 'dim-1', sie_dim_no: 1 }] }) // registry dims
|
||||
enqueue({ data: [] }) // no existing values
|
||||
// Upsert returns the two surviving sanitized codes (KS01 + the capped one).
|
||||
enqueue({ data: [{ id: 'nv1' }, { id: 'nv2' }] })
|
||||
|
||||
const response = await POST(request(), noParams)
|
||||
const { status, body } = await parseJsonResponse<{ created: number }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.created).toBe(2)
|
||||
})
|
||||
|
||||
it('tolerates duplicates in the batch — created counts only the rows the upsert returned', async () => {
|
||||
enqueue({ data: null }) // ensure RPC
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'l1', dimensions: { '1': 'KS01' } },
|
||||
{ id: 'l2', dimensions: { '1': 'KS02' } },
|
||||
],
|
||||
})
|
||||
enqueue({ data: [{ id: 'dim-1', sie_dim_no: 1 }] }) // registry dims
|
||||
enqueue({ data: [] }) // existing-values snapshot missed a raced KS02
|
||||
// ignoreDuplicates upsert skips the conflicting row instead of aborting
|
||||
// the batch — only KS01 comes back.
|
||||
enqueue({ data: [{ id: 'nv1' }] })
|
||||
|
||||
const response = await POST(request(), noParams)
|
||||
const { status, body } = await parseJsonResponse<{ created: number }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.created).toBe(1)
|
||||
})
|
||||
|
||||
it('creates a registry dimension for an unregistered dim number found on lines', async () => {
|
||||
enqueue({ data: null }) // ensure RPC
|
||||
enqueue({ data: [{ id: 'l1', dimensions: { '7': 'AVD-A' } }] }) // lines
|
||||
// Registry only has the system dims — dim 7 is missing.
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'dim-1', sie_dim_no: 1 },
|
||||
{ id: 'dim-6', sie_dim_no: 6 },
|
||||
],
|
||||
})
|
||||
// Upsert of the missing dimension row returns its id.
|
||||
enqueue({ data: [{ id: 'dim-7', sie_dim_no: 7 }] })
|
||||
// No existing values.
|
||||
enqueue({ data: [] })
|
||||
// Value upsert succeeds.
|
||||
enqueue({ data: [{ id: 'nv1' }] })
|
||||
|
||||
const response = await POST(request(), noParams)
|
||||
const { status, body } = await parseJsonResponse<{ created: number }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.created).toBe(1)
|
||||
})
|
||||
|
||||
it('returns 500 DIMENSION_IMPORT_FAILED when the scan blows up', async () => {
|
||||
enqueue({ data: null }) // ensure RPC
|
||||
enqueue({ error: { message: 'relation missing' } }) // fetchAllRows throws
|
||||
|
||||
const response = await POST(request(), noParams)
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
|
||||
|
||||
expect(status).toBe(500)
|
||||
expect(body.error.code).toBe('DIMENSION_IMPORT_FAILED')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* Tests for GET /api/dimensions (dimension registry list).
|
||||
*
|
||||
* Exercises the route through the real withRouteContext wrapper, mocking only
|
||||
* its auth/company dependencies and injecting a queued Supabase mock via
|
||||
* requireAuth. Covers: 401, the ensure-RPC failure path, and the contract
|
||||
* shape ({ dimensions: [...] } with values nested per dimension).
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
import { GET } from '../route'
|
||||
|
||||
interface DimensionsBody {
|
||||
dimensions: Array<{
|
||||
id: string
|
||||
sie_dim_no: number
|
||||
name: string
|
||||
resets_annually: boolean
|
||||
is_system: boolean
|
||||
is_active: boolean
|
||||
sort_order: number
|
||||
values: Array<{
|
||||
id: string
|
||||
code: string
|
||||
name: string
|
||||
is_active: boolean
|
||||
start_date: string | null
|
||||
end_date: string | null
|
||||
}>
|
||||
}>
|
||||
}
|
||||
|
||||
describe('GET /api/dimensions', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const response = await GET(createMockRequest('/api/dimensions'), { params: Promise.resolve({}) })
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('ensures system dims exist, then returns dimensions with nested values', async () => {
|
||||
// 1st DB hit: ensure_company_dimensions RPC.
|
||||
enqueue({ data: null })
|
||||
// 2nd: dimensions list (sorted by sort_order server-side).
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'dim-1', sie_dim_no: 1, name: 'Kostnadsställe', resets_annually: true, is_system: true, is_active: true, sort_order: 10 },
|
||||
{ id: 'dim-6', sie_dim_no: 6, name: 'Projekt', resets_annually: false, is_system: true, is_active: true, sort_order: 20 },
|
||||
],
|
||||
})
|
||||
// 3rd: dimension_values list (sorted by code server-side).
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'v1', dimension_id: 'dim-1', code: 'BUTIK', name: 'Butiken', is_active: true, start_date: null, end_date: null },
|
||||
{ id: 'v2', dimension_id: 'dim-6', code: 'P001', name: 'Projekt Björk', is_active: false, start_date: '2026-01-01', end_date: '2026-06-30' },
|
||||
],
|
||||
})
|
||||
|
||||
const response = await GET(createMockRequest('/api/dimensions'), { params: Promise.resolve({}) })
|
||||
const { status, body } = await parseJsonResponse<DimensionsBody>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(supabase.rpc).toHaveBeenCalledWith('ensure_company_dimensions', {
|
||||
p_company_id: 'company-1',
|
||||
})
|
||||
expect(body.dimensions).toHaveLength(2)
|
||||
expect(body.dimensions[0]).toMatchObject({
|
||||
id: 'dim-1',
|
||||
sie_dim_no: 1,
|
||||
name: 'Kostnadsställe',
|
||||
resets_annually: true,
|
||||
is_system: true,
|
||||
values: [
|
||||
{ id: 'v1', code: 'BUTIK', name: 'Butiken', is_active: true, start_date: null, end_date: null },
|
||||
],
|
||||
})
|
||||
expect(body.dimensions[1].values).toEqual([
|
||||
{ id: 'v2', code: 'P001', name: 'Projekt Björk', is_active: false, start_date: '2026-01-01', end_date: '2026-06-30' },
|
||||
])
|
||||
})
|
||||
|
||||
it('returns a dimension with an empty values array when it has no values', async () => {
|
||||
enqueue({ data: null }) // ensure RPC
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'dim-1', sie_dim_no: 1, name: 'Kostnadsställe', resets_annually: true, is_system: true, is_active: true, sort_order: 10 },
|
||||
],
|
||||
})
|
||||
enqueue({ data: [] })
|
||||
|
||||
const response = await GET(createMockRequest('/api/dimensions'), { params: Promise.resolve({}) })
|
||||
const { status, body } = await parseJsonResponse<DimensionsBody>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.dimensions[0].values).toEqual([])
|
||||
})
|
||||
|
||||
it('returns 500 when the ensure RPC fails', async () => {
|
||||
enqueue({ error: { code: 'XX000', message: 'boom' } })
|
||||
|
||||
const response = await GET(createMockRequest('/api/dimensions'), { params: Promise.resolve({}) })
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
|
||||
|
||||
expect(status).toBe(500)
|
||||
expect(body.error.code).toBeTruthy()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,195 @@
|
||||
/**
|
||||
* Tests for PATCH/DELETE /api/dimensions/[id]/values/[valueId].
|
||||
*
|
||||
* The DELETE suite pins the retention-trigger contract: a P0001 raise from
|
||||
* enforce_dimension_value_retention surfaces as 409 DIMENSION_VALUE_REFERENCED
|
||||
* with the trigger's own Swedish message ("…arkivera det istället") so the UI
|
||||
* can toast it verbatim.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
createQueuedMockSupabase,
|
||||
createMockRequest,
|
||||
createMockRouteParams,
|
||||
parseJsonResponse,
|
||||
} from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
import { PATCH, DELETE } from '../[id]/values/[valueId]/route'
|
||||
|
||||
const params = () => createMockRouteParams({ id: 'dim-1', valueId: 'v1' })
|
||||
const URL_PATH = '/api/dimensions/dim-1/values/v1'
|
||||
|
||||
describe('PATCH /api/dimensions/[id]/values/[valueId]', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const request = createMockRequest(URL_PATH, { method: 'PATCH', body: { name: 'Nytt namn' } })
|
||||
const response = await PATCH(request, params())
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('rejects an empty body with 400', async () => {
|
||||
const request = createMockRequest(URL_PATH, { method: 'PATCH', body: {} })
|
||||
const response = await PATCH(request, params())
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 when the value does not exist in the company', async () => {
|
||||
enqueue({ error: { code: 'PGRST116', message: 'No rows found' } })
|
||||
|
||||
const request = createMockRequest(URL_PATH, { method: 'PATCH', body: { name: 'Nytt namn' } })
|
||||
const response = await PATCH(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
|
||||
|
||||
expect(status).toBe(404)
|
||||
expect(body.error.code).toBe('DIMENSION_VALUE_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('archives a value via is_active=false (happy path)', async () => {
|
||||
// The request carries end_date, so the route first checks the parent
|
||||
// dimension's resets_annually flag (accumulating → dates allowed).
|
||||
enqueue({ data: { id: 'dim-1', resets_annually: false } })
|
||||
enqueue({
|
||||
data: {
|
||||
id: 'v1', dimension_id: 'dim-1', code: 'BUTIK', name: 'Butiken',
|
||||
is_active: false, start_date: null, end_date: '2026-06-30',
|
||||
},
|
||||
})
|
||||
|
||||
const request = createMockRequest(URL_PATH, {
|
||||
method: 'PATCH',
|
||||
body: { is_active: false, end_date: '2026-06-30' },
|
||||
})
|
||||
const response = await PATCH(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ data: { is_active: boolean; code: string } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.is_active).toBe(false)
|
||||
// Code untouched — immutable in v1.
|
||||
expect(body.data.code).toBe('BUTIK')
|
||||
})
|
||||
|
||||
it('rejects start/end dates on a resets-annually dimension with 400', async () => {
|
||||
enqueue({ data: { id: 'dim-1', resets_annually: true } })
|
||||
|
||||
const request = createMockRequest(URL_PATH, {
|
||||
method: 'PATCH',
|
||||
body: { start_date: '2026-01-01' },
|
||||
})
|
||||
const response = await PATCH(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string; message: string } }>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('DIMENSION_VALUE_DATES_NOT_ALLOWED')
|
||||
expect(body.error.message).toBe(
|
||||
'Datum kan bara sättas på ackumulerande dimensioner (t.ex. projekt).',
|
||||
)
|
||||
})
|
||||
|
||||
it('allows clearing dates (explicit null) without checking the dimension', async () => {
|
||||
// start_date: null clears the field — a harmless no-op on any dimension,
|
||||
// so the route must not spend a dimension fetch on it. The single queued
|
||||
// result feeds the update itself.
|
||||
enqueue({
|
||||
data: {
|
||||
id: 'v1', dimension_id: 'dim-1', code: 'BUTIK', name: 'Butiken',
|
||||
is_active: true, start_date: null, end_date: null,
|
||||
},
|
||||
})
|
||||
|
||||
const request = createMockRequest(URL_PATH, {
|
||||
method: 'PATCH',
|
||||
body: { start_date: null, end_date: null },
|
||||
})
|
||||
const response = await PATCH(request, params())
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /api/dimensions/[id]/values/[valueId]', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const request = createMockRequest(URL_PATH, { method: 'DELETE' })
|
||||
const response = await DELETE(request, params())
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('surfaces the retention trigger as 409 with the trigger\'s Swedish message', async () => {
|
||||
const triggerMessage =
|
||||
'Värdet "BUTIK" används på bokförda verifikat och kan inte tas bort — arkivera det istället.'
|
||||
enqueue({ error: { code: 'P0001', message: triggerMessage } })
|
||||
|
||||
const request = createMockRequest(URL_PATH, { method: 'DELETE' })
|
||||
const response = await DELETE(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string; message: string } }>(response)
|
||||
|
||||
expect(status).toBe(409)
|
||||
expect(body.error.code).toBe('DIMENSION_VALUE_REFERENCED')
|
||||
// The trigger's message (naming the code) is surfaced verbatim for the toast.
|
||||
expect(body.error.message).toBe(triggerMessage)
|
||||
expect(body.error.message).toContain('arkivera det istället')
|
||||
})
|
||||
|
||||
it('returns 404 when nothing was deleted', async () => {
|
||||
enqueue({ data: [] })
|
||||
|
||||
const request = createMockRequest(URL_PATH, { method: 'DELETE' })
|
||||
const response = await DELETE(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
|
||||
|
||||
expect(status).toBe(404)
|
||||
expect(body.error.code).toBe('DIMENSION_VALUE_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('deletes an unreferenced value (happy path)', async () => {
|
||||
enqueue({ data: [{ id: 'v1' }] })
|
||||
|
||||
const request = createMockRequest(URL_PATH, { method: 'DELETE' })
|
||||
const response = await DELETE(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ success: boolean }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.success).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* Tests for POST /api/dimensions/[id]/values (create dimension value).
|
||||
*
|
||||
* Covers: 401, the strict Fortnox code format (400), 404 on a foreign
|
||||
* dimension, the duplicate-code conflict (409 with Swedish message), the
|
||||
* dates-on-resets-annually rejection (400), atomic create-as-archived
|
||||
* (is_active=false), and the happy path.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
createQueuedMockSupabase,
|
||||
createMockRequest,
|
||||
createMockRouteParams,
|
||||
parseJsonResponse,
|
||||
} from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
import { POST } from '../[id]/values/route'
|
||||
|
||||
const params = () => createMockRouteParams({ id: 'dim-1' })
|
||||
|
||||
describe('POST /api/dimensions/[id]/values', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/dimensions/dim-1/values', {
|
||||
method: 'POST',
|
||||
body: { code: 'P001', name: 'Projekt Björk' },
|
||||
})
|
||||
const response = await POST(request, params())
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['space in code', 'P 001'],
|
||||
['too long (>20 chars)', 'A'.repeat(21)],
|
||||
['SIE-breaking char', 'P{1}'],
|
||||
])('rejects an invalid code (%s) with 400', async (_label, code) => {
|
||||
const request = createMockRequest('/api/dimensions/dim-1/values', {
|
||||
method: 'POST',
|
||||
body: { code, name: 'Projekt' },
|
||||
})
|
||||
const response = await POST(request, params())
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('rejects end_date before start_date with 400', async () => {
|
||||
const request = createMockRequest('/api/dimensions/dim-1/values', {
|
||||
method: 'POST',
|
||||
body: { code: 'P001', name: 'Projekt', start_date: '2026-06-01', end_date: '2026-01-01' },
|
||||
})
|
||||
const response = await POST(request, params())
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 when the dimension does not belong to the company', async () => {
|
||||
enqueue({ data: null }) // dimension maybeSingle
|
||||
|
||||
const request = createMockRequest('/api/dimensions/dim-1/values', {
|
||||
method: 'POST',
|
||||
body: { code: 'P001', name: 'Projekt Björk' },
|
||||
})
|
||||
const response = await POST(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
|
||||
|
||||
expect(status).toBe(404)
|
||||
expect(body.error.code).toBe('DIMENSION_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('rejects start/end dates on a resets-annually dimension with 400', async () => {
|
||||
// Kostnadsställe-style dims reset annually — value date ranges are only
|
||||
// meaningful on accumulating dims (projekt).
|
||||
enqueue({ data: { id: 'dim-1', resets_annually: true } })
|
||||
|
||||
const request = createMockRequest('/api/dimensions/dim-1/values', {
|
||||
method: 'POST',
|
||||
body: { code: 'KS01', name: 'Kontoret', start_date: '2026-01-01' },
|
||||
})
|
||||
const response = await POST(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string; message: string } }>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('DIMENSION_VALUE_DATES_NOT_ALLOWED')
|
||||
expect(body.error.message).toBe(
|
||||
'Datum kan bara sättas på ackumulerande dimensioner (t.ex. projekt).',
|
||||
)
|
||||
})
|
||||
|
||||
it('creates a value as archived when is_active=false (atomic, no follow-up PATCH)', async () => {
|
||||
enqueue({ data: { id: 'dim-1', resets_annually: false } })
|
||||
enqueue({
|
||||
data: {
|
||||
id: 'v2', dimension_id: 'dim-1', code: 'NEDLAGD', name: 'Nedlagd avdelning',
|
||||
is_active: false, start_date: null, end_date: null,
|
||||
},
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/dimensions/dim-1/values', {
|
||||
method: 'POST',
|
||||
body: { code: 'NEDLAGD', name: 'Nedlagd avdelning', is_active: false },
|
||||
})
|
||||
const response = await POST(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ data: { id: string; is_active: boolean } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.id).toBe('v2')
|
||||
expect(body.data.is_active).toBe(false)
|
||||
})
|
||||
|
||||
it('returns 409 with a Swedish message on a duplicate code', async () => {
|
||||
enqueue({ data: { id: 'dim-1' } })
|
||||
enqueue({ error: { code: '23505', message: 'duplicate key value' } })
|
||||
|
||||
const request = createMockRequest('/api/dimensions/dim-1/values', {
|
||||
method: 'POST',
|
||||
body: { code: 'P001', name: 'Projekt Björk' },
|
||||
})
|
||||
const response = await POST(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string; message: string } }>(response)
|
||||
|
||||
expect(status).toBe(409)
|
||||
expect(body.error.code).toBe('DIMENSION_VALUE_DUPLICATE_CODE')
|
||||
expect(body.error.message).toBe('Ett värde med samma kod finns redan i dimensionen.')
|
||||
})
|
||||
|
||||
it('creates a value (happy path, Swedish chars allowed in code)', async () => {
|
||||
enqueue({ data: { id: 'dim-1' } })
|
||||
enqueue({
|
||||
data: {
|
||||
id: 'v1', dimension_id: 'dim-1', code: 'GÖTEBORG', name: 'Göteborgskontoret',
|
||||
is_active: true, start_date: null, end_date: null,
|
||||
},
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/dimensions/dim-1/values', {
|
||||
method: 'POST',
|
||||
body: { code: 'GÖTEBORG', name: 'Göteborgskontoret' },
|
||||
})
|
||||
const response = await POST(request, params())
|
||||
const { status, body } = await parseJsonResponse<{ data: { id: string; code: string } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.id).toBe('v1')
|
||||
expect(body.data.code).toBe('GÖTEBORG')
|
||||
})
|
||||
})
|
||||
Binary file not shown.
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* GET /api/dimensions — the dimension registry (kostnadsställe/projekt + custom
|
||||
* dims) with nested values, for the register page and pickers.
|
||||
*
|
||||
* Calls ensure_company_dimensions first so the system dims (1 = Kostnadsställe,
|
||||
* 6 = Projekt) always exist — lazy seeding keeps core zero-config for companies
|
||||
* that never touch dimensions (dev_docs/dimensions_implementation_plan.md §6).
|
||||
*
|
||||
* Response contract (PR2 — the register UI builds against this exactly):
|
||||
* 200 { dimensions: [{ id, sie_dim_no, name, resets_annually, is_system,
|
||||
* is_active, sort_order, values: [{ id, code, name, is_active,
|
||||
* start_date, end_date }] }] }
|
||||
* Dimensions sorted by sort_order, values by code.
|
||||
*/
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse } from '@/lib/errors/get-structured-error'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
interface DimensionValueRow {
|
||||
id: string
|
||||
dimension_id: string
|
||||
code: string
|
||||
name: string
|
||||
is_active: boolean
|
||||
start_date: string | null
|
||||
end_date: string | null
|
||||
}
|
||||
|
||||
interface DimensionRow {
|
||||
id: string
|
||||
sie_dim_no: number
|
||||
name: string
|
||||
resets_annually: boolean
|
||||
is_system: boolean
|
||||
is_active: boolean
|
||||
sort_order: number
|
||||
}
|
||||
|
||||
export const GET = withRouteContext(
|
||||
'dimension.list',
|
||||
async (_request, ctx) => {
|
||||
// dimensions_enabled is deliberately NOT enforced here — it is a
|
||||
// UI-visibility flag only (dev_docs/dimensions_implementation_plan.md §2).
|
||||
// Agents/MCP and SIE import must operate on the registry regardless of the
|
||||
// toggle; the security boundary is company scoping (withRouteContext + RLS).
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
|
||||
const { error: ensureError } = await supabase.rpc('ensure_company_dimensions', {
|
||||
p_company_id: companyId,
|
||||
})
|
||||
if (ensureError) {
|
||||
log.error('ensure_company_dimensions failed', ensureError)
|
||||
return errorResponse(ensureError, log, { requestId })
|
||||
}
|
||||
|
||||
const { data: dims, error: dimsError } = await supabase
|
||||
.from('dimensions')
|
||||
.select('id, sie_dim_no, name, resets_annually, is_system, is_active, sort_order')
|
||||
.eq('company_id', companyId)
|
||||
.order('sort_order', { ascending: true })
|
||||
.order('sie_dim_no', { ascending: true })
|
||||
|
||||
if (dimsError) {
|
||||
log.error('dimension list failed', dimsError)
|
||||
return errorResponse(dimsError, log, { requestId })
|
||||
}
|
||||
|
||||
const { data: values, error: valuesError } = await supabase
|
||||
.from('dimension_values')
|
||||
.select('id, dimension_id, code, name, is_active, start_date, end_date')
|
||||
.eq('company_id', companyId)
|
||||
.order('code', { ascending: true })
|
||||
|
||||
if (valuesError) {
|
||||
log.error('dimension value list failed', valuesError)
|
||||
return errorResponse(valuesError, log, { 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 DimensionRow[]).map((d) => ({
|
||||
...d,
|
||||
values: valuesByDimension.get(d.id) ?? [],
|
||||
}))
|
||||
|
||||
return NextResponse.json({ dimensions })
|
||||
},
|
||||
)
|
||||
@@ -7,6 +7,7 @@ import { createLogger } from '@/lib/logger'
|
||||
import { checkRateLimit } from '@/lib/auth/rate-limit-http'
|
||||
import { truncateIp } from '@/lib/api/v1/with-api-v1'
|
||||
import { ensureSandboxAgentProfile } from '@/lib/sandbox/ensure-agent'
|
||||
import { lineDimensionColumns } from '@/lib/bookkeeping/dimension-resolver'
|
||||
|
||||
// Anonymous sign-in is enabled in all environments so visitors can try the
|
||||
// product; a per-/24 cap on the seed endpoint keeps a single network from
|
||||
@@ -146,6 +147,8 @@ export async function POST(request: Request) {
|
||||
onboarding_step: 6,
|
||||
onboarding_complete: true,
|
||||
is_sandbox: true,
|
||||
// Dimensions demo — the register/pickers render out of the box.
|
||||
dimensions_enabled: true,
|
||||
})
|
||||
|
||||
if (settingsError) throw settingsError
|
||||
@@ -157,6 +160,39 @@ export async function POST(request: Request) {
|
||||
})
|
||||
if (coaError) throw coaError
|
||||
|
||||
// 3b. Seed demo dimensions (kostnadsställe/projekt). ensure_company_dimensions
|
||||
// lazily creates the system dims 1/6; two values per dim give the register,
|
||||
// pickers, and the dimension-tagged journal lines below something to show.
|
||||
const { error: dimsRpcError } = await supabase.rpc('ensure_company_dimensions', {
|
||||
p_company_id: companyId,
|
||||
})
|
||||
if (dimsRpcError) throw dimsRpcError
|
||||
|
||||
const { data: demoDims, error: demoDimsError } = await supabase
|
||||
.from('dimensions')
|
||||
.select('id, sie_dim_no')
|
||||
.eq('company_id', companyId)
|
||||
.in('sie_dim_no', [1, 6])
|
||||
if (demoDimsError) throw demoDimsError
|
||||
|
||||
const dimIdByNo = Object.fromEntries(
|
||||
(demoDims ?? []).map(d => [d.sie_dim_no as number, d.id as string])
|
||||
) as Record<number, string>
|
||||
|
||||
if (dimIdByNo[1] && dimIdByNo[6]) {
|
||||
const seededDimensionCodes = ['BUTIK', 'WEBB', 'P001', 'P002']
|
||||
const { error: dimValuesError } = await supabase
|
||||
.from('dimension_values')
|
||||
.insert([
|
||||
{ company_id: companyId, dimension_id: dimIdByNo[1], code: 'BUTIK', name: 'Butiken' },
|
||||
{ company_id: companyId, dimension_id: dimIdByNo[1], code: 'WEBB', name: 'Webbshoppen' },
|
||||
{ company_id: companyId, dimension_id: dimIdByNo[6], code: 'P001', name: 'Projekt Björk' },
|
||||
{ company_id: companyId, dimension_id: dimIdByNo[6], code: 'P002', name: 'Projekt Alm' },
|
||||
])
|
||||
if (dimValuesError) throw dimValuesError
|
||||
log.info('seeded sandbox dimension values', { companyId, codes: seededDimensionCodes })
|
||||
}
|
||||
|
||||
// 4. Create fiscal period (current year)
|
||||
const currentYear = new Date().getFullYear()
|
||||
const { data: fiscalPeriod, error: fpError } = await supabase
|
||||
@@ -424,11 +460,20 @@ export async function POST(request: Request) {
|
||||
|
||||
if (je2Error) throw je2Error
|
||||
|
||||
// 10. Create journal entry lines
|
||||
// 10. Create journal entry lines. The P&L line carries demo dimensions
|
||||
// ({"1":"BUTIK","6":"P001"}) so the register's "antal taggade rader",
|
||||
// voucher-detail badges, and the dimension P&L report light up in the
|
||||
// sandbox. Mirror columns derived via lineDimensionColumns — never set
|
||||
// independently of the dimensions map.
|
||||
const revenueDims = { '1': 'BUTIK', '6': 'P001' }
|
||||
const { error: jelError } = await supabase
|
||||
.from('journal_entry_lines')
|
||||
.insert([
|
||||
// JE1: Invoice creation — Debit AR, Credit Revenue + VAT
|
||||
// NB: `dimensions` must be set explicitly on EVERY row — same PostgREST
|
||||
// bulk-insert normalization as paid_amount below: omitting it on some
|
||||
// rows while one row sets it sends null (violating NOT NULL) instead
|
||||
// of falling through to the schema default '{}'.
|
||||
{
|
||||
journal_entry_id: je1.id,
|
||||
account_number: '1510',
|
||||
@@ -436,6 +481,7 @@ export async function POST(request: Request) {
|
||||
debit_amount: 18750,
|
||||
credit_amount: 0,
|
||||
sort_order: 0,
|
||||
dimensions: {},
|
||||
},
|
||||
{
|
||||
journal_entry_id: je1.id,
|
||||
@@ -444,6 +490,8 @@ export async function POST(request: Request) {
|
||||
debit_amount: 0,
|
||||
credit_amount: 15000,
|
||||
sort_order: 1,
|
||||
dimensions: revenueDims,
|
||||
...lineDimensionColumns(revenueDims),
|
||||
},
|
||||
{
|
||||
journal_entry_id: je1.id,
|
||||
@@ -452,6 +500,7 @@ export async function POST(request: Request) {
|
||||
debit_amount: 0,
|
||||
credit_amount: 3750,
|
||||
sort_order: 2,
|
||||
dimensions: {},
|
||||
},
|
||||
// JE2: Invoice payment — Debit Bank, Credit AR
|
||||
{
|
||||
@@ -461,6 +510,7 @@ export async function POST(request: Request) {
|
||||
debit_amount: 18750,
|
||||
credit_amount: 0,
|
||||
sort_order: 0,
|
||||
dimensions: {},
|
||||
},
|
||||
{
|
||||
journal_entry_id: je2.id,
|
||||
@@ -469,6 +519,7 @@ export async function POST(request: Request) {
|
||||
debit_amount: 0,
|
||||
credit_amount: 18750,
|
||||
sort_order: 1,
|
||||
dimensions: {},
|
||||
},
|
||||
])
|
||||
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* 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 } from '@/lib/api/v1/errors'
|
||||
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.' },
|
||||
})
|
||||
}
|
||||
|
||||
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 = CreateDimensionValueSchema.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
|
||||
|
||||
// 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 },
|
||||
)
|
||||
@@ -0,0 +1,327 @@
|
||||
/**
|
||||
* 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')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* 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 })
|
||||
},
|
||||
)
|
||||
Reference in New Issue
Block a user