feat: counterparty templates with multi-line patterns, batch matching, and settings cleanup (#118)
* feat: separate AR/AP/accounting into distinct nav groups (#92) Split the flat "Finans" sidebar group into three visually distinct sections — Försäljning (AR), Inköp (AP), and Redovisning — so users coming from Fortnox immediately find customer invoicing and supplier invoices as top-level concepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: journal entry detail view, correction chain, and account name display - Add journal entry detail page at /bookkeeping/[id] with full entry view - Add correction chain API and component showing storno relationships - Add JournalEntryStatusBadge component for entry status display - Show debit/credit account names in template picker and review dialogs - Expand client-side BAS account name mapping with additional accounts - Show account codes on transaction inbox suggestion buttons Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address review feedback — N+1 query, duplicate name, nav dedup - Batch reverse-lookup into single query per BFS iteration (was N+1) - Differentiate account 2393 from 2893 in display names - Extract shared loop for desktop/mobile nav group rendering Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: counterparty templates, Skatteverket extension, VAT form completeness, and UI cleanup - Add counterparty-based categorization templates (learned from user approvals and auto-ingestion) with fuzzy matching in the mapping engine - Add Skatteverket extension for direct VAT declaration submission via API - Complete VAT declaration form with all 30 SKV 4700 boxes (ruta 08, 35-42, 50, 60-62) - Fix ruta 49 formula to include import VAT (ruta 60+61+62) - Simplify dashboard UI: remove redundant icons from stat cards, customer cards, invoice list, supplier invoices; use Badge variants consistently - Add SkatteverketPanel component to reports page - Add categorization_templates and skatteverket_tokens migrations - Update tests and helpers for new types Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address PR review feedback — VAT detection, migration timestamps, dedup - Fix detectVatTreatment to derive actual rate (12%/6%) from VAT line description instead of hardcoding standard_25 - Rename skatteverket_tokens migration to 20260324120001 to avoid duplicate timestamp with categorization_templates (fixes Supabase deployment failure) - Make refreshAccessToken accept previousRefreshCount param to enforce refresh limit contract at the type level - Fix rate limiter TOCTOU by claiming slot before await - Extract formatRedovisare/formatRedovisningsperiod to shared lib/skatteverket/format.ts — eliminates duplication between mappers.ts and SkatteverketPanel.tsx Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: multi-line counterparty templates, batch matching, settings restructure Counterparty template engine: - Multi-line booking patterns (line_pattern JSONB) for complex entries with split VAT, tax accounts, and ratio-based allocation - Batch matching (findCounterpartyTemplatesBatch) — 1 DB query for all transactions instead of up to 3 per transaction - SIE voucher population (populateTemplatesFromSieVouchers) — extracts patterns from historical vouchers on import with dominance filtering - Source priority system (user_approved > sie_import > auto_learned) - Centralized counterparty: prefix helpers to prevent string fragility - Fix: re-approval path now updates line_pattern Transaction categorization: - /describe route returns counterparty_match in parallel with templates/AI - /categorize route accepts counterparty_template_id for direct booking - /suggest-categories uses batch matching, injects counterparty suggestions - transaction-entries supports all_lines_complete for multi-line patterns UI: - TemplatePicker shows "Tidigare motparter" section (no AI extension needed) - DescribeTransactionDialog shows counterparty match card with detail - QuickReviewDialog supports counterparty line patterns - JournalEntryPreview renders multi-line patterns with VAT/ratio math - Inline LinePatternEntry types replaced with shared import from @/types Settings restructure: - 8 tabs → 5: merged Säkerhet + Utseende + Kalender into Konto - Renamed "Motparter" → "Mallar" - CounterpartyTemplatesPanel: click-to-expand detail view with account lines, VAT, confidence, aliases, and delete Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address PR review — account_override guard, DELETE body parsing, stale test - Block account_override when counterparty_template_id is set (prevents corrupting stored template via override → upsert correction path) - Wrap DELETE request.json() in try-catch for malformed body (400 not 500) - Clean up stale 3-query mock enqueues in test for batch-based find Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
d8e0a22495
commit
d9c95a7b59
@@ -0,0 +1,259 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { Loader2, Trash2, Users, ChevronDown } from 'lucide-react'
|
||||
import { formatAccountWithName } from '@/lib/bookkeeping/client-account-names'
|
||||
import { formatCounterpartyName } from '@/lib/bookkeeping/counterparty-templates'
|
||||
import type { CategorizationTemplate } from '@/types'
|
||||
|
||||
const SOURCE_LABELS: Record<string, string> = {
|
||||
sie_import: 'SIE-import',
|
||||
user_approved: 'Godkänd',
|
||||
auto_learned: 'Automatisk',
|
||||
sni_default: 'Standard',
|
||||
}
|
||||
|
||||
const VAT_LABELS: Record<string, string> = {
|
||||
standard_25: '25%',
|
||||
reduced_12: '12%',
|
||||
reduced_6: '6%',
|
||||
reverse_charge: 'Omvänd',
|
||||
export: 'Export',
|
||||
exempt: 'Momsfri',
|
||||
}
|
||||
|
||||
function formatDate(iso: string | null) {
|
||||
if (!iso) return '—'
|
||||
return new Date(iso).toLocaleDateString('sv-SE', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
})
|
||||
}
|
||||
|
||||
function confidenceColor(c: number): string {
|
||||
if (c >= 0.8) return 'text-emerald-600 dark:text-emerald-400'
|
||||
if (c >= 0.5) return 'text-amber-600 dark:text-amber-400'
|
||||
return 'text-muted-foreground'
|
||||
}
|
||||
|
||||
export function CounterpartyTemplatesPanel() {
|
||||
const { toast } = useToast()
|
||||
|
||||
const [templates, setTemplates] = useState<CategorizationTemplate[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [deletingId, setDeletingId] = useState<string | null>(null)
|
||||
const [expandedId, setExpandedId] = useState<string | null>(null)
|
||||
|
||||
const fetchTemplates = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch('/api/settings/counterparty-templates')
|
||||
const json = await res.json()
|
||||
if (json.data) {
|
||||
setTemplates(json.data)
|
||||
}
|
||||
} catch {
|
||||
toast({ title: 'Fel', description: 'Kunde inte hämta mallar', variant: 'destructive' })
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}, [toast])
|
||||
|
||||
useEffect(() => {
|
||||
fetchTemplates()
|
||||
}, [fetchTemplates])
|
||||
|
||||
async function handleDelete(id: string) {
|
||||
setDeletingId(id)
|
||||
try {
|
||||
const res = await fetch('/api/settings/counterparty-templates', {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ id }),
|
||||
})
|
||||
if (!res.ok) {
|
||||
toast({ title: 'Fel', description: 'Kunde inte ta bort mall', variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
setTemplates((prev) => prev.filter((t) => t.id !== id))
|
||||
if (expandedId === id) setExpandedId(null)
|
||||
toast({ title: 'Mall borttagen' })
|
||||
} catch {
|
||||
toast({ title: 'Fel', description: 'Kunde inte ta bort mall', variant: 'destructive' })
|
||||
} finally {
|
||||
setDeletingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Bokföringsmallar</CardTitle>
|
||||
<CardDescription>
|
||||
Inlärda mönster som automatiskt föreslår kontering baserat på motpart.
|
||||
Mallar skapas från SIE-import och när du godkänner kategoriseringar.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : templates.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center py-8 text-center">
|
||||
<Users className="h-8 w-8 text-muted-foreground/50 mb-3" />
|
||||
<p className="text-sm text-muted-foreground">Inga mallar ännu.</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Mallar skapas automatiskt när du kategoriserar transaktioner eller importerar en SIE-fil.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
{templates.map((t) => {
|
||||
const isExpanded = expandedId === t.id
|
||||
const isMultiLine = t.line_pattern && t.line_pattern.length > 0
|
||||
|
||||
return (
|
||||
<div key={t.id} className="rounded-md border overflow-hidden">
|
||||
{/* Clickable summary row */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExpandedId(isExpanded ? null : t.id)}
|
||||
className="w-full text-left px-4 py-3 flex items-center gap-3 hover:bg-muted/50 transition-colors"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="text-sm font-medium truncate">{formatCounterpartyName(t.counterparty_name)}</p>
|
||||
<Badge variant="outline" className="text-[10px] shrink-0">
|
||||
{SOURCE_LABELS[t.source] || t.source}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5 mt-0.5 text-xs text-muted-foreground">
|
||||
{isMultiLine ? (
|
||||
<span className="font-mono">
|
||||
{t.line_pattern!.filter(lp => lp.type === 'business').map(lp => lp.account).join(', ')}
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<span className="font-mono">{t.debit_account}</span>
|
||||
<span className="text-muted-foreground/50">→</span>
|
||||
<span className="font-mono">{t.credit_account}</span>
|
||||
</>
|
||||
)}
|
||||
{t.vat_treatment && (
|
||||
<>
|
||||
<span className="text-muted-foreground/30">·</span>
|
||||
<span>{VAT_LABELS[t.vat_treatment] || t.vat_treatment}</span>
|
||||
</>
|
||||
)}
|
||||
<span className="text-muted-foreground/30">·</span>
|
||||
<span>{t.occurrence_count} ggr</span>
|
||||
<span className={`tabular-nums ${confidenceColor(Number(t.confidence))}`}>
|
||||
{Math.round(Number(t.confidence) * 100)}%
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<ChevronDown className={`h-4 w-4 text-muted-foreground shrink-0 transition-transform ${isExpanded ? 'rotate-180' : ''}`} />
|
||||
</button>
|
||||
|
||||
{/* Expanded detail */}
|
||||
{isExpanded && (
|
||||
<div className="border-t bg-muted/30 px-4 py-3 space-y-3">
|
||||
{/* Account lines */}
|
||||
<div>
|
||||
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider mb-1.5">Kontering</p>
|
||||
{isMultiLine ? (
|
||||
<div className="space-y-1">
|
||||
{t.line_pattern!.map((lp, i) => (
|
||||
<div key={i} className="flex items-center gap-2 text-xs">
|
||||
<Badge variant="secondary" className="text-[10px] px-1.5 py-0 w-14 justify-center">
|
||||
{lp.side === 'debit' ? 'Debet' : 'Kredit'}
|
||||
</Badge>
|
||||
<span className="font-mono">{formatAccountWithName(lp.account)}</span>
|
||||
{lp.type === 'vat' && lp.vat_rate && (
|
||||
<span className="text-muted-foreground">({Math.round(lp.vat_rate * 100)}% moms)</span>
|
||||
)}
|
||||
{lp.ratio !== undefined && (
|
||||
<span className="text-muted-foreground">({Math.round(lp.ratio * 100)}%)</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-2 text-xs">
|
||||
<Badge variant="secondary" className="text-[10px] px-1.5 py-0 w-14 justify-center">Debet</Badge>
|
||||
<span className="font-mono">{formatAccountWithName(t.debit_account)}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-xs">
|
||||
<Badge variant="secondary" className="text-[10px] px-1.5 py-0 w-14 justify-center">Kredit</Badge>
|
||||
<span className="font-mono">{formatAccountWithName(t.credit_account)}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Metadata */}
|
||||
<div className="grid grid-cols-2 gap-x-6 gap-y-1 text-xs">
|
||||
{t.vat_treatment && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Moms</span>
|
||||
<span>{VAT_LABELS[t.vat_treatment] || t.vat_treatment}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Antal bokföringar</span>
|
||||
<span className="tabular-nums">{t.occurrence_count}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Säkerhet</span>
|
||||
<span className={`tabular-nums ${confidenceColor(Number(t.confidence))}`}>
|
||||
{Math.round(Number(t.confidence) * 100)}%
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Senast använd</span>
|
||||
<span>{formatDate(t.last_seen_date)}</span>
|
||||
</div>
|
||||
{t.counterparty_aliases && t.counterparty_aliases.length > 1 && (
|
||||
<div className="col-span-2 flex justify-between">
|
||||
<span className="text-muted-foreground">Alias</span>
|
||||
<span className="text-right truncate ml-4">{t.counterparty_aliases.slice(0, 3).join(', ')}{t.counterparty_aliases.length > 3 ? ` +${t.counterparty_aliases.length - 3}` : ''}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Delete */}
|
||||
<div className="flex justify-end pt-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleDelete(t.id)}
|
||||
disabled={deletingId === t.id}
|
||||
className="text-destructive hover:text-destructive text-xs h-7"
|
||||
>
|
||||
{deletingId === t.id ? (
|
||||
<Loader2 className="mr-1.5 h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
<Trash2 className="mr-1.5 h-3 w-3" />
|
||||
)}
|
||||
Ta bort mall
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
import JournalEntryPreview from './JournalEntryPreview'
|
||||
import { formatAccountWithName } from '@/lib/bookkeeping/client-account-names'
|
||||
import type { TransactionWithInvoice } from './transaction-types'
|
||||
import type { LinePatternEntry } from '@/types'
|
||||
|
||||
interface TemplateMatch {
|
||||
template_id: string
|
||||
@@ -46,6 +47,18 @@ interface TemplateMatch {
|
||||
risk_level: string
|
||||
}
|
||||
|
||||
interface CounterpartyMatch {
|
||||
id: string
|
||||
counterparty_name: string
|
||||
debit_account: string
|
||||
credit_account: string
|
||||
vat_treatment: string | null
|
||||
confidence: number
|
||||
occurrence_count: number
|
||||
source: string
|
||||
line_pattern: LinePatternEntry[] | null
|
||||
}
|
||||
|
||||
interface AiSuggestion {
|
||||
debit_account: string
|
||||
credit_account: string
|
||||
@@ -59,6 +72,7 @@ interface AiSuggestion {
|
||||
|
||||
interface DescribeResult {
|
||||
templates: TemplateMatch[]
|
||||
counterparty_match: CounterpartyMatch | null
|
||||
ai_suggestion: AiSuggestion | null
|
||||
needs_more_detail: boolean
|
||||
user_description: string
|
||||
@@ -75,7 +89,7 @@ interface DescribeTransactionDialogProps {
|
||||
}
|
||||
|
||||
type Step = 'describe' | 'pick' | 'batch'
|
||||
type Selection = { type: 'template'; templateId: string } | { type: 'ai' }
|
||||
type Selection = { type: 'template'; templateId: string } | { type: 'ai' } | { type: 'counterparty' }
|
||||
|
||||
function getExamplePrompts(transaction: TransactionWithInvoice): string[] {
|
||||
const desc = (transaction.description || '').toLowerCase()
|
||||
@@ -191,7 +205,14 @@ export default function DescribeTransactionDialog({
|
||||
// Build categorize request based on selection type
|
||||
let body: Record<string, unknown>
|
||||
|
||||
if (selection.type === 'template') {
|
||||
if (selection.type === 'counterparty') {
|
||||
const cp = describeResult.counterparty_match!
|
||||
body = {
|
||||
is_business: true,
|
||||
counterparty_template_id: cp.id,
|
||||
user_description: describeResult.user_description,
|
||||
}
|
||||
} else if (selection.type === 'template') {
|
||||
body = {
|
||||
is_business: true,
|
||||
template_id: selection.templateId,
|
||||
@@ -323,6 +344,8 @@ export default function DescribeTransactionDialog({
|
||||
if (!transaction) return null
|
||||
|
||||
const isIncome = transaction.amount > 0
|
||||
const counterpartyMatch = describeResult?.counterparty_match
|
||||
const isCounterpartySelected = selection?.type === 'counterparty'
|
||||
const aiSuggestion = describeResult?.ai_suggestion
|
||||
// Check if AI agrees with top template
|
||||
const topTemplate = describeResult?.templates[0]
|
||||
@@ -424,6 +447,66 @@ export default function DescribeTransactionDialog({
|
||||
)}
|
||||
|
||||
<div className="overflow-y-auto max-h-[40vh] space-y-2 pr-1">
|
||||
{/* Counterparty Match Card */}
|
||||
{counterpartyMatch && (
|
||||
<Card
|
||||
className={`cursor-pointer transition-colors hover:border-primary/50 ${
|
||||
isCounterpartySelected ? 'border-primary bg-primary/5' : ''
|
||||
}`}
|
||||
onClick={() => setSelection({ type: 'counterparty' })}
|
||||
>
|
||||
<CardContent className="py-3 px-4">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-1.5 mb-1">
|
||||
<Badge variant="secondary" className="text-[10px] px-1.5 py-0 bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300">
|
||||
Tidigare bokföring
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-sm font-medium">{counterpartyMatch.counterparty_name}</p>
|
||||
<div className="flex flex-wrap items-center gap-1.5 mt-1.5">
|
||||
{counterpartyMatch.line_pattern && counterpartyMatch.line_pattern.length > 0 ? (
|
||||
counterpartyMatch.line_pattern.map((lp, i) => (
|
||||
<Badge key={i} variant="secondary" className="text-[10px] px-1.5 py-0">
|
||||
{formatAccountWithName(lp.account)}
|
||||
</Badge>
|
||||
))
|
||||
) : (
|
||||
<>
|
||||
<Badge variant="secondary" className="text-[10px] px-1.5 py-0">
|
||||
D: {formatAccountWithName(counterpartyMatch.debit_account)}
|
||||
</Badge>
|
||||
<Badge variant="secondary" className="text-[10px] px-1.5 py-0">
|
||||
K: {formatAccountWithName(counterpartyMatch.credit_account)}
|
||||
</Badge>
|
||||
{counterpartyMatch.vat_treatment && counterpartyMatch.vat_treatment !== 'exempt' && (
|
||||
<Badge variant="outline" className="text-[10px] px-1.5 py-0">
|
||||
Moms {Math.round(getVatRateFromTreatment(counterpartyMatch.vat_treatment) * 100)}%
|
||||
</Badge>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
{counterpartyMatch.occurrence_count} tidigare bokföringar
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 flex-shrink-0">
|
||||
<Badge
|
||||
variant={counterpartyMatch.confidence >= 0.7 ? 'default' : 'outline'}
|
||||
className="text-[10px] px-1.5 py-0"
|
||||
>
|
||||
{Math.round(counterpartyMatch.confidence * 100)}%
|
||||
</Badge>
|
||||
{isCounterpartySelected && (
|
||||
<Check className="h-4 w-4 text-primary" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* AI Suggestion Card */}
|
||||
{aiSuggestion && (
|
||||
<Card
|
||||
@@ -581,8 +664,20 @@ export default function DescribeTransactionDialog({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Journal entry preview for selected template or AI suggestion */}
|
||||
{/* Journal entry preview for selected template, AI suggestion, or counterparty match */}
|
||||
{selection && (() => {
|
||||
if (selection.type === 'counterparty' && counterpartyMatch) {
|
||||
return (
|
||||
<JournalEntryPreview
|
||||
amount={transaction.amount}
|
||||
currency={transaction.currency}
|
||||
templateDebitAccount={counterpartyMatch.line_pattern ? undefined : counterpartyMatch.debit_account}
|
||||
templateCreditAccount={counterpartyMatch.line_pattern ? undefined : counterpartyMatch.credit_account}
|
||||
templateVatRate={counterpartyMatch.line_pattern ? undefined : getVatRateFromTreatment(counterpartyMatch.vat_treatment)}
|
||||
linePattern={counterpartyMatch.line_pattern ?? undefined}
|
||||
/>
|
||||
)
|
||||
}
|
||||
if (selection.type === 'ai' && aiSuggestion) {
|
||||
return (
|
||||
<JournalEntryPreview
|
||||
|
||||
@@ -5,7 +5,7 @@ import { formatCurrency } from '@/lib/utils'
|
||||
import { formatAccountWithName } from '@/lib/bookkeeping/client-account-names'
|
||||
import { getVatRate, extractVatAmount, extractNetAmount } from '@/lib/bookkeeping/vat-entries'
|
||||
import { getCategoryAccountMapping } from '@/lib/bookkeeping/category-mapping'
|
||||
import type { TransactionCategory, VatTreatment, EntityType } from '@/types'
|
||||
import type { TransactionCategory, VatTreatment, EntityType, LinePatternEntry } from '@/types'
|
||||
|
||||
interface PreviewLine {
|
||||
side: 'debet' | 'kredit'
|
||||
@@ -24,6 +24,9 @@ interface JournalEntryPreviewProps {
|
||||
templateDebitAccount?: string
|
||||
templateCreditAccount?: string
|
||||
templateVatRate?: number
|
||||
/** For multi-line counterparty template bookings */
|
||||
linePattern?: LinePatternEntry[]
|
||||
settlementAccount?: string
|
||||
}
|
||||
|
||||
export default function JournalEntryPreview({
|
||||
@@ -36,11 +39,52 @@ export default function JournalEntryPreview({
|
||||
templateDebitAccount,
|
||||
templateCreditAccount,
|
||||
templateVatRate,
|
||||
linePattern,
|
||||
settlementAccount = '1930',
|
||||
}: JournalEntryPreviewProps) {
|
||||
const lines = useMemo(() => {
|
||||
const result: PreviewLine[] = []
|
||||
const absAmount = Math.abs(amount)
|
||||
|
||||
// Multi-line counterparty template preview
|
||||
if (linePattern && linePattern.length > 0) {
|
||||
const isIncome = amount > 0
|
||||
const settlementSide = isIncome ? 'debet' : 'kredit'
|
||||
|
||||
// Settlement line
|
||||
result.push({ side: settlementSide, account: settlementAccount, amount: absAmount })
|
||||
|
||||
// VAT lines first (from rate)
|
||||
let totalVat = 0
|
||||
for (const entry of linePattern) {
|
||||
if (entry.type === 'vat' && entry.vat_rate) {
|
||||
const vatAmt = Math.round(absAmount * entry.vat_rate / (1 + entry.vat_rate) * 100) / 100
|
||||
totalVat += vatAmt
|
||||
result.push({ side: entry.side === 'debit' ? 'debet' : 'kredit', account: entry.account, amount: vatAmt })
|
||||
}
|
||||
}
|
||||
|
||||
// Business/tax lines (from ratio against non-VAT amount)
|
||||
const nonVatAmt = Math.round((absAmount - totalVat) * 100) / 100
|
||||
let allocated = 0
|
||||
const ratioEntries = linePattern.filter(e => e.ratio !== undefined)
|
||||
for (const entry of ratioEntries) {
|
||||
const amt = Math.round(nonVatAmt * (entry.ratio ?? 0) * 100) / 100
|
||||
allocated += amt
|
||||
result.push({ side: entry.side === 'debit' ? 'debet' : 'kredit', account: entry.account, amount: amt })
|
||||
}
|
||||
|
||||
// Rounding difference to 3740
|
||||
const totalAllocated = Math.round((totalVat + allocated) * 100) / 100
|
||||
const diff = Math.round((absAmount - totalAllocated) * 100) / 100
|
||||
if (diff !== 0) {
|
||||
const businessSide = linePattern.find(e => e.type === 'business')?.side ?? 'credit'
|
||||
result.push({ side: businessSide === 'debit' ? 'debet' : 'kredit', account: '3740', amount: Math.abs(diff) })
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// Template-based preview
|
||||
if (templateDebitAccount && templateCreditAccount) {
|
||||
const vatRate = templateVatRate ?? 0
|
||||
@@ -93,7 +137,7 @@ export default function JournalEntryPreview({
|
||||
}
|
||||
|
||||
return result
|
||||
}, [amount, category, vatTreatment, accountOverride, entityType, templateDebitAccount, templateCreditAccount, templateVatRate])
|
||||
}, [amount, category, vatTreatment, accountOverride, entityType, templateDebitAccount, templateCreditAccount, templateVatRate, linePattern, settlementAccount])
|
||||
|
||||
if (lines.length === 0) return null
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ import type { UploadedFile } from '@/components/bookkeeping/DocumentUploadZone'
|
||||
import VatTreatmentSelect from './VatTreatmentSelect'
|
||||
import { VAT_TREATMENT_OPTIONS } from './transaction-types'
|
||||
import type { TransactionWithInvoice } from './transaction-types'
|
||||
import type { TransactionCategory, VatTreatment, BASAccount, EntityType } from '@/types'
|
||||
import type { TransactionCategory, VatTreatment, BASAccount, EntityType, LinePatternEntry } from '@/types'
|
||||
|
||||
interface QuickReviewDialogProps {
|
||||
open: boolean
|
||||
@@ -30,6 +30,7 @@ interface QuickReviewDialogProps {
|
||||
entityType?: EntityType
|
||||
template?: BookingTemplate | null
|
||||
templateId?: string
|
||||
counterpartyLinePattern?: LinePatternEntry[] | null
|
||||
onConfirm: (
|
||||
id: string,
|
||||
category: TransactionCategory,
|
||||
@@ -51,6 +52,7 @@ export default function QuickReviewDialog({
|
||||
entityType,
|
||||
template,
|
||||
templateId,
|
||||
counterpartyLinePattern,
|
||||
onConfirm,
|
||||
onChangeTemplate,
|
||||
}: QuickReviewDialogProps) {
|
||||
@@ -91,6 +93,8 @@ export default function QuickReviewDialog({
|
||||
if (!transaction || !category) return null
|
||||
|
||||
const isIncome = transaction.amount > 0
|
||||
const isCounterpartyTemplate = !!(counterpartyLinePattern && counterpartyLinePattern.length > 0)
|
||||
const isTemplateBooking = !!templateId || isCounterpartyTemplate
|
||||
const isLiabilityAccount = accountOverride.startsWith('2')
|
||||
|
||||
async function handleConfirm() {
|
||||
@@ -151,7 +155,7 @@ export default function QuickReviewDialog({
|
||||
<DialogHeader>
|
||||
<DialogTitle>Granska bokföring</DialogTitle>
|
||||
<DialogDescription>
|
||||
Kontrollera konto och moms innan du bokför
|
||||
{isTemplateBooking ? 'Granska verifikationen innan du bokför' : 'Kontrollera konto och moms innan du bokför'}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
@@ -179,13 +183,13 @@ export default function QuickReviewDialog({
|
||||
{/* Template or Category */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-muted-foreground">
|
||||
{template ? 'Mall' : 'Kategori'}
|
||||
{isCounterpartyTemplate ? 'Motpartsmall' : template ? 'Mall' : 'Kategori'}
|
||||
</label>
|
||||
<div className="mt-1 flex items-center gap-2">
|
||||
<Badge variant="outline" className="text-sm py-1 px-3">
|
||||
{template ? template.name_sv : categoryLabel}
|
||||
</Badge>
|
||||
{onChangeTemplate && (
|
||||
{onChangeTemplate && !isCounterpartyTemplate && (
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-primary hover:underline"
|
||||
@@ -195,7 +199,7 @@ export default function QuickReviewDialog({
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{template && (
|
||||
{template && !isCounterpartyTemplate && (
|
||||
<p className="mt-1.5 text-xs font-mono text-muted-foreground">
|
||||
D: {formatAccountWithName(template.debit_account)} → K: {formatAccountWithName(template.credit_account)}
|
||||
</p>
|
||||
@@ -236,52 +240,57 @@ export default function QuickReviewDialog({
|
||||
<JournalEntryPreview
|
||||
amount={transaction.amount}
|
||||
currency={transaction.currency}
|
||||
category={category}
|
||||
vatTreatment={isLiabilityAccount ? 'none' : vatTreatment}
|
||||
accountOverride={accountOverride}
|
||||
entityType={entityType}
|
||||
{...(isCounterpartyTemplate
|
||||
? { linePattern: counterpartyLinePattern ?? undefined }
|
||||
: templateId && template
|
||||
? { templateDebitAccount: template.debit_account, templateCreditAccount: template.credit_account, templateVatRate: template.vat_rate }
|
||||
: { category, vatTreatment: isLiabilityAccount ? 'none' : vatTreatment, accountOverride, entityType }
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* Account */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-muted-foreground">Konto</label>
|
||||
<div className="mt-1">
|
||||
<AccountCombobox
|
||||
value={accountOverride}
|
||||
accounts={accounts}
|
||||
onChange={handleAccountChange}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/* Account & VAT — hidden for template bookings (accounts defined by the template) */}
|
||||
{!isTemplateBooking && (
|
||||
<>
|
||||
<div>
|
||||
<label className="text-sm font-medium text-muted-foreground">Konto</label>
|
||||
<div className="mt-1">
|
||||
<AccountCombobox
|
||||
value={accountOverride}
|
||||
accounts={accounts}
|
||||
onChange={handleAccountChange}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* VAT treatment */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-muted-foreground">Momsbehandling</label>
|
||||
<div className="mt-1">
|
||||
{isLiabilityAccount ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Ingen moms för skuld-/eget kapital-konton
|
||||
</p>
|
||||
) : showVatDropdown ? (
|
||||
<VatTreatmentSelect
|
||||
value={vatTreatment}
|
||||
onValueChange={setVatTreatment}
|
||||
/>
|
||||
) : (
|
||||
<p className="text-sm">
|
||||
{VAT_TREATMENT_OPTIONS.find(o => o.value === vatTreatment)?.label || 'Ingen moms'}
|
||||
{' '}
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-primary hover:underline"
|
||||
onClick={() => setShowVatDropdown(true)}
|
||||
>
|
||||
Ändra
|
||||
</button>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium text-muted-foreground">Momsbehandling</label>
|
||||
<div className="mt-1">
|
||||
{isLiabilityAccount ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Ingen moms för skuld-/eget kapital-konton
|
||||
</p>
|
||||
) : showVatDropdown ? (
|
||||
<VatTreatmentSelect
|
||||
value={vatTreatment}
|
||||
onValueChange={setVatTreatment}
|
||||
/>
|
||||
) : (
|
||||
<p className="text-sm">
|
||||
{VAT_TREATMENT_OPTIONS.find(o => o.value === vatTreatment)?.label || 'Ingen moms'}
|
||||
{' '}
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-primary hover:underline"
|
||||
onClick={() => setShowVatDropdown(true)}
|
||||
>
|
||||
Ändra
|
||||
</button>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Document upload */}
|
||||
<div className="rounded-lg border">
|
||||
@@ -335,7 +344,7 @@ export default function QuickReviewDialog({
|
||||
<Button
|
||||
className="flex-1"
|
||||
onClick={handleConfirm}
|
||||
disabled={isProcessing || !accountOverride}
|
||||
disabled={isProcessing || (!isTemplateBooking && !accountOverride)}
|
||||
>
|
||||
<Check className="mr-2 h-4 w-4" />
|
||||
{isProcessing ? 'Bokför...' : 'Bokför'}
|
||||
|
||||
@@ -13,6 +13,8 @@ import {
|
||||
type TemplateGroup,
|
||||
} from '@/lib/bookkeeping/booking-templates'
|
||||
import { formatAccountWithName } from '@/lib/bookkeeping/client-account-names'
|
||||
import { isCounterpartyTemplateId } from '@/lib/bookkeeping/counterparty-templates'
|
||||
import { getAccountName } from '@/lib/bookkeeping/client-account-names'
|
||||
import type { EntityType } from '@/types'
|
||||
import type { SuggestedTemplate } from '@/lib/transactions/category-suggestions'
|
||||
|
||||
@@ -134,6 +136,7 @@ interface TemplatePickerProps {
|
||||
suggestedTemplates?: SuggestedTemplate[]
|
||||
recentTemplateIds?: string[]
|
||||
onSelect: (template: BookingTemplate) => void
|
||||
onSelectCounterparty?: (templateId: string) => void
|
||||
selectedTemplateId?: string
|
||||
}
|
||||
|
||||
@@ -142,6 +145,7 @@ export default function TemplatePicker({
|
||||
entityType,
|
||||
suggestedTemplates,
|
||||
onSelect,
|
||||
onSelectCounterparty,
|
||||
selectedTemplateId,
|
||||
}: TemplatePickerProps) {
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
@@ -196,8 +200,17 @@ export default function TemplatePicker({
|
||||
onSelect(template)
|
||||
}
|
||||
|
||||
// Suggested templates section
|
||||
const hasSuggestions = suggestedTemplates && suggestedTemplates.length > 0
|
||||
// Split suggestions: counterparty templates vs regular booking templates
|
||||
const counterpartySuggestions = useMemo(() => {
|
||||
if (!suggestedTemplates) return []
|
||||
return suggestedTemplates.filter(s => isCounterpartyTemplateId(s.template_id))
|
||||
}, [suggestedTemplates])
|
||||
const resolvedSuggestions = useMemo(() => {
|
||||
if (!suggestedTemplates) return []
|
||||
return suggestedTemplates.filter(s => !isCounterpartyTemplateId(s.template_id))
|
||||
}, [suggestedTemplates])
|
||||
const hasCounterparty = counterpartySuggestions.length > 0 && !!onSelectCounterparty
|
||||
const hasSuggestions = resolvedSuggestions.length > 0
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
@@ -233,12 +246,51 @@ export default function TemplatePicker({
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Counterparty templates — learned from history */}
|
||||
{hasCounterparty && (
|
||||
<div>
|
||||
<p className="text-xs font-medium text-muted-foreground mb-2">Tidigare motparter</p>
|
||||
<div className="space-y-1.5">
|
||||
{counterpartySuggestions.slice(0, 3).map((s) => (
|
||||
<button
|
||||
key={s.template_id}
|
||||
type="button"
|
||||
onClick={() => onSelectCounterparty!(s.template_id)}
|
||||
className="w-full text-left rounded-lg border border-border px-3 py-2.5 transition-colors hover:bg-muted/50"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="font-medium text-sm leading-tight">{s.name_sv}</p>
|
||||
<div className="flex items-center gap-2 mt-1 flex-wrap">
|
||||
{s.line_pattern && s.line_pattern.length > 0 ? (
|
||||
s.line_pattern.filter(lp => lp.type === 'business').map((lp, i) => (
|
||||
<span key={i} className="text-xs font-mono text-muted-foreground">
|
||||
{formatAccountWithName(lp.account)}
|
||||
</span>
|
||||
))
|
||||
) : (
|
||||
<span className="text-xs font-mono text-muted-foreground">
|
||||
D: {getAccountName(s.debit_account)} · K: {getAccountName(s.credit_account)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<span className="text-[10px] text-muted-foreground flex-shrink-0 mt-0.5">
|
||||
{s.description_sv}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Suggested templates */}
|
||||
{hasSuggestions && (
|
||||
<div>
|
||||
<p className="text-xs font-medium text-muted-foreground mb-2">Föreslagna</p>
|
||||
<div className="space-y-1.5">
|
||||
{suggestedTemplates!.slice(0, 5).map((s) => {
|
||||
{resolvedSuggestions.slice(0, 5).map((s) => {
|
||||
// Find the full template object
|
||||
const fullTemplate = allCommon.find((t) => t.id === s.template_id) ||
|
||||
allAdvanced.find((t) => t.id === s.template_id)
|
||||
|
||||
@@ -8,8 +8,9 @@ import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { cn, formatCurrency, formatDate } from '@/lib/utils'
|
||||
import { ArrowUpRight, ArrowDownRight, FileText, Loader2, MessageSquareText, Paperclip } from 'lucide-react'
|
||||
import { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } from '@/components/ui/info-tooltip'
|
||||
import { formatAccountWithName } from '@/lib/bookkeeping/client-account-names'
|
||||
import { getAccountName, formatAccountWithName } from '@/lib/bookkeeping/client-account-names'
|
||||
import { getTemplateById } from '@/lib/bookkeeping/booking-templates'
|
||||
import { isCounterpartyTemplateId } from '@/lib/bookkeeping/counterparty-templates'
|
||||
import type { TransactionWithInvoice, CategorizeHandler } from './transaction-types'
|
||||
import type { SuggestedCategory, SuggestedTemplate } from '@/lib/transactions/category-suggestions'
|
||||
|
||||
@@ -178,7 +179,8 @@ export default function TransactionInboxCard({
|
||||
) : templateSuggestions && templateSuggestions.length > 0 ? (
|
||||
<>
|
||||
{templateSuggestions.slice(0, 2).map((ts, idx) => {
|
||||
const tmpl = getTemplateById(ts.template_id)
|
||||
const isCounterparty = isCounterpartyTemplateId(ts.template_id)
|
||||
const tmpl = isCounterparty ? null : getTemplateById(ts.template_id)
|
||||
return (
|
||||
<Button
|
||||
key={ts.template_id}
|
||||
@@ -186,7 +188,7 @@ export default function TransactionInboxCard({
|
||||
variant={idx === 0 ? 'default' : 'outline'}
|
||||
className="h-auto py-1.5 text-xs"
|
||||
onClick={() => {
|
||||
if (onOpenTemplateReview && tmpl) {
|
||||
if (onOpenTemplateReview && (isCounterparty || tmpl)) {
|
||||
onOpenTemplateReview(transaction, ts.template_id)
|
||||
} else if (topSuggestion) {
|
||||
handleSuggestionClick(topSuggestion)
|
||||
@@ -201,8 +203,11 @@ export default function TransactionInboxCard({
|
||||
) : null}
|
||||
{ts.name_sv}
|
||||
</div>
|
||||
<span className="opacity-70 font-normal font-mono text-[10px]">
|
||||
D: {formatAccountWithName(ts.debit_account)} → K: {formatAccountWithName(ts.credit_account)}
|
||||
<span className="opacity-70 font-normal text-[10px]">
|
||||
{isCounterparty
|
||||
? `${ts.description_sv}`
|
||||
: getAccountName(tmpl?.debit_account || ts.debit_account)
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
</Button>
|
||||
|
||||
Reference in New Issue
Block a user