feat(invoices): allow BAS class 1-3 posting-account overrides and complete the aktiekapital note (#1121)
- invoice/article posting-account overrides accept active class 1-3 accounts; class 1-2 (balance-sheet) accounts are rejected on VAT-bearing lines so the ruta 05 tax base always books to a 3xxx account - shared posting-account regex across server schemas, pending-operation re-validation, and client forms - share-capital settings (aktiekapital/antal_aktier) feed the annual-report note; kvotvarde derived per ABL 1 kap 6 $; all-or-nothing pair constraint - signed per-rate VAT breakdown on credit-note PDFs; U+2212 to ASCII hyphen Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
b0044bfe98
commit
43f7ccab9e
@@ -0,0 +1,68 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { InvoiceItem } from '@/types'
|
||||
import { buildPdfVatBreakdown, formatPdfCurrency } from '@/lib/invoices/pdf-template'
|
||||
|
||||
function makeItem(overrides: Partial<InvoiceItem> = {}): InvoiceItem {
|
||||
return {
|
||||
id: 'item-1',
|
||||
invoice_id: 'invoice-1',
|
||||
sort_order: 0,
|
||||
line_type: 'product',
|
||||
description: 'Invoice row',
|
||||
quantity: 1,
|
||||
unit: 'st',
|
||||
unit_price: 100,
|
||||
line_total: 100,
|
||||
vat_rate: 25,
|
||||
vat_amount: 25,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('formatPdfCurrency', () => {
|
||||
it('uses a PDF-safe minus for Swedish negative amounts', () => {
|
||||
const formatted = formatPdfCurrency(-12.34, 'SEK', 'sv')
|
||||
|
||||
expect(formatted).toBe('-12,34 SEK')
|
||||
expect(formatted).not.toContain('\u2212')
|
||||
})
|
||||
|
||||
it('preserves English negative amount formatting', () => {
|
||||
expect(formatPdfCurrency(-12.34, 'SEK', 'en')).toBe('-12.34 SEK')
|
||||
})
|
||||
|
||||
it('does not change positive Swedish amount formatting', () => {
|
||||
expect(formatPdfCurrency(18_992.2, 'SEK', 'sv')).toBe('18\u00a0992,20 SEK')
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildPdfVatBreakdown', () => {
|
||||
it('subtracts a negative adjustment from its VAT group', () => {
|
||||
const breakdown = buildPdfVatBreakdown([
|
||||
makeItem({ id: 'sale', line_total: 100, vat_amount: 25 }),
|
||||
makeItem({ id: 'deduction', line_total: -12.34, vat_amount: -3.09 }),
|
||||
])
|
||||
|
||||
expect(breakdown.get(25)).toEqual({ base: 87.66, vat: 21.91 })
|
||||
})
|
||||
|
||||
it('keeps whole credit-note VAT groups negative', () => {
|
||||
const breakdown = buildPdfVatBreakdown([
|
||||
makeItem({ line_total: -100, vat_amount: -25 }),
|
||||
])
|
||||
|
||||
expect(breakdown.get(25)).toEqual({ base: -100, vat: -25 })
|
||||
})
|
||||
|
||||
it('keeps mixed VAT rates signed and excludes text rows', () => {
|
||||
const breakdown = buildPdfVatBreakdown([
|
||||
makeItem({ id: 'rate-25', line_total: 200, vat_rate: 25, vat_amount: 50 }),
|
||||
makeItem({ id: 'rate-12', line_total: 100, vat_rate: 12, vat_amount: 12 }),
|
||||
makeItem({ id: 'rate-12-deduction', line_total: -20, vat_rate: 12, vat_amount: -2.4 }),
|
||||
makeItem({ id: 'text', line_type: 'text', line_total: 999, vat_rate: 25, vat_amount: 999 }),
|
||||
])
|
||||
|
||||
expect(breakdown.get(25)).toEqual({ base: 200, vat: 50 })
|
||||
expect(breakdown.get(12)).toEqual({ base: 80, vat: 9.6 })
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import type { Currency, Customer, InvoiceDocumentType } from '@/types'
|
||||
import { getVatRules, getAvailableVatRates } from '@/lib/invoices/vat-rules'
|
||||
import { isBalanceSheetAccount } from '@/lib/invoices/posting-account'
|
||||
import { fetchExchangeRate, convertToSEK } from '@/lib/currency/riksbanken'
|
||||
import { DEFAULT_DEFERRED_REVENUE_ACCOUNT } from '@/lib/bookkeeping/accruals/account-suggestions'
|
||||
import {
|
||||
@@ -226,16 +227,33 @@ export async function buildInvoiceWriteData(params: {
|
||||
},
|
||||
}
|
||||
}
|
||||
// A class 1-2 (balance-sheet) posting override is only valid on
|
||||
// zero-VAT lines (deposits, advances, outlays). On a VAT-bearing line
|
||||
// it would divert the tax base away from a 3xxx account and understate
|
||||
// ruta 05 of the momsdeklaration (ML 17 kap 24§).
|
||||
if (
|
||||
item.revenue_account &&
|
||||
isBalanceSheetAccount(item.revenue_account) &&
|
||||
itemRate > 0
|
||||
) {
|
||||
return {
|
||||
ok: false,
|
||||
code: 'INVOICE_CREATE_POSTING_ACCOUNT_VAT_CONFLICT',
|
||||
details: { account: item.revenue_account, vatRate: itemRate },
|
||||
}
|
||||
}
|
||||
const lineTotal = item.quantity * item.unit_price
|
||||
vatAmount += Math.round(lineTotal * itemRate / 100 * 100) / 100
|
||||
}
|
||||
}
|
||||
const total = documentType === 'delivery_note' ? 0 : subtotal + vatAmount
|
||||
|
||||
// Validate any per-line revenue-account override against the company's chart
|
||||
// of accounts. Zod already constrains the shape to a 3xxx string; here we
|
||||
// confirm each is a real, active class-3 account so a typo or a non-revenue
|
||||
// account can never be booked. Never trust the client.
|
||||
// Validate any per-line posting-account override against the company's chart
|
||||
// of accounts. The legacy field name is revenue_account, but balance-sheet
|
||||
// accounts are valid for deposits, customer advances, and genuine outlays.
|
||||
// Zod already constrains the shape to classes 1-3; here we
|
||||
// confirm each is a real, active account so a typo or unsuitable account
|
||||
// can never be booked. Never trust the client.
|
||||
const overrideAccounts = Array.from(
|
||||
new Set(
|
||||
items
|
||||
@@ -248,7 +266,8 @@ export async function buildInvoiceWriteData(params: {
|
||||
.from('chart_of_accounts')
|
||||
.select('account_number')
|
||||
.eq('company_id', companyId)
|
||||
.eq('account_class', 3)
|
||||
.gte('account_class', 1)
|
||||
.lte('account_class', 3)
|
||||
.eq('is_active', true)
|
||||
.in('account_number', overrideAccounts)
|
||||
|
||||
|
||||
@@ -597,15 +597,30 @@ function createStyles(branding?: InvoiceBranding) {
|
||||
// Format currency with explicit ISO code so non-Swedish recipients see "1 234,56 SEK"
|
||||
// instead of the Swedish symbol "kr". Decimal style + appended code works for any
|
||||
// currency (SEK/EUR/USD) and avoids Intl's locale-specific symbol quirks.
|
||||
function formatCurrency(amount: number, currency: string = 'SEK', language: PdfLang = 'sv'): string {
|
||||
export function formatPdfCurrency(amount: number, currency: string = 'SEK', language: PdfLang = 'sv'): string {
|
||||
const formatted = new Intl.NumberFormat(language === 'en' ? 'en-US' : 'sv-SE', {
|
||||
style: 'decimal',
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
}).format(amount)
|
||||
// sv-SE emits U+2212, which standard PDF fonts can silently drop. The
|
||||
// ASCII minus is supported by every allowed invoice font.
|
||||
}).format(amount).replaceAll('\u2212', '-')
|
||||
return `${formatted} ${currency}`
|
||||
}
|
||||
|
||||
export function buildPdfVatBreakdown(items: InvoiceItem[]): Map<number, { base: number; vat: number }> {
|
||||
const vatByRate = new Map<number, { base: number; vat: number }>()
|
||||
for (const item of items) {
|
||||
if (isTextLikeLine(item)) continue
|
||||
const rate = item.vat_rate ?? 0
|
||||
const group = vatByRate.get(rate) || { base: 0, vat: 0 }
|
||||
group.base += item.line_total
|
||||
group.vat += item.vat_amount || 0
|
||||
vatByRate.set(rate, group)
|
||||
}
|
||||
return vatByRate
|
||||
}
|
||||
|
||||
// Format date as ISO yyyy-MM-dd in both locales: universally unambiguous and
|
||||
// matches the project's formatDate() convention (lib/utils.ts).
|
||||
// Input is already a YYYY-MM-DD string from the DB, so slice avoids the
|
||||
@@ -678,16 +693,9 @@ export function InvoicePDF({ invoice, customer, items, company, originalInvoiceN
|
||||
const showVatColumn = hasPerLineVat && uniqueRates.size > 1
|
||||
|
||||
// Calculate per-rate VAT breakdown for totals
|
||||
const vatByRate = new Map<number, { base: number; vat: number }>()
|
||||
if (hasPerLineVat) {
|
||||
for (const item of billableItems) {
|
||||
const rate = item.vat_rate ?? 0
|
||||
const group = vatByRate.get(rate) || { base: 0, vat: 0 }
|
||||
group.base += Math.abs(item.line_total)
|
||||
group.vat += Math.abs(item.vat_amount || 0)
|
||||
vatByRate.set(rate, group)
|
||||
}
|
||||
}
|
||||
const vatByRate = hasPerLineVat
|
||||
? buildPdfVatBreakdown(billableItems)
|
||||
: new Map<number, { base: number; vat: number }>()
|
||||
const docType = (invoice as Invoice & { document_type?: InvoiceDocumentType }).document_type || 'invoice'
|
||||
const isDeliveryNote = docType === 'delivery_note'
|
||||
const isProforma = docType === 'proforma'
|
||||
@@ -891,13 +899,13 @@ export function InvoicePDF({ invoice, customer, items, company, originalInvoiceN
|
||||
<Text style={styles.colQty}>{item.quantity}</Text>
|
||||
<Text style={styles.colUnit}>{item.unit}</Text>
|
||||
{!isDeliveryNote && (
|
||||
<Text style={styles.colPrice}>{formatCurrency(item.unit_price, invoice.currency, lang)}</Text>
|
||||
<Text style={styles.colPrice}>{formatPdfCurrency(item.unit_price, invoice.currency, lang)}</Text>
|
||||
)}
|
||||
{!isDeliveryNote && showVatColumn && (
|
||||
<Text style={styles.colVat}>{item.vat_rate ?? 0}%</Text>
|
||||
)}
|
||||
{!isDeliveryNote && (
|
||||
<Text style={styles.colTotal}>{formatCurrency(item.line_total, invoice.currency, lang)}</Text>
|
||||
<Text style={styles.colTotal}>{formatPdfCurrency(item.line_total, invoice.currency, lang)}</Text>
|
||||
)}
|
||||
</View>
|
||||
)
|
||||
@@ -910,7 +918,7 @@ export function InvoicePDF({ invoice, customer, items, company, originalInvoiceN
|
||||
<View style={styles.totalsSection}>
|
||||
<View style={styles.totalRow}>
|
||||
<Text style={styles.totalLabel}>{L.subtotal}</Text>
|
||||
<Text style={styles.totalValue}>{formatCurrency(invoice.subtotal, invoice.currency, lang)}</Text>
|
||||
<Text style={styles.totalValue}>{formatPdfCurrency(invoice.subtotal, invoice.currency, lang)}</Text>
|
||||
</View>
|
||||
{vatByRate.size > 1 ? (
|
||||
Array.from(vatByRate.entries())
|
||||
@@ -919,12 +927,12 @@ export function InvoicePDF({ invoice, customer, items, company, originalInvoiceN
|
||||
<View key={rate}>
|
||||
<View style={styles.totalRow}>
|
||||
<Text style={styles.totalLabel}>{L.net(rate)}</Text>
|
||||
<Text style={styles.totalValue}>{formatCurrency(group.base, invoice.currency, lang)}</Text>
|
||||
<Text style={styles.totalValue}>{formatPdfCurrency(group.base, invoice.currency, lang)}</Text>
|
||||
</View>
|
||||
{group.vat > 0 && (
|
||||
{group.vat !== 0 && (
|
||||
<View style={styles.totalRow}>
|
||||
<Text style={styles.totalLabel}>{L.vatRow(rate)}</Text>
|
||||
<Text style={styles.totalValue}>{formatCurrency(group.vat, invoice.currency, lang)}</Text>
|
||||
<Text style={styles.totalValue}>{formatPdfCurrency(group.vat, invoice.currency, lang)}</Text>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
@@ -938,7 +946,7 @@ export function InvoicePDF({ invoice, customer, items, company, originalInvoiceN
|
||||
!(company.vat_registered === false && invoice.vat_amount === 0) && (
|
||||
<View style={styles.totalRow}>
|
||||
<Text style={styles.totalLabel}>{L.vatRow(invoice.vat_rate ?? (vatByRate.size === 1 ? (vatByRate.keys().next().value ?? 0) : 0))}</Text>
|
||||
<Text style={styles.totalValue}>{formatCurrency(invoice.vat_amount, invoice.currency, lang)}</Text>
|
||||
<Text style={styles.totalValue}>{formatPdfCurrency(invoice.vat_amount, invoice.currency, lang)}</Text>
|
||||
</View>
|
||||
)
|
||||
)}
|
||||
@@ -952,20 +960,23 @@ export function InvoicePDF({ invoice, customer, items, company, originalInvoiceN
|
||||
{rounding.applies && (
|
||||
<View style={styles.totalRow}>
|
||||
<Text style={[styles.totalLabel, { fontSize: 8 }]}>{L.rounding}</Text>
|
||||
<Text style={[styles.totalValue, { fontSize: 8 }]}>{formatCurrency(rounding.roundingDelta, 'SEK', lang)}</Text>
|
||||
<Text style={[styles.totalValue, { fontSize: 8 }]}>{formatPdfCurrency(rounding.roundingDelta, 'SEK', lang)}</Text>
|
||||
</View>
|
||||
)}
|
||||
{showDeduction && (
|
||||
<View style={styles.totalRow}>
|
||||
<Text style={styles.totalLabel}>{L.deductionRow}</Text>
|
||||
<Text style={styles.totalValue}>
|
||||
−{formatCurrency(invoice.deduction_total ?? 0, invoice.currency, lang)}
|
||||
{/* deduction_total is stored as a positive magnitude;
|
||||
-Math.abs() keeps the row a reduction even if the
|
||||
stored sign convention ever changes. */}
|
||||
{formatPdfCurrency(-Math.abs(invoice.deduction_total ?? 0), invoice.currency, lang)}
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
<View style={styles.grandTotal}>
|
||||
<Text style={styles.grandTotalLabel}>{isCreditNote ? L.toCredit : L.toPay}</Text>
|
||||
<Text style={styles.grandTotalValue}>{formatCurrency(grandTotal, invoice.currency, lang)}</Text>
|
||||
<Text style={styles.grandTotalValue}>{formatPdfCurrency(grandTotal, invoice.currency, lang)}</Text>
|
||||
</View>
|
||||
</>
|
||||
)
|
||||
@@ -975,12 +986,12 @@ export function InvoicePDF({ invoice, customer, items, company, originalInvoiceN
|
||||
{invoice.vat_amount_sek != null && invoice.vat_amount_sek !== 0 && (
|
||||
<View style={styles.totalRow}>
|
||||
<Text style={[styles.totalLabel, { fontSize: 9 }]}>{L.vatInSek(invoice.exchange_rate ?? '')}</Text>
|
||||
<Text style={[styles.totalValue, { fontSize: 9 }]}>{formatCurrency(invoice.vat_amount_sek, 'SEK', lang)}</Text>
|
||||
<Text style={[styles.totalValue, { fontSize: 9 }]}>{formatPdfCurrency(invoice.vat_amount_sek, 'SEK', lang)}</Text>
|
||||
</View>
|
||||
)}
|
||||
<View style={styles.totalRow}>
|
||||
<Text style={[styles.totalLabel, { fontSize: 9 }]}>{L.totalInSek}</Text>
|
||||
<Text style={[styles.totalValue, { fontSize: 9 }]}>{formatCurrency(invoice.total_sek, 'SEK', lang)}</Text>
|
||||
<Text style={[styles.totalValue, { fontSize: 9 }]}>{formatPdfCurrency(invoice.total_sek, 'SEK', lang)}</Text>
|
||||
</View>
|
||||
</View>
|
||||
)}
|
||||
@@ -1036,7 +1047,7 @@ export function InvoicePDF({ invoice, customer, items, company, originalInvoiceN
|
||||
const work = i.work_type ? `, ${i.work_type}` : ''
|
||||
return (
|
||||
<Text key={idx} style={styles.deductionLineItem}>
|
||||
{`${kind}${work}: ${i.description}, ${formatCurrency(i.deduction_amount ?? 0, invoice.currency, lang)}`}
|
||||
{`${kind}${work}: ${i.description}, ${formatPdfCurrency(i.deduction_amount ?? 0, invoice.currency, lang)}`}
|
||||
</Text>
|
||||
)
|
||||
})}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Canonical shape for a per-line invoice posting-account override: a 4-digit
|
||||
* BAS class 1-3 account. Single source of truth shared by the server-side Zod
|
||||
* schemas (lib/api/schemas.ts) and the client-side form schemas
|
||||
* (ArticleForm, InvoiceEditor) so the two layers cannot drift apart.
|
||||
*
|
||||
* Classes 4-8 stay excluded: an invoice line never books to cost, payroll,
|
||||
* or financial accounts. Class 1-2 (balance-sheet) overrides exist for
|
||||
* deposits, customer advances, and genuine outlays; they are only bookable
|
||||
* on zero-VAT lines (enforced server-side in build-invoice-write.ts).
|
||||
*/
|
||||
export const INVOICE_POSTING_ACCOUNT_REGEX = /^[123]\d{3}$/
|
||||
|
||||
/** True when the account is a balance-sheet account (BAS class 1-2). */
|
||||
export function isBalanceSheetAccount(account: string): boolean {
|
||||
return /^[12]/.test(account)
|
||||
}
|
||||
Reference in New Issue
Block a user