Files
accounted/app/api/dimensions/__tests__/values.test.ts
T
Jakob Wennberg 8bb49c07a2 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>
2026-07-02 12:26:42 +02:00

176 lines
6.1 KiB
TypeScript

/**
* 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')
})
})