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>
This commit is contained in:
Mattsson
2026-07-12 00:56:16 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent 0ef5593388
commit 7d7f604e00
35 changed files with 945 additions and 56 deletions
@@ -58,6 +58,34 @@ describe('buildInvoiceWriteData', () => {
})
})
it('maps payment_link_url to a concrete trimmed value, null when absent', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: { vat_registered: true }, error: null })
const customer = makeCustomer({ customer_type: 'swedish_business' })
const withLink = await call(enqueue, supabase as unknown as SupabaseClient, customer, {
...baseHeader,
payment_link_url: ' https://buy.stripe.com/test_abc123 ',
items: [{ description: 'Konsult', quantity: 1, unit: 'tim', unit_price: 1000, vat_rate: 25 }],
})
expect(withLink.ok).toBe(true)
if (!withLink.ok) return
expect(withLink.invoiceFields.payment_link_url).toBe('https://buy.stripe.com/test_abc123')
// Absent input must still produce an explicit null (not undefined):
// supabase-js drops undefined keys, and a draft edit that cleared the
// field relies on the NULL actually being written.
const { supabase: supabase2, enqueue: enqueue2 } = createQueuedMockSupabase()
enqueue2({ data: { vat_registered: true }, error: null })
const withoutLink = await call(enqueue2, supabase2 as unknown as SupabaseClient, customer, {
...baseHeader,
items: [{ description: 'Konsult', quantity: 1, unit: 'tim', unit_price: 1000, vat_rate: 25 }],
})
expect(withoutLink.ok).toBe(true)
if (!withoutLink.ok) return
expect(withoutLink.invoiceFields.payment_link_url).toBeNull()
})
it('handles a mixed-rate invoice (vat_rate becomes null on the header)', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: { vat_registered: true }, error: null })
@@ -13,8 +13,8 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import sharp from 'sharp'
import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers'
import { makeCompanySettings } from '@/tests/helpers'
import { prepareInvoicePdfRender, buildPaymentLinkQrDataUrl } from '@/lib/invoices/pdf-render-helpers'
import { makeCompanySettings, makeInvoice } from '@/tests/helpers'
const PNG_DATA_URL_PREFIX = 'data:image/png;base64,'
@@ -177,3 +177,29 @@ describe('prepareInvoicePdfRender: logo resolution (issue #772)', () => {
expect(branding.primaryColor).toBe('#c2410c')
})
})
describe('buildPaymentLinkQrDataUrl', () => {
it('encodes the payment link as a PNG QR data URL for a real invoice', async () => {
const invoice = makeInvoice({ payment_link_url: 'https://buy.stripe.com/test_abc123' })
const qr = await buildPaymentLinkQrDataUrl(invoice)
expect(qr).toMatch(new RegExp(`^${PNG_DATA_URL_PREFIX}`))
})
it('returns null when the invoice has no payment link', async () => {
expect(await buildPaymentLinkQrDataUrl(makeInvoice())).toBeNull()
expect(await buildPaymentLinkQrDataUrl(makeInvoice({ payment_link_url: ' ' }))).toBeNull()
})
it('returns null for non-payable documents (proforma, delivery note, credit note)', async () => {
const url = 'https://buy.stripe.com/test_abc123'
expect(
await buildPaymentLinkQrDataUrl(makeInvoice({ payment_link_url: url, document_type: 'proforma' })),
).toBeNull()
expect(
await buildPaymentLinkQrDataUrl(makeInvoice({ payment_link_url: url, document_type: 'delivery_note' })),
).toBeNull()
expect(
await buildPaymentLinkQrDataUrl(makeInvoice({ payment_link_url: url, credited_invoice_id: 'inv-orig' })),
).toBeNull()
})
})
+44 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { getDisplayTotal } from '@/lib/invoices/rounding'
import { getAmountToPay, getDisplayTotal } from '@/lib/invoices/rounding'
const inv = (total: number, currency: 'SEK' | 'EUR' = 'SEK') => ({ total, currency })
const co = (ore_rounding: boolean) => ({ ore_rounding })
@@ -69,3 +69,46 @@ describe('getDisplayTotal', () => {
expect(r.displayed).toBe(99.99)
})
})
describe('getAmountToPay', () => {
it('equals the rounded display total when there is no deduction', () => {
const r = getAmountToPay(inv(1234.56), co(true))
expect(r.toPay).toBe(1235)
expect(r.deductionApplies).toBe(false)
expect(r.rounding.applies).toBe(true)
expect(r.rounding.roundingDelta).toBe(0.44)
})
it('subtracts the ROT/RUT deduction from the ROUNDED total', () => {
const r = getAmountToPay({ ...inv(1234.56), deduction_total: 500 }, co(true))
expect(r.deductionApplies).toBe(true)
expect(r.toPay).toBe(735)
})
it('subtracts the deduction from the raw total when rounding is off', () => {
const r = getAmountToPay({ ...inv(1234.56), deduction_total: 500 }, co(false))
expect(r.rounding.applies).toBe(false)
expect(r.toPay).toBe(734.56)
})
it('keeps öre precision in the deduction subtraction', () => {
// 1235 - 166.67 must not pick up float noise.
const r = getAmountToPay({ ...inv(1234.56), deduction_total: 166.67 }, co(true))
expect(r.toPay).toBe(1068.33)
})
it('ignores the deduction on credit notes (fakturamodellen does not apply)', () => {
const r = getAmountToPay(
{ ...inv(-1234.56), deduction_total: 500, credited_invoice_id: 'inv-1' },
co(true),
)
expect(r.deductionApplies).toBe(false)
expect(r.toPay).toBe(-1235)
})
it('does not round non-SEK invoices but still applies the deduction', () => {
const r = getAmountToPay({ ...inv(1234.56, 'EUR'), deduction_total: 100 }, co(true))
expect(r.rounding.applies).toBe(false)
expect(r.toPay).toBe(1134.56)
})
})
+6
View File
@@ -68,6 +68,8 @@ export interface InvoiceWriteInput {
your_reference?: string
our_reference?: string
notes?: string
/** Optional https payment link (schema-validated). Omitted/empty → null. */
payment_link_url?: string
/** Per-invoice öresavrundning override (display-only). Omitted → null (inherit company setting). */
ore_rounding?: boolean
deduction_personnummer?: string
@@ -105,6 +107,7 @@ export type InvoiceWriteFields = {
your_reference: string | null | undefined
our_reference: string | null | undefined
notes: string | null | undefined
payment_link_url: string | null
ore_rounding: boolean | null
document_type: InvoiceDocumentType
deduction_total: number
@@ -365,6 +368,9 @@ export async function buildInvoiceWriteData(params: {
your_reference: input.your_reference,
our_reference: input.our_reference,
notes: input.notes,
// Always a concrete value (never undefined) so a draft edit that cleared
// the field actually NULLs the column: supabase-js drops undefined keys.
payment_link_url: input.payment_link_url?.trim() || null,
// Display-only öresavrundning override; null inherits company_settings.ore_rounding.
ore_rounding: input.ore_rounding ?? null,
document_type: documentType,
+24
View File
@@ -27,6 +27,7 @@ import { getDisplayTotal } from '@/lib/invoices/rounding'
import { createLogger } from '@/lib/logger'
const log = createLogger('invoice.swish-qr')
const paymentLinkLog = createLogger('invoice.payment-link-qr')
export interface InvoicePdfRenderExtras {
branding: InvoiceBranding
@@ -163,6 +164,29 @@ export async function prepareInvoicePdfRender(
* `swishQrDataUrl` prop; the template gates rendering on the same payment box
* that already shows the Swish number.
*/
/**
* Build the payment-link QR for an invoice as a PNG data URL, or null when the
* invoice carries no payment_link_url or it isn't a payable document (credit
* notes, proformas and delivery notes show no payment box). The URL was
* https-validated at write time (lib/api/schemas.ts); the QR simply encodes it
* locally with the `qrcode` lib: no call to any payment provider.
*/
export async function buildPaymentLinkQrDataUrl(invoice: Invoice): Promise<string | null> {
const url = invoice.payment_link_url?.trim()
if (!url) return null
const docType = invoice.document_type || 'invoice'
if (docType !== 'invoice' || invoice.credited_invoice_id) return null
try {
return await QRCode.toDataURL(url, { margin: 1, width: 240, errorCorrectionLevel: 'M' })
} catch (err) {
paymentLinkLog.warn('payment link QR generation failed', {
invoiceId: invoice.id,
error: err instanceof Error ? err.message : String(err),
})
return null
}
}
export async function buildSwishQrDataUrl(
company: CompanySettings,
invoice: Invoice,
+31 -10
View File
@@ -4,11 +4,12 @@ import {
Text,
View,
Image,
Link,
StyleSheet,
} from '@react-pdf/renderer'
import type { Invoice, InvoiceItem, Customer, CompanySettings, InvoiceDocumentType } from '@/types'
import { generateOcrReference } from '@/lib/bankgiro/luhn'
import { getDisplayTotal } from '@/lib/invoices/rounding'
import { getAmountToPay } from '@/lib/invoices/rounding'
type PdfLang = 'sv' | 'en'
@@ -86,6 +87,8 @@ const LABELS = {
paymentReference: 'Betalningsreferens:',
invoiceNumber: 'Fakturanummer:',
swishQrCaption: 'Skanna för att betala med Swish',
payOnline: 'Betala online:',
paymentLinkQrCaption: 'Skanna för att betala online',
// Footer
orgNoLong: 'Org.nr:',
vatRegNo: 'Momsreg.nr:',
@@ -152,6 +155,8 @@ const LABELS = {
paymentReference: 'Payment reference:',
invoiceNumber: 'Invoice number:',
swishQrCaption: 'Scan to pay with Swish',
payOnline: 'Pay online:',
paymentLinkQrCaption: 'Scan to pay online',
orgNoLong: 'Reg. no.:',
vatRegNo: 'VAT reg. no.:',
// Statutory Swedish phrase: kept verbatim in both locales. Peppol SE-R-005
@@ -636,9 +641,12 @@ interface InvoicePDFProps {
/** Pre-rendered Swish payment QR (PNG data URL). Built offline in
* pdf-render-helpers; null/omitted renders no QR. */
swishQrDataUrl?: string | null
/** Pre-rendered payment-link QR (PNG data URL) for invoice.payment_link_url.
* Built offline in pdf-render-helpers; null/omitted renders no QR. */
paymentLinkQrDataUrl?: string | null
}
export function InvoicePDF({ invoice, customer, items, company, originalInvoiceNumber, isPreview, language, branding, swishQrDataUrl }: InvoicePDFProps) {
export function InvoicePDF({ invoice, customer, items, company, originalInvoiceNumber, isPreview, language, branding, swishQrDataUrl, paymentLinkQrDataUrl }: InvoicePDFProps) {
const lang: PdfLang = language ?? customer.language ?? 'sv'
const L = LABELS[lang]
// Build the stylesheet per-render so each invoice picks up its company's
@@ -915,14 +923,10 @@ export function InvoicePDF({ invoice, customer, items, company, originalInvoiceN
)
)}
{(() => {
const rounding = getDisplayTotal(invoice, company)
// ROT/RUT-avdrag reduces "Att betala": the customer only owes
// (total - deduction); the rest is reclaimed from Skatteverket
// via fakturamodellen. The rule does not apply to credit notes.
const showDeduction = !isCreditNote && (invoice.deduction_total ?? 0) > 0
const grandTotal = showDeduction
? Math.round((rounding.displayed - (invoice.deduction_total ?? 0)) * 100) / 100
: rounding.displayed
// Shared with the invoice email (lib/email/invoice-templates.ts)
// so the mail and the PDF always state the same "Att betala".
const { rounding, deductionApplies: showDeduction, toPay: grandTotal } =
getAmountToPay(invoice, company)
return (
<>
{rounding.applies && (
@@ -1033,6 +1037,16 @@ export function InvoicePDF({ invoice, customer, items, company, originalInvoiceN
{!isCreditNote && !isProforma && !isDeliveryNote && (
<View style={styles.paymentSection}>
<Text style={styles.paymentTitle}>{L.paymentHeading}</Text>
{invoice.payment_link_url && (
<View style={styles.paymentRow}>
<Text style={styles.paymentLabel}>{L.payOnline}</Text>
<Link src={invoice.payment_link_url} style={styles.paymentValue}>
{invoice.payment_link_url.length > 60
? `${invoice.payment_link_url.slice(0, 57)}...`
: invoice.payment_link_url}
</Link>
</View>
)}
{company.bank_name && (
<View style={styles.paymentRow}>
<Text style={styles.paymentLabel}>{L.bank}</Text>
@@ -1099,6 +1113,13 @@ export function InvoicePDF({ invoice, customer, items, company, originalInvoiceN
<Text style={[styles.paymentLabel, { width: 'auto', marginTop: 2, textAlign: 'center' }]}>{L.swishQrCaption}</Text>
</View>
)}
{/* Payment-link QR: shifts left when the Swish QR occupies the corner. */}
{paymentLinkQrDataUrl && (
<View style={{ position: 'absolute', top: 15, right: swishQrDataUrl ? 125 : 15, width: 96, alignItems: 'center' }}>
<Image src={paymentLinkQrDataUrl} style={{ width: 96, height: 96 }} />
<Text style={[styles.paymentLabel, { width: 'auto', marginTop: 2, textAlign: 'center' }]}>{L.paymentLinkQrCaption}</Text>
</View>
)}
</View>
)}
+35
View File
@@ -55,3 +55,38 @@ export function getDisplayTotal(
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 }
}