* 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>
92 lines
3.4 KiB
TypeScript
92 lines
3.4 KiB
TypeScript
/**
|
|
* 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 },
|
|
)
|