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
@@ -317,6 +317,98 @@ describe('generateGeneralLedger', () => {
expect(acc.lines[2].description).toBe('Second')
})
it('rolls lines before fromDate into the opening balance and drops lines after toDate', async () => {
mockResults = {
fiscal_periods: [
{ data: { period_start: '2026-01-01', period_end: '2026-12-31', opening_balance_entry_id: null }, error: null },
],
'rpc:compute_prior_opening_balances': [
{
data: [{ account_number: '1930', debit: 10000, credit: 0 }],
error: null,
},
],
journal_entries: [
{
data: [
{ id: 'e1', entry_date: '2026-03-15', voucher_number: 1, voucher_series: 'A', description: 'Pre-range', source_type: 'manual' },
{ id: 'e2', entry_date: '2026-06-10', voucher_number: 2, voucher_series: 'A', description: 'In range', source_type: 'manual' },
{ id: 'e3', entry_date: '2026-09-01', voucher_number: 3, voucher_series: 'A', description: 'Post-range', source_type: 'manual' },
],
error: null,
},
],
journal_entry_lines: [
{
data: [
// Before the range: rolls into opening
{ account_number: '1930', debit_amount: 0, credit_amount: 2000, journal_entry_id: 'e1' },
// Inside the range: shown
{ account_number: '1930', debit_amount: 500, credit_amount: 0, journal_entry_id: 'e2' },
// After the range: dropped entirely
{ account_number: '1930', debit_amount: 0, credit_amount: 300, journal_entry_id: 'e3' },
],
error: null,
},
],
chart_of_accounts: [
{ data: [{ account_number: '1930', account_name: 'Företagskonto' }], error: null },
],
}
const report = await generateGeneralLedger(supabase, 'company-1', 'period-1', undefined, undefined, {
fromDate: '2026-06-01',
toDate: '2026-06-30',
})
const acc = report.accounts.find((a) => a.account_number === '1930')!
// Opening at range start = period IB 10000 - pre-range 2000
expect(acc.opening_balance).toBe(8000)
expect(acc.lines).toHaveLength(1)
expect(acc.lines[0].description).toBe('In range')
expect(acc.lines[0].balance).toBe(8500)
// Closing = opening + in-range movement only; post-range line excluded
expect(acc.closing_balance).toBe(8500)
expect(report.period).toEqual({ start: '2026-06-01', end: '2026-06-30' })
})
it('keeps an account visible when all its lines fall before the range', async () => {
mockResults = {
fiscal_periods: [
{ data: { period_start: '2026-01-01', period_end: '2026-12-31', opening_balance_entry_id: null }, error: null },
],
journal_entries: [
{
data: [
{ id: 'e1', entry_date: '2026-02-01', voucher_number: 1, voucher_series: 'A', description: 'Hyra feb', source_type: 'manual' },
],
error: null,
},
],
journal_entry_lines: [
{
data: [
{ account_number: '5010', debit_amount: 4000, credit_amount: 0, journal_entry_id: 'e1' },
],
error: null,
},
],
chart_of_accounts: [
{ data: [{ account_number: '5010', account_name: 'Lokalhyra' }], error: null },
],
}
const report = await generateGeneralLedger(supabase, 'company-1', 'period-1', undefined, undefined, {
fromDate: '2026-06-01',
toDate: '2026-06-30',
})
const acc = report.accounts.find((a) => a.account_number === '5010')!
expect(acc.opening_balance).toBe(4000)
expect(acc.lines).toHaveLength(0)
expect(acc.closing_balance).toBe(4000)
})
it('uses Math.round for monetary precision', async () => {
mockResults = {
fiscal_periods: [
+1 -1
View File
@@ -246,7 +246,7 @@ export const REPORT_CATALOG: ReportDescriptor[] = [
labelKey: 'name_huvudbok',
descKey: 'desc_huvudbok',
category: 'ledgers',
params: 'fiscal',
params: 'fiscal-range',
exports: ['xlsx'],
dimensions: true,
},
+47 -8
View File
@@ -1,5 +1,6 @@
import type { SupabaseClient } from '@supabase/supabase-js'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import { roundOre } from '@/lib/money'
import { fetchEntryLines, type EntryLinesQuery } from '@/lib/bookkeeping/entry-lines'
import { getOpeningBalances } from './opening-balances'
@@ -59,6 +60,13 @@ export async function generateGeneralLedger(
/** SIE dim → code filter ({"6":"P001"}). Opening balances are dropped
* when set: they are company-wide and cannot be dimension-scoped. */
dimensions?: Record<string, string>
/** Inclusive date sub-range within the fiscal period (kontoanalys).
* Lines before fromDate roll into each account's opening balance so
* the running balance at the range start matches the full-year ledger;
* lines after toDate are dropped. Callers validate the bounds
* (parseReportDateRange). */
fromDate?: string
toDate?: string
}
): Promise<GeneralLedgerReport> {
const dimensionFilter =
@@ -135,7 +143,13 @@ export async function generateGeneralLedger(
})
if (rawLines.length === 0 && openingBalances.size === 0) {
return { accounts: [], period: { start: period.period_start, end: period.period_end } }
return {
accounts: [],
period: {
start: options?.fromDate ?? period.period_start,
end: options?.toDate ?? period.period_end,
},
}
}
// Fetch account names
@@ -153,12 +167,25 @@ export async function generateGeneralLedger(
accountNameMap.set(acc.account_number, acc.account_name)
}
// Group lines by account
// Group lines by account. Lines before fromDate accumulate per account so
// they can roll into the opening balance below; lines after toDate drop.
const fromDate = options?.fromDate
const toDate = options?.toDate
const accountLines = new Map<string, GeneralLedgerLine[]>()
const preRangeMovements = new Map<string, number>()
for (const line of rawLines) {
const entry = line.journal_entries
const accNum = line.account_number
const debit = Math.round((Number(line.debit_amount) || 0) * 100) / 100
const credit = Math.round((Number(line.credit_amount) || 0) * 100) / 100
if (toDate && entry.entry_date > toDate) continue
if (fromDate && entry.entry_date < fromDate) {
preRangeMovements.set(accNum, (preRangeMovements.get(accNum) || 0) + debit - credit)
continue
}
if (!accountLines.has(accNum)) {
accountLines.set(accNum, [])
}
@@ -172,15 +199,24 @@ export async function generateGeneralLedger(
journal_entry_id: line.journal_entry_id,
description: entry.description || '',
source_type: entry.source_type || '',
debit: Math.round((Number(line.debit_amount) || 0) * 100) / 100,
credit: Math.round((Number(line.credit_amount) || 0) * 100) / 100,
debit,
credit,
balance: 0, // computed below
...(hasDims ? { dimensions: line.dimensions as Record<string, string> } : {}),
})
}
// Include accounts that have opening balance but no period lines
for (const [accNum, balance] of openingBalances) {
// Opening balance at the range start: period IB plus movements before
// fromDate. Under a dimension filter the IB map is empty (company-wide IB
// cannot be dimension-scoped) but pre-range movements are dimension-scoped
// by the query, so they still roll in.
const effectiveOpening = new Map<string, number>(openingBalances)
for (const [accNum, movement] of preRangeMovements) {
effectiveOpening.set(accNum, roundOre((effectiveOpening.get(accNum) || 0) + movement))
}
// Include accounts that carry a balance into the range but have no lines in it
for (const [accNum, balance] of effectiveOpening) {
if (!accountLines.has(accNum) && Math.abs(balance) > 0.005) {
accountLines.set(accNum, [])
}
@@ -201,7 +237,7 @@ export async function generateGeneralLedger(
return a.voucher_number - b.voucher_number
})
const opening = Math.round((openingBalances.get(accNum) || 0) * 100) / 100
const opening = Math.round((effectiveOpening.get(accNum) || 0) * 100) / 100
let runningBalance = opening
for (const line of accLines) {
@@ -228,6 +264,9 @@ export async function generateGeneralLedger(
return {
accounts: result,
period: { start: period.period_start, end: period.period_end },
period: {
start: fromDate ?? period.period_start,
end: toDate ?? period.period_end,
},
}
}