feat(invoicing): artikelregister (product/article catalog) with per-article revenue account (#703)
* feat(invoicing): artikelregister (product/article catalog) with per-article revenue account Add a lean, non-inventory article catalog (artikelregister) so users can define reusable invoice-line presets (name, unit, price excl VAT, VAT rate) with an optional per-article BAS class-3 revenue-account override. - DB: articles table (RLS via user_company_ids(), audit + updated_at triggers, unique-per-company article_number), generate_article_number RPC (atomic + idempotent), company_settings counter, nullable invoice_items.revenue_account + article_id, pending_operations CHECK expansion. - Engine: generatePerRateLines groups revenue by (vat_rate, account) — byte-identical with no override, balance-safe when split (last account absorbs the rounding remainder), reverse_charge/export still force 3308/3305. - API: /api/articles CRUD (soft-deactivate); override validated against chart_of_accounts (active class-3) and frozen onto invoice lines at create. - Propagation: override carried through send/mark-sent/credit/convert/cash and the staged commit paths (recurring deferred — documented inline). - MCP: gnubok_list/create/update_article (staged, scoped, risk-tiered). - UI: articles register (list/detail/form) + nav + bilingual i18n + invoice-line article picker & "Spara som artikel" quick-create. - Tests: engine regression, route, and pg-real (RPC/RLS/triggers). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(mcp): strip ILIKE _ wildcard from gnubok_list_articles search Underscore is a single-character ILIKE wildcard; stripping it (alongside the existing %,()\* set) keeps a stray char in the article search from matching every row. Read-only + RLS-scoped, so no security impact — addresses PR #703 reviewer + compliance-swarm CC6.3 notes. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
07ecb98389
commit
c0b006fcc1
@@ -298,6 +298,113 @@ describe('createInvoiceJournalEntry — per-line VAT', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('createInvoiceJournalEntry — per-article revenue account override', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('without an override, two 25% lines collapse into one 3001 revenue line (unchanged behaviour)', async () => {
|
||||
const invoice = makeInvoice({
|
||||
subtotal: 1000,
|
||||
vat_amount: 250,
|
||||
total: 1250,
|
||||
vat_treatment: 'standard_25',
|
||||
vat_rate: null as unknown as number,
|
||||
items: [
|
||||
makeItem({ description: 'A', unit_price: 600, line_total: 600, vat_rate: 25, vat_amount: 150 }),
|
||||
makeItem({ id: 'item-2', description: 'B', unit_price: 400, line_total: 400, vat_rate: 25, vat_amount: 100 }),
|
||||
],
|
||||
})
|
||||
|
||||
await createInvoiceJournalEntry(null as never, 'company-1', 'user-1', invoice)
|
||||
const input = mockedCreateEntry.mock.calls[0][3]
|
||||
|
||||
const rev3001 = input.lines.filter((l) => l.account_number === '3001')
|
||||
expect(rev3001).toHaveLength(1)
|
||||
expect(rev3001[0].credit_amount).toBe(1000)
|
||||
const vat2611 = input.lines.filter((l) => l.account_number === '2611')
|
||||
expect(vat2611).toHaveLength(1)
|
||||
expect(vat2611[0].credit_amount).toBe(250)
|
||||
})
|
||||
|
||||
it('splits one rate into two revenue accounts but keeps a single VAT line, balanced', async () => {
|
||||
const invoice = makeInvoice({
|
||||
subtotal: 1000,
|
||||
vat_amount: 250,
|
||||
total: 1250,
|
||||
vat_treatment: 'standard_25',
|
||||
vat_rate: null as unknown as number,
|
||||
items: [
|
||||
makeItem({ description: 'Goods', unit_price: 600, line_total: 600, vat_rate: 25, vat_amount: 150 }), // no override → 3001
|
||||
makeItem({ id: 'item-2', description: 'Consulting', unit_price: 400, line_total: 400, vat_rate: 25, vat_amount: 100, revenue_account: '3041' }),
|
||||
],
|
||||
})
|
||||
|
||||
await createInvoiceJournalEntry(null as never, 'company-1', 'user-1', invoice)
|
||||
const input = mockedCreateEntry.mock.calls[0][3]
|
||||
|
||||
expect(input.lines.find((l) => l.account_number === '3001')?.credit_amount).toBe(600)
|
||||
expect(input.lines.find((l) => l.account_number === '3041')?.credit_amount).toBe(400)
|
||||
const vat = input.lines.filter((l) => l.account_number === '2611')
|
||||
expect(vat).toHaveLength(1)
|
||||
expect(vat[0].credit_amount).toBe(250)
|
||||
|
||||
const debit = input.lines.reduce((s, l) => s + l.debit_amount, 0)
|
||||
const credit = input.lines.reduce((s, l) => s + l.credit_amount, 0)
|
||||
expect(debit).toBe(credit)
|
||||
expect(debit).toBe(1250)
|
||||
})
|
||||
|
||||
it('ignores a per-line override on reverse charge — revenue stays on 3308', async () => {
|
||||
const invoice = makeInvoice({
|
||||
subtotal: 5000,
|
||||
vat_amount: 0,
|
||||
total: 5000,
|
||||
vat_treatment: 'reverse_charge',
|
||||
vat_rate: 0,
|
||||
items: [
|
||||
makeItem({ unit_price: 5000, line_total: 5000, vat_rate: 0, vat_amount: 0, revenue_account: '3041' }),
|
||||
],
|
||||
})
|
||||
|
||||
await createInvoiceJournalEntry(null as never, 'company-1', 'user-1', invoice)
|
||||
const input = mockedCreateEntry.mock.calls[0][3]
|
||||
|
||||
expect(input.lines.find((l) => l.account_number === '3308')?.credit_amount).toBe(5000)
|
||||
expect(input.lines.find((l) => l.account_number === '3041')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('absorbs rounding on the last account so a split rate still balances against 1510', async () => {
|
||||
// Two 25% lines to different accounts whose individual SEK rounding would
|
||||
// otherwise drift from the rate-level total (10.005 → 10.01 each = 20.02,
|
||||
// but the rate total is round(20.01) = 20.01).
|
||||
const invoice = makeInvoice({
|
||||
subtotal: 20.01,
|
||||
vat_amount: 5.0,
|
||||
total: 25.01,
|
||||
vat_treatment: 'standard_25',
|
||||
vat_rate: null as unknown as number,
|
||||
items: [
|
||||
makeItem({ description: 'A', unit_price: 10.005, line_total: 10.005, vat_rate: 25, vat_amount: 2.5 }),
|
||||
makeItem({ id: 'item-2', description: 'B', unit_price: 10.005, line_total: 10.005, vat_rate: 25, vat_amount: 2.5, revenue_account: '3041' }),
|
||||
],
|
||||
})
|
||||
|
||||
await createInvoiceJournalEntry(null as never, 'company-1', 'user-1', invoice)
|
||||
const input = mockedCreateEntry.mock.calls[0][3]
|
||||
|
||||
const revSum = input.lines
|
||||
.filter((l) => l.account_number === '3001' || l.account_number === '3041')
|
||||
.reduce((s, l) => s + l.credit_amount, 0)
|
||||
expect(Math.round(revSum * 100) / 100).toBe(20.01)
|
||||
|
||||
const debit = Math.round(input.lines.reduce((s, l) => s + l.debit_amount, 0) * 100) / 100
|
||||
const credit = Math.round(input.lines.reduce((s, l) => s + l.credit_amount, 0) * 100) / 100
|
||||
expect(debit).toBe(credit)
|
||||
expect(debit).toBe(25.01)
|
||||
})
|
||||
})
|
||||
|
||||
describe('createCreditNoteJournalEntry — per-line VAT', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
@@ -108,29 +108,65 @@ function generatePerRateLines(
|
||||
return lines
|
||||
}
|
||||
|
||||
// Group items by vat_rate
|
||||
const rateGroups = new Map<number, { subtotal: number; vatAmount: number }>()
|
||||
// Group items by vat_rate (preserve first-seen rate order). Within each rate,
|
||||
// sub-group revenue by the resolved BAS account so a per-line/article account
|
||||
// override produces its own credit line. VAT stays aggregated per rate (the
|
||||
// VAT account is a function of the treatment, never of the revenue override).
|
||||
type RateGroup = {
|
||||
vatAmount: number
|
||||
// resolved revenue account -> summed line_total (first-seen account order)
|
||||
byAccount: Map<string, number>
|
||||
}
|
||||
const rateGroups = new Map<number, RateGroup>()
|
||||
|
||||
for (const item of items) {
|
||||
const rate = item.vat_rate ?? 0
|
||||
const group = rateGroups.get(rate) || { subtotal: 0, vatAmount: 0 }
|
||||
group.subtotal += item.line_total
|
||||
const treatment = rate === 0 && (invoiceVatTreatment === 'reverse_charge' || invoiceVatTreatment === 'export')
|
||||
? invoiceVatTreatment
|
||||
: getVatTreatmentForRate(rate)
|
||||
// reverse_charge / export force the statutory revenue account (3308/3305);
|
||||
// a per-line override only applies to ordinary domestic rates so EU/export
|
||||
// sales keep landing in the right VAT-declaration ruta.
|
||||
const isSpecialTreatment = treatment === 'reverse_charge' || treatment === 'export'
|
||||
const account = !isSpecialTreatment && item.revenue_account
|
||||
? item.revenue_account
|
||||
: getRevenueAccount(treatment, entityType)
|
||||
|
||||
const group = rateGroups.get(rate) ?? { vatAmount: 0, byAccount: new Map<string, number>() }
|
||||
group.vatAmount += item.vat_amount || 0
|
||||
group.byAccount.set(account, (group.byAccount.get(account) ?? 0) + item.line_total)
|
||||
rateGroups.set(rate, group)
|
||||
}
|
||||
|
||||
// Generate revenue + VAT lines per 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(toSek(group.subtotal) * 100) / 100
|
||||
|
||||
lines.push({
|
||||
account_number: revenueAccount,
|
||||
debit_amount: 0,
|
||||
credit_amount: roundedSubtotal,
|
||||
line_description: `Försäljning faktura ${invoiceTagText}`,
|
||||
// The rate-level rounded subtotal is the balance anchor — identical to the
|
||||
// pre-override single-account behaviour. When a rate splits across multiple
|
||||
// accounts, distribute that exact total so independent per-account rounding
|
||||
// can never introduce a 1-öre imbalance against the 1510 debit: every
|
||||
// account but the last rounds normally; the last absorbs the remainder.
|
||||
const rateSubtotalSek = Math.round(
|
||||
toSek(Array.from(group.byAccount.values()).reduce((sum, v) => sum + v, 0)) * 100
|
||||
) / 100
|
||||
|
||||
const accounts = Array.from(group.byAccount.entries())
|
||||
let allocated = 0
|
||||
accounts.forEach(([account, subtotal], idx) => {
|
||||
const isLast = idx === accounts.length - 1
|
||||
const credit = isLast
|
||||
? Math.round((rateSubtotalSek - allocated) * 100) / 100
|
||||
: Math.round(toSek(subtotal) * 100) / 100
|
||||
allocated = Math.round((allocated + credit) * 100) / 100
|
||||
lines.push({
|
||||
account_number: account,
|
||||
debit_amount: 0,
|
||||
credit_amount: credit,
|
||||
line_description: `Försäljning faktura ${invoiceTagText}`,
|
||||
})
|
||||
})
|
||||
|
||||
const roundedVat = Math.round(toSek(group.vatAmount) * 100) / 100
|
||||
|
||||
Reference in New Issue
Block a user