Files
accounted/components/bookkeeping/BookingTemplatePicker.tsx
T
Mattsson abe9ac9d8c Fix/attributes config (#926)
* fix(git): pin LF on generated extension registry and vitest snapshots

setup:extensions and vitest write these files with LF; with
core.autocrlf=true git expects CRLF and flags them as phantom
modifications on every dev/build run.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(security): enforce MFA on mcp-oauth consent and gate viewer storno route

mcp-oauth/authorize renders an HTML consent page and issues 303 redirects that withRouteContext cannot express, so it kept raw getUser() and thereby skipped the AAL2 gate: a password-only (AAL1) session could approve consent that mints a long-lived, MFA-bypassing API key. Add a route-local requireAal2() step-up on GET and POST; AAL1 sessions redirect to /mfa/verify, BankID users are exempt.

Separately, POST /api/reports/vat-declaration/rc-basis-gaps/fix calls correctEntry() (storno of a posted entry) but lacked requireWrite, so viewer-role members could trigger it. Add { requireWrite: true }.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(api): route transactions endpoints through withRouteContext

Migrate the transactions routes off hand-rolled supabase.auth.getUser() onto the MFA-enforcing withRouteContext wrapper; add requireWrite on mutating handlers (book, uncategorize, attach-document, ignore, batch-match, create-from-document). Behavior and response shapes preserved; tests updated to the wrapper mock pattern.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(api): route SIE import and bank reconciliation through withRouteContext

Migrate import/sie and reconciliation/bank routes onto the MFA-enforcing wrapper; requireWrite on mutations (import execute, create-accounts, mappings write verbs, link/unlink/run/mark-opening-balance). Reads (status, unmatched-entries) stay ungated. Response shapes preserved; tests added/updated to the wrapper mock pattern.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(api): route salary endpoints through withRouteContext

Migrate salary employees and runs routes (plus ku, payroll-config, tax-tables) onto the MFA-enforcing wrapper; requireWrite on mutations. Personnummer masking/encryption untouched; file downloads (AGI XML, payslip PDF, payment files) keep their headers. Two payment-file GETs retain requireWrite because they stamp *_file_generated_at and previously gated viewers. Tests added/updated to the wrapper mock pattern.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(api): route report endpoints through withRouteContext

Migrate the read-only report routes (trial balance, balansrapport, resultatrapport, income statement, ledgers, KPI, VAT declaration, salary journal, monthly breakdown, journal register, continuity check, full archive, etc.) onto the MFA-enforcing wrapper. All read-only, no requireWrite. JSON/XLSX/PDF/ZIP response bodies and headers preserved byte-for-byte; tests updated to the wrapper mock pattern.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(api): route invoices, skatteverket, agent and extension endpoints through withRouteContext

Migrate invoices, supplier-invoices, skatteverket tax-payments, and dynamic extension routes onto the MFA-enforcing wrapper with requireWrite on mutations. The two NDJSON streaming agent routes (invoke, onboarding/stream) use requireAuth() directly (the wrapper can't wrap a streaming response) so MFA is still enforced. skatteverket payment-file GET keeps requireWrite (stamps a generated-at field). Response shapes and file headers preserved; tests added/updated.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(api): route documents, events, team and account endpoints through withRouteContext

Migrate documents, events, kpi/preferences, vat/validate, support/contact onto the MFA-enforcing wrapper with requireWrite on mutations. account/password, team/accept and team/members use requireAuth() directly (user-level or pre-membership flows with no active company context) so MFA is still enforced. events keeps its dual API-key-or-session auth. Document retention guard untouched; tests added/updated.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(api): route settings and pending-operations endpoints through withRouteContext

Migrate settings (api-keys, oauth-clients, booking-templates, counterparty-templates, logo, company settings) and pending-operations (commit, bulk-commit, reject, edit-before-approve) onto the MFA-enforcing wrapper with requireWrite on mutations. Credential-guarding routes keep their per-user ownership filters. Response shapes preserved; tests added/updated to the wrapper mock pattern.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(guards): ratchet raw-route-auth baseline 119->1 after A1 migration

Lock in the withRouteContext migration so the count cannot regress. The single remaining entry, mcp-oauth/authorize, is a documented exception (HTML consent + redirects, MFA enforced via route-local step-up). Record the campaign and requireWrite decisions in DECISIONS.md.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(vat): add eSKD momsdeklaration file export for "Deklarera via fil"

Generate the Skatteverket eSKDUpload v6.0 XML file so users can file VAT by
upload instead of typing every ruta into the form. Extract buildFiledAmounts()
as the shared whole-krona source of truth (öre truncated per SFL 22 kap 1 §) so
the XML file and the manual-filing PDF can never disagree. Adds the /eskd API
route, an XML option in the report export menu, and the upload button on the
manual-filing card. Strings in sv + en.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(vat): add 'vat_settlement' source type and update related components

* fix(booking): adjust search input layout and enable autofocus

* fix(vat): support 12-digit org numbers and adjust emission order for eSKD file

* fix(migration): add 'vat_settlement' to journal_entries.source_type CHECK

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 09:54:46 +02:00

262 lines
9.8 KiB
TypeScript

'use client'
import { useState, useEffect, useMemo, useCallback } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { useToast } from '@/components/ui/use-toast'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog'
import { BookOpen, Search, Building2, Users, Globe } from 'lucide-react'
import { TEMPLATE_CATEGORY_LABELS, SCOPE_LABELS, getTemplateScope, applyTemplate } from '@/lib/bookkeeping/template-library'
import type { BookingTemplateLibrary, BookingTemplateCategory, EntityType } from '@/types'
import type { FormLine } from '@/components/bookkeeping/JournalEntryForm'
interface Props {
onApply: (lines: FormLine[], description: string, category?: BookingTemplateCategory) => void
entityType?: EntityType
/** Prefill the "total amount" field when the caller already knows it (e.g.
* booking from an underlag with a known total). The user can still edit it. */
defaultAmount?: number
}
const SCOPE_ICONS = {
system: Globe,
team: Users,
company: Building2,
} as const
export default function BookingTemplatePicker({ onApply, entityType, defaultAmount }: Props) {
const { toast } = useToast()
const [open, setOpen] = useState(false)
const [templates, setTemplates] = useState<BookingTemplateLibrary[]>([])
const [isLoading, setIsLoading] = useState(false)
const [search, setSearch] = useState('')
const [selectedCategory, setSelectedCategory] = useState<BookingTemplateCategory | 'all'>('all')
const [amount, setAmount] = useState('')
const [selectedId, setSelectedId] = useState<string | null>(null)
// Prefill the amount from the caller's known total each time the picker
// opens. Only when provided: callers without a known amount (e.g. the
// journal-entry form) keep the blank-then-type behaviour.
useEffect(() => {
if (open && defaultAmount != null && defaultAmount > 0) {
setAmount(String(Math.round(defaultAmount * 100) / 100))
}
}, [open, defaultAmount])
const fetchTemplates = useCallback(async (signal?: AbortSignal) => {
setIsLoading(true)
try {
const r = await fetch('/api/settings/booking-templates', { signal })
const { data } = await r.json()
setTemplates(data || [])
} catch (err) {
if (err instanceof DOMException && err.name === 'AbortError') return
toast({ title: 'Kunde inte hämta mallar', variant: 'destructive' })
} finally {
setIsLoading(false)
}
}, [toast])
useEffect(() => {
if (!open) return
const controller = new AbortController()
fetchTemplates(controller.signal)
return () => { controller.abort() }
}, [open, fetchTemplates])
const filtered = useMemo(() => {
let result = templates
// Filter by entity type
if (entityType) {
result = result.filter((t) => t.entity_type === 'all' || t.entity_type === entityType)
}
// Filter by category
if (selectedCategory !== 'all') {
result = result.filter((t) => t.category === selectedCategory)
}
// Filter by search
if (search) {
const lower = search.toLowerCase()
result = result.filter(
(t) =>
t.name.toLowerCase().includes(lower) ||
t.description.toLowerCase().includes(lower),
)
}
return result
}, [templates, entityType, selectedCategory, search])
// Unique categories present in templates
const availableCategories = useMemo(() => {
const cats = new Set(templates.map((t) => t.category))
return Array.from(cats).sort()
}, [templates])
const selected = selectedId ? templates.find((t) => t.id === selectedId) : null
function handleApply() {
if (!selected) return
const totalAmount = parseFloat(amount)
if (!totalAmount || totalAmount <= 0) {
toast({ title: 'Ange belopp', description: 'Ange ett belopp för att använda mallen.', variant: 'destructive' })
return
}
const lines = applyTemplate(selected.lines, totalAmount)
// Fire-and-forget MRU bump so this template surfaces at the top next time.
fetch(`/api/settings/booking-templates/${selected.id}/touch`, { method: 'POST' }).catch(() => {})
onApply(lines, selected.name, selected.category)
setOpen(false)
setSelectedId(null)
setAmount('')
setSearch('')
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button variant="outline" size="sm" type="button">
<BookOpen className="h-3.5 w-3.5 mr-1.5" />
Använd mall
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl max-h-[80vh] flex flex-col">
<DialogHeader>
<DialogTitle>Bokföringsmallar</DialogTitle>
</DialogHeader>
{/* Search + category filter */}
<div className="flex flex-col gap-3">
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Sök mall..."
className="pl-9"
autoFocus
/>
</div>
<div className="flex gap-1 flex-wrap">
<Button
variant={selectedCategory === 'all' ? 'default' : 'outline'}
size="sm"
onClick={() => setSelectedCategory('all')}
type="button"
>
Alla
</Button>
{availableCategories.map((cat) => (
<Button
key={cat}
variant={selectedCategory === cat ? 'default' : 'outline'}
size="sm"
onClick={() => setSelectedCategory(cat as BookingTemplateCategory)}
type="button"
>
{TEMPLATE_CATEGORY_LABELS[cat as BookingTemplateCategory]}
</Button>
))}
</div>
</div>
{/* Template list */}
<div className="flex-1 overflow-y-auto space-y-1 min-h-0">
{isLoading ? (
<p className="text-sm text-muted-foreground py-8 text-center">Laddar mallar...</p>
) : filtered.length === 0 ? (
<p className="text-sm text-muted-foreground py-8 text-center">Inga mallar hittades.</p>
) : (
filtered.map((t) => {
const scope = getTemplateScope(t)
const ScopeIcon = SCOPE_ICONS[scope]
const isSelected = selectedId === t.id
return (
<button
key={t.id}
type="button"
onClick={() => setSelectedId(isSelected ? null : t.id)}
className={`w-full text-left rounded-lg border p-3 transition-colors ${
isSelected
? 'border-primary bg-primary/5'
: 'border-border hover:border-primary/40 hover:bg-muted/50'
}`}
>
<div className="flex items-start justify-between gap-2">
<div className="flex-1 min-w-0">
<div className="font-medium text-sm">{t.name}</div>
<div className="flex items-center gap-1 text-[11px] text-muted-foreground mt-0.5">
<ScopeIcon className="h-3 w-3 shrink-0" />
<span>
{SCOPE_LABELS[scope]}
{t.entity_type !== 'all' &&
` · ${t.entity_type === 'enskild_firma' ? 'EF' : 'AB'}`}
</span>
</div>
{t.description && (
<p className="text-xs text-muted-foreground mt-0.5 line-clamp-2">
{t.description}
</p>
)}
</div>
</div>
{/* Show lines preview when selected */}
{isSelected && (
<div className="mt-2 pt-2 border-t space-y-1">
{t.lines.map((line, i) => (
<div key={i} className="flex items-center gap-2 text-xs font-mono text-muted-foreground">
<span className="w-10">{line.account}</span>
<span className="flex-1 truncate">{line.label}</span>
<span className={line.side === 'debit' ? 'text-foreground' : ''}>
{line.side === 'debit' ? (line.type === 'vat' && line.vat_rate ? `${(line.vat_rate * 100).toFixed(0)}% moms` : 'D') : ''}
</span>
<span className={line.side === 'credit' ? 'text-foreground' : ''}>
{line.side === 'credit' ? (line.type === 'vat' && line.vat_rate ? `${(line.vat_rate * 100).toFixed(0)}% moms` : 'K') : ''}
</span>
</div>
))}
</div>
)}
</button>
)
})
)}
</div>
{/* Apply section */}
{selected && (
<div className="flex items-end gap-3 pt-3 border-t">
<div className="flex-1">
<label className="text-xs font-medium text-muted-foreground mb-1 block">
Totalt belopp (inkl. moms)
</label>
<Input
type="number"
value={amount}
onChange={(e) => setAmount(e.target.value)}
placeholder="0,00"
min="0"
step="0.01"
inputMode="decimal"
autoFocus
/>
</div>
<Button onClick={handleApply} type="button">
Använd mall
</Button>
</div>
)}
</DialogContent>
</Dialog>
)
}