Files
accounted/lib/invoices/rounding.ts
T
Mattsson 7d7f604e00 Add/stripe invoice link (#998)
* feat(supplier-invoices): show registered invoices under "Att betala" with inline approve

Registered supplier invoices are already booked as debt (2440) but were
hidden from the "Att betala" tab until approved, which confused users.
The tab now shows registered invoices too, marked "Ej godkand" with a
compact inline approve button. Approval remains the gate for payment,
not visibility; status model and approve API untouched.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(reports): add date range filter to huvudbok (kontoanalys)

Mounts the existing ReportDateRange control on /reports/huvudbok so the
ledger can be narrowed to any date range within the fiscal year, matching
Fortnox kontoanalys. Lines before the range roll into each account's
opening balance so running balances stay correct at the range start;
lines after the range are dropped. Applies to the XLSX export too.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(invoices): add optional payment link on invoices (paste-link MVP)

The user pastes a payment link created in their PSP dashboard (e.g. a
Stripe Payment Link) onto an invoice. The recipient gets a "Betala
online" button in the invoice email and a QR code + clickable link in
the PDF payment box. No PSP integration server-side: this is the
demand probe; a future Stripe Connect integration would auto-fill the
same column.

- invoices.payment_link_url (migration 20260709090000), https-only +
  2048-char cap enforced in CreateInvoiceSchema; empty string
  normalises to undefined and build-invoice-write always writes a
  concrete value so clearing the field on a draft edit NULLs the column
- editor field (real invoices only) with one-link-per-invoice hint;
  strings in sv+en (messages landed via e0e11066)
- email button (customer.language, hidden for credit notes/proforma/
  delivery notes, URL escaped for the href attribute) + URL in the
  plain-text part
- PDF QR + link row following the Swish QR pattern; wired into send,
  download and preview routes
- derived documents (credit note, proforma convert, recurring) do NOT
  copy the link: it encodes one amount for one specific invoice
- MCP gnubok_create_invoice accepts payment_link_url (validated at
  staging and re-checked in the commit executor); v1 API exposes the
  column; tools/list token ceiling bumped 45K -> 45.5K (ledger entry
  in payload-size.bench.test.ts, headroom was <10 tokens)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(invoices): show oresavrundning on editor/form totals, supplier list and invoice email

The rounding logic (getDisplayTotal) was correct but only applied on the
PDF, invoice list/detail and review dialog. The invoice editor summary,
the supplier invoice form totals and the supplier invoice list showed the
raw ore total right next to the toggle, and the invoice email said
"Att betala" with the unrounded invoice.total while the attached PDF
showed the rounded amount (and the email also ignored the ROT/RUT
deduction).

Extract the PDF's Att betala block into getAmountToPay
(lib/invoices/rounding.ts) and point PDF + email at it so they cannot
drift; behavior-identical refactor for the PDF. Booked amounts stay
ore-exact; display-only as designed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test(reports): adapt huvudbok date-range tests to the two-step entry-lines fetch

The date-range tests (0969168f) mocked the old single-query shape with the
parent entry embedded on each line; main's refactor (fetchEntryLines)
queries journal_entries first and reattaches. Queue entry rows like the
other tests so the merge of the two features is actually exercised.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(invoices): fetch full invoice projection in v1 send so ROT/RUT deduction and payment link reach the PDF and email

The v1 send route's hand-rolled column list omitted deduction_total,
deduction_personnummer_last4, payment_link_url and the item-level
ROT/RUT fields, so invoices sent via the public API overstated
'Att betala' and dropped the deduction box. Reuse the shared
INVOICE_FULL_COLUMNS/INVOICE_ITEM_FULL_COLUMNS so the send row can
never drift from the GET shape again.

Also harden the supplier-invoice inline approve: a thrown fetch left
the button stuck spinning; failures now refetch the true server state.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-12 00:56:16 +02:00

93 lines
3.7 KiB
TypeScript

import type { Invoice, CompanySettings } from '@/types'
/**
* Shape accepted by getDisplayTotal. `currency` is widened to `string` so the
* helper works for both customer (`Invoice`) and supplier (`SupplierInvoice`)
* rows. `ore_rounding` is the optional per-invoice override (see below).
*/
type InvoiceTotalShape = {
total: Invoice['total']
currency: string
/** Per-invoice öresavrundning override. Wins over the company setting when set. */
ore_rounding?: boolean | null
}
type CompanyRoundingShape = Pick<CompanySettings, 'ore_rounding'>
export interface DisplayTotal {
/** Total to render to the user (rounded if öresavrundning applies, raw otherwise). */
displayed: number
/** displayed - raw total. Zero when rounding does not apply or the total is already an integer. */
roundingDelta: number
/** True when rounding is enabled, currency is SEK, and there are öre to round. */
applies: boolean
}
/**
* Single source of truth for öresavrundning display logic. Mirrors the rule
* baked into the PDF template since day one: only SEK invoices, only when
* rounding is enabled, and only when there's actually a non-integer total to
* round. The helper centralizes the rule so the list, detail page, and PDF
* cannot drift apart.
*
* Resolution order for "is rounding enabled":
* 1. the per-invoice override (`invoice.ore_rounding`) when not null,
* 2. else the company-wide setting (`company.ore_rounding`),
* 3. else default-on.
* Callers that want a different null-fallback (e.g. supplier invoices, where
* rounding never existed historically) pass `{ ore_rounding: false }` as the
* company arg so a null per-invoice flag resolves to off.
*/
export function getDisplayTotal(
invoice: InvoiceTotalShape,
company: CompanyRoundingShape | null | undefined,
): DisplayTotal {
const enabled = invoice.ore_rounding ?? company?.ore_rounding ?? true
if (!enabled || invoice.currency !== 'SEK') {
return { displayed: invoice.total, roundingDelta: 0, applies: false }
}
const rounded = Math.round(invoice.total)
if (rounded === invoice.total) {
return { displayed: invoice.total, roundingDelta: 0, applies: false }
}
return {
displayed: rounded,
roundingDelta: Math.round((rounded - invoice.total) * 100) / 100,
applies: true,
}
}
type AmountToPayShape = InvoiceTotalShape & {
/** ROT/RUT deduction (fakturamodellen). Reduces what the customer owes. */
deduction_total?: number | null
/** Set on credit notes; the deduction rule does not apply to those. */
credited_invoice_id?: string | null
}
export interface AmountToPay {
/** The öresavrundning outcome on the invoice total (before any deduction). */
rounding: DisplayTotal
/** True when a ROT/RUT deduction reduces the amount to pay. */
deductionApplies: boolean
/** Customer-facing "Att betala": rounded total minus any ROT/RUT deduction. */
toPay: number
}
/**
* Customer-facing "Att betala" for an invoice: öresavrundning via
* getDisplayTotal, then the ROT/RUT deduction (the customer only owes
* total - deduction; the rest is reclaimed from Skatteverket via
* fakturamodellen). Extracted from the PDF totals block so the invoice email
* shows the exact same amount as the attached PDF and the two cannot drift.
*/
export function getAmountToPay(
invoice: AmountToPayShape,
company: CompanyRoundingShape | null | undefined,
): AmountToPay {
const rounding = getDisplayTotal(invoice, company)
const deductionApplies = !invoice.credited_invoice_id && (invoice.deduction_total ?? 0) > 0
const toPay = deductionApplies
? Math.round((rounding.displayed - (invoice.deduction_total ?? 0)) * 100) / 100
: rounding.displayed
return { rounding, deductionApplies, toPay }
}