Files
accounted/lib/invoices/copy-invoice.ts
T
MattssonandClaude Fable 5 f216a60bf8 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>
2026-08-31 15:34:06 +02:00

112 lines
3.3 KiB
TypeScript

import type {
Currency,
Invoice,
InvoiceDocumentType,
InvoiceItem,
InvoiceStatus,
} from '@/types'
const COPYABLE_STATUSES: ReadonlySet<InvoiceStatus> = new Set([
'sent',
'paid',
'partially_paid',
'overdue',
'credited',
])
export type InvoiceCopySource = Invoice & { items: InvoiceItem[] }
export interface InvoiceCopyItem {
line_type: 'product' | 'text'
description: string
quantity: number
unit: string
unit_price: number
discount_percent: number
vat_rate: number
article_id: null
revenue_account: string | null
deduction_type: 'rot' | 'rut' | null
labor_hours: number | null
work_type: string | null
housing_designation: null
apartment_number: null
brf_org_number: null
accrual_period_start: null
accrual_period_end: null
accrual_balance_account: null
dimensions: Record<string, string> | null
}
export interface InvoiceCopyInitial {
source_invoice_number: string
customer_id: string
currency: Currency
document_type: InvoiceDocumentType
our_reference: string
notes: string
ore_rounding: boolean | null
default_dimensions: Record<string, string>
items: InvoiceCopyItem[]
}
export function canCopyInvoice(
invoice: Pick<Invoice, 'status' | 'document_type' | 'credited_invoice_id' | 'is_self_billed'>,
): boolean {
return (
invoice.document_type === 'invoice' &&
!invoice.credited_invoice_id &&
!invoice.is_self_billed &&
COPYABLE_STATUSES.has(invoice.status)
)
}
/**
* Builds a safe starting point for a new invoice draft.
*
* The copied data is limited to reusable commercial content. Identity,
* lifecycle, payment, bookkeeping, date, accrual, and recipient-specific
* ROT/RUT fields are deliberately absent or cleared.
*/
export function buildInvoiceCopyInitial(source: InvoiceCopySource): InvoiceCopyInitial {
return {
source_invoice_number: source.invoice_number ?? '',
customer_id: source.customer_id,
currency: source.currency,
document_type: 'invoice',
our_reference: source.our_reference ?? '',
notes: source.notes ?? '',
ore_rounding: source.ore_rounding,
default_dimensions: source.default_dimensions ?? {},
items: [...source.items]
.sort((a, b) => a.sort_order - b.sort_order)
.map((item) => ({
line_type: item.line_type ?? 'product',
description: item.description,
quantity: item.quantity,
unit: item.unit,
unit_price: item.unit_price,
// Agreed price reduction is reusable commercial content, like the price.
discount_percent: item.discount_percent ?? 0,
vat_rate: item.vat_rate ?? 25,
// A copied line keeps the frozen description and price, but is not
// linked to a possibly changed or archived article preset.
article_id: null,
revenue_account: item.revenue_account ?? null,
deduction_type: item.deduction_type ?? null,
labor_hours: item.labor_hours ?? null,
work_type: item.work_type ?? null,
housing_designation: null,
apartment_number: null,
brf_org_number: null,
// Accrual dates belong to the original accounting period.
accrual_period_start: null,
accrual_period_end: null,
accrual_balance_account: null,
dimensions: item.dimensions && Object.keys(item.dimensions).length > 0
? item.dimensions
: null,
})),
}
}