26e29f47bc
* feat(company): ideell förening as a third legal form, behind a flag (#2072 step 1) Why the problem occurred: the legal form was modelled as a binary flag in ~300 files. `EntityType` was a two-member union, but nothing dispatched on it exhaustively: 28 sites defaulted `?? 'enskild_firma'` (invoice, categorize, match, stripe, invoice-inbox) or `?? 'aktiebolag'` (year-end, bokslut, MCP), and every form-dependent choice was an `=== 'aktiebolag' ? A : B` ternary. Widening the union compiled everywhere and changed nothing, so a förening would have booked as an enskild firma in the app and as an aktiebolag in bokslut and MCP, with no error anywhere. The lookup refused föreningar at the door (mapEntityType returned null), which is what the tester hit. What was removed or simplified: the silent defaults. One module, lib/company/entity-type.ts, now holds the list (ENTITY_TYPES), the parser (never defaults), the resolver (settings hint, then companies.entity_type, then throw) and `byEntityType`, whose Record arms make the compiler refuse the next widening until each site has an answer. The form-dependent facts (closing account, owner settlement account, calendar-year lock, default method, K1/K2 label, personnummer vs 16-prefix) live there once instead of in the ternaries. On the SQL side supported_entity_types() replaces four copies of the literal list in the create RPCs. Why this shape and not the proposed one: the tracker asked for the enum widening plus a chart; that alone was the dangerous version (compiles, books wrong). Bundling stiftelse was considered and dropped: identical plumbing but no chart block. Creation sits behind NEXT_PUBLIC_IDEELL_FORENING_ENABLED so the CHECK, RPCs and seed can ship now and the first partner is switched on without a migration; the flag goes when Phase 2 (packs, INK3, årsbokslut, Swish) lands on the tracker. Domain choices (DECISIONS.md 2026-09-08, verify with an accountant before Phase 2): result closes to 2069 with 2068 as prior-year carry; no owner accounts, member settlement on 2890; accrual default; brutet räkenskapsår allowed; K1 label for the 5 000 kr accrual threshold (BFNAR 2010:1); org number gets the 16 prefix. Migration 20260908110835 widens the three CHECK constraints, adds supported_entity_types(), re-creates the three create RPCs with the widened guard and adds the förening block to seed_chart_of_accounts. Applied to staging and covered by ideell-forening-entity-type.pg.test.ts. Part of #2072 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PdGafpUA7jVV1oYjkwfQCh * fix(company): close the förening paths the skeptic refuted (#2072) Five refutations from the /skeptic pass on 7a05c54d2, each fixed at the shared definition rather than the reported site: 1. Privately paid supplier invoices and the utlägg dialog resolved the owner account in lib/expenses/payer.ts with its own AB/EF ternary, so a förening member's invoice was built on 2893 and then refused by the expense-claim service (which already said 2890), burning an ankomstnummer. The helper now uses ownerSettlementAccount. 2. Booking templates substitute their `_ab` accounts only for an aktiebolag; the `private_expense` template kept its base 2013 for a förening. Template accounts now resolve through templateAccountForForm: EF base, AB override, förening base with owner accounts translated to 2890 (booking-templates.ts and proposal-lines.ts share it). 3. A VAT-registered förening with helårsmoms got no momsdeklaration deadline: the annual VAT rule bailed on anything but AB/EF. A förening is a juridisk person and follows the räkenskapsår schedule (SFL 26 kap 33 §), so the rule now keys on fiscalYearLockedToCalendar instead of the two literals; same in the MCP VAT report. 4. 2069 would have accumulated across years: the year-open omföring was AB-only with 2099/2098 hard-coded. planResultAppropriation now takes the pair from resultClosingAccounts (AB 2099 -> 2098, förening 2069 -> 2068) and skips forms with no carry (EF). 5. With the flag off, a registry lookup that returned "Ideell förening" was prefilled into the onboarding journey, the form picker was skipped and the create step answered "Ogiltig företagsform" with no way back. The journey, the BankID picker, the onboarding page and the MCP lookup now use mapSetupEntityType, which maps only creatable forms, so a flagged-off form falls through to the picker as before. Also: form picker keeps its AB-first order; tests for each fix. Part of #2072 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PdGafpUA7jVV1oYjkwfQCh * chore(migrations): move ideell förening migration after main's latest version (20260908143051) Two migrations landed on main after the branch forked; a lower version would be skipped by the merge-time apply. Staging history row renamed to match. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PdGafpUA7jVV1oYjkwfQCh * chore(skills): regenerate accounted-api reference for the widened entity_type enum Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PdGafpUA7jVV1oYjkwfQCh --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
387 lines
16 KiB
TypeScript
387 lines
16 KiB
TypeScript
'use client'
|
|
|
|
import { useTranslations } from 'next-intl'
|
|
import { useState, useMemo } from 'react'
|
|
import type { EntityType } from '@/types'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Input } from '@/components/ui/input'
|
|
import { Label } from '@/components/ui/label'
|
|
import { Textarea } from '@/components/ui/textarea'
|
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
|
import { useToast } from '@/components/ui/use-toast'
|
|
import { Loader2, Trash2, Plus } from 'lucide-react'
|
|
import { TEMPLATE_CATEGORY_LABELS, convertLibraryToBookingTemplate, applyTemplate } from '@/lib/bookkeeping/template-library'
|
|
import { InfoTooltip } from '@/components/ui/info-tooltip'
|
|
import { formatCurrency } from '@/lib/utils'
|
|
import type { BookingTemplateLibrary, BookingTemplateCategory, BookingTemplateLibraryLine } from '@/types'
|
|
|
|
export type TemplateFormMode = 'create' | 'edit' | 'duplicate'
|
|
|
|
/**
|
|
* Shared editor for booking templates. Seeds its state once from
|
|
* `initialTemplate` (used by the settings panel to edit/customize a template,
|
|
* and by "Spara som mall" in the booking dialog to pre-fill a derived draft).
|
|
*
|
|
* Submit behaviour is driven by `mode`: 'edit' PUTs the existing template,
|
|
* 'create' and 'duplicate' both POST a new company-scoped template.
|
|
*/
|
|
export function TemplateForm({
|
|
mode,
|
|
initialTemplate,
|
|
entityLabels,
|
|
duplicateNamePool = [],
|
|
onSaved,
|
|
}: {
|
|
mode: TemplateFormMode
|
|
initialTemplate?: BookingTemplateLibrary
|
|
entityLabels: Record<string, string>
|
|
duplicateNamePool?: string[]
|
|
onSaved: () => void
|
|
}) {
|
|
const t = useTranslations('settings_booking_templates')
|
|
const { toast } = useToast()
|
|
const [isSubmitting, setIsSubmitting] = useState(false)
|
|
// When customizing a system template (mode 'duplicate') we suggest a distinct
|
|
// "(anpassad)" name so the company copy doesn't read as the standard one.
|
|
const [name, setName] = useState(() =>
|
|
initialTemplate
|
|
? mode === 'duplicate'
|
|
? t('copy_name_suffix', { name: initialTemplate.name })
|
|
: initialTemplate.name
|
|
: '',
|
|
)
|
|
const [description, setDescription] = useState(initialTemplate?.description ?? '')
|
|
const [category, setCategory] = useState<BookingTemplateCategory>(initialTemplate?.category ?? 'other')
|
|
const [entityType, setEntityType] = useState<'all' | EntityType>(
|
|
initialTemplate?.entity_type ?? 'all',
|
|
)
|
|
const [lines, setLines] = useState<BookingTemplateLibraryLine[]>(() =>
|
|
initialTemplate
|
|
? initialTemplate.lines.map((l) => ({ ...l }))
|
|
: [
|
|
{ account: '', label: '', side: 'debit', type: 'business', ratio: 1 },
|
|
{ account: '', label: '', side: 'credit', type: 'settlement', ratio: 1 },
|
|
],
|
|
)
|
|
|
|
function updateLine(index: number, field: keyof BookingTemplateLibraryLine, value: string | number) {
|
|
setLines((prev) => {
|
|
const updated = [...prev]
|
|
updated[index] = { ...updated[index], [field]: value }
|
|
return updated
|
|
})
|
|
}
|
|
|
|
function updateLineType(index: number, newType: BookingTemplateLibraryLine['type']) {
|
|
setLines((prev) => {
|
|
const updated = [...prev]
|
|
const current = updated[index]
|
|
const next: BookingTemplateLibraryLine = { ...current, type: newType }
|
|
// Auto-pick a sensible default for the type-specific field so the
|
|
// converter (and applyTemplate) sees a complete line shape.
|
|
if (newType === 'vat' && next.vat_rate === undefined) {
|
|
next.vat_rate = 0.25
|
|
}
|
|
updated[index] = next
|
|
return updated
|
|
})
|
|
}
|
|
|
|
// Default new lines to a VAT line — the 2-line template starts with one
|
|
// business + one settlement, and the natural extension is a VAT leg.
|
|
// Defaulting to 'business' instead would silently break the converter
|
|
// (which requires exactly one business line) and the template would
|
|
// disappear from the transaction picker.
|
|
function addLine() {
|
|
setLines((prev) => [...prev, { account: '', label: '', side: 'debit', type: 'vat', vat_rate: 0.25 }])
|
|
}
|
|
|
|
function removeLine(index: number) {
|
|
if (lines.length <= 2) return
|
|
setLines((prev) => prev.filter((_, i) => i !== index))
|
|
}
|
|
|
|
// Ratio is only load-bearing when a template splits the amount across more
|
|
// than one cost/revenue line. Hide it for the simple case to keep the form
|
|
// approachable for non-accountants; it stays 1.0 under the hood.
|
|
const businessLineCount = lines.filter((l) => l.type === 'business').length
|
|
const showRatio = businessLineCount > 1
|
|
// The ratio only validates against cost/revenue lines (businessRatioSum), so
|
|
// only those get an editable input. The settlement leg is the full counter-
|
|
// amount (ratio 1.0) and is shown in the live preview, not as a control —
|
|
// an editable settlement ratio that doesn't feed the sum check would mislead.
|
|
const firstRatioIndex = showRatio ? lines.findIndex((l) => l.type === 'business') : -1
|
|
const businessRatioSum = lines
|
|
.filter((l) => l.type === 'business')
|
|
.reduce((sum, l) => sum + (l.ratio ?? 1), 0)
|
|
const ratioSumOff = showRatio && Math.abs(businessRatioSum - 1) > 0.001
|
|
|
|
// Live split preview for a 1 000 kr amount. Computed only once every line has
|
|
// an account so the table doesn't flicker while the form is half-filled.
|
|
const preview = useMemo(() => {
|
|
if (lines.some((l) => !l.account)) return null
|
|
try {
|
|
return applyTemplate(lines, 1000)
|
|
} catch {
|
|
return null
|
|
}
|
|
}, [lines])
|
|
|
|
// Soft, non-blocking hint when the chosen name collides with an existing
|
|
// company template (no DB unique constraint — duplicates are allowed).
|
|
const nameCollision =
|
|
mode !== 'edit' &&
|
|
name.trim().length > 0 &&
|
|
duplicateNamePool.some((n) => n.trim().toLowerCase() === name.trim().toLowerCase())
|
|
|
|
// Real-time check: can this draft be picked from the transaction sheet?
|
|
// If not, we show a hint — save remains allowed (templates may still be
|
|
// useful from the journal-entry form).
|
|
const isConvertible = (() => {
|
|
const draft: BookingTemplateLibrary = {
|
|
id: initialTemplate?.id ?? '',
|
|
company_id: null,
|
|
team_id: null,
|
|
created_by: null,
|
|
name,
|
|
description,
|
|
category,
|
|
entity_type: entityType,
|
|
lines,
|
|
is_system: false,
|
|
is_active: true,
|
|
created_at: '',
|
|
updated_at: '',
|
|
}
|
|
return convertLibraryToBookingTemplate(draft) !== null
|
|
})()
|
|
|
|
async function handleSubmit(e: React.FormEvent) {
|
|
e.preventDefault()
|
|
if (!name || lines.some((l) => !l.account || !l.label)) {
|
|
toast({ title: t('toast_fill_all_fields'), variant: 'destructive' })
|
|
return
|
|
}
|
|
|
|
setIsSubmitting(true)
|
|
try {
|
|
// Edit updates the existing template in place (PUT); create and duplicate
|
|
// both write a new company-scoped template (POST).
|
|
const isEdit = mode === 'edit'
|
|
const url = isEdit
|
|
? `/api/settings/booking-templates/${initialTemplate!.id}`
|
|
: '/api/settings/booking-templates'
|
|
const res = await fetch(url, {
|
|
method: isEdit ? 'PUT' : 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ name, description, category, entity_type: entityType, lines }),
|
|
})
|
|
if (!res.ok) {
|
|
const json = await res.json().catch(() => ({}))
|
|
toast({ title: json.error || t('toast_create_failed'), variant: 'destructive' })
|
|
return
|
|
}
|
|
toast({ title: isEdit ? t('toast_updated') : t('toast_created') })
|
|
onSaved()
|
|
} finally {
|
|
setIsSubmitting(false)
|
|
}
|
|
}
|
|
|
|
return (
|
|
<form onSubmit={handleSubmit} className="space-y-4">
|
|
<div>
|
|
<Label>{t('name_label')}</Label>
|
|
<Input
|
|
value={name}
|
|
onChange={(e) => setName(e.target.value)}
|
|
placeholder={t('name_placeholder')}
|
|
autoFocus={mode === 'duplicate'}
|
|
onFocus={mode === 'duplicate' ? (e) => e.target.select() : undefined}
|
|
/>
|
|
</div>
|
|
<div>
|
|
<Label>{t('description_label')} <span className="text-muted-foreground font-normal">{t('optional_suffix')}</span></Label>
|
|
<Textarea value={description} onChange={(e) => setDescription(e.target.value)} placeholder={t('description_placeholder')} rows={2} className="resize-none" />
|
|
</div>
|
|
<div className="grid grid-cols-2 gap-3">
|
|
<div>
|
|
<Label>{t('category_label')}</Label>
|
|
<Select value={category} onValueChange={(v) => setCategory(v as BookingTemplateCategory)}>
|
|
<SelectTrigger className="mt-1"><SelectValue /></SelectTrigger>
|
|
<SelectContent>
|
|
{Object.entries(TEMPLATE_CATEGORY_LABELS).map(([k, v]) => (
|
|
<SelectItem key={k} value={k}>{v}</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
<div>
|
|
<Label>{t('entity_type_label')}</Label>
|
|
<Select value={entityType} onValueChange={(v) => setEntityType(v as typeof entityType)}>
|
|
<SelectTrigger className="mt-1"><SelectValue /></SelectTrigger>
|
|
<SelectContent>
|
|
{Object.entries(entityLabels).map(([k, v]) => (
|
|
<SelectItem key={k} value={k}>{v}</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
</div>
|
|
|
|
<div>
|
|
<div className="flex items-center gap-1">
|
|
<Label>{t('lines_label')}</Label>
|
|
<InfoTooltip content={t('line_types_help')} />
|
|
</div>
|
|
<div className="space-y-2 mt-1">
|
|
{lines.map((line, i) => {
|
|
const showRatioInput = showRatio && line.type === 'business'
|
|
return (
|
|
<div key={i} className="rounded-lg border border-border p-2 space-y-1.5">
|
|
<div className="flex items-center gap-2">
|
|
<Input
|
|
value={line.account}
|
|
onChange={(e) => updateLine(i, 'account', e.target.value.replace(/\D/g, '').slice(0, 4))}
|
|
placeholder={t('account_placeholder')}
|
|
className="w-20 font-mono"
|
|
maxLength={4}
|
|
/>
|
|
<Input
|
|
value={line.label}
|
|
onChange={(e) => updateLine(i, 'label', e.target.value)}
|
|
placeholder={t('description_short_placeholder')}
|
|
className="flex-1 min-w-0"
|
|
/>
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
size="sm"
|
|
onClick={() => removeLine(i)}
|
|
disabled={lines.length <= 2}
|
|
className="h-8 w-8 p-0 shrink-0"
|
|
>
|
|
<Trash2 className="h-3.5 w-3.5" />
|
|
</Button>
|
|
</div>
|
|
<div className="flex items-center gap-2">
|
|
<Select value={line.side} onValueChange={(v) => updateLine(i, 'side', v)}>
|
|
<SelectTrigger className="w-24"><SelectValue /></SelectTrigger>
|
|
<SelectContent>
|
|
<SelectItem value="debit">{t('debit_label')}</SelectItem>
|
|
<SelectItem value="credit">{t('credit_label')}</SelectItem>
|
|
</SelectContent>
|
|
</Select>
|
|
<Select value={line.type} onValueChange={(v) => updateLineType(i, v as BookingTemplateLibraryLine['type'])}>
|
|
<SelectTrigger className="flex-1"><SelectValue /></SelectTrigger>
|
|
<SelectContent>
|
|
<SelectItem value="business">{t('type_cost_revenue')}</SelectItem>
|
|
<SelectItem value="vat">{t('type_vat')}</SelectItem>
|
|
<SelectItem value="settlement">{t('type_settlement')}</SelectItem>
|
|
</SelectContent>
|
|
</Select>
|
|
{line.type === 'vat' && (
|
|
<Select
|
|
value={String(line.vat_rate ?? 0.25)}
|
|
onValueChange={(v) => updateLine(i, 'vat_rate', Number(v))}
|
|
>
|
|
<SelectTrigger className="w-24" aria-label={t('vat_rate_label')}><SelectValue /></SelectTrigger>
|
|
<SelectContent>
|
|
<SelectItem value="0.25">{t('vat_rate_25')}</SelectItem>
|
|
<SelectItem value="0.12">{t('vat_rate_12')}</SelectItem>
|
|
<SelectItem value="0.06">{t('vat_rate_6')}</SelectItem>
|
|
<SelectItem value="0">{t('vat_rate_0')}</SelectItem>
|
|
</SelectContent>
|
|
</Select>
|
|
)}
|
|
{showRatioInput && (
|
|
<div className="flex items-center gap-1 shrink-0">
|
|
<Input
|
|
type="number"
|
|
inputMode="decimal"
|
|
step="0.1"
|
|
min={0}
|
|
max={10}
|
|
value={String(line.ratio ?? 1)}
|
|
onChange={(e) => {
|
|
const n = Number(e.target.value)
|
|
if (!Number.isNaN(n)) updateLine(i, 'ratio', n)
|
|
}}
|
|
aria-label={t('ratio_label')}
|
|
className="w-16 font-mono tabular-nums text-right"
|
|
/>
|
|
{i === firstRatioIndex && <InfoTooltip content={t('ratio_help')} />}
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
)})}
|
|
<Button type="button" variant="outline" size="sm" onClick={addLine}>
|
|
<Plus className="h-3 w-3 mr-1" />
|
|
{t('add_line')}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
|
|
{ratioSumOff && (
|
|
<div className="rounded-lg border border-border bg-muted/30 px-3 py-2">
|
|
<p className="text-xs text-attn leading-snug">
|
|
{t('ratio_sum_warning')}
|
|
</p>
|
|
</div>
|
|
)}
|
|
|
|
{preview && (
|
|
<div>
|
|
<Label>{t('preview_label')}</Label>
|
|
<table className="w-full text-xs mt-1">
|
|
<thead className="[&_th]:font-medium [&_th]:text-[11px] [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-muted-foreground">
|
|
<tr className="border-b">
|
|
<th className="text-left py-1 w-14">{t('th_account')}</th>
|
|
<th className="text-left py-1">{t('th_description')}</th>
|
|
<th className="text-right py-1 w-20">{t('th_debit')}</th>
|
|
<th className="text-right py-1 w-20">{t('th_credit')}</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{preview.map((pl, i) => (
|
|
<tr key={i} className="border-b last:border-0">
|
|
<td className="py-1 font-mono">{pl.account_number}</td>
|
|
<td className="py-1">{pl.line_description}</td>
|
|
<td className="py-1 text-right tabular-nums">
|
|
{pl.debit_amount ? formatCurrency(Number(pl.debit_amount)) : ''}
|
|
</td>
|
|
<td className="py-1 text-right tabular-nums">
|
|
{pl.credit_amount ? formatCurrency(Number(pl.credit_amount)) : ''}
|
|
</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
)}
|
|
|
|
{nameCollision && (
|
|
<div className="rounded-lg border border-border bg-muted/30 px-3 py-2">
|
|
<p className="text-xs text-attn leading-snug">
|
|
{t('duplicate_name_warning')}
|
|
</p>
|
|
</div>
|
|
)}
|
|
|
|
{!isConvertible && (
|
|
<div className="rounded-lg border border-border bg-muted/30 px-3 py-2">
|
|
<p className="text-xs text-attn leading-snug">
|
|
{t('unconvertible_hint')}
|
|
</p>
|
|
</div>
|
|
)}
|
|
|
|
<Button type="submit" disabled={isSubmitting} className="w-full">
|
|
{isSubmitting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
|
{mode === 'create' ? t('create_button') : t('save_button')}
|
|
</Button>
|
|
</form>
|
|
)
|
|
}
|