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
@@ -357,4 +357,96 @@ describe('invoice email templates', () => {
.toBe('F\u00f6ljesedel 1045 fr\u00e5n Acme AB')
})
})
describe('payment link (payment_link_url)', () => {
const svCustomer = makeCustomer({ name: 'Erik Andersson', email: 'erik@example.se', language: 'sv' })
const linkUrl = 'https://buy.stripe.com/test_abc123'
it('renders a pay-online button in HTML and the URL in plain text when set', () => {
const linked = makeInvoice({ invoice_number: '1042', payment_link_url: linkUrl })
const html = generateInvoiceEmailHtml({ invoice: linked, customer: svCustomer, company })
expect(html).toContain(`href="${linkUrl}"`)
expect(html).toContain('Betala online')
const text = generateInvoiceEmailText({ invoice: linked, customer: svCustomer, company })
expect(text).toContain(`Betala online: ${linkUrl}`)
})
it('uses the English label for English customers', () => {
const enCustomer = makeCustomer({ name: 'Jane Doe', email: 'jane@example.com', language: 'en' })
const linked = makeInvoice({ invoice_number: '1042', payment_link_url: linkUrl })
const html = generateInvoiceEmailHtml({ invoice: linked, customer: enCustomer, company })
expect(html).toContain('Pay online')
expect(html).not.toContain('Betala online')
})
it('omits the button when no link is set', () => {
const html = generateInvoiceEmailHtml({ invoice, customer: svCustomer, company })
expect(html).not.toContain('Betala online')
const text = generateInvoiceEmailText({ invoice, customer: svCustomer, company })
expect(text).not.toContain('Betala online')
})
it('hides the button on credit notes even if a link is present on the row', () => {
const creditNote = makeInvoice({
invoice_number: '1043',
credited_invoice_id: 'inv-orig',
total: -5000,
payment_link_url: linkUrl,
})
const html = generateInvoiceEmailHtml({ invoice: creditNote, customer: svCustomer, company })
expect(html).not.toContain('Betala online')
})
it('escapes quote characters in the URL for the href attribute', () => {
const sneaky = 'https://pay.example.se/x?a="onmouseover=alert(1)'
const linked = makeInvoice({ invoice_number: '1042', payment_link_url: sneaky })
const html = generateInvoiceEmailHtml({ invoice: linked, customer: svCustomer, company })
expect(html).not.toContain('a="onmouseover')
expect(html).toContain('&quot;onmouseover=alert(1)')
})
})
describe('öresavrundning: "Att betala" matches the PDF', () => {
const svCustomer = makeCustomer({ name: 'Erik Andersson', email: 'erik@example.se', language: 'sv' })
it('rounds the SEK total to whole kronor when rounding is on (company default)', () => {
const oreInvoice = makeInvoice({ invoice_number: '1042', total: 1234.56 })
const html = generateInvoiceEmailHtml({ invoice: oreInvoice, customer: svCustomer, company })
expect(html).toMatch(/1[\s ]235,00 SEK/)
expect(html).not.toContain('234,56')
const text = generateInvoiceEmailText({ invoice: oreInvoice, customer: svCustomer, company })
expect(text).toMatch(/Att betala: 1[\s ]235,00 SEK/)
})
it('keeps the exact öre when the per-invoice flag turns rounding off', () => {
const exactInvoice = makeInvoice({ invoice_number: '1042', total: 1234.56, ore_rounding: false })
const html = generateInvoiceEmailHtml({ invoice: exactInvoice, customer: svCustomer, company })
expect(html).toMatch(/1[\s ]234,56 SEK/)
expect(html).not.toMatch(/1[\s ]235,00 SEK/)
})
it('does not round non-SEK invoices', () => {
const eurInvoice = makeInvoice({ invoice_number: '1042', currency: 'EUR', total: 1234.56 })
const text = generateInvoiceEmailText({ invoice: eurInvoice, customer: svCustomer, company })
expect(text).toMatch(/1[\s ]234,56 EUR/)
})
it('subtracts the ROT/RUT deduction so the email states what the customer owes', () => {
const rotInvoice = makeInvoice({ invoice_number: '1042', total: 1234.56, deduction_total: 500 })
const html = generateInvoiceEmailHtml({ invoice: rotInvoice, customer: svCustomer, company })
expect(html).toContain('735,00 SEK')
const text = generateInvoiceEmailText({ invoice: rotInvoice, customer: svCustomer, company })
expect(text).toContain('Att betala: 735,00 SEK')
})
it('uses the rounded amount for the {belopp} placeholder', () => {
const withBelopp = makeCompanySettings({
company_name: 'Acme AB',
invoice_email_texts: { sv: { body: 'Summa: {belopp}' } },
})
const oreInvoice = makeInvoice({ invoice_number: '1042', total: 1234.56 })
const text = generateInvoiceEmailText({ invoice: oreInvoice, customer: svCustomer, company: withBelopp })
expect(text).toMatch(/Summa: 1[\s ]235,00 SEK/)
})
})
})
+19 -4
View File
@@ -1,6 +1,7 @@
import type { Invoice, Customer, CompanySettings, InvoiceDocumentType } from '@/types'
import { formatDate, getCompanyDisplayName, getCompanyPrimaryName } from '@/lib/utils'
import { applyPlaceholders, sanitizeSubjectLine, userTextToHtml } from './user-text'
import { getAmountToPay } from '@/lib/invoices/rounding'
import { applyPlaceholders, escapeHtml, sanitizeSubjectLine, userTextToHtml } from './user-text'
type EmailLang = 'sv' | 'en'
@@ -23,6 +24,7 @@ const LABELS = {
bodyCreditNote: 'Bifogat hittar du en kreditfaktura som korrigerar en tidigare faktura.',
bodyInvoice: 'Tack för ditt förtroende! Bifogat hittar du din faktura.',
toPay: 'Att betala:',
payOnline: 'Betala online',
paymentHeading: 'Betalningsinformation',
bank: 'Bank:',
account: 'Kontonummer:',
@@ -51,6 +53,7 @@ const LABELS = {
bodyCreditNote: 'Attached you will find a credit note that corrects an earlier invoice.',
bodyInvoice: 'Thank you for your business. Attached you will find your invoice.',
toPay: 'Total due:',
payOnline: 'Pay online',
paymentHeading: 'Payment information',
bank: 'Bank:',
account: 'Account number:',
@@ -150,7 +153,7 @@ function buildPlaceholderValues(data: InvoiceEmailData, lang: EmailLang): Record
förnamn: fullName ? fullName.split(' ')[0] : '',
företag: getCompanyPrimaryName(company),
förfallodatum: formatDate(invoice.due_date),
belopp: formatCurrencyForCustomer(invoice.total, invoice.currency, lang),
belopp: formatCurrencyForCustomer(getAmountToPay(invoice, company).toPay, invoice.currency, lang),
}
}
@@ -267,12 +270,23 @@ export function generateInvoiceEmailHtml(data: InvoiceEmailData): string {
<tr>
<td style="padding: 8px 0; font-size: 18px; font-weight: 600;">${L.toPay}</td>
<td style="padding: 8px 0; text-align: right; font-size: 18px; font-weight: 600; color: ${isCreditNote ? '#059669' : primaryColor};">
${formatCurrencyForCustomer(invoice.total, invoice.currency, lang)}
${formatCurrencyForCustomer(getAmountToPay(invoice, company).toPay, invoice.currency, lang)}
</td>
</tr>
</table>
</div>
<!-- Pay-online button: only when the user pasted a payment link on this
invoice. The URL is schema-validated (https-only) but still escaped
for the attribute context: a URL may legally contain quotes. -->
${!hidePayment && invoice.payment_link_url ? `
<div style="margin-bottom: 30px; text-align: center;">
<a href="${escapeHtml(invoice.payment_link_url)}" style="display: inline-block; background: ${primaryColor}; color: #ffffff; text-decoration: none; padding: 12px 32px; border-radius: 6px; font-size: 16px; font-weight: 600;">
${L.payOnline}
</a>
</div>
` : ''}
<!-- Payment Details -->
${!hidePayment ? `
<div style="margin-bottom: 30px;">
@@ -364,11 +378,12 @@ export function generateInvoiceEmailText(data: InvoiceEmailData): string {
text += `${L.documentNumber(documentType)} ${invoice.invoice_number}\n`
text += `${L.documentDate(documentType)} ${formatDate(invoice.invoice_date)}\n`
text += `${L.dueDate} ${formatDate(invoice.due_date)}\n`
text += `${L.toPay} ${formatCurrencyForCustomer(invoice.total, invoice.currency, lang)}\n`
text += `${L.toPay} ${formatCurrencyForCustomer(getAmountToPay(invoice, company).toPay, invoice.currency, lang)}\n`
text += `---\n\n`
if (!hidePayment) {
text += `${L.paymentHeading}:\n`
if (invoice.payment_link_url) text += `${L.payOnline}: ${invoice.payment_link_url}\n`
if (company.bank_name) text += `${L.bank} ${company.bank_name}\n`
if (company.clearing_number && company.account_number) {
text += `${L.account} ${company.clearing_number}-${company.account_number}\n`