feat: semi-manual invoice payment booking dialog (#37)
* 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> --------- 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
93413a8fd0
commit
3e82295cce
@@ -31,6 +31,7 @@ import {
|
||||
MessageSquare,
|
||||
Trash2,
|
||||
} from 'lucide-react'
|
||||
import PaymentBookingDialog from '@/components/invoices/PaymentBookingDialog'
|
||||
import type { Invoice, InvoiceItem, Customer, InvoiceStatus, InvoiceReminder, InvoiceDocumentType } from '@/types'
|
||||
|
||||
const statusConfig: Record<InvoiceStatus, { label: string; variant: 'default' | 'secondary' | 'success' | 'warning' | 'destructive'; icon: React.ElementType }> = {
|
||||
@@ -65,6 +66,7 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
|
||||
const [creditNote, setCreditNote] = useState<Invoice | null>(null)
|
||||
const [originalInvoice, setOriginalInvoice] = useState<Invoice | null>(null)
|
||||
const [convertedFromInvoice, setConvertedFromInvoice] = useState<Invoice | null>(null)
|
||||
const [showPaymentDialog, setShowPaymentDialog] = useState(false)
|
||||
const [isConverting, setIsConverting] = useState(false)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [isUpdating, setIsUpdating] = useState(false)
|
||||
@@ -173,15 +175,6 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
|
||||
const data = await response.json()
|
||||
throw new Error(data.error || 'Kunde inte markera som skickad')
|
||||
}
|
||||
} else if (status === 'paid') {
|
||||
// Use mark-paid API for proper bookkeeping
|
||||
const response = await fetch(`/api/invoices/${invoice.id}/mark-paid`, {
|
||||
method: 'POST',
|
||||
})
|
||||
if (!response.ok) {
|
||||
const data = await response.json()
|
||||
throw new Error(data.error || 'Kunde inte markera som betald')
|
||||
}
|
||||
} else if (status === 'cancelled') {
|
||||
// Only drafts and proformas can be cancelled directly — sent/overdue/paid
|
||||
// invoices have committed journal entries and require a credit note instead
|
||||
@@ -418,7 +411,7 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
|
||||
</Button>
|
||||
)}
|
||||
{(invoice.status === 'sent' || invoice.status === 'overdue') && isRealInvoice && (
|
||||
<Button onClick={() => updateStatus('paid')} disabled={isUpdating}>
|
||||
<Button onClick={() => setShowPaymentDialog(true)} disabled={isUpdating}>
|
||||
<CheckCircle className="mr-2 h-4 w-4" />
|
||||
Markera som betald
|
||||
</Button>
|
||||
@@ -904,7 +897,7 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
|
||||
<>
|
||||
<Button
|
||||
className="w-full"
|
||||
onClick={() => updateStatus('paid')}
|
||||
onClick={() => setShowPaymentDialog(true)}
|
||||
disabled={isUpdating}
|
||||
>
|
||||
<CheckCircle className="mr-2 h-4 w-4" />
|
||||
@@ -931,6 +924,19 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<PaymentBookingDialog
|
||||
open={showPaymentDialog}
|
||||
onOpenChange={setShowPaymentDialog}
|
||||
invoice={invoice}
|
||||
onSuccess={() => {
|
||||
fetchInvoice()
|
||||
toast({
|
||||
title: 'Betald',
|
||||
description: `Faktura ${invoice.invoice_number} har markerats som betald och bokförts`,
|
||||
})
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -26,6 +26,15 @@ vi.mock('@/lib/bookkeeping/invoice-entries', () => ({
|
||||
mockCreateInvoiceCashEntry(...args),
|
||||
}))
|
||||
|
||||
const mockCreateJournalEntry = vi.fn()
|
||||
const mockFindFiscalPeriod = vi.fn()
|
||||
vi.mock('@/lib/bookkeeping/engine', () => ({
|
||||
createJournalEntry: (...args: unknown[]) =>
|
||||
mockCreateJournalEntry(...args),
|
||||
findFiscalPeriod: (...args: unknown[]) =>
|
||||
mockFindFiscalPeriod(...args),
|
||||
}))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
describe('POST /api/invoices/[id]/mark-paid', () => {
|
||||
@@ -189,4 +198,135 @@ describe('POST /api/invoices/[id]/mark-paid', () => {
|
||||
expect(body.success).toBe(true)
|
||||
expect(body.journal_entry_id).toBeNull()
|
||||
})
|
||||
|
||||
it('uses custom lines when provided instead of auto-generating', async () => {
|
||||
const invoice = makeInvoice({ id: 'inv-1', status: 'sent', total: 12500 })
|
||||
|
||||
// Fetch invoice
|
||||
enqueue({ data: invoice, error: null })
|
||||
// Update invoice status
|
||||
enqueue({ data: null, error: null })
|
||||
// Fetch company settings
|
||||
enqueue({ data: { accounting_method: 'accrual', entity_type: 'enskild_firma' }, error: null })
|
||||
|
||||
mockFindFiscalPeriod.mockResolvedValue('fp-1')
|
||||
mockCreateJournalEntry.mockResolvedValue({ id: 'je-custom' })
|
||||
|
||||
const customLines = [
|
||||
{ account_number: '1920', debit_amount: 12500, credit_amount: 0, line_description: 'Betalning' },
|
||||
{ account_number: '1510', debit_amount: 0, credit_amount: 12500, line_description: 'Betalning' },
|
||||
]
|
||||
|
||||
const request = createMockRequest('/api/invoices/inv-1/mark-paid', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
payment_date: '2025-03-17',
|
||||
lines: customLines,
|
||||
},
|
||||
})
|
||||
const response = await POST(request, createMockRouteParams({ id: 'inv-1' }))
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
success: boolean
|
||||
journal_entry_id: string | null
|
||||
}>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.success).toBe(true)
|
||||
expect(body.journal_entry_id).toBe('je-custom')
|
||||
// Should NOT call auto-generation functions
|
||||
expect(mockCreateInvoicePaymentJournalEntry).not.toHaveBeenCalled()
|
||||
expect(mockCreateInvoiceCashEntry).not.toHaveBeenCalled()
|
||||
// Should call createJournalEntry directly with custom lines
|
||||
expect(mockCreateJournalEntry).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
'user-1',
|
||||
expect.objectContaining({
|
||||
entry_date: '2025-03-17',
|
||||
source_type: 'invoice_paid',
|
||||
lines: customLines,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('returns 400 when custom lines are unbalanced', async () => {
|
||||
const invoice = makeInvoice({ id: 'inv-1', status: 'sent', total: 12500 })
|
||||
|
||||
// Fetch invoice
|
||||
enqueue({ data: invoice, error: null })
|
||||
// Update invoice status
|
||||
enqueue({ data: null, error: null })
|
||||
// Fetch company settings
|
||||
enqueue({ data: { accounting_method: 'accrual', entity_type: 'enskild_firma' }, error: null })
|
||||
|
||||
const unbalancedLines = [
|
||||
{ account_number: '1920', debit_amount: 12500, credit_amount: 0 },
|
||||
{ account_number: '1510', debit_amount: 0, credit_amount: 10000 },
|
||||
]
|
||||
|
||||
const request = createMockRequest('/api/invoices/inv-1/mark-paid', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
payment_date: '2025-03-17',
|
||||
lines: unbalancedLines,
|
||||
},
|
||||
})
|
||||
const response = await POST(request, createMockRouteParams({ id: 'inv-1' }))
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toContain('balanserade')
|
||||
expect(mockCreateJournalEntry).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 400 when body has invalid schema (e.g. bad account number)', async () => {
|
||||
const invoice = makeInvoice({ id: 'inv-1', status: 'sent', total: 12500 })
|
||||
|
||||
// Fetch invoice
|
||||
enqueue({ data: invoice, error: null })
|
||||
|
||||
const request = createMockRequest('/api/invoices/inv-1/mark-paid', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
payment_date: '2025-03-17',
|
||||
lines: [
|
||||
{ account_number: 'XXXX', debit_amount: 12500, credit_amount: 0 },
|
||||
],
|
||||
},
|
||||
})
|
||||
const response = await POST(request, createMockRouteParams({ id: 'inv-1' }))
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('falls back to auto-generation when lines are not provided', async () => {
|
||||
const customer = makeCustomer()
|
||||
const invoice = makeInvoice({
|
||||
id: 'inv-1',
|
||||
status: 'sent',
|
||||
total: 12500,
|
||||
customer,
|
||||
})
|
||||
|
||||
enqueue({ data: invoice, error: null })
|
||||
enqueue({ data: null, error: null })
|
||||
enqueue({ data: { accounting_method: 'accrual', entity_type: 'enskild_firma' }, error: null })
|
||||
|
||||
mockCreateInvoicePaymentJournalEntry.mockResolvedValue({ id: 'je-auto' })
|
||||
|
||||
const request = createMockRequest('/api/invoices/inv-1/mark-paid', {
|
||||
method: 'POST',
|
||||
body: { payment_date: '2025-03-17' },
|
||||
})
|
||||
const response = await POST(request, createMockRouteParams({ id: 'inv-1' }))
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
success: boolean
|
||||
journal_entry_id: string | null
|
||||
}>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.journal_entry_id).toBe('je-auto')
|
||||
expect(mockCreateInvoicePaymentJournalEntry).toHaveBeenCalled()
|
||||
expect(mockCreateJournalEntry).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -4,9 +4,10 @@ import {
|
||||
createInvoicePaymentJournalEntry,
|
||||
createInvoiceCashEntry,
|
||||
} from '@/lib/bookkeeping/invoice-entries'
|
||||
import { createJournalEntry, findFiscalPeriod } from '@/lib/bookkeeping/engine'
|
||||
import { MarkInvoicePaidSchema } from '@/lib/api/schemas'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import type { EntityType, Invoice } from '@/types'
|
||||
import type { CreateJournalEntryInput, EntityType, Invoice } from '@/types'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
@@ -56,19 +57,25 @@ export async function POST(
|
||||
// Parse optional body (backward compatible — body may be empty)
|
||||
let exchangeRateDifference: number | undefined
|
||||
let bodyPaymentDate: string | undefined
|
||||
let customLines: { account_number: string; debit_amount: number; credit_amount: number; line_description?: string }[] | undefined
|
||||
let rawBody: unknown
|
||||
try {
|
||||
const text = await request.text()
|
||||
if (text) {
|
||||
const parsed = MarkInvoicePaidSchema.safeParse(JSON.parse(text))
|
||||
if (parsed.success) {
|
||||
exchangeRateDifference = parsed.data.exchange_rate_difference
|
||||
bodyPaymentDate = parsed.data.payment_date
|
||||
}
|
||||
}
|
||||
if (text) rawBody = JSON.parse(text)
|
||||
} catch {
|
||||
// No body or invalid JSON — use defaults
|
||||
}
|
||||
|
||||
if (rawBody) {
|
||||
const parsed = MarkInvoicePaidSchema.safeParse(rawBody)
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: 'Ogiltig förfrågan', details: parsed.error.flatten() }, { status: 400 })
|
||||
}
|
||||
exchangeRateDifference = parsed.data.exchange_rate_difference
|
||||
bodyPaymentDate = parsed.data.payment_date
|
||||
customLines = parsed.data.lines
|
||||
}
|
||||
|
||||
const now = new Date().toISOString()
|
||||
const paymentDate = bodyPaymentDate || now.split('T')[0]
|
||||
|
||||
@@ -103,7 +110,33 @@ export async function POST(
|
||||
|
||||
if (isRealInvoice) {
|
||||
try {
|
||||
if (accountingMethod === 'accrual') {
|
||||
if (customLines) {
|
||||
// Server-side balance validation — never commit imbalanced entries
|
||||
const totalDebit = customLines.reduce((s, l) => s + l.debit_amount, 0)
|
||||
const totalCredit = customLines.reduce((s, l) => s + l.credit_amount, 0)
|
||||
if (Math.round((totalDebit - totalCredit) * 100) !== 0 || totalDebit <= 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Verifikationsraderna är inte balanserade (debet ≠ kredit)' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// User-provided lines from PaymentBookingDialog
|
||||
const fiscalPeriodId = await findFiscalPeriod(supabase, user.id, paymentDate)
|
||||
if (fiscalPeriodId) {
|
||||
const sourceType = accountingMethod === 'accrual' ? 'invoice_paid' : 'invoice_cash_payment'
|
||||
const input: CreateJournalEntryInput = {
|
||||
fiscal_period_id: fiscalPeriodId,
|
||||
entry_date: paymentDate,
|
||||
description: `Betalning faktura ${invoice.invoice_number}`,
|
||||
source_type: sourceType,
|
||||
source_id: invoice.id,
|
||||
lines: customLines,
|
||||
}
|
||||
const journalEntry = await createJournalEntry(supabase, user.id, input)
|
||||
journalEntryId = journalEntry?.id ?? null
|
||||
}
|
||||
} else if (accountingMethod === 'accrual') {
|
||||
// Faktureringsmetoden: clear receivable (Debit 1930, Credit 1510)
|
||||
const journalEntry = await createInvoicePaymentJournalEntry(
|
||||
supabase,
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
'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-48"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Journal entry lines */}
|
||||
<div className="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}>
|
||||
Avbryt
|
||||
</Button>
|
||||
<Button onClick={handleSubmit} disabled={!isBalanced || isSubmitting || !isInitialized}>
|
||||
{isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Bekräfta & bokför
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -174,6 +174,12 @@ export const MarkInvoicePaidSchema = z.object({
|
||||
payment_date: isoDate.optional(),
|
||||
exchange_rate_difference: z.number().optional(),
|
||||
notes: z.string().optional(),
|
||||
lines: z.array(z.object({
|
||||
account_number: accountNumber,
|
||||
debit_amount: nonNegativeAmount.default(0),
|
||||
credit_amount: nonNegativeAmount.default(0),
|
||||
line_description: z.string().optional(),
|
||||
})).min(2).optional(),
|
||||
})
|
||||
|
||||
// ============================================================
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { proposePaymentLines } from '../propose-payment-lines'
|
||||
import type { InvoiceItem, VatTreatment } from '@/types'
|
||||
|
||||
function makeItem(overrides: Partial<InvoiceItem> = {}): InvoiceItem {
|
||||
return {
|
||||
id: 'item-1',
|
||||
invoice_id: 'inv-1',
|
||||
description: 'Konsulttjänst',
|
||||
quantity: 1,
|
||||
unit: 'st',
|
||||
unit_price: 10000,
|
||||
line_total: 10000,
|
||||
vat_rate: 25,
|
||||
vat_amount: 2500,
|
||||
sort_order: 0,
|
||||
created_at: '2025-01-01',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function makeInvoiceInput(overrides: Partial<{
|
||||
invoice_number: string
|
||||
total: number
|
||||
total_sek: number | null
|
||||
subtotal: number
|
||||
subtotal_sek: number | null
|
||||
vat_amount: number
|
||||
vat_amount_sek: number | null
|
||||
currency: string
|
||||
exchange_rate: number | null
|
||||
vat_treatment: VatTreatment
|
||||
items: InvoiceItem[]
|
||||
}> = {}) {
|
||||
return {
|
||||
invoice_number: '2025-001',
|
||||
total: 12500,
|
||||
total_sek: null,
|
||||
subtotal: 10000,
|
||||
subtotal_sek: null,
|
||||
vat_amount: 2500,
|
||||
vat_amount_sek: null,
|
||||
currency: 'SEK',
|
||||
exchange_rate: null,
|
||||
vat_treatment: 'standard_25' as VatTreatment,
|
||||
items: [makeItem()],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('proposePaymentLines', () => {
|
||||
describe('accrual method', () => {
|
||||
it('SEK invoice → 2 lines (debit payment account, credit 1510)', () => {
|
||||
const lines = proposePaymentLines({
|
||||
invoice: makeInvoiceInput(),
|
||||
accountingMethod: 'accrual',
|
||||
entityType: 'enskild_firma',
|
||||
})
|
||||
|
||||
expect(lines).toHaveLength(2)
|
||||
expect(lines[0]).toEqual({
|
||||
account_number: '1930',
|
||||
debit_amount: '12500',
|
||||
credit_amount: '',
|
||||
line_description: 'Betalning faktura 2025-001',
|
||||
})
|
||||
expect(lines[1]).toEqual({
|
||||
account_number: '1510',
|
||||
debit_amount: '',
|
||||
credit_amount: '12500',
|
||||
line_description: 'Betalning faktura 2025-001',
|
||||
})
|
||||
})
|
||||
|
||||
it('custom bank account (1920) → debit goes to 1920', () => {
|
||||
const lines = proposePaymentLines({
|
||||
invoice: makeInvoiceInput(),
|
||||
accountingMethod: 'accrual',
|
||||
entityType: 'enskild_firma',
|
||||
paymentAccount: '1920',
|
||||
})
|
||||
|
||||
expect(lines).toHaveLength(2)
|
||||
expect(lines[0].account_number).toBe('1920')
|
||||
expect(lines[1].account_number).toBe('1510')
|
||||
})
|
||||
|
||||
it('foreign currency with exchange rate gain → 3 lines', () => {
|
||||
const lines = proposePaymentLines({
|
||||
invoice: makeInvoiceInput({
|
||||
total: 1000,
|
||||
total_sek: 10000,
|
||||
currency: 'EUR',
|
||||
exchange_rate: 10,
|
||||
}),
|
||||
accountingMethod: 'accrual',
|
||||
entityType: 'enskild_firma',
|
||||
exchangeRateDifference: 500,
|
||||
})
|
||||
|
||||
expect(lines).toHaveLength(3)
|
||||
// Bank: actual received = 10000 + 500 = 10500
|
||||
expect(lines[0].account_number).toBe('1930')
|
||||
expect(lines[0].debit_amount).toBe('10500')
|
||||
// Clear receivable at booked amount
|
||||
expect(lines[1].account_number).toBe('1510')
|
||||
expect(lines[1].credit_amount).toBe('10000')
|
||||
// Exchange gain
|
||||
expect(lines[2].account_number).toBe('3960')
|
||||
expect(lines[2].credit_amount).toBe('500')
|
||||
})
|
||||
|
||||
it('foreign currency with exchange rate loss → 3 lines with 7960 debit', () => {
|
||||
const lines = proposePaymentLines({
|
||||
invoice: makeInvoiceInput({
|
||||
total: 1000,
|
||||
total_sek: 10000,
|
||||
currency: 'EUR',
|
||||
exchange_rate: 10,
|
||||
}),
|
||||
accountingMethod: 'accrual',
|
||||
entityType: 'enskild_firma',
|
||||
exchangeRateDifference: -300,
|
||||
})
|
||||
|
||||
expect(lines).toHaveLength(3)
|
||||
expect(lines[0].debit_amount).toBe('9700')
|
||||
expect(lines[2].account_number).toBe('7960')
|
||||
expect(lines[2].debit_amount).toBe('300')
|
||||
})
|
||||
})
|
||||
|
||||
describe('cash method', () => {
|
||||
it('single VAT rate → debit 1930, credit 3001, credit 2611', () => {
|
||||
const lines = proposePaymentLines({
|
||||
invoice: makeInvoiceInput(),
|
||||
accountingMethod: 'cash',
|
||||
entityType: 'enskild_firma',
|
||||
})
|
||||
|
||||
expect(lines).toHaveLength(3)
|
||||
expect(lines[0]).toEqual({
|
||||
account_number: '1930',
|
||||
debit_amount: '12500',
|
||||
credit_amount: '',
|
||||
line_description: 'Betalning faktura 2025-001',
|
||||
})
|
||||
expect(lines[1]).toEqual({
|
||||
account_number: '3001',
|
||||
debit_amount: '',
|
||||
credit_amount: '10000',
|
||||
line_description: 'Försäljning faktura 2025-001',
|
||||
})
|
||||
expect(lines[2]).toEqual({
|
||||
account_number: '2611',
|
||||
debit_amount: '',
|
||||
credit_amount: '2500',
|
||||
line_description: 'Utgående moms 25%',
|
||||
})
|
||||
})
|
||||
|
||||
it('mixed VAT rates → multiple credit lines', () => {
|
||||
const items = [
|
||||
makeItem({ id: 'i1', vat_rate: 25, line_total: 8000, vat_amount: 2000, unit_price: 8000 }),
|
||||
makeItem({ id: 'i2', vat_rate: 12, line_total: 2000, vat_amount: 240, unit_price: 2000 }),
|
||||
]
|
||||
|
||||
const lines = proposePaymentLines({
|
||||
invoice: makeInvoiceInput({
|
||||
total: 12240,
|
||||
subtotal: 10000,
|
||||
vat_amount: 2240,
|
||||
items,
|
||||
}),
|
||||
accountingMethod: 'cash',
|
||||
entityType: 'enskild_firma',
|
||||
})
|
||||
|
||||
// 1 debit + 2 revenue + 2 VAT = 5 lines
|
||||
expect(lines).toHaveLength(5)
|
||||
expect(lines[0].account_number).toBe('1930')
|
||||
|
||||
// Find the revenue/VAT lines by account
|
||||
const accounts = lines.slice(1).map((l) => l.account_number)
|
||||
expect(accounts).toContain('3001') // 25% revenue
|
||||
expect(accounts).toContain('2611') // 25% VAT
|
||||
expect(accounts).toContain('3002') // 12% revenue
|
||||
expect(accounts).toContain('2621') // 12% VAT
|
||||
})
|
||||
|
||||
it('defaults payment account to 1930', () => {
|
||||
const lines = proposePaymentLines({
|
||||
invoice: makeInvoiceInput(),
|
||||
accountingMethod: 'cash',
|
||||
entityType: 'enskild_firma',
|
||||
})
|
||||
|
||||
expect(lines[0].account_number).toBe('1930')
|
||||
})
|
||||
|
||||
it('uses custom payment account', () => {
|
||||
const lines = proposePaymentLines({
|
||||
invoice: makeInvoiceInput(),
|
||||
accountingMethod: 'cash',
|
||||
entityType: 'enskild_firma',
|
||||
paymentAccount: '1910',
|
||||
})
|
||||
|
||||
expect(lines[0].account_number).toBe('1910')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,239 @@
|
||||
/**
|
||||
* Pure function to compute proposed journal entry lines for an invoice payment.
|
||||
* Used by the PaymentBookingDialog to pre-fill the editable line grid.
|
||||
*
|
||||
* No DB or Supabase dependency — all inputs are plain data.
|
||||
*/
|
||||
import { resolveSekAmount } from './currency-utils'
|
||||
import { getRevenueAccount, getOutputVatAccount } from './invoice-entries'
|
||||
import { getVatTreatmentForRate } from '@/lib/invoices/vat-rules'
|
||||
import type { FormLine } from '@/components/bookkeeping/JournalEntryForm'
|
||||
import type { EntityType, InvoiceItem, VatTreatment } from '@/types'
|
||||
|
||||
export interface ProposePaymentLinesInput {
|
||||
invoice: {
|
||||
invoice_number: string
|
||||
total: number
|
||||
total_sek?: number | null
|
||||
subtotal: number
|
||||
subtotal_sek?: number | null
|
||||
vat_amount: number
|
||||
vat_amount_sek?: number | null
|
||||
currency: string
|
||||
exchange_rate?: number | null
|
||||
vat_treatment: VatTreatment
|
||||
items?: InvoiceItem[]
|
||||
}
|
||||
accountingMethod: 'accrual' | 'cash'
|
||||
entityType: EntityType
|
||||
paymentAccount?: string
|
||||
exchangeRateDifference?: number
|
||||
}
|
||||
|
||||
function toFormAmount(n: number): string {
|
||||
const rounded = Math.round(n * 100) / 100
|
||||
return rounded === 0 ? '' : rounded.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* Propose journal entry lines for an invoice payment.
|
||||
*
|
||||
* Accrual: Debit paymentAccount, Credit 1510, optional exchange rate diff.
|
||||
* Cash: Debit paymentAccount, Credit 30xx + 26xx per VAT rate group.
|
||||
*/
|
||||
export function proposePaymentLines(input: ProposePaymentLinesInput): FormLine[] {
|
||||
const { invoice, accountingMethod, entityType, exchangeRateDifference } = input
|
||||
const paymentAccount = input.paymentAccount || '1930'
|
||||
const desc = `Betalning faktura ${invoice.invoice_number}`
|
||||
|
||||
if (accountingMethod === 'accrual') {
|
||||
return proposeAccrualLines(invoice, paymentAccount, desc, exchangeRateDifference)
|
||||
}
|
||||
return proposeCashLines(invoice, paymentAccount, desc, entityType)
|
||||
}
|
||||
|
||||
function proposeAccrualLines(
|
||||
invoice: ProposePaymentLinesInput['invoice'],
|
||||
paymentAccount: string,
|
||||
desc: string,
|
||||
exchangeRateDifference?: number
|
||||
): FormLine[] {
|
||||
const bookedSekAmount = resolveSekAmount(
|
||||
invoice.total,
|
||||
invoice.total_sek,
|
||||
invoice.currency,
|
||||
invoice.exchange_rate
|
||||
)
|
||||
const lines: FormLine[] = []
|
||||
|
||||
if (exchangeRateDifference && exchangeRateDifference !== 0) {
|
||||
const actualSekReceived = bookedSekAmount + exchangeRateDifference
|
||||
|
||||
lines.push({
|
||||
account_number: paymentAccount,
|
||||
debit_amount: toFormAmount(actualSekReceived),
|
||||
credit_amount: '',
|
||||
line_description: desc,
|
||||
})
|
||||
|
||||
lines.push({
|
||||
account_number: '1510',
|
||||
debit_amount: '',
|
||||
credit_amount: toFormAmount(bookedSekAmount),
|
||||
line_description: desc,
|
||||
})
|
||||
|
||||
if (exchangeRateDifference > 0) {
|
||||
lines.push({
|
||||
account_number: '3960',
|
||||
debit_amount: '',
|
||||
credit_amount: toFormAmount(exchangeRateDifference),
|
||||
line_description: 'Valutakursvinst',
|
||||
})
|
||||
} else {
|
||||
lines.push({
|
||||
account_number: '7960',
|
||||
debit_amount: toFormAmount(Math.abs(exchangeRateDifference)),
|
||||
credit_amount: '',
|
||||
line_description: 'Valutakursförlust',
|
||||
})
|
||||
}
|
||||
} else {
|
||||
const amount = Math.round(bookedSekAmount * 100) / 100
|
||||
lines.push({
|
||||
account_number: paymentAccount,
|
||||
debit_amount: toFormAmount(amount),
|
||||
credit_amount: '',
|
||||
line_description: desc,
|
||||
})
|
||||
lines.push({
|
||||
account_number: '1510',
|
||||
debit_amount: '',
|
||||
credit_amount: toFormAmount(amount),
|
||||
line_description: desc,
|
||||
})
|
||||
}
|
||||
|
||||
return lines
|
||||
}
|
||||
|
||||
function proposeCashLines(
|
||||
invoice: ProposePaymentLinesInput['invoice'],
|
||||
paymentAccount: string,
|
||||
desc: string,
|
||||
entityType: EntityType
|
||||
): FormLine[] {
|
||||
const lines: FormLine[] = []
|
||||
const isForeign = invoice.currency !== 'SEK'
|
||||
|
||||
const toSek = (amount: number): number => {
|
||||
if (!isForeign) return amount
|
||||
if (invoice.exchange_rate != null && invoice.exchange_rate > 0) {
|
||||
return Math.round(amount * invoice.exchange_rate * 100) / 100
|
||||
}
|
||||
return amount
|
||||
}
|
||||
|
||||
// Build credit lines per VAT rate group
|
||||
const creditLines: FormLine[] = []
|
||||
|
||||
if (invoice.items && invoice.items.length > 0) {
|
||||
const hasPerLineVat = invoice.items.some((item) => item.vat_rate !== undefined && item.vat_rate !== null)
|
||||
|
||||
if (!hasPerLineVat) {
|
||||
// Legacy: single rate from invoice level
|
||||
const revenueAccount = getRevenueAccount(invoice.vat_treatment, entityType)
|
||||
const subtotal = invoice.items.reduce((sum, item) => sum + item.line_total, 0)
|
||||
creditLines.push({
|
||||
account_number: revenueAccount,
|
||||
debit_amount: '',
|
||||
credit_amount: toFormAmount(toSek(subtotal)),
|
||||
line_description: `Försäljning faktura ${invoice.invoice_number}`,
|
||||
})
|
||||
|
||||
const totalVat = invoice.items.reduce((sum, item) => sum + (item.vat_amount || 0), 0)
|
||||
if (totalVat > 0) {
|
||||
const vatAccount = getOutputVatAccount(invoice.vat_treatment)
|
||||
creditLines.push({
|
||||
account_number: vatAccount,
|
||||
debit_amount: '',
|
||||
credit_amount: toFormAmount(toSek(totalVat)),
|
||||
line_description: 'Utgående moms',
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// Group items by vat_rate
|
||||
const rateGroups = new Map<number, { subtotal: number; vatAmount: number }>()
|
||||
for (const item of invoice.items) {
|
||||
const rate = item.vat_rate ?? 0
|
||||
const group = rateGroups.get(rate) || { subtotal: 0, vatAmount: 0 }
|
||||
group.subtotal += item.line_total
|
||||
group.vatAmount += item.vat_amount || 0
|
||||
rateGroups.set(rate, group)
|
||||
}
|
||||
|
||||
for (const [rate, group] of rateGroups) {
|
||||
const treatment = rate === 0 && (invoice.vat_treatment === 'reverse_charge' || invoice.vat_treatment === 'export')
|
||||
? invoice.vat_treatment
|
||||
: getVatTreatmentForRate(rate)
|
||||
const revenueAccount = getRevenueAccount(treatment, entityType)
|
||||
|
||||
creditLines.push({
|
||||
account_number: revenueAccount,
|
||||
debit_amount: '',
|
||||
credit_amount: toFormAmount(Math.round(toSek(group.subtotal) * 100) / 100),
|
||||
line_description: `Försäljning faktura ${invoice.invoice_number}`,
|
||||
})
|
||||
|
||||
const roundedVat = Math.round(toSek(group.vatAmount) * 100) / 100
|
||||
if (roundedVat !== 0) {
|
||||
const vatAccount = getOutputVatAccount(treatment)
|
||||
creditLines.push({
|
||||
account_number: vatAccount,
|
||||
debit_amount: '',
|
||||
credit_amount: toFormAmount(roundedVat),
|
||||
line_description: `Utgående moms ${rate}%`,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Fallback: invoice-level amounts
|
||||
const revenueAccount = getRevenueAccount(invoice.vat_treatment, entityType)
|
||||
const subtotalSek = resolveSekAmount(invoice.subtotal, invoice.subtotal_sek, invoice.currency, invoice.exchange_rate)
|
||||
creditLines.push({
|
||||
account_number: revenueAccount,
|
||||
debit_amount: '',
|
||||
credit_amount: toFormAmount(subtotalSek),
|
||||
line_description: `Försäljning faktura ${invoice.invoice_number}`,
|
||||
})
|
||||
|
||||
if (invoice.vat_amount > 0) {
|
||||
const vatSek = resolveSekAmount(invoice.vat_amount, invoice.vat_amount_sek, invoice.currency, invoice.exchange_rate)
|
||||
const vatAccount = getOutputVatAccount(invoice.vat_treatment)
|
||||
creditLines.push({
|
||||
account_number: vatAccount,
|
||||
debit_amount: '',
|
||||
credit_amount: toFormAmount(vatSek),
|
||||
line_description: `Utgående moms faktura ${invoice.invoice_number}`,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Debit: balance guarantee
|
||||
const totalCredits = creditLines.reduce((sum, l) => sum + (parseFloat(l.credit_amount) || 0), 0)
|
||||
const debitAmount = isForeign
|
||||
? Math.round(totalCredits * 100) / 100
|
||||
: resolveSekAmount(invoice.total, invoice.total_sek, invoice.currency, invoice.exchange_rate)
|
||||
|
||||
lines.push({
|
||||
account_number: paymentAccount,
|
||||
debit_amount: toFormAmount(debitAmount),
|
||||
credit_amount: '',
|
||||
line_description: desc,
|
||||
})
|
||||
|
||||
lines.push(...creditLines)
|
||||
|
||||
return lines
|
||||
}
|
||||
@@ -51,13 +51,13 @@ export async function generateGeneralLedger(
|
||||
return { accounts: [], period: { start: '', end: '' } }
|
||||
}
|
||||
|
||||
// Fetch posted entries for this period
|
||||
// Fetch posted and reversed entries for this period (reversed entries must appear alongside their storno)
|
||||
const { data: entries } = await supabase
|
||||
.from('journal_entries')
|
||||
.select('id, entry_date, voucher_number, voucher_series, description, source_type')
|
||||
.eq('user_id', userId)
|
||||
.eq('fiscal_period_id', periodId)
|
||||
.eq('status', 'posted')
|
||||
.in('status', ['posted', 'reversed'])
|
||||
|
||||
if (!entries || entries.length === 0) {
|
||||
return { accounts: [], period: { start: period.period_start, end: period.period_end } }
|
||||
@@ -90,12 +90,12 @@ export async function generateGeneralLedger(
|
||||
accountNameMap.set(acc.account_number, acc.account_name)
|
||||
}
|
||||
|
||||
// Compute opening balances: sum all posted lines from entries before this period
|
||||
// Compute opening balances: sum all posted/reversed lines from entries before this period
|
||||
const { data: priorEntries } = await supabase
|
||||
.from('journal_entries')
|
||||
.select('id')
|
||||
.eq('user_id', userId)
|
||||
.eq('status', 'posted')
|
||||
.in('status', ['posted', 'reversed'])
|
||||
.lt('entry_date', period.period_start)
|
||||
|
||||
const openingBalances = new Map<string, number>()
|
||||
|
||||
@@ -233,7 +233,7 @@ export async function generateINK2Declaration(
|
||||
.select('*, lines:journal_entry_lines(*)')
|
||||
.eq('user_id', userId)
|
||||
.eq('fiscal_period_id', fiscalPeriodId)
|
||||
.eq('status', 'posted')
|
||||
.in('status', ['posted', 'reversed'])
|
||||
|
||||
if (entriesError) {
|
||||
throw new Error(`Failed to fetch journal entries: ${entriesError.message}`)
|
||||
|
||||
@@ -190,7 +190,7 @@ export async function generateNEDeclaration(
|
||||
.select('*, lines:journal_entry_lines(*)')
|
||||
.eq('user_id', userId)
|
||||
.eq('fiscal_period_id', fiscalPeriodId)
|
||||
.eq('status', 'posted')
|
||||
.in('status', ['posted', 'reversed'])
|
||||
|
||||
if (entriesError) {
|
||||
throw new Error(`Failed to fetch journal entries: ${entriesError.message}`)
|
||||
|
||||
@@ -46,7 +46,7 @@ export async function generateSIEExport(
|
||||
.select('*, lines:journal_entry_lines(*)')
|
||||
.eq('user_id', userId)
|
||||
.eq('fiscal_period_id', options.fiscal_period_id)
|
||||
.eq('status', 'posted')
|
||||
.in('status', ['posted', 'reversed'])
|
||||
.order('voucher_number')
|
||||
|
||||
// Fetch cost centers and projects for dimension records
|
||||
|
||||
@@ -66,7 +66,7 @@ async function generateTrialBalanceManual(
|
||||
.select('id')
|
||||
.eq('user_id', userId)
|
||||
.eq('fiscal_period_id', fiscalPeriodId)
|
||||
.eq('status', 'posted')
|
||||
.in('status', ['posted', 'reversed'])
|
||||
|
||||
if (entriesError || !entries || entries.length === 0) {
|
||||
return { rows: [], totalDebit: 0, totalCredit: 0, isBalanced: true }
|
||||
|
||||
@@ -143,7 +143,7 @@ export async function calculateVatDeclaration(
|
||||
`)
|
||||
.in('account_number', VAT_ACCOUNTS)
|
||||
.eq('journal_entries.user_id', userId)
|
||||
.eq('journal_entries.status', 'posted')
|
||||
.in('journal_entries.status', ['posted', 'reversed'])
|
||||
.gte('journal_entries.entry_date', start)
|
||||
.lte('journal_entries.entry_date', end)
|
||||
.range(from, to)
|
||||
@@ -193,7 +193,7 @@ export async function calculateVatDeclaration(
|
||||
.from('journal_entries')
|
||||
.select('source_type')
|
||||
.eq('user_id', userId)
|
||||
.eq('status', 'posted')
|
||||
.in('status', ['posted', 'reversed'])
|
||||
.gte('entry_date', start)
|
||||
.lte('entry_date', end)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user