8bb49c07a2
* 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>
124 lines
4.2 KiB
TypeScript
124 lines
4.2 KiB
TypeScript
'use client'
|
|
|
|
import { useState } from 'react'
|
|
import Link from 'next/link'
|
|
import { useLocale, useTranslations } from 'next-intl'
|
|
import { ExternalLink } from 'lucide-react'
|
|
import { Switch } from '@/components/ui/switch'
|
|
import { Label } from '@/components/ui/label'
|
|
import { useToast } from '@/components/ui/use-toast'
|
|
import { useSettings } from '@/components/settings/useSettings'
|
|
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
|
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
|
|
|
/**
|
|
* Company-level toggle for the dimensions register (kostnadsställen &
|
|
* projekt). Persists company_settings.dimensions_enabled through the standard
|
|
* settings PUT — the flag gates UI visibility only (nav row + register),
|
|
* never correctness (dimensions plan §2).
|
|
*
|
|
* Toggling ON runs the "Importera befintliga koder" scan
|
|
* (POST /api/dimensions/import-existing): codes already present on
|
|
* journal_entry_lines.dimensions but missing from the registry are created as
|
|
* archived placeholder values, and the user is told how many were found.
|
|
*/
|
|
export function DimensionsToggle() {
|
|
const t = useTranslations('dimensions')
|
|
const errorLocale = useLocale() as ErrorLocale
|
|
const { settings, updateSettings } = useSettings()
|
|
const { canWrite } = useCanWrite()
|
|
const { toast } = useToast()
|
|
const [isSaving, setIsSaving] = useState(false)
|
|
|
|
const enabled = settings?.dimensions_enabled ?? false
|
|
|
|
async function handleChange(next: boolean) {
|
|
setIsSaving(true)
|
|
try {
|
|
const res = await fetch('/api/settings', {
|
|
method: 'PUT',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ dimensions_enabled: next }),
|
|
})
|
|
const json = await res.json().catch(() => null)
|
|
if (!res.ok) {
|
|
toast({
|
|
title: t('settings_save_failed_title'),
|
|
description: getErrorMessage(json, { locale: errorLocale }),
|
|
variant: 'destructive',
|
|
})
|
|
return
|
|
}
|
|
updateSettings({ dimensions_enabled: next })
|
|
|
|
if (next) {
|
|
// Import scan: registry rows for codes already used on lines. Failure
|
|
// is non-fatal — the toggle stays on and the scan can be re-run by
|
|
// toggling again.
|
|
try {
|
|
const importRes = await fetch('/api/dimensions/import-existing', {
|
|
method: 'POST',
|
|
})
|
|
const importJson = await importRes.json().catch(() => null)
|
|
if (importRes.ok) {
|
|
const created: number =
|
|
importJson?.created ?? importJson?.data?.created ?? 0
|
|
if (created > 0) {
|
|
toast({
|
|
title: t('settings_imported_toast_title'),
|
|
description: t('settings_imported_toast', { count: created }),
|
|
})
|
|
}
|
|
} else {
|
|
toast({
|
|
title: t('settings_import_failed_title'),
|
|
description: getErrorMessage(importJson, { locale: errorLocale }),
|
|
variant: 'destructive',
|
|
})
|
|
}
|
|
} catch {
|
|
toast({
|
|
title: t('settings_import_failed_title'),
|
|
variant: 'destructive',
|
|
})
|
|
}
|
|
}
|
|
} finally {
|
|
setIsSaving(false)
|
|
}
|
|
}
|
|
|
|
return (
|
|
<section className="space-y-4">
|
|
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
|
{t('settings_heading')}
|
|
</h2>
|
|
<div className="flex items-start justify-between gap-4">
|
|
<div className="space-y-1">
|
|
<Label htmlFor="dimensions-enabled" className="text-sm">
|
|
{t('settings_toggle_label')}
|
|
</Label>
|
|
<p className="text-xs text-muted-foreground max-w-md">
|
|
{t('settings_toggle_help')}
|
|
</p>
|
|
</div>
|
|
<Switch
|
|
id="dimensions-enabled"
|
|
checked={enabled}
|
|
onCheckedChange={(next) => void handleChange(next)}
|
|
disabled={isSaving || !canWrite}
|
|
/>
|
|
</div>
|
|
{enabled && (
|
|
<Link
|
|
href="/dimensions"
|
|
className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors"
|
|
>
|
|
<ExternalLink className="h-3.5 w-3.5" />
|
|
{t('settings_open_register')}
|
|
</Link>
|
|
)}
|
|
</section>
|
|
)
|
|
}
|