feat(invoices): per-line percentage discount and separate fakturamarkning (#2084)
* feat(invoices): per-line percentage discount and separate fakturamarkning User request: rabatt i procent per artikelrad, and a marking field separate from Er referens. - invoice_items.discount_percent (0-100, default 0): line_total and vat_amount are stored NET of the discount. Shared exact-ore math in lib/invoices/line-amounts.ts (gross, discount, net) used by the web builder, staged-operation commit, editor preview, PDF, and Peppol. Undiscounted lines keep the legacy unrounded qty*price byte-identical. - ROT/RUT deduction computes on the discounted net line total. - invoices.invoice_marking: printed on the PDF next to the references and mapped to Peppol BT-10 BuyerReference (marking wins over your_reference; either satisfies the BT-10 requirement). - Peppol renders the discount as a BG-27 line AllowanceCharge (reason code 95, MultiplierFactorNumeric, Amount, BaseAmount). - Editor: "Lagg till rabatt" in the row menu (same reveal pattern as ROT/RUT), Markning row next to Er referens, forval chip, review dialog shows discounts and marking. - Plumbed through v1 REST projections, MCP create/get/update invoice tools, pending-operations update path, and copy-invoice (discount copied; marking deliberately not, it is recipient-specific). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JJAt9yM7tgZ69f1XnNnq52 * fix(invoices): carry discount_percent through every deduction, credit, convert and preview path Skeptic + CI findings on the discount/marking feature, one pass: - generateRotRutLines and propose-send-lines now pass discount_percent into computeDeduction: the send/credit/cash verifikat booked 1513 on the GROSS line while deduction_total, the PDF and the Skatteverket claim carried the net, stranding the difference on 1513 and pushing 1510 negative once the customer paid. Test pins 1513=3000/1510=7000 for a 20%-discounted 10 000 kr ROT line. - preview-pdf route accepts discount_percent (net totals + net-based deduction) and invoice_marking; the editor now sends the marking, so the preview equals the invoice it becomes. - Credit notes carry discount_percent (buildCreditNoteItem, v1 credit route select+insert, MCP credit executor) and invoice_marking, so the kreditfaktura face arithmetic multiplies out and shows the Rabatt column (ML 17 kap 24 §). - Proforma->invoice convert copies discount_percent + invoice_marking: the converted invoice previously failed Peppol LINE_TOTAL_MISMATCH and lost the rebate on the next builder pass. - Editor hides the discount menu in self-billed mode (the self-billed wire shape has no discount; previewed net would book gross). - MCP staging and commitCreateInvoice reject a non-number discount_percent (a string coerced past the range check but was ignored by the totals math and still stored). - Regenerated skills/accounted-api (apiskill:check CI failure). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JJAt9yM7tgZ69f1XnNnq52 --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
84c8e1ce59
commit
f216a60bf8
@@ -52,4 +52,19 @@ describe('buildCreditNoteItem', () => {
|
||||
dimensions: { '6': 'P001' },
|
||||
})
|
||||
})
|
||||
|
||||
it('carries discount_percent so the kreditfaktura face arithmetic multiplies out', () => {
|
||||
// Original: 2 x 1000 with 10% rabatt → net 1800. The credit row must keep
|
||||
// the discount, or -2 x 1000 next to Summa -1800 prints with no visible
|
||||
// prisnedsättning (ML 17 kap 24 §) and violates the stored net invariant.
|
||||
const result = buildCreditNoteItem('credit-1', item({ discount_percent: 10, line_total: 1800, vat_amount: 450 }))
|
||||
expect(result).toMatchObject({
|
||||
quantity: -2,
|
||||
discount_percent: 10,
|
||||
line_total: -1800,
|
||||
vat_amount: -450,
|
||||
})
|
||||
// Legacy rows without the column default to 0.
|
||||
expect(buildCreditNoteItem('credit-1', item()).discount_percent).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { createQueuedMockSupabase, makeCustomer } from '@/tests/helpers'
|
||||
import { computeLineAmounts, computeLineNet, hasLineDiscount } from '@/lib/invoices/line-amounts'
|
||||
import { computeDeduction } from '@/lib/invoices/rot-rut-rules'
|
||||
import { buildInvoiceWriteData } from '@/lib/invoices/build-invoice-write'
|
||||
|
||||
describe('computeLineAmounts', () => {
|
||||
it('passes qty * price through untouched when no discount applies', () => {
|
||||
// Legacy parity: existing invoices store the unrounded product.
|
||||
expect(computeLineAmounts(3, 33.333)).toEqual({
|
||||
gross: 3 * 33.333,
|
||||
discount: 0,
|
||||
net: 3 * 33.333,
|
||||
})
|
||||
expect(computeLineAmounts(2, 100, null)).toEqual({ gross: 200, discount: 0, net: 200 })
|
||||
expect(computeLineAmounts(2, 100, 0)).toEqual({ gross: 200, discount: 0, net: 200 })
|
||||
})
|
||||
|
||||
it('computes discount and net in exact ore arithmetic', () => {
|
||||
expect(computeLineAmounts(2, 100, 10)).toEqual({ gross: 200, discount: 20, net: 180 })
|
||||
// 1 * 99.99 at 33%: gross 99.99, discount round(32.9967) = 33.00, net 66.99.
|
||||
expect(computeLineAmounts(1, 99.99, 33)).toEqual({ gross: 99.99, discount: 33, net: 66.99 })
|
||||
// gross - discount is always exact: net + discount reconstructs gross.
|
||||
const amounts = computeLineAmounts(7, 123.45, 12.5)
|
||||
expect(amounts.net + amounts.discount).toBeCloseTo(amounts.gross, 10)
|
||||
})
|
||||
|
||||
it('handles a 100% discount as a zero net line', () => {
|
||||
expect(computeLineAmounts(4, 250, 100)).toEqual({ gross: 1000, discount: 1000, net: 0 })
|
||||
expect(computeLineNet(4, 250, 100)).toBe(0)
|
||||
})
|
||||
|
||||
it('hasLineDiscount treats null/undefined/0 as no discount', () => {
|
||||
expect(hasLineDiscount(undefined)).toBe(false)
|
||||
expect(hasLineDiscount(null)).toBe(false)
|
||||
expect(hasLineDiscount(0)).toBe(false)
|
||||
expect(hasLineDiscount(0.5)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('computeDeduction with a line discount', () => {
|
||||
it('deducts on the net line total (what the customer pays)', () => {
|
||||
// 10 tim * 1000 = 10 000, 10% rabatt -> 9 000 net, incl VAT 11 250,
|
||||
// ROT 30% = 3 375 (vs 3 750 undiscounted).
|
||||
expect(
|
||||
computeDeduction({
|
||||
unit_price: 1000,
|
||||
quantity: 10,
|
||||
discount_percent: 10,
|
||||
deduction_type: 'rot',
|
||||
vat_rate: 25,
|
||||
}),
|
||||
).toBe(3375)
|
||||
expect(
|
||||
computeDeduction({ unit_price: 1000, quantity: 10, deduction_type: 'rot', vat_rate: 25 }),
|
||||
).toBe(3750)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildInvoiceWriteData with per-line discount and invoice_marking', () => {
|
||||
const baseHeader = {
|
||||
customer_id: 'customer-1',
|
||||
invoice_date: '2026-06-15',
|
||||
due_date: '2026-07-15',
|
||||
currency: 'SEK' as const,
|
||||
}
|
||||
|
||||
it('stores net line totals, VAT on the net, and the discount on the row', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { vat_registered: true }, error: null })
|
||||
|
||||
const customer = makeCustomer({ customer_type: 'swedish_business' })
|
||||
const result = await buildInvoiceWriteData({
|
||||
supabase: supabase as unknown as SupabaseClient,
|
||||
companyId: 'company-1',
|
||||
customer,
|
||||
documentType: 'invoice',
|
||||
input: {
|
||||
...baseHeader,
|
||||
items: [
|
||||
{ description: 'Konsult', quantity: 10, unit: 'tim', unit_price: 1000, vat_rate: 25, discount_percent: 10 },
|
||||
{ description: 'Resa', quantity: 1, unit: 'st', unit_price: 500, vat_rate: 25 },
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
// 10 000 - 10% = 9 000 net + 500 undiscounted.
|
||||
expect(result.invoiceFields.subtotal).toBe(9500)
|
||||
expect(result.invoiceFields.vat_amount).toBe(2375)
|
||||
expect(result.invoiceFields.total).toBe(11875)
|
||||
expect(result.items[0]).toMatchObject({
|
||||
discount_percent: 10,
|
||||
line_total: 9000,
|
||||
vat_amount: 2250,
|
||||
unit_price: 1000,
|
||||
})
|
||||
expect(result.items[1]).toMatchObject({ discount_percent: 0, line_total: 500 })
|
||||
})
|
||||
|
||||
it('maps invoice_marking to a concrete trimmed value, null when absent or blank', async () => {
|
||||
const customer = makeCustomer({ customer_type: 'swedish_business' })
|
||||
const items = [{ description: 'Konsult', quantity: 1, unit: 'tim', unit_price: 100, vat_rate: 25 }]
|
||||
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { vat_registered: true }, error: null })
|
||||
const withMarking = await buildInvoiceWriteData({
|
||||
supabase: supabase as unknown as SupabaseClient,
|
||||
companyId: 'company-1',
|
||||
customer,
|
||||
documentType: 'invoice',
|
||||
input: { ...baseHeader, invoice_marking: ' KST 4711 ', items },
|
||||
})
|
||||
expect(withMarking.ok).toBe(true)
|
||||
if (!withMarking.ok) return
|
||||
expect(withMarking.invoiceFields.invoice_marking).toBe('KST 4711')
|
||||
|
||||
// Absent/blank input must produce an explicit null (supabase-js drops
|
||||
// undefined keys, and a draft edit that cleared the field relies on NULL
|
||||
// actually being written).
|
||||
const { supabase: supabase2, enqueue: enqueue2 } = createQueuedMockSupabase()
|
||||
enqueue2({ data: { vat_registered: true }, error: null })
|
||||
const withoutMarking = await buildInvoiceWriteData({
|
||||
supabase: supabase2 as unknown as SupabaseClient,
|
||||
companyId: 'company-1',
|
||||
customer,
|
||||
documentType: 'invoice',
|
||||
input: { ...baseHeader, invoice_marking: ' ', items },
|
||||
})
|
||||
expect(withoutMarking.ok).toBe(true)
|
||||
if (!withoutMarking.ok) return
|
||||
expect(withoutMarking.invoiceFields.invoice_marking).toBeNull()
|
||||
})
|
||||
|
||||
it('computes the ROT deduction on the discounted line total', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { vat_registered: true }, error: null })
|
||||
|
||||
const customer = makeCustomer({ customer_type: 'individual' })
|
||||
const result = await buildInvoiceWriteData({
|
||||
supabase: supabase as unknown as SupabaseClient,
|
||||
companyId: 'company-1',
|
||||
customer,
|
||||
documentType: 'invoice',
|
||||
input: {
|
||||
...baseHeader,
|
||||
deduction_personnummer: '199001019802',
|
||||
deduction_housing_designation: 'Testbrand 1:1',
|
||||
items: [
|
||||
{
|
||||
description: 'Renovering arbete',
|
||||
quantity: 10,
|
||||
unit: 'tim',
|
||||
unit_price: 1000,
|
||||
vat_rate: 25,
|
||||
discount_percent: 10,
|
||||
deduction_type: 'rot',
|
||||
work_type: 'BYGG',
|
||||
labor_hours: 10,
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
// Net 9 000 excl VAT -> 11 250 incl VAT -> ROT 30% = 3 375.
|
||||
expect(result.items[0].deduction_amount).toBe(3375)
|
||||
expect(result.invoiceFields.deduction_total).toBe(3375)
|
||||
})
|
||||
})
|
||||
@@ -259,6 +259,71 @@ describe('generatePeppolBisBillingInvoice', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('prefers invoice_marking over your_reference for BT-10 BuyerReference', () => {
|
||||
const input = makeValidInput()
|
||||
input.invoice = makeInvoice({ ...input.invoice, invoice_marking: 'KST 4711' })
|
||||
|
||||
const result = generatePeppolBisBillingInvoice(input)
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.xml).toContain('<cbc:BuyerReference>KST 4711</cbc:BuyerReference>')
|
||||
})
|
||||
|
||||
it('accepts a marking-only invoice (no your_reference) as buyer reference', () => {
|
||||
const input = makeValidInput()
|
||||
input.invoice = makeInvoice({
|
||||
...input.invoice,
|
||||
your_reference: null,
|
||||
invoice_marking: 'PO-2026-17',
|
||||
})
|
||||
|
||||
const result = generatePeppolBisBillingInvoice(input)
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.xml).toContain('<cbc:BuyerReference>PO-2026-17</cbc:BuyerReference>')
|
||||
})
|
||||
|
||||
it('renders a per-line discount as a BG-27 allowance with net LineExtensionAmount', () => {
|
||||
const input = makeValidInput()
|
||||
// 2 × 100 = 200 gross, 10% discount = 20, net 180, VAT 25% on net = 45.
|
||||
input.items = [
|
||||
makeItem({ discount_percent: 10, line_total: 180, vat_amount: 45 }),
|
||||
]
|
||||
input.invoice = makeInvoice({
|
||||
...input.invoice,
|
||||
subtotal: 180,
|
||||
vat_amount: 45,
|
||||
total: 225,
|
||||
remaining_amount: 225,
|
||||
})
|
||||
|
||||
const result = generatePeppolBisBillingInvoice(input)
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.xml).toContain('<cbc:LineExtensionAmount currencyID="SEK">180.00</cbc:LineExtensionAmount>')
|
||||
expect(result.xml).toContain('<cbc:ChargeIndicator>false</cbc:ChargeIndicator>')
|
||||
expect(result.xml).toContain('<cbc:AllowanceChargeReasonCode>95</cbc:AllowanceChargeReasonCode>')
|
||||
expect(result.xml).toContain('<cbc:MultiplierFactorNumeric>10</cbc:MultiplierFactorNumeric>')
|
||||
expect(result.xml).toContain('<cbc:Amount currencyID="SEK">20.00</cbc:Amount>')
|
||||
expect(result.xml).toContain('<cbc:BaseAmount currencyID="SEK">200.00</cbc:BaseAmount>')
|
||||
// The undiscounted unit price stays in cac:Price (BT-146).
|
||||
expect(result.xml).toContain('<cbc:PriceAmount currencyID="SEK">100</cbc:PriceAmount>')
|
||||
})
|
||||
|
||||
it('rejects a discounted line whose stored total is not net of the discount', () => {
|
||||
const input = makeValidInput()
|
||||
input.items = [makeItem({ discount_percent: 10, line_total: 200, vat_amount: 50 })]
|
||||
|
||||
const result = generatePeppolBisBillingInvoice(input)
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) return
|
||||
expect(result.issues.map(({ code }) => code)).toContain('LINE_TOTAL_MISMATCH')
|
||||
})
|
||||
|
||||
it('rejects credit notes and self-billed invoices in the generation layer', () => {
|
||||
for (const invoice of [
|
||||
makeInvoice({
|
||||
|
||||
@@ -19,6 +19,7 @@ function makeItem(overrides: Partial<InvoiceWriteItemRow> = {}): InvoiceWriteIte
|
||||
quantity: 1,
|
||||
unit: 'tim',
|
||||
unit_price: 1000,
|
||||
discount_percent: 0,
|
||||
line_total: 1000,
|
||||
vat_rate: 25,
|
||||
vat_amount: 250,
|
||||
|
||||
Reference in New Issue
Block a user