d9c95a7b59
* 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>
273 lines
12 KiB
TypeScript
273 lines
12 KiB
TypeScript
'use client'
|
|
|
|
import { motion } from 'framer-motion'
|
|
import { Card, CardContent } from '@/components/ui/card'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Badge } from '@/components/ui/badge'
|
|
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 { 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'
|
|
|
|
interface TransactionInboxCardProps {
|
|
transaction: TransactionWithInvoice
|
|
suggestions?: SuggestedCategory[]
|
|
templateSuggestions?: SuggestedTemplate[]
|
|
processingId: string | null
|
|
isBatchMode: boolean
|
|
isSelected: boolean
|
|
entityType?: string
|
|
onCategorize: CategorizeHandler
|
|
onMarkPrivate: (id: string) => void
|
|
onOpenMatchDialog: (transaction: TransactionWithInvoice) => void
|
|
onOpenCategoryDialog: (transaction: TransactionWithInvoice) => void
|
|
onOpenDescribe?: (transaction: TransactionWithInvoice) => void
|
|
onOpenQuickReview?: (transaction: TransactionWithInvoice, suggestion: SuggestedCategory) => void
|
|
onOpenTemplateReview?: (transaction: TransactionWithInvoice, templateId: string) => void
|
|
onToggleSelect: (id: string) => void
|
|
onAnimationComplete?: (id: string) => void
|
|
}
|
|
|
|
export default function TransactionInboxCard({
|
|
transaction,
|
|
suggestions,
|
|
templateSuggestions,
|
|
processingId,
|
|
isBatchMode,
|
|
isSelected,
|
|
entityType = 'enskild_firma',
|
|
onCategorize,
|
|
onMarkPrivate,
|
|
onOpenMatchDialog,
|
|
onOpenCategoryDialog,
|
|
onOpenDescribe,
|
|
onOpenQuickReview,
|
|
onOpenTemplateReview,
|
|
onToggleSelect,
|
|
onAnimationComplete,
|
|
}: TransactionInboxCardProps) {
|
|
const isProcessing = processingId === transaction.id
|
|
const isDisabled = processingId !== null && processingId !== transaction.id
|
|
const isIncome = transaction.amount > 0
|
|
const hasInvoiceMatch = !!transaction.potential_invoice && !transaction.invoice_id
|
|
const hasSupplierInvoiceMatch = !!transaction.potential_supplier_invoice && !transaction.supplier_invoice_id
|
|
const topSuggestion = suggestions?.[0]
|
|
const isUncategorized = transaction.is_business === null && !transaction.journal_entry_id
|
|
const showCheckbox = isBatchMode && isUncategorized
|
|
const hasDocumentMatch = !!transaction.matched_inbox_item
|
|
|
|
function handleSuggestionClick(suggestion: SuggestedCategory) {
|
|
if (onOpenQuickReview) {
|
|
onOpenQuickReview(transaction, suggestion)
|
|
} else {
|
|
onCategorize(transaction.id, true, suggestion.category)
|
|
}
|
|
}
|
|
|
|
return (
|
|
<motion.div
|
|
layout
|
|
initial={{ opacity: 1, scale: 1 }}
|
|
exit={{ opacity: 0, scale: 0.95, x: -16 }}
|
|
transition={{ duration: 0.25, ease: [0.25, 0.46, 0.45, 0.94] }}
|
|
onAnimationComplete={(definition) => {
|
|
// Only call on exit animation
|
|
if (typeof definition === 'object' && 'opacity' in definition && definition.opacity === 0) {
|
|
onAnimationComplete?.(transaction.id)
|
|
}
|
|
}}
|
|
>
|
|
<Card
|
|
className={cn(
|
|
'transition-colors',
|
|
hasInvoiceMatch || hasSupplierInvoiceMatch ? 'border-primary/50' : 'border-warning/50',
|
|
isSelected && 'border-primary bg-primary/[0.02]',
|
|
isDisabled && 'opacity-50'
|
|
)}
|
|
onClick={showCheckbox ? () => onToggleSelect(transaction.id) : undefined}
|
|
>
|
|
<CardContent className="py-4">
|
|
<div className="flex items-start justify-between gap-4">
|
|
{/* Left: checkbox + icon + info */}
|
|
<div className="flex items-start gap-3 min-w-0 flex-1">
|
|
{showCheckbox && (
|
|
<Checkbox
|
|
checked={isSelected}
|
|
onCheckedChange={() => onToggleSelect(transaction.id)}
|
|
onClick={(e) => e.stopPropagation()}
|
|
className="mt-1"
|
|
/>
|
|
)}
|
|
<div
|
|
className={`h-9 w-9 rounded-full flex items-center justify-center flex-shrink-0 ${isIncome ? 'bg-success/10 text-success' : 'bg-destructive/10 text-destructive'}`}
|
|
aria-hidden="true"
|
|
>
|
|
{isIncome ? (
|
|
<ArrowUpRight className="h-5 w-5" />
|
|
) : (
|
|
<ArrowDownRight className="h-5 w-5" />
|
|
)}
|
|
</div>
|
|
<div className="min-w-0">
|
|
<p className="font-medium truncate">{transaction.description}</p>
|
|
<div className="flex items-center gap-2">
|
|
<p className="text-sm text-muted-foreground">{formatDate(transaction.date)}</p>
|
|
{hasDocumentMatch && (
|
|
<Badge variant="secondary" className="text-xs gap-1">
|
|
<Paperclip className="h-3 w-3" />
|
|
{transaction.matched_inbox_item!.document_type === 'receipt' ? 'Kvitto' :
|
|
transaction.matched_inbox_item!.document_type === 'supplier_invoice' ? 'Faktura' : 'Dokument'}
|
|
</Badge>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Right: amount */}
|
|
<div className="text-right flex-shrink-0">
|
|
<p className={cn('font-medium tabular-nums', isIncome && 'text-success')}>
|
|
{isIncome ? '+' : ''}
|
|
{formatCurrency(transaction.amount, transaction.currency)}
|
|
</p>
|
|
{transaction.currency !== 'SEK' && transaction.amount_sek && (
|
|
<p className="text-sm text-muted-foreground">
|
|
{formatCurrency(transaction.amount_sek)}
|
|
</p>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
{/* Inline action buttons - only shown when not in batch mode */}
|
|
{!isBatchMode && (
|
|
<div className="flex flex-wrap items-center gap-2 mt-3 pt-3 border-t">
|
|
{/* Primary action: invoice match or top suggestion */}
|
|
{hasInvoiceMatch ? (
|
|
<Button
|
|
size="sm"
|
|
variant="default"
|
|
className="h-9 text-xs max-w-full truncate"
|
|
onClick={() => onOpenMatchDialog(transaction)}
|
|
disabled={isProcessing || isDisabled}
|
|
>
|
|
{isProcessing ? (
|
|
<Loader2 className="mr-1.5 h-3 w-3 animate-spin flex-shrink-0" />
|
|
) : (
|
|
<FileText className="mr-1.5 h-3 w-3 flex-shrink-0" />
|
|
)}
|
|
Matcha Faktura {transaction.potential_invoice!.invoice_number}
|
|
</Button>
|
|
) : hasSupplierInvoiceMatch ? (
|
|
<Button
|
|
size="sm"
|
|
variant="default"
|
|
className="h-9 text-xs max-w-full truncate"
|
|
onClick={() => onOpenMatchDialog(transaction)}
|
|
disabled={isProcessing || isDisabled}
|
|
>
|
|
{isProcessing ? (
|
|
<Loader2 className="mr-1.5 h-3 w-3 animate-spin flex-shrink-0" />
|
|
) : (
|
|
<FileText className="mr-1.5 h-3 w-3 flex-shrink-0" />
|
|
)}
|
|
Matcha Leverantörsfaktura {transaction.potential_supplier_invoice!.supplier_invoice_number}
|
|
</Button>
|
|
) : templateSuggestions && templateSuggestions.length > 0 ? (
|
|
<>
|
|
{templateSuggestions.slice(0, 2).map((ts, idx) => {
|
|
const isCounterparty = isCounterpartyTemplateId(ts.template_id)
|
|
const tmpl = isCounterparty ? null : getTemplateById(ts.template_id)
|
|
return (
|
|
<Button
|
|
key={ts.template_id}
|
|
size="sm"
|
|
variant={idx === 0 ? 'default' : 'outline'}
|
|
className="h-auto py-1.5 text-xs"
|
|
onClick={() => {
|
|
if (onOpenTemplateReview && (isCounterparty || tmpl)) {
|
|
onOpenTemplateReview(transaction, ts.template_id)
|
|
} else if (topSuggestion) {
|
|
handleSuggestionClick(topSuggestion)
|
|
}
|
|
}}
|
|
disabled={isProcessing || isDisabled}
|
|
>
|
|
<div className="flex flex-col items-start">
|
|
<div className="flex items-center">
|
|
{isProcessing && idx === 0 ? (
|
|
<Loader2 className="mr-1.5 h-3 w-3 animate-spin" />
|
|
) : null}
|
|
{ts.name_sv}
|
|
</div>
|
|
<span className="opacity-70 font-normal text-[10px]">
|
|
{isCounterparty
|
|
? `${ts.description_sv}`
|
|
: getAccountName(tmpl?.debit_account || ts.debit_account)
|
|
}
|
|
</span>
|
|
</div>
|
|
</Button>
|
|
)
|
|
})}
|
|
</>
|
|
) : topSuggestion ? (
|
|
<Button
|
|
size="sm"
|
|
variant="default"
|
|
className="h-9 text-xs"
|
|
onClick={() => handleSuggestionClick(topSuggestion)}
|
|
disabled={isProcessing || isDisabled}
|
|
>
|
|
{isProcessing ? (
|
|
<Loader2 className="mr-1.5 h-3 w-3 animate-spin" />
|
|
) : null}
|
|
{topSuggestion.label}
|
|
{topSuggestion.account && (
|
|
<span className="ml-1 opacity-70 font-normal">
|
|
({formatAccountWithName(topSuggestion.account)})
|
|
</span>
|
|
)}
|
|
{topSuggestion.confidence >= 0.8 && (
|
|
<Badge variant="secondary" className="ml-1.5 text-[10px] px-1 py-0">
|
|
{Math.round(topSuggestion.confidence * 100)}%
|
|
</Badge>
|
|
)}
|
|
</Button>
|
|
) : null}
|
|
|
|
{/* Describe transaction */}
|
|
{onOpenDescribe && (
|
|
<Button
|
|
size="sm"
|
|
variant="outline"
|
|
className="h-9 text-xs"
|
|
onClick={() => onOpenDescribe(transaction)}
|
|
disabled={isProcessing || isDisabled}
|
|
>
|
|
<MessageSquareText className="mr-1.5 h-3 w-3" />
|
|
Beskriv...
|
|
</Button>
|
|
)}
|
|
|
|
{/* Open category dialog / template picker */}
|
|
<Button
|
|
size="sm"
|
|
variant={!hasInvoiceMatch && !hasSupplierInvoiceMatch && !topSuggestion && (!templateSuggestions || templateSuggestions.length === 0) ? 'default' : 'outline'}
|
|
className="h-9 text-xs"
|
|
onClick={() => onOpenCategoryDialog(transaction)}
|
|
disabled={isProcessing || isDisabled}
|
|
>
|
|
Välj mall...
|
|
</Button>
|
|
</div>
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
</motion.div>
|
|
)
|
|
}
|