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
@@ -79,6 +79,8 @@ export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
reverse_charge_text: proforma.reverse_charge_text,
|
||||
your_reference: proforma.your_reference,
|
||||
our_reference: proforma.our_reference,
|
||||
// Buyer routing survives conversion (Peppol BT-10 may rely on it alone).
|
||||
invoice_marking: proforma.invoice_marking ?? null,
|
||||
notes: proforma.notes,
|
||||
document_type: 'invoice',
|
||||
converted_from_id: id,
|
||||
@@ -92,7 +94,7 @@ export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
return NextResponse.json({ error: getUserErrorMessage(invoiceError) }, { status: 500 })
|
||||
}
|
||||
|
||||
const items = (proforma.items || []).map((item: { sort_order: number; line_type?: 'product' | 'text'; description: string; quantity: number; unit: string; unit_price: number; line_total: number; dimensions?: Record<string, string> }) => ({
|
||||
const items = (proforma.items || []).map((item: { sort_order: number; line_type?: 'product' | 'text'; description: string; quantity: number; unit: string; unit_price: number; discount_percent?: number | null; line_total: number; dimensions?: Record<string, string> }) => ({
|
||||
invoice_id: invoice.id,
|
||||
sort_order: item.sort_order,
|
||||
line_type: item.line_type ?? 'product',
|
||||
@@ -100,6 +102,10 @@ export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
quantity: item.quantity,
|
||||
unit: item.unit,
|
||||
unit_price: item.unit_price,
|
||||
// The stored line_total is net of this; dropping it would make the
|
||||
// converted invoice fail the Peppol line check and lose the rebate on
|
||||
// the next builder pass.
|
||||
discount_percent: item.discount_percent ?? 0,
|
||||
line_total: item.line_total,
|
||||
dimensions: item.dimensions ?? {},
|
||||
}))
|
||||
|
||||
@@ -9,6 +9,8 @@ import { contentDisposition } from '@/lib/api/content-disposition'
|
||||
import type { InvoiceItem, Customer, CompanySettings, InvoiceDocumentType } from '@/types'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { computeDeduction, computeInvoiceDeductionTotal, type DeductionType } from '@/lib/invoices/rot-rut-rules'
|
||||
import { computeLineNet } from '@/lib/invoices/line-amounts'
|
||||
import { roundOre } from '@/lib/money'
|
||||
import { expandPersonnummerTo12, maskPersonnummer, validatePersonnummer } from '@/lib/salary/personnummer'
|
||||
import { revealStoredCustomerPersonalNumber } from '@/lib/customers/protect-personal-number'
|
||||
import {
|
||||
@@ -29,6 +31,8 @@ interface PreviewItemInput {
|
||||
quantity: number
|
||||
unit: string
|
||||
unit_price: number
|
||||
/** Line discount 0-100; amounts render net of it (line-amounts.ts). */
|
||||
discount_percent?: number | null
|
||||
vat_rate?: number
|
||||
deduction_type?: DeductionType | null
|
||||
labor_hours?: number | null
|
||||
@@ -83,7 +87,8 @@ export const POST = withRouteContext('invoice.preview_pdf', async (request, {
|
||||
}) => {
|
||||
const body = await request.json()
|
||||
const {
|
||||
customer_id, invoice_date, due_date, delivery_date, currency, items, your_reference, our_reference, notes,
|
||||
customer_id, invoice_date, due_date, delivery_date, currency, items, your_reference, our_reference,
|
||||
invoice_marking, notes,
|
||||
document_type, invoice_number, payment_link_url,
|
||||
deduction_personnummer, deduction_housing_designation, deduction_apartment_number, deduction_brf_org_number,
|
||||
} = body
|
||||
@@ -227,15 +232,19 @@ export const POST = withRouteContext('invoice.preview_pdf', async (request, {
|
||||
// deduction, mirroring build-invoice-write.ts so the preview states the
|
||||
// same avdrag row, info box and "Att betala" as the invoice it becomes.
|
||||
const invoiceItems: InvoiceItem[] = items.map((item: PreviewItemInput, index: number) => {
|
||||
const lineTotal = Math.round(item.quantity * item.unit_price * 100) / 100
|
||||
// Net of any per-line discount, same math as build-invoice-write.ts, so
|
||||
// the preview totals equal the invoice the form creates.
|
||||
const discountPercent = item.discount_percent ?? 0
|
||||
const lineTotal = roundOre(computeLineNet(item.quantity, item.unit_price, discountPercent))
|
||||
const rate = zeroVat ? 0 : (item.vat_rate ?? vatRules.rate)
|
||||
const deductionType = deductionsApply ? (item.deduction_type ?? null) : null
|
||||
// Same base as the write path: the line total inkl. moms at the rate the
|
||||
// line is rendered with (HUSFL 6-9 §§).
|
||||
// Same base as the write path: the NET line total inkl. moms at the rate
|
||||
// the line is rendered with (HUSFL 6-9 §§).
|
||||
const deductionAmount = deductionType
|
||||
? computeDeduction({
|
||||
unit_price: item.unit_price,
|
||||
quantity: item.quantity,
|
||||
discount_percent: discountPercent,
|
||||
deduction_type: deductionType,
|
||||
vat_rate: rate,
|
||||
})
|
||||
@@ -248,6 +257,7 @@ export const POST = withRouteContext('invoice.preview_pdf', async (request, {
|
||||
quantity: item.quantity,
|
||||
unit: item.unit,
|
||||
unit_price: item.unit_price,
|
||||
discount_percent: discountPercent,
|
||||
line_total: lineTotal,
|
||||
vat_rate: rate,
|
||||
vat_amount: isDeliveryNote ? 0 : Math.round(lineTotal * (rate / 100) * 100) / 100,
|
||||
@@ -275,6 +285,7 @@ export const POST = withRouteContext('invoice.preview_pdf', async (request, {
|
||||
invoiceItems.map((item) => ({
|
||||
unit_price: item.unit_price,
|
||||
quantity: item.quantity,
|
||||
discount_percent: item.discount_percent ?? 0,
|
||||
deduction_type: item.deduction_type ?? null,
|
||||
vat_rate: item.vat_rate,
|
||||
})),
|
||||
@@ -314,6 +325,7 @@ export const POST = withRouteContext('invoice.preview_pdf', async (request, {
|
||||
moms_ruta: vatRules.momsRuta,
|
||||
your_reference: your_reference || null,
|
||||
our_reference: our_reference || null,
|
||||
invoice_marking: (typeof invoice_marking === 'string' && invoice_marking.trim()) || null,
|
||||
notes: notes || null,
|
||||
payment_link_url: previewPaymentLink,
|
||||
reverse_charge_text: vatRules.reverseChargeText || null,
|
||||
|
||||
@@ -392,6 +392,8 @@ async function createCreditNote(
|
||||
reverse_charge_text: originalInvoice.reverse_charge_text,
|
||||
your_reference: originalInvoice.your_reference,
|
||||
our_reference: originalInvoice.our_reference,
|
||||
// Same buyer routing on the kreditfaktura as the original.
|
||||
invoice_marking: originalInvoice.invoice_marking ?? null,
|
||||
// Positive magnitude, unlike the negated amounts above: the DB has
|
||||
// CHECK (deduction_total >= 0), and every reader either recomputes the
|
||||
// ROT/RUT amount from the items or skips credit notes entirely.
|
||||
|
||||
@@ -39,7 +39,7 @@ const CreditNoteRequest = z.object({
|
||||
})
|
||||
|
||||
const ORIGINAL_INVOICE_COLUMNS =
|
||||
'id, invoice_number, customer_id, invoice_date, due_date, delivery_date, status, currency, exchange_rate, exchange_rate_date, subtotal, subtotal_sek, vat_amount, vat_amount_sek, total, total_sek, vat_treatment, vat_rate, moms_ruta, your_reference, our_reference, notes, reverse_charge_text, credited_invoice_id, document_type, default_dimensions'
|
||||
'id, invoice_number, customer_id, invoice_date, due_date, delivery_date, status, currency, exchange_rate, exchange_rate_date, subtotal, subtotal_sek, vat_amount, vat_amount_sek, total, total_sek, vat_treatment, vat_rate, moms_ruta, your_reference, our_reference, invoice_marking, notes, reverse_charge_text, credited_invoice_id, document_type, default_dimensions'
|
||||
|
||||
// default_dimensions stays in this projection: the inserted credit-note row is
|
||||
// handed to createCreditNoteJournalEntry, which reads the bag off the row so
|
||||
@@ -48,7 +48,7 @@ const CREDIT_NOTE_RESPONSE_COLUMNS =
|
||||
'id, invoice_number, customer_id, invoice_date, due_date, delivery_date, status, currency, exchange_rate, exchange_rate_date, subtotal, subtotal_sek, vat_amount, vat_amount_sek, total, total_sek, vat_treatment, vat_rate, moms_ruta, your_reference, our_reference, notes, reverse_charge_text, credited_invoice_id, document_type, paid_at, paid_amount, remaining_amount, default_dimensions, created_at, updated_at'
|
||||
|
||||
const ORIGINAL_ITEMS_COLUMNS =
|
||||
'sort_order, description, quantity, unit, unit_price, line_total, vat_rate, vat_amount, dimensions'
|
||||
'sort_order, description, quantity, unit, unit_price, discount_percent, line_total, vat_rate, vat_amount, dimensions'
|
||||
|
||||
const CreditNoteCreated = z.object({
|
||||
id: z.string().uuid(),
|
||||
@@ -181,6 +181,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
quantity: number
|
||||
unit: string
|
||||
unit_price: number
|
||||
discount_percent?: number | null
|
||||
line_total: number
|
||||
vat_rate?: number | null
|
||||
vat_amount?: number | null
|
||||
@@ -246,6 +247,8 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
reverse_charge_text: original.reverse_charge_text ?? null,
|
||||
your_reference: original.your_reference ?? null,
|
||||
our_reference: original.our_reference ?? null,
|
||||
// Same buyer routing on the kreditfaktura as the original.
|
||||
invoice_marking: original.invoice_marking ?? null,
|
||||
notes: reason || `Krediterar faktura ${original.invoice_number ?? original.id}`,
|
||||
credited_invoice_id: originalId,
|
||||
status: 'sent' as const,
|
||||
@@ -261,6 +264,9 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
quantity: -Math.abs(item.quantity),
|
||||
unit: item.unit,
|
||||
unit_price: item.unit_price,
|
||||
// Carried so the kreditfaktura's face arithmetic multiplies out and the
|
||||
// Rabatt column renders (ML 17 kap 24 §).
|
||||
discount_percent: item.discount_percent ?? 0,
|
||||
line_total: -Math.abs(item.line_total),
|
||||
vat_rate: item.vat_rate ?? 0,
|
||||
vat_amount: -Math.abs(item.vat_amount ?? 0),
|
||||
|
||||
Reference in New Issue
Block a user