'use client' import { useState, useEffect, useMemo } from 'react' import { useAccounts, useCompanySettings } from '@/lib/reference-data/hooks' import { useRouter } from 'next/navigation' import { useTranslations } from 'next-intl' 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 { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs' import { useToast } from '@/components/ui/use-toast' import AccountCombobox from '@/components/bookkeeping/AccountCombobox' import LinkVoucherPicker from '@/components/invoices/LinkVoucherPicker' import { proposePaymentLines, resolveInvoicePaymentSourceType } from '@/lib/bookkeeping/propose-payment-lines' import { getErrorMessage } from '@/lib/errors/get-error-message' import { formatCurrency, formatDate } from '@/lib/utils' import { useCompany } from '@/contexts/CompanyContext' import { Plus, Trash2, Loader2 } from 'lucide-react' import type { FormLine } from '@/components/bookkeeping/JournalEntryForm' import type { EntityType } from '@/types' import type { InvoiceWithRelations } from '@/components/invoices/types' import { loadBasCatalog, type CatalogAccount } from '@/lib/bookkeeping/bas-catalog-client' 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 } 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 { company } = useCompany() const t = useTranslations('invoice_payment_dialog') const MATCH_REASON_LABEL: Record = { ocr_exact: t('match_reason_ocr_exact'), name_amount_fuzzy: t('match_reason_name_amount_fuzzy'), amount_only: t('match_reason_amount_only'), } // Session-cached reference data (lib/reference-data), seeded by the // dashboard layout: the chart and the settings are known on the first // paint, so the proposed lines and the voucher preview resolve as soon as // the dialog opens instead of after two sequential requests. const { accounts, isLoading: accountsLoading, error: accountsError } = useAccounts() const { settings: companySettings, isLoading: settingsLoading, error: settingsError, } = useCompanySettings() const [catalog, setCatalog] = useState([]) const [lines, setLines] = useState([]) const accountNameByNumber = useMemo(() => { const names = new Map(catalog.map((account) => [account.account_number, account.account_name])) for (const account of accounts) names.set(account.account_number, account.account_name) return names }, [accounts, catalog]) 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) const [tab, setTab] = useState<'new' | 'existing'>('new') // Drives the "Befintlig verifikation" picker copy: cash links against a 19xx // debit, accrual against a 1510 credit. const accountingMethod: 'accrual' | 'cash' = companySettings?.accounting_method === 'cash' ? 'cash' : 'accrual' // source_type the booking will use: drives the voucher-series preview so the // number shown matches what mark-paid will actually create. const [sourceType, setSourceType] = useState<'invoice_cash_payment' | 'invoice_paid' | null>(null) const [nextVoucher, setNextVoucher] = useState<{ series: string; next: number | null } | null>(null) // Load accounts and settings when dialog opens useEffect(() => { if (!open) { setIsInitialized(false) setDuplicateCandidates(null) setTab('new') setSourceType(null) setNextVoucher(null) return } // Reference data still loading (no seed, first mount of the session): // the effect re-runs once it lands. if (accountsLoading || settingsLoading) return let cancelled = false async function init() { try { if (accountsError) throw new Error(t('load_chart_failed')) if (!company?.id) throw new Error(t('no_active_company')) if (settingsError) throw new Error(t('load_settings_failed')) const fetchedCatalog = await loadBasCatalog() if (cancelled) return setCatalog(fetchedCatalog) const settings = companySettings // /api/settings used to fall back to the company row's entity type // when company_settings.entity_type is null; the cached row does not. const entityType: EntityType = (settings?.entity_type as EntityType | null | undefined) ?? company.entity_type ?? 'enskild_firma' setSourceType( resolveInvoicePaymentSourceType({ invoiceAlreadyBooked: !!invoice.journal_entry_id, accountingMethod, }), ) 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, default_dimensions: invoice.default_dimensions, ore_rounding: invoice.ore_rounding, deduction_total: invoice.deduction_total, // #1717: lets the proposal clear the actual remaining on a // partially_paid invoice (öre write-off when < 1 kr remains). paid_amount: invoice.paid_amount, remaining_amount: invoice.remaining_amount, }, accountingMethod, entityType, companyOreRounding: typeof settings?.ore_rounding === 'boolean' ? settings.ore_rounding : undefined, }) setLines(proposed) setPaymentDate(new Date().toISOString().split('T')[0]) setIsInitialized(true) } catch (err) { if (cancelled) return toast({ title: t('load_dialog_failed_title'), description: err instanceof Error ? getErrorMessage(err) : t('try_again'), variant: 'destructive', }) onOpenChange(false) } } init() return () => { cancelled = true } // companySettings and accountingMethod are read at init time on purpose: a // background revalidation of the settings row must not re-run init() // (and reset the user's lines) mid-dialog. // eslint-disable-next-line react-hooks/exhaustive-deps }, [open, invoice.id, company?.id, accountsLoading, settingsLoading, accountsError, settingsError]) // Voucher-series preview: resolve the upcoming serie + nummer the same way the // booking engine will, so a misconfigured series is visible before confirming. // Re-runs when the payment date changes (vouchers are numbered per period). useEffect(() => { if (!open || !sourceType) return let cancelled = false const qs = new URLSearchParams({ source_type: sourceType, date: paymentDate }) fetch(`/api/bookkeeping/voucher-sequences/next?${qs}`) .then((res) => (res.ok ? res.json() : null)) .then((json) => { if (cancelled || !json?.data) return setNextVoucher({ series: json.data.series, next: json.data.next }) }) .catch(() => { if (!cancelled) setNextVoucher(null) }) return () => { cancelled = true } }, [open, sourceType, paymentDate]) // 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, // Dimensions PR7: the proposal re-propagates the invoice default; // whatever the grid holds is what gets booked. dimensions: l.dimensions && Object.keys(l.dimensions).length > 0 ? l.dimensions : 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(t('mark_paid_failed')) 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: t('booking_failed_title'), 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 ( {/* data-ph-mask: the invoice number is user data */} {t('title')}{invoice.invoice_number ? ( {t('title_suffix', { number: invoice.invoice_number })} ) : ''} {nextVoucher && ( ({nextVoucher.series}{nextVoucher.next}) )} {formatCurrency(invoice.total, invoice.currency)} {invoice.currency !== 'SEK' && invoice.total_sek && ( <>{t('description_sek_suffix', { amount: formatCurrency(invoice.total_sek) })} )} {duplicateCandidates && duplicateCandidates.length > 0 ? (

{t('duplicate_title')}

{duplicateCandidates.length === 1 ? t('duplicate_one') : t('duplicate_many', { count: duplicateCandidates.length })}

    {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 || '-'}

  • ) })}
) : ( setTab(v as 'new' | 'existing')}> {t('tab_new_payment')} {t('tab_existing_voucher')} { onOpenChange(false) onSuccess() }} onCancel={() => setTab('new')} /> {!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)} selectedName={accountNameByNumber.get(line.account_number)} />
updateLine(index, 'debit_amount', e.target.value)} className="tabular-nums text-right" inputMode="decimal" />
updateLine(index, 'credit_amount', e.target.value)} className="tabular-nums text-right" inputMode="decimal" />
))}
{/* Desktop table layout */}
{/* Header */}
{t('account_label')} {t('debit_label')} {t('credit_label')}
{/* Lines */} {lines.map((line, index) => (
updateLine(index, 'account_number', val)} selectedName={accountNameByNumber.get(line.account_number)} />
updateLine(index, 'debit_amount', e.target.value)} className="tabular-nums text-right" /> updateLine(index, 'credit_amount', e.target.value)} className="tabular-nums text-right" />
))} {/* Add row */}
{/* Balance indicator */}
{isBalanced ? ( {t('balanced_badge')} ) : ( {t('unbalanced_badge', { delta: formatCurrency(Math.abs(totalDebit - totalCredit)) })} )}
{formatCurrency(totalDebit)} / {formatCurrency(totalCredit)}
)}
)} {(duplicateCandidates && duplicateCandidates.length > 0) || tab === 'new' ? ( {duplicateCandidates && duplicateCandidates.length > 0 ? ( ) : ( )} ) : null}
) }