* feat: copy voucher, MRU booking templates, and PDF export for reports - Add "Kopiera verifikat" action on the journal-entry detail page that prefills a new draft with the source entry's lines, description, and notes. Date defaults to today so locked-period posts can't happen by accident; source_type resets to manual. - Track per-company MRU for booking_template_library rows via a new booking_template_usage table (fire-and-forget touch endpoint hooked into both pickers) and sort the list most-recently-used first for the active company. - Generate downloadable PDFs for balansräkning and resultaträkning using the existing @react-pdf/renderer toolchain. Adds a reusable parameterized template and two API routes, with download buttons on the matching report views. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: address PR review feedback on copy-voucher + report PDFs Compliance review (Swedish accounting): - Balance-sheet PDF now refuses to render when tillgångar ≠ eget kapital och skulder; the stale "Differens" summary row is gone. The on-screen view still surfaces the existing "Balanserar ej" warning so users can diagnose the imbalance before downloading. ÅRL 3 kap / K2 / K3 require exact balance. - Both PDF routes now 400 when the requested fiscal period cannot be resolved — identifiable period is part of räkenskapsinformation under BFL 7 kap. - Income-statement PDF adds the mandatory "Resultat efter finansiella poster" subtotal when financial items are present, per K2/K3 uppställningsform (ÅRL bilaga 2). - Copy-voucher flow now shows a clear banner ("Kopia av verifikat X — nytt, fristående verifikat skapas") so users cannot mistake the copy for a rättelse/storno. Code review (Greptile): - New migration adds updated_at column + trigger to booking_template_usage (project convention; applied to the Supabase project). - Replace localeCompare on ISO timestamps with plain relational comparison to avoid any locale-dependent ordering. - UUID-format validation on the copy_from query param before it goes into the fetch URL. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: second round of Swedish compliance fixes on report PDFs - Balance-sheet PDF imbalance check now compares rounded-to-whole-kronor totals (SFL 22:1 convention). The previous 0.5-öre tolerance could reject a legitimate balance sheet when accumulated floating-point noise across hundreds of ledger lines exceeded the threshold. The on-screen view still surfaces the öre-precise "Balanserar ej" badge for diagnostic visibility. - Both PDFs now carry a prominent "Arbetsutkast — ej undertecknat" notice per ÅRL 2 kap 7 §. Prevents a downloaded PDF from being mistaken for or filed as an approved årsredovisning. - Income-statement PDF now follows K2/K3 uppställningsform (ÅRL bilaga 2) by splitting class 8 into three blocks with named subtotals: Finansiella poster (80–84), Bokslutsdispositioner (88), Skatter (89). The summary now always shows a "Skatt på årets resultat" row so the reader can verify the tax calculation, and adds "Resultat efter finansiella poster" / "Bokslutsdispositioner" subtotals when each block is present. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: harden report PDFs against out-of-band filing + future BAS growth - Append "-utkast" to downloaded PDF filenames. The filename survives the PDF's disclaimer context — a file named balansrakning-2026-01-01.pdf in a Downloads folder or forwarded attachment is ambiguous, whereas balansrakning-2026-01-01-utkast.pdf makes the draft status legible even without opening the document. - Add a catch-all "Övriga finansiella poster" bucket in the income-statement PDF for any class-8 section whose account prefix isn't one of the known K2/K3 blocks (80–84 / 88 / 89). Counted in the "Resultat efter finansiella poster" subtotal so arithmetic stays consistent. Future-proofs the PDF against a generator change that starts emitting 85–87 sections. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
253 lines
9.4 KiB
TypeScript
253 lines
9.4 KiB
TypeScript
'use client'
|
|
|
|
import { useState, useEffect, useMemo, useCallback } from 'react'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Input } from '@/components/ui/input'
|
|
import { Badge } from '@/components/ui/badge'
|
|
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) => void
|
|
entityType?: EntityType
|
|
}
|
|
|
|
const SCOPE_ICONS = {
|
|
system: Globe,
|
|
team: Users,
|
|
company: Building2,
|
|
} as const
|
|
|
|
export default function BookingTemplatePicker({ onApply, entityType }: 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)
|
|
|
|
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: 'Fel', description: '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)
|
|
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 sm:flex-row gap-2">
|
|
<div className="relative flex-1">
|
|
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
|
|
<Input
|
|
value={search}
|
|
onChange={(e) => setSearch(e.target.value)}
|
|
placeholder="Sök mall..."
|
|
className="pl-9"
|
|
/>
|
|
</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="flex items-center gap-2">
|
|
<span className="font-medium text-sm">{t.name}</span>
|
|
<Badge variant="secondary" className="text-[10px] px-1.5 py-0 shrink-0">
|
|
<ScopeIcon className="h-3 w-3 mr-0.5" />
|
|
{SCOPE_LABELS[scope]}
|
|
</Badge>
|
|
{t.entity_type !== 'all' && (
|
|
<Badge variant="outline" className="text-[10px] px-1.5 py-0 shrink-0">
|
|
{t.entity_type === 'enskild_firma' ? 'EF' : 'AB'}
|
|
</Badge>
|
|
)}
|
|
</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>
|
|
)
|
|
}
|