fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,370 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
|
||||
import { Loader2, Plus } from 'lucide-react'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import {
|
||||
DIMENSION_CODE_PATTERN,
|
||||
type DimensionValueDto,
|
||||
} from '@/components/dimensions/types'
|
||||
import { useDimensions } from '@/lib/reference-data/hooks'
|
||||
import { invalidateReferenceData } from '@/lib/reference-data/invalidate'
|
||||
|
||||
interface DimensionComboboxProps {
|
||||
/** SIE dimension number as a string ('1' = kostnadsställe, '6' = projekt). */
|
||||
sieDimNo: string
|
||||
/** Selected object code, or null when the line carries no value for this dim. */
|
||||
value: string | null
|
||||
onChange: (code: string | null) => void
|
||||
disabled?: boolean
|
||||
/** Extra classes merged into the trigger Input (callers pass `h-8` for dense rows). */
|
||||
className?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Searchable picker for dimension values: sibling of
|
||||
* components/bookkeeping/AccountCombobox.tsx and deliberately mirrors its
|
||||
* interaction model: plain Input trigger, keyboard-first dropdown
|
||||
* (arrows/Enter/Escape), close-on-outside-click, and an inline "Skapa ny…"
|
||||
* affordance that creates the value via POST /api/dimensions/[id]/values and
|
||||
* selects it.
|
||||
*
|
||||
* Fetches the registry lazily on first open and filters client-side (value
|
||||
* lists are small). Only active values are offered: archived codes stay
|
||||
* pickable in history but are never suggested.
|
||||
*
|
||||
* Strings are hardcoded Swedish per the AccountCombobox convention: the
|
||||
* component mounts on the voucher editor (PR3), a stays-Swedish surface per
|
||||
* .claude/rules/i18n.md.
|
||||
*/
|
||||
export default function DimensionCombobox({
|
||||
sieDimNo,
|
||||
value,
|
||||
onChange,
|
||||
disabled,
|
||||
className,
|
||||
}: DimensionComboboxProps) {
|
||||
const [search, setSearch] = useState(value ?? '')
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const [highlightedIndex, setHighlightedIndex] = useState(0)
|
||||
// Registry from the session cache (lib/reference-data): every combobox on
|
||||
// the page shares one entry, so opening a picker costs no request.
|
||||
const { dimensions, isLoading: registryLoading, error: registryError } = useDimensions()
|
||||
const loadState: 'loading' | 'loaded' | 'error' = registryLoading
|
||||
? 'loading'
|
||||
: registryError
|
||||
? 'error'
|
||||
: 'loaded'
|
||||
const dimension = useMemo(
|
||||
() => dimensions.find((d) => String(d.sie_dim_no) === sieDimNo) ?? null,
|
||||
[dimensions, sieDimNo],
|
||||
)
|
||||
const dimensionId = dimension?.id ?? null
|
||||
const values = useMemo(
|
||||
() => dimension?.values.filter((v) => v.is_active) ?? [],
|
||||
[dimension],
|
||||
)
|
||||
// The committed value's registry row, looked up in the FULL list: an
|
||||
// archived code stays readable in history even though it is never offered.
|
||||
const selected = useMemo(
|
||||
() => (value ? dimension?.values.find((v) => v.code === value) ?? null : null),
|
||||
[dimension, value],
|
||||
)
|
||||
const selectedNameId = useId()
|
||||
const [isCreating, setIsCreating] = useState(false)
|
||||
const [createError, setCreateError] = useState<string | null>(null)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
// Refs mirroring the committed `value` prop and the fetched values. The
|
||||
// blur timeout below runs 150ms after render, so reading `value`/`values`
|
||||
// directly would act on a stale snapshot: a selection landing during that
|
||||
// window (updating the prop via onChange) must win over the revert.
|
||||
const committedRef = useRef(value)
|
||||
const valuesRef = useRef(values)
|
||||
|
||||
// Sync external value changes into the search field
|
||||
useEffect(() => {
|
||||
committedRef.current = value
|
||||
setSearch(value ?? '')
|
||||
}, [value])
|
||||
|
||||
useEffect(() => {
|
||||
valuesRef.current = values
|
||||
}, [values])
|
||||
|
||||
const openDropdown = useCallback(() => {
|
||||
setIsOpen(true)
|
||||
setCreateError(null)
|
||||
}, [])
|
||||
|
||||
const filteredValues = useMemo(() => {
|
||||
const term = search.trim().toLowerCase()
|
||||
if (!term) return values
|
||||
return values.filter(
|
||||
(v) =>
|
||||
v.code.toLowerCase().includes(term) || v.name.toLowerCase().includes(term),
|
||||
)
|
||||
}, [values, search])
|
||||
|
||||
// Inline create is offered when the typed text is a valid new code.
|
||||
const createCandidate = useMemo(() => {
|
||||
const term = search.trim()
|
||||
if (!term || !dimensionId) return null
|
||||
if (!DIMENSION_CODE_PATTERN.test(term)) return null
|
||||
if (values.some((v) => v.code.toLowerCase() === term.toLowerCase())) return null
|
||||
return term
|
||||
}, [search, values, dimensionId])
|
||||
|
||||
// Keyboard list: matching values first, the create affordance last.
|
||||
const optionCount = filteredValues.length + (createCandidate ? 1 : 0)
|
||||
|
||||
useEffect(() => {
|
||||
setHighlightedIndex(0)
|
||||
}, [filteredValues, createCandidate])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen || !listRef.current) return
|
||||
const highlighted = listRef.current.querySelector('[data-highlighted="true"]')
|
||||
if (highlighted) highlighted.scrollIntoView({ block: 'nearest' })
|
||||
}, [highlightedIndex, isOpen])
|
||||
|
||||
useEffect(() => {
|
||||
function handleClickOutside(e: MouseEvent | TouchEvent) {
|
||||
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
|
||||
setIsOpen(false)
|
||||
}
|
||||
}
|
||||
document.addEventListener('mousedown', handleClickOutside)
|
||||
document.addEventListener('touchstart', handleClickOutside)
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', handleClickOutside)
|
||||
document.removeEventListener('touchstart', handleClickOutside)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const selectValue = useCallback(
|
||||
(code: string) => {
|
||||
onChange(code)
|
||||
setSearch(code)
|
||||
setIsOpen(false)
|
||||
},
|
||||
[onChange],
|
||||
)
|
||||
|
||||
const createValue = useCallback(
|
||||
async (code: string) => {
|
||||
if (!dimensionId || isCreating) return
|
||||
setIsCreating(true)
|
||||
setCreateError(null)
|
||||
try {
|
||||
const res = await fetch(`/api/dimensions/${dimensionId}/values`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ code, name: code }),
|
||||
})
|
||||
const json = await res.json().catch(() => null)
|
||||
if (!res.ok) {
|
||||
setCreateError(getErrorMessage(json, { locale: 'sv' }))
|
||||
return
|
||||
}
|
||||
const created: DimensionValueDto = json?.data ?? {
|
||||
id: code,
|
||||
code,
|
||||
name: code,
|
||||
is_active: true,
|
||||
start_date: null,
|
||||
end_date: null,
|
||||
}
|
||||
// Refresh the shared registry so every picker offers the new value.
|
||||
await invalidateReferenceData('ref:dimensions')
|
||||
selectValue(created.code)
|
||||
} finally {
|
||||
setIsCreating(false)
|
||||
}
|
||||
},
|
||||
[dimensionId, isCreating, selectValue],
|
||||
)
|
||||
|
||||
const activateOption = useCallback(
|
||||
(index: number) => {
|
||||
if (index < filteredValues.length) {
|
||||
selectValue(filteredValues[index].code)
|
||||
} else if (createCandidate) {
|
||||
void createValue(createCandidate)
|
||||
}
|
||||
},
|
||||
[filteredValues, createCandidate, selectValue, createValue],
|
||||
)
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (!isOpen) {
|
||||
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
|
||||
openDropdown()
|
||||
e.preventDefault()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
switch (e.key) {
|
||||
case 'ArrowDown':
|
||||
e.preventDefault()
|
||||
setHighlightedIndex((prev) => Math.min(prev + 1, optionCount - 1))
|
||||
break
|
||||
case 'ArrowUp':
|
||||
e.preventDefault()
|
||||
setHighlightedIndex((prev) => Math.max(prev - 1, 0))
|
||||
break
|
||||
case 'Enter':
|
||||
e.preventDefault()
|
||||
if (optionCount > 0) activateOption(highlightedIndex)
|
||||
break
|
||||
case 'Escape':
|
||||
e.preventDefault()
|
||||
setIsOpen(false)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setSearch(e.target.value)
|
||||
setCreateError(null)
|
||||
if (!isOpen) openDropdown()
|
||||
}
|
||||
|
||||
const handleBlur = () => {
|
||||
setIsOpen(false)
|
||||
// Small delay so a dropdown mousedown fires first (same trick as
|
||||
// AccountCombobox: option clicks preventDefault, so they never blur).
|
||||
// An emptied field clears the dimension; anything that isn't a known
|
||||
// code reverts to the committed value. Committed value and values are
|
||||
// read through refs so a selection that lands during the 150ms window
|
||||
// wins over the revert (the closure's render snapshot would be stale).
|
||||
const snapshot = search
|
||||
setTimeout(() => {
|
||||
const committed = committedRef.current
|
||||
const trimmed = snapshot.trim()
|
||||
if (!trimmed) {
|
||||
setSearch('')
|
||||
if (committed !== null) onChange(null)
|
||||
return
|
||||
}
|
||||
if (trimmed !== committed && !valuesRef.current.some((v) => v.code === trimmed)) {
|
||||
setSearch(committed ?? '')
|
||||
}
|
||||
}, 150)
|
||||
}
|
||||
|
||||
// After a pick the field holds only the code ("1"), which told the user
|
||||
// nothing (issue #2219). Write the value's full name under it, exactly as
|
||||
// AccountCombobox does for the account name, whenever the field shows the
|
||||
// committed code and the name adds something beyond the code itself.
|
||||
const showSelectedName = Boolean(
|
||||
selected && selected.name !== selected.code && value !== null && search === value,
|
||||
)
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="relative">
|
||||
<Input
|
||||
value={search}
|
||||
onChange={handleInputChange}
|
||||
onFocus={openDropdown}
|
||||
onBlur={handleBlur}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Sök värde…"
|
||||
disabled={disabled}
|
||||
className={`font-mono ${className ?? ''}`.trim()}
|
||||
autoComplete="off"
|
||||
aria-describedby={showSelectedName ? selectedNameId : undefined}
|
||||
/>
|
||||
|
||||
{showSelectedName && selected ? (
|
||||
<p
|
||||
id={selectedNameId}
|
||||
data-ph-mask=""
|
||||
className="mt-1 break-words px-1 text-xs leading-snug text-muted-foreground"
|
||||
>
|
||||
{selected.name}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{/* Dropdown */}
|
||||
{isOpen && !disabled && (
|
||||
<div
|
||||
ref={listRef}
|
||||
className="absolute z-50 top-full left-0 mt-1 min-w-[16rem] w-[max(100%,20rem)] max-h-[300px] overflow-y-auto rounded-lg border border-input bg-card shadow-md"
|
||||
>
|
||||
{loadState === 'loading' && (
|
||||
<div className="flex items-center gap-2 px-2 py-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
Laddar…
|
||||
</div>
|
||||
)}
|
||||
{loadState === 'error' && (
|
||||
<p className="px-2 py-2 text-sm text-muted-foreground">
|
||||
Kunde inte hämta värden.
|
||||
</p>
|
||||
)}
|
||||
{loadState === 'loaded' && optionCount === 0 && (
|
||||
<p className="px-2 py-2 text-sm text-muted-foreground">
|
||||
Hittade inget värde som matchar.
|
||||
</p>
|
||||
)}
|
||||
{loadState === 'loaded' &&
|
||||
filteredValues.map((item, index) => {
|
||||
const isHighlighted = index === highlightedIndex
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
data-highlighted={isHighlighted}
|
||||
className={`w-full text-left px-2 py-1.5 text-sm cursor-pointer flex items-baseline gap-2 ${
|
||||
isHighlighted ? 'bg-primary/10 text-primary' : 'hover:bg-muted/50'
|
||||
}`}
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault()
|
||||
selectValue(item.code)
|
||||
}}
|
||||
onMouseEnter={() => setHighlightedIndex(index)}
|
||||
>
|
||||
<span className="font-mono shrink-0">{item.code}</span>
|
||||
<span className="flex-1 min-w-0 break-words text-muted-foreground">
|
||||
{item.name !== item.code ? item.name : ''}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
{loadState === 'loaded' && createCandidate && (
|
||||
<button
|
||||
type="button"
|
||||
data-highlighted={highlightedIndex === filteredValues.length}
|
||||
className={`w-full text-left px-2 py-1.5 text-sm cursor-pointer flex items-center gap-2 border-t border-input ${
|
||||
highlightedIndex === filteredValues.length
|
||||
? 'bg-primary/10 text-primary'
|
||||
: 'hover:bg-muted/50'
|
||||
}`}
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault()
|
||||
void createValue(createCandidate)
|
||||
}}
|
||||
onMouseEnter={() => setHighlightedIndex(filteredValues.length)}
|
||||
>
|
||||
{isCreating ? (
|
||||
<Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin" />
|
||||
) : (
|
||||
<Plus className="h-3.5 w-3.5 shrink-0" />
|
||||
)}
|
||||
<span className="truncate">Skapa ny "{createCandidate}"</span>
|
||||
</button>
|
||||
)}
|
||||
{createError && (
|
||||
<p className="px-2 py-1.5 text-xs text-destructive border-t border-input">
|
||||
{createError}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useForm, Controller } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { z } from 'zod'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { DestructiveConfirmDialog } from '@/components/ui/destructive-confirm-dialog'
|
||||
import { Loader2, Trash2 } from 'lucide-react'
|
||||
import {
|
||||
DIMENSION_CODE_PATTERN,
|
||||
PROJECT_DIM_NO,
|
||||
type DimensionDto,
|
||||
type DimensionValueDto,
|
||||
} from '@/components/dimensions/types'
|
||||
|
||||
export interface DimensionValueFormInput {
|
||||
code: string
|
||||
name: string
|
||||
is_active: boolean
|
||||
start_date: string | null
|
||||
end_date: string | null
|
||||
}
|
||||
|
||||
interface DimensionValueFormProps {
|
||||
/** The dimension the value belongs to (drives the Projekt date fields). */
|
||||
dimension: DimensionDto
|
||||
/** When set, the form edits this value (code becomes immutable). */
|
||||
value?: DimensionValueDto | null
|
||||
isSaving?: boolean
|
||||
onSubmit: (input: DimensionValueFormInput) => void | Promise<void>
|
||||
/** Rendered only when editing. The caller performs the DELETE and surfaces
|
||||
* the retention-trigger error ("…arkivera det istället") as a toast. */
|
||||
onDelete?: () => void | Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* Create/edit form for a dimension value (#OBJEKT), hosted in the
|
||||
* DimensionsManager dialog. Code is immutable in v1: the field is disabled
|
||||
* when editing. Start/end dates appear only for Projekt (dim 6), matching the
|
||||
* SIE model where projects span a date range while cost centres do not.
|
||||
*/
|
||||
export default function DimensionValueForm({
|
||||
dimension,
|
||||
value,
|
||||
isSaving = false,
|
||||
onSubmit,
|
||||
onDelete,
|
||||
}: DimensionValueFormProps) {
|
||||
const t = useTranslations('dimensions')
|
||||
const isEditing = Boolean(value)
|
||||
const isProject = dimension.sie_dim_no === PROJECT_DIM_NO
|
||||
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false)
|
||||
|
||||
const schema = useMemo(
|
||||
() =>
|
||||
z
|
||||
.object({
|
||||
// Legacy/backfilled codes can be looser than the strict format, so
|
||||
// the pattern is only enforced when the code is user-typed (create).
|
||||
code: isEditing
|
||||
? z.string()
|
||||
: z.string().regex(DIMENSION_CODE_PATTERN, t('form_code_invalid')),
|
||||
name: z.string().min(1, t('form_name_invalid')).max(120, t('form_name_invalid')),
|
||||
is_active: z.boolean(),
|
||||
start_date: z.string().optional(),
|
||||
end_date: z.string().optional(),
|
||||
})
|
||||
.refine(
|
||||
(data) =>
|
||||
!data.start_date || !data.end_date || data.end_date >= data.start_date,
|
||||
{ message: t('form_date_order_invalid'), path: ['end_date'] },
|
||||
),
|
||||
[isEditing, t],
|
||||
)
|
||||
|
||||
type FormData = z.infer<typeof schema>
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
control,
|
||||
formState: { errors },
|
||||
} = useForm<FormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: {
|
||||
code: value?.code ?? '',
|
||||
name: value?.name ?? '',
|
||||
is_active: value?.is_active ?? true,
|
||||
start_date: value?.start_date ?? '',
|
||||
end_date: value?.end_date ?? '',
|
||||
},
|
||||
})
|
||||
|
||||
function submit(data: FormData) {
|
||||
return onSubmit({
|
||||
code: data.code.trim(),
|
||||
name: data.name.trim(),
|
||||
is_active: data.is_active,
|
||||
start_date: isProject && data.start_date ? data.start_date : null,
|
||||
end_date: isProject && data.end_date ? data.end_date : null,
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit(submit)} className="space-y-6">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="dimension-value-code">{t('form_code_label')}</Label>
|
||||
<Input
|
||||
id="dimension-value-code"
|
||||
{...register('code')}
|
||||
disabled={isEditing}
|
||||
className="font-mono"
|
||||
autoComplete="off"
|
||||
autoFocus={!isEditing}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{isEditing ? t('form_code_immutable_help') : t('form_code_help')}
|
||||
</p>
|
||||
{errors.code && (
|
||||
<p className="text-xs text-destructive">{errors.code.message}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="dimension-value-name">{t('form_name_label')}</Label>
|
||||
<Input
|
||||
id="dimension-value-name"
|
||||
{...register('name')}
|
||||
autoComplete="off"
|
||||
autoFocus={isEditing}
|
||||
/>
|
||||
{errors.name && (
|
||||
<p className="text-xs text-destructive">{errors.name.message}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isProject && (
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="dimension-value-start">{t('form_start_label')}</Label>
|
||||
<Input
|
||||
id="dimension-value-start"
|
||||
type="date"
|
||||
{...register('start_date')}
|
||||
className="tabular-nums"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="dimension-value-end">{t('form_end_label')}</Label>
|
||||
<Input
|
||||
id="dimension-value-end"
|
||||
type="date"
|
||||
{...register('end_date')}
|
||||
className="tabular-nums"
|
||||
/>
|
||||
{errors.end_date && (
|
||||
<p className="text-xs text-destructive">{errors.end_date.message}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="dimension-value-active">{t('form_active_label')}</Label>
|
||||
<p className="text-xs text-muted-foreground max-w-md">
|
||||
{t('form_active_help')}
|
||||
</p>
|
||||
</div>
|
||||
<Controller
|
||||
name="is_active"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<Switch
|
||||
id="dimension-value-active"
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between gap-3 pt-2">
|
||||
{isEditing && onDelete ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="text-destructive hover:text-destructive"
|
||||
disabled={isSaving}
|
||||
onClick={() => setConfirmDeleteOpen(true)}
|
||||
>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
{t('form_delete')}
|
||||
</Button>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
<Button type="submit" disabled={isSaving}>
|
||||
{isSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{isEditing ? t('form_save') : t('form_create')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{onDelete && (
|
||||
<DestructiveConfirmDialog
|
||||
open={confirmDeleteOpen}
|
||||
onOpenChange={setConfirmDeleteOpen}
|
||||
title={t('delete_confirm_title')}
|
||||
description={t('delete_confirm_description', { code: value?.code ?? '' })}
|
||||
confirmLabel={t('delete_confirm_label')}
|
||||
cancelLabel={t('delete_cancel_label')}
|
||||
onConfirm={onDelete}
|
||||
/>
|
||||
)}
|
||||
</form>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,78 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import DimensionCombobox from '@/components/dimensions/DimensionCombobox'
|
||||
import { useDimensions } from '@/lib/reference-data/hooks'
|
||||
|
||||
interface LineDimensionFieldsProps {
|
||||
/** Current dimensions map ({sie_dim_no: object_code}), a line's map or the header default. */
|
||||
dimensions: Record<string, string> | undefined
|
||||
/** Fired per dimension; `code === null` clears the value. */
|
||||
onChange: (sieDimNo: string, code: string | null) => void
|
||||
disabled?: boolean
|
||||
/** Vertical layout for narrow containers (row popover); default is a 2-col grid. */
|
||||
stacked?: boolean
|
||||
/** Extra classes merged into the combobox inputs (pass 'h-8' for dense contexts). */
|
||||
inputClassName?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* While the registry loads (or if the fetch fails) we render the seeded
|
||||
* system pair (SIE dims 1/6) so the tagging affordance never disappears:
|
||||
* the registry always contains at least these two.
|
||||
*/
|
||||
const FALLBACK_FIELDS: { sieDimNo: string; label: string }[] = [
|
||||
{ sieDimNo: '1', label: 'Kostnadsställe' },
|
||||
{ sieDimNo: '6', label: 'Projekt' },
|
||||
]
|
||||
|
||||
/**
|
||||
* Registry-driven dimension comboboxes used by the voucher form's header
|
||||
* default, the per-row tag popover, and the mobile line cards. One combobox
|
||||
* per active registry dimension, ordered by sort_order then sie_dim_no (the
|
||||
* seeded 1/6 pair sorts first). Labels are the registry dimension names and
|
||||
* hardcoded-Swedish fallbacks: the component mounts on the voucher editor,
|
||||
* a stays-Swedish surface per .claude/rules/i18n.md (same convention as
|
||||
* DimensionCombobox).
|
||||
*/
|
||||
export default function LineDimensionFields({
|
||||
dimensions,
|
||||
onChange,
|
||||
disabled,
|
||||
stacked,
|
||||
inputClassName,
|
||||
}: LineDimensionFieldsProps) {
|
||||
// Registry from the session cache (lib/reference-data): one entry shared
|
||||
// by every line picker on the page; empty while loading or on failure,
|
||||
// which keeps the hardcoded 1/6 fallback below.
|
||||
const { dimensions: registry } = useDimensions()
|
||||
|
||||
const fields = useMemo(() => {
|
||||
const active = registry.filter((d) => d.is_active)
|
||||
if (active.length === 0) return FALLBACK_FIELDS
|
||||
return [...active]
|
||||
.sort((a, b) => a.sort_order - b.sort_order || a.sie_dim_no - b.sie_dim_no)
|
||||
.map((d) => ({ sieDimNo: String(d.sie_dim_no), label: d.name }))
|
||||
}, [registry])
|
||||
|
||||
return (
|
||||
<div className={stacked ? 'space-y-3' : 'grid grid-cols-2 gap-3'}>
|
||||
{fields.map((field) => (
|
||||
<div key={field.sieDimNo}>
|
||||
{/* data-ph-mask: the label is the user's own dimension name, not chrome */}
|
||||
<Label data-ph-mask="" className="text-xs text-muted-foreground">{field.label}</Label>
|
||||
<div className="mt-1">
|
||||
<DimensionCombobox
|
||||
sieDimNo={field.sieDimNo}
|
||||
value={dimensions?.[field.sieDimNo] ?? null}
|
||||
onChange={(code) => onChange(field.sieDimNo, code)}
|
||||
disabled={disabled}
|
||||
className={inputClassName}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import LineDimensionFields from '@/components/dimensions/LineDimensionFields'
|
||||
import { AccountNumber } from '@/components/ui/account-number'
|
||||
|
||||
export interface RetagLine {
|
||||
id: string
|
||||
account_number: string
|
||||
line_description: string | null
|
||||
debit_amount: number
|
||||
credit_amount: number
|
||||
dimensions?: Record<string, string> | null
|
||||
}
|
||||
|
||||
interface Props {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
line: RetagLine | null
|
||||
/** Fired after a successful retag so the host refetches the entry. */
|
||||
onRetagged: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Tier-2 retro-tagging on a posted voucher line (dimensions plan PR6).
|
||||
* Edits ONLY the dimension tags via the audited retag RPC; the verifikat
|
||||
* itself is untouchable. Dims other than 1/6 pass through unedited (same
|
||||
* merge semantics as the voucher editor). Hardcoded Swedish: voucher
|
||||
* detail is a stays-Swedish surface.
|
||||
*/
|
||||
export default function RetagLineDialog({ open, onOpenChange, line, onRetagged }: Props) {
|
||||
const { toast } = useToast()
|
||||
const [dims, setDims] = useState<Record<string, string>>({})
|
||||
const [reason, setReason] = useState('')
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (open && line) {
|
||||
setDims({ ...(line.dimensions ?? {}) })
|
||||
setReason('')
|
||||
setError(null)
|
||||
}
|
||||
}, [open, line])
|
||||
|
||||
if (!line) return null
|
||||
|
||||
const amount = Number(line.debit_amount) > 0 ? Number(line.debit_amount) : Number(line.credit_amount)
|
||||
const side = Number(line.debit_amount) > 0 ? 'Debet' : 'Kredit'
|
||||
|
||||
const handleChange = (dimNo: string, code: string | null) => {
|
||||
setDims((prev) => {
|
||||
const next = { ...prev }
|
||||
if (code) next[dimNo] = code
|
||||
else delete next[dimNo]
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
setIsSaving(true)
|
||||
setError(null)
|
||||
try {
|
||||
const res = await fetch(`/api/bookkeeping/journal-entry-lines/${line.id}/retag`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ dimensions: dims, reason }),
|
||||
})
|
||||
const payload = await res.json()
|
||||
if (!res.ok) {
|
||||
setError(typeof payload.error === 'string' ? payload.error : 'Kunde inte ändra dimensioner')
|
||||
return
|
||||
}
|
||||
if (payload.data?.changed === false) {
|
||||
toast({ title: 'Inga ändringar', description: 'Dimensionerna var redan de valda.' })
|
||||
} else {
|
||||
toast({ title: 'Dimensioner ändrade', description: 'Ändringen är loggad i ändringshistoriken.' })
|
||||
}
|
||||
onOpenChange(false)
|
||||
onRetagged()
|
||||
} catch {
|
||||
setError('Kunde inte ändra dimensioner')
|
||||
} finally {
|
||||
setIsSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const reasonValid = reason.trim().length >= 3
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Ändra dimensioner</DialogTitle>
|
||||
<DialogDescription>
|
||||
Påverkar endast internredovisningen, inte verifikatet. Ändringen
|
||||
loggas med före/efter och anledning.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="rounded-lg border border-border p-3 text-sm">
|
||||
<AccountNumber number={line.account_number} showName />
|
||||
<div className="mt-1 flex items-center justify-between text-muted-foreground">
|
||||
<span className="truncate">{line.line_description || '-'}</span>
|
||||
<span className="tabular-nums shrink-0 ml-3">
|
||||
{amount.toLocaleString('sv-SE', { minimumFractionDigits: 2 })} kr {side}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LineDimensionFields dimensions={dims} onChange={handleChange} />
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="retag-reason">Anledning</Label>
|
||||
<Input
|
||||
id="retag-reason"
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
placeholder="t.ex. Raden hörde till projekt P002"
|
||||
maxLength={500}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSaving}>
|
||||
Avbryt
|
||||
</Button>
|
||||
<Button onClick={handleSave} disabled={isSaving || !reasonValid}>
|
||||
{isSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Spara ändring
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Client-side contract types for the dimensions registry API (PR2 of
|
||||
* dev_docs/dimensions_implementation_plan.md).
|
||||
*
|
||||
* The routes live under /api/dimensions and are built against the same locked
|
||||
* contract: this module codes against the contract, not the route files, so
|
||||
* the register UI (DimensionsManager) and the shared picker (DimensionCombobox)
|
||||
* can ship independently of the API package.
|
||||
*/
|
||||
|
||||
export interface DimensionValueDto {
|
||||
id: string
|
||||
code: string
|
||||
name: string
|
||||
is_active: boolean
|
||||
start_date: string | null
|
||||
end_date: string | null
|
||||
}
|
||||
|
||||
export interface DimensionDto {
|
||||
id: string
|
||||
/** SIE #DIM number (1 = Kostnadsställe, 6 = Projekt, 20+ = custom). */
|
||||
sie_dim_no: number
|
||||
name: string
|
||||
resets_annually: boolean
|
||||
is_system: boolean
|
||||
is_active: boolean
|
||||
sort_order: number
|
||||
/** SIE #UNDERDIM parent — the sie_dim_no of the parent dimension, or null. */
|
||||
parent_sie_dim_no: number | null
|
||||
/** Sorted by code by the API. */
|
||||
values: DimensionValueDto[]
|
||||
}
|
||||
|
||||
export type DimensionRuleType = 'required' | 'default' | 'fixed'
|
||||
|
||||
/**
|
||||
* Per-account dimension rule as served by GET /api/dimensions/rules —
|
||||
* a flattened join row (rule + dimension + optional pinned value).
|
||||
*/
|
||||
export interface AccountDimensionRuleDto {
|
||||
account_dimension_rule_id: string
|
||||
account_number: string
|
||||
dimension_id: string
|
||||
sie_dim_no: number
|
||||
dimension_name: string
|
||||
rule_type: DimensionRuleType
|
||||
value_id: string | null
|
||||
value_code: string | null
|
||||
value_name: string | null
|
||||
is_active: boolean
|
||||
}
|
||||
|
||||
/** SIE dimension number whose values carry start/end dates (Projekt). */
|
||||
export const PROJECT_DIM_NO = 6
|
||||
|
||||
/**
|
||||
* Strict Fortnox-compatible code format enforced by the API for user-created
|
||||
* codes (the DB CHECK is deliberately looser so legacy free-text survives the
|
||||
* backfill). Mirrored client-side for inline validation before POST.
|
||||
*/
|
||||
export const DIMENSION_CODE_PATTERN = /^[A-Za-z0-9ÅÄÖåäö_+\-]{1,20}$/
|
||||
|
||||
Reference in New Issue
Block a user