'use client' import { useState, useEffect, useMemo } from 'react' import { useRouter } from 'next/navigation' import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from '@/components/ui/dialog' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Badge } from '@/components/ui/badge' import { useToast } from '@/components/ui/use-toast' import AccountCombobox from '@/components/bookkeeping/AccountCombobox' import { proposePaymentLines } from '@/lib/bookkeeping/propose-payment-lines' import { getErrorMessage } from '@/lib/errors/get-error-message' import { formatCurrency, formatDate } from '@/lib/utils' import { createClient } from '@/lib/supabase/client' import { useCompany } from '@/contexts/CompanyContext' import { Plus, Trash2, Loader2 } from 'lucide-react' import type { FormLine } from '@/components/bookkeeping/JournalEntryForm' import type { Invoice, InvoiceItem, Customer, BASAccount, EntityType } from '@/types' type DuplicateMatchReason = 'ocr_exact' | 'name_amount_fuzzy' | 'amount_only' interface DuplicateCandidate { id: string date: string amount: number description: string | null merchant_name: string | null reference: string | null match_reason: DuplicateMatchReason match_confidence: number } const MATCH_REASON_LABEL: Record = { ocr_exact: 'Exakt OCR-träff', name_amount_fuzzy: 'Sannolik träff', amount_only: 'Möjlig träff', } interface InvoiceWithRelations extends Invoice { customer: Customer items: InvoiceItem[] } interface PaymentBookingDialogProps { open: boolean onOpenChange: (open: boolean) => void invoice: InvoiceWithRelations onSuccess: () => void } const BLANK_LINE: FormLine = { account_number: '', debit_amount: '', credit_amount: '', line_description: '' } export default function PaymentBookingDialog({ open, onOpenChange, invoice, onSuccess, }: PaymentBookingDialogProps) { const { toast } = useToast() const router = useRouter() const supabase = createClient() const { company } = useCompany() const [accounts, setAccounts] = useState([]) const [lines, setLines] = useState([]) const [paymentDate, setPaymentDate] = useState(() => new Date().toISOString().split('T')[0]) const [isSubmitting, setIsSubmitting] = useState(false) const [isInitialized, setIsInitialized] = useState(false) const [duplicateCandidates, setDuplicateCandidates] = useState(null) // Load accounts and settings when dialog opens useEffect(() => { if (!open) { setIsInitialized(false) setDuplicateCandidates(null) return } let cancelled = false async function init() { try { // Fetch accounts const accountsRes = await fetch('/api/bookkeeping/accounts') if (!accountsRes.ok) throw new Error('Kunde inte ladda kontoplanen') const accountsData = await accountsRes.json() const fetchedAccounts: BASAccount[] = accountsData.data || [] if (!company?.id) throw new Error('Inget aktivt företag') // Fetch company settings const { data: settings, error: settingsError } = await supabase .from('company_settings') .select('accounting_method, entity_type') .eq('company_id', company.id) .maybeSingle() if (settingsError) throw new Error('Kunde inte ladda företagsinställningar') if (cancelled) return setAccounts(fetchedAccounts) const accountingMethod = (settings?.accounting_method || 'accrual') as 'accrual' | 'cash' const entityType = (settings?.entity_type as EntityType) || 'enskild_firma' const proposed = proposePaymentLines({ invoice: { invoice_number: invoice.invoice_number, total: invoice.total, total_sek: invoice.total_sek, subtotal: invoice.subtotal, subtotal_sek: invoice.subtotal_sek, vat_amount: invoice.vat_amount, vat_amount_sek: invoice.vat_amount_sek, currency: invoice.currency, exchange_rate: invoice.exchange_rate, vat_treatment: invoice.vat_treatment, items: invoice.items, }, accountingMethod, entityType, }) setLines(proposed) setPaymentDate(new Date().toISOString().split('T')[0]) setIsInitialized(true) } catch (err) { if (cancelled) return toast({ title: 'Kunde inte ladda bokföringsdialog', description: err instanceof Error ? err.message : 'Försök igen.', variant: 'destructive', }) onOpenChange(false) } } init() return () => { cancelled = true } }, [open, invoice.id, company?.id]) // Balance computation const { totalDebit, totalCredit, isBalanced } = useMemo(() => { let totalDebit = 0 let totalCredit = 0 for (const line of lines) { totalDebit += parseFloat(line.debit_amount) || 0 totalCredit += parseFloat(line.credit_amount) || 0 } const isBalanced = Math.round((totalDebit - totalCredit) * 100) === 0 && totalDebit > 0 return { totalDebit, totalCredit, isBalanced } }, [lines]) const updateLine = (index: number, field: keyof FormLine, value: string) => { setLines((prev) => { const next = [...prev] const updated = { ...next[index], [field]: value } // Debit/credit exclusion: clear the other when one is entered if (field === 'debit_amount' && value) { updated.credit_amount = '' } else if (field === 'credit_amount' && value) { updated.debit_amount = '' } next[index] = updated return next }) } const addLine = () => { setLines((prev) => [...prev, { ...BLANK_LINE }]) } const removeLine = (index: number) => { if (lines.length <= 2) return setLines((prev) => prev.filter((_, i) => i !== index)) } const submit = async (force: boolean) => { if (!isBalanced) return setIsSubmitting(true) try { const apiLines = lines .filter((l) => l.account_number && (parseFloat(l.debit_amount) || parseFloat(l.credit_amount))) .map((l) => ({ account_number: l.account_number, debit_amount: parseFloat(l.debit_amount) || 0, credit_amount: parseFloat(l.credit_amount) || 0, line_description: l.line_description || undefined, })) const response = await fetch(`/api/invoices/${invoice.id}/mark-paid`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ payment_date: paymentDate, lines: apiLines, ...(force ? { force: true } : {}), }), }) if (!response.ok) { const data = await response.json() const code = (data as { error?: { code?: string } })?.error?.code if (code === 'INVOICE_PAID_LIKELY_DUPLICATE') { const details = (data as { error?: { details?: { candidates?: DuplicateCandidate[] } } }) ?.error?.details setDuplicateCandidates(details?.candidates ?? []) setIsSubmitting(false) return } const error = new Error('Kunde inte markera som betald') as Error & { body?: unknown; status?: number } error.body = data error.status = response.status throw error } onOpenChange(false) onSuccess() } catch (error) { const anyErr = error as { body?: unknown; status?: number } toast({ title: 'Bokföring misslyckades', description: getErrorMessage(anyErr.body ?? error, { context: 'invoice', statusCode: anyErr.status }), variant: 'destructive', }) } setIsSubmitting(false) } const handleSubmit = () => submit(false) const handleForceSubmit = () => submit(true) const handleLinkExisting = (transactionId: string) => { onOpenChange(false) router.push(`/transactions?highlight=${encodeURIComponent(transactionId)}`) } return ( Bokför betalning{invoice.invoice_number ? ` — ${invoice.invoice_number}` : ''} {formatCurrency(invoice.total, invoice.currency)} {invoice.currency !== 'SEK' && invoice.total_sek && ( <> ({formatCurrency(invoice.total_sek)} SEK) )} {duplicateCandidates && duplicateCandidates.length > 0 ? (

Möjlig dubblettbetalning

{duplicateCandidates.length === 1 ? 'En inkommande banktransaktion ser ut att vara denna betalning. Länka den istället för att skapa en ny verifikation, eller bokför ändå om du är säker.' : `${duplicateCandidates.length} inkommande banktransaktioner ser ut att kunna vara denna betalning. Länka rätt transaktion istället för att skapa en ny verifikation, eller bokför ändå om du är säker.`}

    {duplicateCandidates.map((c) => { const reasonVariant: 'success' | 'secondary' | 'outline' = c.match_reason === 'ocr_exact' ? 'success' : c.match_reason === 'name_amount_fuzzy' ? 'secondary' : 'outline' return (
  • {MATCH_REASON_LABEL[c.match_reason]} {formatDate(c.date)} {formatCurrency(c.amount, invoice.currency)}

    {c.merchant_name || c.description || '—'}

  • ) })}
) : !isInitialized ? (
) : (
{/* Payment date */}
setPaymentDate(e.target.value)} className="w-full sm:w-48" />
{/* Journal entry lines */} {/* Mobile card layout */}
{lines.map((line, index) => (
updateLine(index, 'account_number', val)} />
updateLine(index, 'debit_amount', e.target.value)} className="font-mono text-right" inputMode="decimal" />
updateLine(index, 'credit_amount', e.target.value)} className="font-mono text-right" inputMode="decimal" />
))}
{/* Desktop table layout */}
{/* Header */}
Konto Debet Kredit
{/* Lines */} {lines.map((line, index) => (
updateLine(index, 'account_number', val)} />
updateLine(index, 'debit_amount', e.target.value)} className="font-mono text-right h-8" /> updateLine(index, 'credit_amount', e.target.value)} className="font-mono text-right h-8" />
))} {/* Add row */}
{/* Balance indicator */}
{isBalanced ? ( Debet = Kredit ) : ( Obalanserad ({formatCurrency(Math.abs(totalDebit - totalCredit))}) )}
{formatCurrency(totalDebit)} / {formatCurrency(totalCredit)}
)} {duplicateCandidates && duplicateCandidates.length > 0 ? ( ) : ( )}
) }