* fix: include reversed entries in all reports (general ledger, trial balance, VAT, SIE, NE, INK2) Reversed entries (storno) must appear alongside their original posted entries in reports for a complete audit trail. Previously, filtering by status='posted' excluded them, causing discrepancies when corrections had been made. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: semi-manual invoice payment booking with editable journal lines When marking an invoice as paid, users now see a dialog where they can: - Choose which bank/cash account the payment goes to (1910, 1920, 1930, etc.) - Review and edit the proposed journal entry lines before committing - The happy path remains fast — lines are pre-filled correctly Implementation: - Pure proposePaymentLines() function for line computation (accrual + cash) - PaymentBookingDialog with AccountCombobox, balance validation, date picker - API accepts optional custom lines, falls back to auto-generation without them - 18 tests (8 unit + 10 API) all passing Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address Greptile review — validation fallback, balance check, error handling - P1: Return 400 on invalid body instead of silently falling back to auto-generated lines (split JSON parse from schema validation) - P1: Add server-side balance check for custom lines before committing (debit must equal credit, totalDebit > 0) - P2: Wrap PaymentBookingDialog init() in try/catch with toast on failure and auto-close instead of silent empty state - Add 2 new tests: unbalanced lines → 400, invalid schema → 400 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: OAuth callback redirect for local dev and timeout resilience - Pass redirectUri dynamically from NEXT_PUBLIC_APP_URL so OAuth callbacks work on localhost (not just production) - Encode consentId/provider in OAuth state (base64url JSON) so the callback doesn't depend on session storage - Add skipAuth flag to extension API routes for OAuth callbacks (external provider redirects have no user session cookie) - Wrap AbortError in descriptive timeout messages in arcim-client - Make preview endpoint resilient to partial failures (company info and SIE fetch are individually non-blocking) - Simplify login page (remove unused magic link auth mode) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: create journal entry before marking invoice as paid Move journal entry creation before the invoice status update so that if accounting fails, the invoice is not permanently marked paid without a corresponding entry. Previously the error was silently swallowed. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: update mark-paid tests for journal-first ordering Reorder mock queue to match new flow (settings before update), update failure test to expect 500 instead of silent success, add try-catch with proper error response in route handler. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add reverse charge VAT (ruta 20-32) and improve mobile UX across dashboard Add full reverse charge (omvänd skattskyldighet) support to the VAT declaration: - Map accounts 2614/2624/2634 to ruta 30/31/32 for self-assessed output VAT - Calculate purchase bases (ruta 20-24) from supplier invoices by supplier type - Include ruta 30-32 in ruta 49 formula and totalOutputVat summary - Display reverse charge section in reports UI and composition chart - Add comprehensive test coverage for all reverse charge scenarios Improve mobile UX across the app: - Convert nav drawer to bottom sheet with drag handle and safe area padding - Add mobile card layout for PaymentBookingDialog journal lines - Replace settings tab pills with dropdown selector on mobile - Make wizard step indicators responsive (collapsed on mobile) - Ensure all dialog footers stack buttons full-width on mobile - Add 44px minimum touch targets throughout - Make onboarding buttons full-width on mobile Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address Greptile review — indentation, query efficiency, tab dedup - Fix misleading try-block indentation in mark-paid route - Filter reversed entries at DB level (.eq('status', 'posted')) instead of fetching then discarding in memory - Extract shared settingsTabs array so mobile Select and desktop TabsList stay in sync automatically Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
390 lines
14 KiB
TypeScript
390 lines
14 KiB
TypeScript
'use client'
|
|
|
|
import { useState, useEffect, useMemo } from 'react'
|
|
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 { formatCurrency } from '@/lib/utils'
|
|
import { createClient } from '@/lib/supabase/client'
|
|
import { Plus, Trash2, Loader2, CheckCircle2, AlertTriangle } from 'lucide-react'
|
|
import type { FormLine } from '@/components/bookkeeping/JournalEntryForm'
|
|
import type { Invoice, InvoiceItem, Customer, BASAccount, EntityType } from '@/types'
|
|
|
|
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 supabase = createClient()
|
|
|
|
const [accounts, setAccounts] = useState<BASAccount[]>([])
|
|
const [lines, setLines] = useState<FormLine[]>([])
|
|
const [paymentDate, setPaymentDate] = useState(() => new Date().toISOString().split('T')[0])
|
|
const [isSubmitting, setIsSubmitting] = useState(false)
|
|
const [isInitialized, setIsInitialized] = useState(false)
|
|
|
|
// Load accounts and settings when dialog opens
|
|
useEffect(() => {
|
|
if (!open) {
|
|
setIsInitialized(false)
|
|
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 || []
|
|
|
|
// Fetch company settings
|
|
const { data: settings, error: settingsError } = await supabase
|
|
.from('company_settings')
|
|
.select('accounting_method, entity_type')
|
|
.single()
|
|
|
|
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])
|
|
|
|
// 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 handleSubmit = async () => {
|
|
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,
|
|
}),
|
|
})
|
|
|
|
if (!response.ok) {
|
|
const data = await response.json()
|
|
throw new Error(data.error || 'Kunde inte markera som betald')
|
|
}
|
|
|
|
onOpenChange(false)
|
|
onSuccess()
|
|
} catch (error) {
|
|
toast({
|
|
title: 'Bokföring misslyckades',
|
|
description: error instanceof Error ? error.message : 'Försök igen.',
|
|
variant: 'destructive',
|
|
})
|
|
}
|
|
|
|
setIsSubmitting(false)
|
|
}
|
|
|
|
return (
|
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
|
<DialogContent className="sm:max-w-[680px]">
|
|
<DialogHeader>
|
|
<DialogTitle>Bokför betalning — {invoice.invoice_number}</DialogTitle>
|
|
<DialogDescription>
|
|
{formatCurrency(invoice.total, invoice.currency)}
|
|
{invoice.currency !== 'SEK' && invoice.total_sek && (
|
|
<> ({formatCurrency(invoice.total_sek)} SEK)</>
|
|
)}
|
|
</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
{!isInitialized ? (
|
|
<div className="flex items-center justify-center py-12">
|
|
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
|
</div>
|
|
) : (
|
|
<div className="space-y-4">
|
|
{/* Payment date */}
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor="payment-date">Betalningsdatum</Label>
|
|
<Input
|
|
id="payment-date"
|
|
type="date"
|
|
value={paymentDate}
|
|
onChange={(e) => setPaymentDate(e.target.value)}
|
|
className="w-full sm:w-48"
|
|
/>
|
|
</div>
|
|
|
|
{/* Journal entry lines */}
|
|
{/* Mobile card layout */}
|
|
<div className="sm:hidden space-y-3">
|
|
{lines.map((line, index) => (
|
|
<div key={index} className="rounded-lg border bg-card p-3 space-y-2">
|
|
<div className="flex items-start gap-2">
|
|
<div className="flex-1">
|
|
<AccountCombobox
|
|
value={line.account_number}
|
|
accounts={accounts}
|
|
onChange={(val) => updateLine(index, 'account_number', val)}
|
|
/>
|
|
</div>
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="sm"
|
|
className="h-8 w-8 p-0 min-h-[44px] min-w-[44px] shrink-0 -mr-1 -mt-1"
|
|
onClick={() => removeLine(index)}
|
|
disabled={lines.length <= 2}
|
|
>
|
|
<Trash2 className="h-3.5 w-3.5" />
|
|
</Button>
|
|
</div>
|
|
<div className="grid grid-cols-2 gap-2">
|
|
<div className="space-y-1">
|
|
<Label className="text-xs text-muted-foreground">Debet</Label>
|
|
<Input
|
|
type="number"
|
|
step="0.01"
|
|
min="0"
|
|
placeholder="0,00"
|
|
value={line.debit_amount}
|
|
onChange={(e) => updateLine(index, 'debit_amount', e.target.value)}
|
|
className="font-mono text-right"
|
|
inputMode="decimal"
|
|
/>
|
|
</div>
|
|
<div className="space-y-1">
|
|
<Label className="text-xs text-muted-foreground">Kredit</Label>
|
|
<Input
|
|
type="number"
|
|
step="0.01"
|
|
min="0"
|
|
placeholder="0,00"
|
|
value={line.credit_amount}
|
|
onChange={(e) => updateLine(index, 'credit_amount', e.target.value)}
|
|
className="font-mono text-right"
|
|
inputMode="decimal"
|
|
/>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
))}
|
|
<Button type="button" variant="outline" size="sm" onClick={addLine} className="w-full">
|
|
<Plus className="mr-1 h-3.5 w-3.5" /> Lägg till rad
|
|
</Button>
|
|
</div>
|
|
|
|
{/* Desktop table layout */}
|
|
<div className="hidden sm:block space-y-2">
|
|
{/* Header */}
|
|
<div className="grid grid-cols-[1fr_120px_120px_32px] gap-2 text-xs font-medium text-muted-foreground px-1">
|
|
<span>Konto</span>
|
|
<span className="text-right">Debet</span>
|
|
<span className="text-right">Kredit</span>
|
|
<span />
|
|
</div>
|
|
|
|
{/* Lines */}
|
|
{lines.map((line, index) => (
|
|
<div key={index} className="grid grid-cols-[1fr_120px_120px_32px] gap-2 items-start">
|
|
<div className="min-w-0">
|
|
<AccountCombobox
|
|
value={line.account_number}
|
|
accounts={accounts}
|
|
onChange={(val) => updateLine(index, 'account_number', val)}
|
|
/>
|
|
</div>
|
|
<Input
|
|
type="number"
|
|
step="0.01"
|
|
min="0"
|
|
placeholder="0,00"
|
|
value={line.debit_amount}
|
|
onChange={(e) => updateLine(index, 'debit_amount', e.target.value)}
|
|
className="font-mono text-right h-8"
|
|
/>
|
|
<Input
|
|
type="number"
|
|
step="0.01"
|
|
min="0"
|
|
placeholder="0,00"
|
|
value={line.credit_amount}
|
|
onChange={(e) => updateLine(index, 'credit_amount', e.target.value)}
|
|
className="font-mono text-right h-8"
|
|
/>
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="icon"
|
|
className="h-8 w-8 text-muted-foreground hover:text-destructive"
|
|
onClick={() => removeLine(index)}
|
|
disabled={lines.length <= 2}
|
|
>
|
|
<Trash2 className="h-3.5 w-3.5" />
|
|
</Button>
|
|
</div>
|
|
))}
|
|
|
|
{/* Add row */}
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="sm"
|
|
onClick={addLine}
|
|
className="text-muted-foreground"
|
|
>
|
|
<Plus className="mr-1 h-3.5 w-3.5" />
|
|
Lägg till rad
|
|
</Button>
|
|
</div>
|
|
|
|
{/* Balance indicator */}
|
|
<div className="flex items-center justify-between border-t pt-3">
|
|
<div className="flex items-center gap-2">
|
|
{isBalanced ? (
|
|
<Badge variant="secondary" className="bg-success/10 text-success gap-1">
|
|
<CheckCircle2 className="h-3 w-3" />
|
|
Debet = Kredit
|
|
</Badge>
|
|
) : (
|
|
<Badge variant="destructive" className="gap-1">
|
|
<AlertTriangle className="h-3 w-3" />
|
|
Obalanserad ({formatCurrency(Math.abs(totalDebit - totalCredit))})
|
|
</Badge>
|
|
)}
|
|
</div>
|
|
<div className="text-sm text-muted-foreground font-mono">
|
|
{formatCurrency(totalDebit)} / {formatCurrency(totalCredit)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
<DialogFooter>
|
|
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting} className="w-full sm:w-auto min-h-11">
|
|
Avbryt
|
|
</Button>
|
|
<Button onClick={handleSubmit} disabled={!isBalanced || isSubmitting || !isInitialized} className="w-full sm:w-auto min-h-11">
|
|
{isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
|
Bekräfta & bokför
|
|
</Button>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
)
|
|
}
|