feat: per-line VAT, invoice document types, ledger-based VAT declaration, bank reconciliation, and pagination

Per-line VAT rates:
- Add generatePerRateLines() to group invoice items by vat_rate with separate
  revenue + VAT lines per rate group (invoice-entries.ts)
- Add getAvailableVatRates() and getVatTreatmentForRate() (vat-rules.ts)
- PDF template shows per-line VAT column and per-rate totals for mixed-rate invoices
- Invoice create/review UI supports per-line rate selection
- Types: add vat_rate/vat_amount to InvoiceItem, vat_rate to CreateInvoiceItemInput

Invoice document types (proforma, delivery note):
- Add InvoiceDocumentType, document_type and converted_from_id to Invoice type
- PDF hides prices for delivery notes, adds proforma notice
- Email templates support all document types
- mark-paid skips journal entries for non-invoice document types
- Migration 031: invoice_document_type

Accounting method support:
- Add AccountingMethod type (accrual/cash)
- Migration 032: add_accounting_method column to company_settings

VAT declaration rewrite:
- Rewrite to read directly from general ledger (26xx/3xxx account lines)
  instead of aggregating invoices/transactions/receipts
- ACCOUNT_RUTA mapping drives momsdeklaration boxes from GL balances

Bank reconciliation:
- Transaction ingest now pre-fetches unlinked GL lines and attempts
  auto-reconciliation during import
- Add transaction.reconciled event type
- Add ReconciliationMethod type and reconciliation_method on Transaction
- Migration 030: bank_reconciliation
- New reconciliation engine, API routes, and BankReconciliationView component

Pagination (fetchAllRows):
- New lib/supabase/fetch-all.ts overcomes PostgREST 1000-row limit
- Adopted in all report generators, SIE/SRU export, account list APIs

Fiscal period validation:
- New validate-period-duration.ts enforces max 18 months per BFL 3 kap.
- Applied in period-service.ts and fiscal-periods API

Account mapper simplification:
- Remove Levenshtein/fuzzy matching, use exact account number match only

Swedbank parser improvements:
- Support abbreviated headers (Clnr, Bokfdag, Radnr)
- Use Referens column as counterparty

Chart of accounts management:
- Add DELETE endpoint with system account and usage protection
- PUT uses partial updates
- New AccountCombobox, AddAccountDialog, EditAccountDialog, ChartOfAccountsManager

Tax deadline corrections:
- Rewrite inkomstdeklaration_ab using Skatteverket lookup table
- Rewrite arsredovisning deadline to 7 months after FY end per ÅRL 8:3

Onboarding first fiscal year:
- Add first fiscal year toggle with date pickers and 18-month validation

UI terminology:
- Change "okategoriserad/kategorisera" to "obokförd/bokföra" throughout

Report column fix:
- Fix start_date/end_date to period_start/period_end in report queries

Supplier invoice input:
- CreateSupplierInvoiceItemInput uses amount field (legacy quantity/unit_price kept)

Misc:
- SIE import uses upsert for idempotent account creation
- account-descriptions.ts falls back to BAS reference data
- Add invoice_default_notes to CompanySettings
- Update CLAUDE.md to reflect current project state

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-02-21 14:57:15 +01:00
co-authored by Claude Opus 4.6
parent f1d187c005
commit 91e2c1705a
106 changed files with 9950 additions and 1641 deletions
@@ -1,5 +1,104 @@
import { describe, it, expect } from 'vitest'
import { getRevenueAccount } from '../invoice-entries'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { getRevenueAccount, getOutputVatAccount } from '../invoice-entries'
import type { Invoice, InvoiceItem, CreateJournalEntryInput } from '@/types'
// Mock the engine so we can capture the input passed to createJournalEntry
vi.mock('../engine', () => ({
findFiscalPeriod: vi.fn().mockResolvedValue('period-1'),
createJournalEntry: vi.fn().mockImplementation(
async (_userId: string, input: CreateJournalEntryInput) => ({
id: 'entry-1',
...input,
lines: input.lines,
})
),
}))
// Mock vat-entries to avoid indirect dependency issues
vi.mock('../vat-entries', () => ({
generateSalesVatLines: vi.fn().mockImplementation(({ vatTreatment, baseAmount }: { vatTreatment: string; baseAmount: number }) => {
const rate = vatTreatment === 'standard_25' ? 0.25
: vatTreatment === 'reduced_12' ? 0.12
: vatTreatment === 'reduced_6' ? 0.06 : 0
if (rate === 0) return []
const account = vatTreatment === 'standard_25' ? '2611'
: vatTreatment === 'reduced_12' ? '2621' : '2631'
return [{
account_number: account,
debit_amount: 0,
credit_amount: Math.round(baseAmount * rate * 100) / 100,
line_description: `Utgående moms`,
}]
}),
generateReverseChargeLines: vi.fn().mockReturnValue([]),
}))
const { createJournalEntry } = await import('../engine')
const mockedCreateEntry = vi.mocked(createJournalEntry)
// Import functions under test AFTER mocks are set up
const {
createInvoiceJournalEntry,
createCreditNoteJournalEntry,
createInvoiceCashEntry,
} = await import('../invoice-entries')
// Helper to build a minimal Invoice with items
function makeInvoice(overrides: Partial<Invoice> & { items?: InvoiceItem[] }): Invoice {
return {
id: 'inv-1',
user_id: 'user-1',
customer_id: 'cust-1',
invoice_number: '1001',
invoice_date: '2024-06-15',
due_date: '2024-07-15',
currency: 'SEK',
exchange_rate: null,
exchange_rate_date: null,
subtotal: 1000,
subtotal_sek: null,
vat_amount: 250,
vat_amount_sek: null,
total: 1250,
total_sek: null,
vat_treatment: 'standard_25',
vat_rate: 25,
moms_ruta: '05',
reverse_charge_text: null,
your_reference: null,
our_reference: null,
notes: null,
status: 'sent',
sent_at: null,
paid_at: null,
payment_date: null,
credited_invoice_id: null,
journal_entry_id: null,
payment_journal_entry_id: null,
document_type: 'invoice',
created_at: '2024-06-15T00:00:00Z',
updated_at: '2024-06-15T00:00:00Z',
items: [],
...overrides,
} as Invoice
}
function makeItem(overrides: Partial<InvoiceItem> = {}): InvoiceItem {
return {
id: 'item-1',
invoice_id: 'inv-1',
sort_order: 0,
description: 'Service',
quantity: 1,
unit: 'st',
unit_price: 1000,
line_total: 1000,
vat_rate: 25,
vat_amount: 250,
created_at: '2024-06-15T00:00:00Z',
...overrides,
}
}
describe('getRevenueAccount', () => {
it('standard_25 returns 3001', () => {
@@ -37,3 +136,255 @@ describe('getRevenueAccount', () => {
expect(getRevenueAccount('export', 'aktiebolag')).toBe('3305')
})
})
describe('getOutputVatAccount', () => {
it('standard_25 returns 2611', () => {
expect(getOutputVatAccount('standard_25')).toBe('2611')
})
it('reduced_12 returns 2621', () => {
expect(getOutputVatAccount('reduced_12')).toBe('2621')
})
it('reduced_6 returns 2631', () => {
expect(getOutputVatAccount('reduced_6')).toBe('2631')
})
})
describe('createInvoiceJournalEntry — per-line VAT', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('single-rate invoice creates one revenue + one VAT line', async () => {
const invoice = makeInvoice({
subtotal: 1000,
vat_amount: 250,
total: 1250,
vat_treatment: 'standard_25',
items: [
makeItem({ description: 'A', quantity: 2, unit_price: 300, line_total: 600, vat_rate: 25, vat_amount: 150 }),
makeItem({ id: 'item-2', description: 'B', quantity: 1, unit_price: 400, line_total: 400, vat_rate: 25, vat_amount: 100 }),
],
})
await createInvoiceJournalEntry('user-1', invoice)
expect(mockedCreateEntry).toHaveBeenCalledOnce()
const input = mockedCreateEntry.mock.calls[0][1]
// Should have 3 lines: 1510 debit, 3001 credit, 2611 credit
expect(input.lines).toHaveLength(3)
// Debit 1510 = total
const debit1510 = input.lines.find((l) => l.account_number === '1510')
expect(debit1510?.debit_amount).toBe(1250)
expect(debit1510?.credit_amount).toBe(0)
// Credit 3001 = subtotal
const credit3001 = input.lines.find((l) => l.account_number === '3001')
expect(credit3001?.debit_amount).toBe(0)
expect(credit3001?.credit_amount).toBe(1000)
// Credit 2611 = VAT
const credit2611 = input.lines.find((l) => l.account_number === '2611')
expect(credit2611?.debit_amount).toBe(0)
expect(credit2611?.credit_amount).toBe(250)
})
it('mixed 25%/12% creates two revenue + two VAT lines', async () => {
const invoice = makeInvoice({
subtotal: 1000,
vat_amount: 184, // 600*0.25 + 400*0.12 = 150 + 48 = 198... let's recalc
total: 1198,
vat_treatment: 'standard_25',
vat_rate: null as unknown as number,
items: [
makeItem({ description: 'Consulting', quantity: 1, unit_price: 600, line_total: 600, vat_rate: 25, vat_amount: 150 }),
makeItem({ id: 'item-2', description: 'Food service', quantity: 1, unit_price: 400, line_total: 400, vat_rate: 12, vat_amount: 48 }),
],
})
invoice.vat_amount = 198
invoice.total = 1198
await createInvoiceJournalEntry('user-1', invoice)
expect(mockedCreateEntry).toHaveBeenCalledOnce()
const input = mockedCreateEntry.mock.calls[0][1]
// Should have 5 lines: 1510, 3001(25%), 2611(25%), 3002(12%), 2621(12%)
expect(input.lines).toHaveLength(5)
// Debit 1510 = total
const debit1510 = input.lines.find((l) => l.account_number === '1510')
expect(debit1510?.debit_amount).toBe(1198)
// Revenue 3001 (25% group)
const credit3001 = input.lines.find((l) => l.account_number === '3001')
expect(credit3001?.credit_amount).toBe(600)
// VAT 2611 (25% group)
const credit2611 = input.lines.find((l) => l.account_number === '2611')
expect(credit2611?.credit_amount).toBe(150)
// Revenue 3002 (12% group)
const credit3002 = input.lines.find((l) => l.account_number === '3002')
expect(credit3002?.credit_amount).toBe(400)
// VAT 2621 (12% group)
const credit2621 = input.lines.find((l) => l.account_number === '2621')
expect(credit2621?.credit_amount).toBe(48)
})
it('reverse charge creates single 3308, no VAT lines', async () => {
const invoice = makeInvoice({
subtotal: 5000,
vat_amount: 0,
total: 5000,
vat_treatment: 'reverse_charge',
vat_rate: 0,
items: [
makeItem({ quantity: 1, unit_price: 5000, line_total: 5000, vat_rate: 0, vat_amount: 0 }),
],
})
await createInvoiceJournalEntry('user-1', invoice)
expect(mockedCreateEntry).toHaveBeenCalledOnce()
const input = mockedCreateEntry.mock.calls[0][1]
// Should have 2 lines: 1510 debit, 3308 credit (no VAT)
expect(input.lines).toHaveLength(2)
const debit1510 = input.lines.find((l) => l.account_number === '1510')
expect(debit1510?.debit_amount).toBe(5000)
const credit3308 = input.lines.find((l) => l.account_number === '3308')
expect(credit3308?.credit_amount).toBe(5000)
// No VAT lines
const vatLines = input.lines.filter((l) =>
l.account_number.startsWith('26')
)
expect(vatLines).toHaveLength(0)
})
it('balance: debit(1510) = sum(revenue + VAT credits)', async () => {
const invoice = makeInvoice({
subtotal: 2000,
vat_amount: 380, // 1200*0.25 + 500*0.12 + 300*0.06 = 300 + 60 + 18 = 378
total: 2378,
vat_treatment: 'standard_25',
vat_rate: null as unknown as number,
items: [
makeItem({ description: 'A', quantity: 1, unit_price: 1200, line_total: 1200, vat_rate: 25, vat_amount: 300 }),
makeItem({ id: 'item-2', description: 'B', quantity: 1, unit_price: 500, line_total: 500, vat_rate: 12, vat_amount: 60 }),
makeItem({ id: 'item-3', description: 'C', quantity: 1, unit_price: 300, line_total: 300, vat_rate: 6, vat_amount: 18 }),
],
})
invoice.vat_amount = 378
invoice.total = 2378
await createInvoiceJournalEntry('user-1', invoice)
const input = mockedCreateEntry.mock.calls[0][1]
const totalDebit = input.lines.reduce((sum, l) => sum + l.debit_amount, 0)
const totalCredit = input.lines.reduce((sum, l) => sum + l.credit_amount, 0)
expect(totalDebit).toBe(totalCredit)
expect(totalDebit).toBe(2378)
})
})
describe('createCreditNoteJournalEntry — per-line VAT', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('reverses per-rate lines correctly for mixed rates', async () => {
const creditNote = makeInvoice({
invoice_number: 'KR-1001',
subtotal: -1000,
vat_amount: -198,
total: -1198,
vat_treatment: 'standard_25',
items: [
makeItem({ quantity: -1, unit_price: 600, line_total: -600, vat_rate: 25, vat_amount: -150 }),
makeItem({ id: 'item-2', quantity: -1, unit_price: 400, line_total: -400, vat_rate: 12, vat_amount: -48 }),
],
})
await createCreditNoteJournalEntry('user-1', creditNote)
expect(mockedCreateEntry).toHaveBeenCalledOnce()
const input = mockedCreateEntry.mock.calls[0][1]
// Revenue and VAT lines should be debits (reversed)
const debit3001 = input.lines.find((l) => l.account_number === '3001')
expect(debit3001?.debit_amount).toBe(600)
expect(debit3001?.credit_amount).toBe(0)
const debit2611 = input.lines.find((l) => l.account_number === '2611')
expect(debit2611?.debit_amount).toBe(150)
const debit3002 = input.lines.find((l) => l.account_number === '3002')
expect(debit3002?.debit_amount).toBe(400)
const debit2621 = input.lines.find((l) => l.account_number === '2621')
expect(debit2621?.debit_amount).toBe(48)
// 1510 should be credit
const credit1510 = input.lines.find((l) => l.account_number === '1510')
expect(credit1510?.credit_amount).toBe(1198)
expect(credit1510?.debit_amount).toBe(0)
// Balance check
const totalDebit = input.lines.reduce((sum, l) => sum + l.debit_amount, 0)
const totalCredit = input.lines.reduce((sum, l) => sum + l.credit_amount, 0)
expect(totalDebit).toBe(totalCredit)
})
})
describe('createInvoiceCashEntry — per-line VAT', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('cash method with mixed rates creates per-rate revenue + VAT', async () => {
const invoice = makeInvoice({
subtotal: 1000,
vat_amount: 198,
total: 1198,
vat_treatment: 'standard_25',
items: [
makeItem({ quantity: 1, unit_price: 600, line_total: 600, vat_rate: 25, vat_amount: 150 }),
makeItem({ id: 'item-2', quantity: 1, unit_price: 400, line_total: 400, vat_rate: 12, vat_amount: 48 }),
],
})
await createInvoiceCashEntry('user-1', invoice, '2024-07-01')
expect(mockedCreateEntry).toHaveBeenCalledOnce()
const input = mockedCreateEntry.mock.calls[0][1]
// Debit 1930 (bank account) instead of 1510
const debit1930 = input.lines.find((l) => l.account_number === '1930')
expect(debit1930?.debit_amount).toBe(1198)
// Same per-rate credits as accrual
const credit3001 = input.lines.find((l) => l.account_number === '3001')
expect(credit3001?.credit_amount).toBe(600)
const credit2611 = input.lines.find((l) => l.account_number === '2611')
expect(credit2611?.credit_amount).toBe(150)
const credit3002 = input.lines.find((l) => l.account_number === '3002')
expect(credit3002?.credit_amount).toBe(400)
// Balance
const totalDebit = input.lines.reduce((sum, l) => sum + l.debit_amount, 0)
const totalCredit = input.lines.reduce((sum, l) => sum + l.credit_amount, 0)
expect(totalDebit).toBe(totalCredit)
})
})
@@ -0,0 +1,80 @@
import { describe, it, expect } from 'vitest'
import { validatePeriodDuration, monthsBetween } from '../validate-period-duration'
describe('monthsBetween', () => {
it('returns 12 for a standard calendar year', () => {
expect(monthsBetween('2025-01-01', '2025-12-31')).toBe(12)
})
it('returns 18 for an 18-month period', () => {
expect(monthsBetween('2025-07-01', '2026-12-31')).toBe(18)
})
it('returns 1 for a single month', () => {
expect(monthsBetween('2025-03-01', '2025-03-31')).toBe(1)
})
it('returns 3 for a quarter', () => {
expect(monthsBetween('2025-10-01', '2025-12-31')).toBe(3)
})
})
describe('validatePeriodDuration', () => {
it('returns null for a valid 12-month period', () => {
expect(validatePeriodDuration('2025-01-01', '2025-12-31')).toBeNull()
})
it('returns null for exactly 18 months (max allowed)', () => {
expect(validatePeriodDuration('2025-07-01', '2026-12-31')).toBeNull()
})
it('returns null for a short first year (1 month)', () => {
expect(validatePeriodDuration('2025-12-01', '2025-12-31')).toBeNull()
})
it('returns null for a short first year (3 months)', () => {
expect(validatePeriodDuration('2025-10-01', '2025-12-31')).toBeNull()
})
it('returns error for 19 months (exceeds max)', () => {
const result = validatePeriodDuration('2025-06-01', '2026-12-31')
expect(result).toContain('19 months')
expect(result).toContain('18 months')
})
it('returns error when end is before start', () => {
expect(validatePeriodDuration('2025-06-01', '2025-01-31')).toBe(
'Period end must be after period start'
)
})
it('returns error when start is not 1st of month', () => {
expect(validatePeriodDuration('2025-01-15', '2025-12-31')).toBe(
'Period start must be the 1st of a month'
)
})
it('returns error when end is not last day of month', () => {
expect(validatePeriodDuration('2025-01-01', '2025-12-15')).toBe(
'Period end must be the last day of a month'
)
})
it('handles February end correctly (non-leap year)', () => {
expect(validatePeriodDuration('2025-01-01', '2025-02-28')).toBeNull()
})
it('handles February end correctly (leap year)', () => {
expect(validatePeriodDuration('2024-01-01', '2024-02-29')).toBeNull()
})
it('rejects Feb 28 in a leap year (not last day)', () => {
expect(validatePeriodDuration('2024-01-01', '2024-02-28')).toBe(
'Period end must be the last day of a month'
)
})
it('returns null for a broken fiscal year (May-Apr)', () => {
expect(validatePeriodDuration('2025-05-01', '2026-04-30')).toBeNull()
})
})
+49 -1
View File
@@ -326,7 +326,55 @@ const ACCOUNT_DESCRIPTIONS: Record<string, AccountDescription> = {
}
export function getAccountDescription(accountNumber: string): AccountDescription | undefined {
return ACCOUNT_DESCRIPTIONS[accountNumber]
// Check hardcoded descriptions first (most detailed explanations)
const hardcoded = ACCOUNT_DESCRIPTIONS[accountNumber]
if (hardcoded) return hardcoded
// Fall back to BAS reference data for accounts not in the hardcoded list
try {
// Dynamic import avoided — use lazy require pattern
const { getBASReference, ACCOUNT_CLASS_LABELS } = require('./bas-reference')
const ref = getBASReference(accountNumber)
if (ref) {
const classLabel = ACCOUNT_CLASS_LABELS[ref.account_class] || ''
return {
name: ref.account_name,
classLabel,
type: ref.account_type,
explanation: ref.description,
}
}
} catch {
// BAS reference not available — that's fine
}
return undefined
}
/**
* Get a human-readable account class name for BAS account classes.
*/
export function getAccountClassName(accountClass: number): string {
switch (accountClass) {
case 1:
return '1xxx - Tillgångar'
case 2:
return '2xxx - Eget kapital & Skulder'
case 3:
return '3xxx - Intäkter'
case 4:
return '4xxx - Varuinköp'
case 5:
return '5xxx - Externa kostnader'
case 6:
return '6xxx - Övriga externa kostnader'
case 7:
return '7xxx - Personal'
case 8:
return '8xxx - Finansiella poster'
default:
return `${accountClass}xxx - Övrigt`
}
}
export { ACCOUNT_DESCRIPTIONS }
File diff suppressed because it is too large Load Diff
+160 -57
View File
@@ -1,21 +1,104 @@
import { createJournalEntry, findFiscalPeriod } from './engine'
import { generateSalesVatLines, generateReverseChargeLines } from './vat-entries'
import { getVatTreatmentForRate } from '@/lib/invoice/vat-rules'
import type {
CreateJournalEntryInput,
CreateJournalEntryLineInput,
EntityType,
Invoice,
InvoiceItem,
JournalEntry,
VatTreatment,
} from '@/types'
/**
* Group invoice items by VAT rate and generate per-rate revenue + VAT lines.
* Returns credit lines only (revenue + VAT). The caller adds the debit side.
*/
function generatePerRateLines(
items: InvoiceItem[],
invoiceVatTreatment: VatTreatment,
entityType: EntityType,
invoiceNumber: string
): CreateJournalEntryLineInput[] {
const lines: CreateJournalEntryLineInput[] = []
// Check if items have per-line vat_rate set (new invoices)
const hasPerLineVat = items.some((item) => item.vat_rate !== undefined && item.vat_rate !== null)
if (!hasPerLineVat) {
// Legacy fallback: single rate from invoice level
const revenueAccount = getRevenueAccount(invoiceVatTreatment, entityType)
const subtotal = items.reduce((sum, item) => sum + item.line_total, 0)
lines.push({
account_number: revenueAccount,
debit_amount: 0,
credit_amount: subtotal,
line_description: `Försäljning faktura ${invoiceNumber}`,
})
const totalVat = items.reduce((sum, item) => sum + (item.vat_amount || 0), 0)
if (totalVat > 0) {
const vatLines = generateSalesVatLines({
vatTreatment: invoiceVatTreatment,
baseAmount: subtotal,
direction: 'sales',
})
lines.push(...vatLines)
}
return lines
}
// Group items by vat_rate
const rateGroups = new Map<number, { subtotal: number; vatAmount: number }>()
for (const item of items) {
const rate = item.vat_rate ?? 25
const group = rateGroups.get(rate) || { subtotal: 0, vatAmount: 0 }
group.subtotal += item.line_total
group.vatAmount += item.vat_amount || 0
rateGroups.set(rate, group)
}
// Generate revenue + VAT lines per rate group
for (const [rate, group] of rateGroups) {
const treatment = rate === 0 && (invoiceVatTreatment === 'reverse_charge' || invoiceVatTreatment === 'export')
? invoiceVatTreatment
: getVatTreatmentForRate(rate)
const revenueAccount = getRevenueAccount(treatment, entityType)
const roundedSubtotal = Math.round(group.subtotal * 100) / 100
lines.push({
account_number: revenueAccount,
debit_amount: 0,
credit_amount: roundedSubtotal,
line_description: `Försäljning faktura ${invoiceNumber}`,
})
const roundedVat = Math.round(group.vatAmount * 100) / 100
if (roundedVat !== 0) {
const vatAccount = getOutputVatAccount(treatment)
lines.push({
account_number: vatAccount,
debit_amount: 0,
credit_amount: roundedVat,
line_description: `Utgående moms ${rate}%`,
})
}
}
return lines
}
/**
* Create journal entry when an invoice is created (status != draft)
*
* Supports mixed VAT rates per line item. Groups items by vat_rate
* and creates separate revenue + VAT lines per rate.
*
* Standard domestic invoice (25% VAT):
* Debit 1510 Kundfordringar [total incl VAT]
* Credit 30xx Försäljning [subtotal]
* Credit 2611 Utgående moms 25% [vat_amount]
* Credit 30xx Försäljning [subtotal per rate]
* Credit 26xx Utgående moms [vat per rate]
*
* EU reverse charge:
* Debit 1510 Kundfordringar [subtotal]
@@ -38,9 +121,6 @@ export async function createInvoiceJournalEntry(
const lines: CreateJournalEntryLineInput[] = []
// Determine revenue account based on VAT treatment
const revenueAccount = getRevenueAccount(invoice.vat_treatment, entityType)
// Debit: Kundfordringar (total including VAT)
lines.push({
account_number: '1510',
@@ -52,22 +132,27 @@ export async function createInvoiceJournalEntry(
exchange_rate: invoice.exchange_rate || undefined,
})
// Credit: Revenue account (subtotal, excl VAT)
lines.push({
account_number: revenueAccount,
debit_amount: 0,
credit_amount: invoice.subtotal,
line_description: `Försäljning faktura ${invoice.invoice_number}`,
})
// VAT lines (if applicable)
if (invoice.vat_amount > 0) {
const vatLines = generateSalesVatLines({
vatTreatment: invoice.vat_treatment,
baseAmount: invoice.subtotal,
direction: 'sales',
// Credit lines: revenue + VAT per rate group
if (invoice.items && invoice.items.length > 0) {
lines.push(...generatePerRateLines(invoice.items, invoice.vat_treatment, entityType, invoice.invoice_number))
} else {
// Fallback: no items available, use invoice-level amounts
const revenueAccount = getRevenueAccount(invoice.vat_treatment, entityType)
lines.push({
account_number: revenueAccount,
debit_amount: 0,
credit_amount: invoice.subtotal,
line_description: `Försäljning faktura ${invoice.invoice_number}`,
})
lines.push(...vatLines)
if (invoice.vat_amount > 0) {
const vatLines = generateSalesVatLines({
vatTreatment: invoice.vat_treatment,
baseAmount: invoice.subtotal,
direction: 'sales',
})
lines.push(...vatLines)
}
}
const input: CreateJournalEntryInput = {
@@ -128,9 +213,10 @@ export async function createInvoicePaymentJournalEntry(
/**
* Create journal entry for a credit note (reversed version of original invoice entry)
* Supports per-item VAT rates with reversed debit/credit sides.
*
* Debit 30xx Försäljning [subtotal]
* Debit 26xx Utgående moms [vat_amount]
* Debit 30xx Försäljning [subtotal per rate]
* Debit 26xx Utgående moms [vat per rate]
* Credit 1510 Kundfordringar [total]
*/
export async function createCreditNoteJournalEntry(
@@ -144,30 +230,43 @@ export async function createCreditNoteJournalEntry(
return null
}
const revenueAccount = getRevenueAccount(creditNote.vat_treatment, entityType)
const absSubtotal = Math.abs(creditNote.subtotal)
const absVat = Math.abs(creditNote.vat_amount)
const absTotal = Math.abs(creditNote.total)
const lines: CreateJournalEntryLineInput[] = []
// Debit: Revenue account (reverse the credit)
lines.push({
account_number: revenueAccount,
debit_amount: absSubtotal,
credit_amount: 0,
line_description: `Kreditfaktura ${creditNote.invoice_number}`,
})
// Generate reversed revenue + VAT lines per rate group
if (creditNote.items && creditNote.items.length > 0) {
const creditLines = generatePerRateLines(creditNote.items, creditNote.vat_treatment, entityType, creditNote.invoice_number)
// Swap debit/credit for credit note reversal (make amounts absolute first)
for (const line of creditLines) {
lines.push({
...line,
debit_amount: Math.abs(line.credit_amount),
credit_amount: Math.abs(line.debit_amount),
line_description: `Kreditfaktura ${creditNote.invoice_number}`,
})
}
} else {
// Fallback: invoice-level amounts
const revenueAccount = getRevenueAccount(creditNote.vat_treatment, entityType)
const absSubtotal = Math.abs(creditNote.subtotal)
const absVat = Math.abs(creditNote.vat_amount)
// Debit: VAT account (reverse the credit, if applicable)
if (absVat > 0) {
const vatAccount = getOutputVatAccount(creditNote.vat_treatment)
lines.push({
account_number: vatAccount,
debit_amount: absVat,
account_number: revenueAccount,
debit_amount: absSubtotal,
credit_amount: 0,
line_description: `Moms kreditfaktura ${creditNote.invoice_number}`,
line_description: `Kreditfaktura ${creditNote.invoice_number}`,
})
if (absVat > 0) {
const vatAccount = getOutputVatAccount(creditNote.vat_treatment)
lines.push({
account_number: vatAccount,
debit_amount: absVat,
credit_amount: 0,
line_description: `Moms kreditfaktura ${creditNote.invoice_number}`,
})
}
}
// Credit: Kundfordringar (reverse the debit)
@@ -192,11 +291,11 @@ export async function createCreditNoteJournalEntry(
/**
* Create journal entry for kontantmetoden (cash method) when payment is received.
* Combined entry: revenue + VAT recognised at payment.
* Supports per-item VAT rates. Revenue + VAT recognised at payment.
*
* Debit 1930 Företagskonto [total]
* Credit 30xx Försäljning [subtotal]
* Credit 26xx Utgående moms [vat_amount] (if applicable)
* Credit 30xx Försäljning [subtotal per rate]
* Credit 26xx Utgående moms [vat per rate] (if applicable)
*/
export async function createInvoiceCashEntry(
userId: string,
@@ -210,7 +309,6 @@ export async function createInvoiceCashEntry(
return null
}
const revenueAccount = getRevenueAccount(invoice.vat_treatment, entityType)
const lines: CreateJournalEntryLineInput[] = []
// Debit: Företagskonto (total received)
@@ -221,23 +319,28 @@ export async function createInvoiceCashEntry(
line_description: `Betalning faktura ${invoice.invoice_number}`,
})
// Credit: Revenue account (subtotal excl VAT)
lines.push({
account_number: revenueAccount,
debit_amount: 0,
credit_amount: invoice.subtotal,
line_description: `Försäljning faktura ${invoice.invoice_number}`,
})
// Credit: Output VAT (if applicable)
if (invoice.vat_amount > 0) {
const vatAccount = getOutputVatAccount(invoice.vat_treatment)
// Credit lines: revenue + VAT per rate group
if (invoice.items && invoice.items.length > 0) {
lines.push(...generatePerRateLines(invoice.items, invoice.vat_treatment, entityType, invoice.invoice_number))
} else {
// Fallback: invoice-level amounts
const revenueAccount = getRevenueAccount(invoice.vat_treatment, entityType)
lines.push({
account_number: vatAccount,
account_number: revenueAccount,
debit_amount: 0,
credit_amount: invoice.vat_amount,
line_description: `Utgående moms faktura ${invoice.invoice_number}`,
credit_amount: invoice.subtotal,
line_description: `Försäljning faktura ${invoice.invoice_number}`,
})
if (invoice.vat_amount > 0) {
const vatAccount = getOutputVatAccount(invoice.vat_treatment)
lines.push({
account_number: vatAccount,
debit_amount: 0,
credit_amount: invoice.vat_amount,
line_description: `Utgående moms faktura ${invoice.invoice_number}`,
})
}
}
const input: CreateJournalEntryInput = {
+1 -1
View File
@@ -190,7 +190,7 @@ function getDefaultResult(transaction: Transaction): MappingResult {
requires_review: true,
default_private: false,
vat_lines: [],
description: 'Okategoriserad transaktion',
description: 'Obokförd transaktion',
}
}
@@ -0,0 +1,48 @@
/**
* Validates fiscal period duration per BFL 3 kap.
* Maximum 18 months for any fiscal period (first year may be extended).
* Normal ongoing periods are 12 months.
*/
/**
* Calculate the number of months between two dates (inclusive of partial months).
* Assumes start is 1st of month and end is last of month.
*/
export function monthsBetween(start: string, end: string): number {
const s = new Date(start)
const e = new Date(end)
return (e.getFullYear() - s.getFullYear()) * 12 + (e.getMonth() - s.getMonth()) + 1
}
/**
* Validate a fiscal period's duration and date constraints.
* Returns null if valid, or an error message string if invalid.
*/
export function validatePeriodDuration(start: string, end: string): string | null {
const startDate = new Date(start)
const endDate = new Date(end)
// end must be after start
if (endDate <= startDate) {
return 'Period end must be after period start'
}
// start must be 1st of month
if (startDate.getDate() !== 1) {
return 'Period start must be the 1st of a month'
}
// end must be last day of month
const lastDayOfEndMonth = new Date(endDate.getFullYear(), endDate.getMonth() + 1, 0).getDate()
if (endDate.getDate() !== lastDayOfEndMonth) {
return 'Period end must be the last day of a month'
}
// Max 18 months per BFL 3 kap.
const months = monthsBetween(start, end)
if (months > 18) {
return `Period duration ${months} months exceeds maximum 18 months (BFL 3 kap.)`
}
return null
}