Files
accounted/lib/email/reminder-templates.ts
T
MattssonandClaude Fable 5.1 d670fe6663 feat(invoices): named payee accounts and per-invoice choice of bank account (#2233)
* fix(enable-banking): read BBAN from AccountIdentification.other and store it on the account

Enable Banking has no top-level `bban` key on AccountIdentification: a
Swedish BBAN (clearing + account number) arrives as `other.identification`
with `other.scheme_name = 'BBAN'`, or in `all_account_ids`. The client typed
`bban?: string` and read `.bban`, so the value was always undefined: no
connected account ever carried its clearing + account number, and domestic
counterparty accounts on transactions were dropped.

Type the identifiers per the OpenAPI spec, add extractBban() and
pickAccountIdentifier(), read counterparty identifiers through the scheme
list (IBAN, then BBAN/BGNR/PGNR, then anything), and store `bban` on
StoredAccount from the OAuth callback. The external_id dedup scope stays
IBAN-then-uid and is untouched.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV

* feat(invoices): named payee accounts on cash_accounts with a default per currency

A company had exactly one set of payment instructions per invoice currency
(company_settings.invoice_payment_accounts), picked by currency alone. A
second SEK bank account, or a second bankgiro number, had nowhere to live.

cash_accounts is already the per-company bank-account entity. Migration
20260903150000 adds the payee fields (bankgiro, plusgiro, clearing +
account number, BBAN, BIC, Swish, foreign routing) plus invoice_payee, a
small invoice_payee_defaults table (one default account per currency; one
account may be the default for several currencies, a SEK account with an
IBAN is the usual EUR payee), and a SECURITY DEFINER mirror that rewrites
the legacy map and the SEK bank columns from the default accounts. Every
existing reader (PDF, email, reminders, v1, MCP) keeps working; the three
writers that only touched legacy columns (PUT /api/settings, v1 settings,
MCP update_company_settings) now write through to the default account, so
what an agent sets is what the PDF prints. Peppol PaymentMeans is built
from the resolver instead of the raw legacy column. bg_pg is dropped
(never read or written; NULL on every prod and staging row).

Backfill lands only on existing cash accounts (primary, IBAN match, or the
only enabled account in the currency). Entries with no target stay in the
map as the resolver fallback and get an attach action in settings.

New: POST /api/cash-accounts (manual bank account on the next free 19xx),
PATCH /api/cash-accounts/[id] payee fields (owner/admin), GET/PUT
/api/cash-accounts/payee-defaults. Settings page rewritten as an account
list with per-currency defaults. Behandlingshistorik and the full archive
cover the new table and columns.

Verified on staging: migration applied (11 defaults landed), mirror
trigger observed rewriting company_settings from a payee edit.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV

* feat(invoices): choose which bank account an invoice is paid to, frozen at issue

Migration 20260903160000 adds invoices.payment_cash_account_id (FK to
cash_accounts, SET NULL) and invoices.payment_details, the payee fields
frozen when the account is chosen and refreshed at issue.

Resolver: resolveInvoicePaymentAccount / companyWithInvoicePaymentAccount /
assertInvoicePaymentAccountForRender take an optional override, and
hasRequiredInvoicePaymentAccount reads it from the invoice row, so every
surface (PDF, Swish QR, email, reminders, payment confirmation, Peppol,
recurring, staged MCP send) prints the frozen payee when one exists and the
company default per currency otherwise. Invoices that never chose an
account behave exactly as before.

Issue paths (mark-sent, send, v1 send, v1 mark-sent, Peppol send,
recurring, MCP send and mark-sent) refresh the snapshot from the account as
it is at issue; a chosen account that is disabled, un-flagged or unusable
for the currency blocks with INVOICE_SEND_PAYMENT_ACCOUNT_INVALID.

Writers: dashboard POST/PATCH, v1 create/update and MCP create_invoice
accept payment_cash_account_id and validate it against the company's payee
accounts (INVOICE_PAYEE_ACCOUNT_INVALID). Credit notes inherit the
original's payee; copies carry the choice; preview-pdf renders the chosen
account. The editor shows "Betalas till" under the currency when the
company has two or more usable payee accounts for that currency.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV

* feat(invoices): book manual payments on the invoice's chosen bank account

Manual mark-paid (dashboard, v1, MCP gnubok_mark_invoice_as_paid) and the
booking dialog's proposed lines debited 1930 regardless of which bank
account the invoice asked to be paid to. They now resolve the chosen
payee account's ledger account (resolveInvoiceSettlementAccount) and fall
back to 1930 only when no account was chosen or the row is gone.

Bank-transaction matching keeps debiting the account the money landed on
and does not filter by the chosen account; between equal-confidence
candidates it prefers the invoice that asked to be paid to the landing
account. Scores are untouched, so nothing new auto-matches.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV

* chore(invoices): keep the payload-size and phantom-column ceilings after the payee work

Shorten the new gnubok_create_invoice argument description (tools/list
payload was 29 bytes over the 60 kB budget), inline the cash-account payee
UPDATE/INSERT payloads and the settings select strings as literals so the
phantom-column scanner can read their columns, and reuse ACCOUNT_NUMBER_RE
instead of a hand-rolled copy.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV

* fix(invoices): harden the payee model after review (admin-only payee columns, separate payee IBAN, company-scoped FK)

Review findings from CodeRabbit, Superagent, the Swedish accounting review
and three skeptic passes, resolved in one batch:

Schema (both migrations are unshipped and edited in place):
- cash_accounts.payee_iban: the printed IBAN is its own column. iban stays
  the bank identity written by every sync and used to re-pair on reconnect,
  so a sync can no longer rewrite an invoice instruction or resurrect a
  cleared IBAN. The backfill copies each currency entry verbatim onto the
  target account (IBAN match first, then primary), so every invoice keeps
  printing exactly what it printed before; the bank IBAN is never pushed
  onto invoices that did not carry one.
- Payee columns are owner/admin-only at the database (BEFORE trigger,
  service role exempt): cash_accounts is member-writable for bank sync, and
  the SECURITY DEFINER mirror would otherwise have let a member rewrite
  where customers pay.
- Revoking an account as payee or disabling it drops its defaults; deleting
  a default drops that currency from the map and clears the legacy SEK
  columns (an admin saying "nothing to print" must not keep printing a
  closed account). The mirror leaves the legacy SEK columns alone when the
  map has no SEK entry, so legacy-only companies are never wiped by a
  mirror run for another currency.
- Audit and mirror triggers fire on the same column set; anon and
  authenticated can no longer execute the trigger-only definer functions.
- invoices.payment_cash_account_id is a composite same-company FK with
  SET NULL scoped to the account column.

Code:
- Only 19xx bank accounts can be payee: PATCH, the defaults PUT (which now
  also requires enabled, payee-flagged and usable for the currency),
  resolveInvoicePayeeChoice, and the mark-paid settlement resolver (which
  also refuses disabled rows and logs every fallback to 1930).
- createManualBankAccount excludes every ledger slot any row already holds
  (findFreeLedgerAccount treats a manual holder as free; this path inserts).
- The legacy settings writers (PUT /api/settings, v1, MCP) write through to
  the account BEFORE updating company_settings and fail the request on
  error; the account is written before it is adopted as default so the
  mirror never sees an empty payee.
- snapshotInvoicePayee: dry runs no longer persist; a failed snapshot write
  blocks issue (INVOICE_PAYEE_SNAPSHOT_FAILED). v1 mark-sent/mark-paid
  projections carry the payee columns; v1 create validates the payee
  before the dry-run return and echoes it in the preview.
- pickAccountIdentifier: supplementary IBAN wins over a primary BBAN, and
  non-account schemes (card PANs) are never persisted.
- Editor shows the payee select for a single usable account with no
  default; the booking dialog waits for cash accounts before proposing
  lines; a failed default write no longer hides a created account.
- Behandlingshistorik names the account on created/deleted defaults.
- Regenerated skills/accounted-api; MCP argument description trimmed under
  the tools/list payload ceiling.

Declined: clearing legacy columns via a forward migration (the mirror now
does it on delete); Swedish review's "show the debit account in the
mark-paid UI" (the booking dialog already proposes and lets the user edit
the debit line); manual ledger collision (UNIQUE exists, and the create
path now rejects it with a clear error); Peppol aligning to the PDF value
for companies whose legacy column had drifted from the map (the PDF is the
customer-facing document; both now agree).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV

* fix(invoices): read NEW.invoice_payee only on the cash_accounts branch of the mirror trigger

trg_mirror_invoice_payee_defaults fires for both tables; plpgsql resolves
record fields per expression, so the combined condition failed with
"record new has no field invoice_payee" whenever a default row changed,
which took down every pg-real case on the payee tables. The revoke/disable
check now sits inside its own TG_TABLE_NAME branch. The MCP settings
executor test mocks the payee write-through like the settings route test
already does.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV

* fix(invoices): keep member disables from revoking payee defaults, gate payee on 1920-1999, fit the MCP payload

Cycle 3 of /resolve-pr on #2233.

Superagent P1: the SECURITY DEFINER mirror trigger deleted an admin's
invoice_payee_defaults rows whenever cash_accounts.enabled flipped to
false, and enabled is member-writable (the bank picker's "Synkas ej"), so
a member could undo an admin's payee decision. The trigger now drops
defaults only on the admin-only invoice_payee true -> false revoke; the
mirror trigger's WHEN no longer lists enabled. Disabled accounts stay out
of the pick lists and the send gate already refuses an invoice that chose
one. Applied to staging as the same function + trigger definition and
probed inside a rolled-back block: disable keeps the default and the
mirrored bankgiro, revoke clears both.

pg-real: the admin-guard test ran three expectations inside one
withUserContext transaction; the first raise aborted it and the next
statement failed with "current transaction is aborted". One transaction
per expectation now, and the member case also flips enabled to prove the
column stays member-level.

Swedish review: payee eligibility was /^19\d\d$/, which admits 1910 Kassa
and the 1911-1919 tills. A customer pays to a giro or bank account, so
isBankCashAccount, CreateCashAccountSchema.ledger_account and the PATCH
route now require BAS 1920-1999; tests cover 1910 and 1919.

Unit tests (3/4): the tools/list payload guard read 60 025, then 60 014
tokens after main merged #2166 and #2163 alongside this branch. The
ceiling is not bumped and no read on this surface is a demotion
candidate, so gnubok_create_invoice drops payment_cash_account_id;
agent-created invoices print the per-currency default and v1 REST plus
the editor keep the field. Recorded in DECISIONS.md.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV

* chore(migrations): move invoices_payment_cash_account to 20260903183000 after colliding with main's KPI migration

origin/main merged 20260903160000_kpi_monthly_include_reversed_originals
while this branch held the same version; identical versions abort the
Supabase apply. Staging's schema_migrations row was moved to the new
version with the file.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UaZTY21HVN57hJoPXKSLjV

* fix(invoices): gate invoice_payee on BAS 1920-1999 at the database, and unblock the typecheck ratchet

Cycle 4 of /resolve-pr on #2233, on Emil's go.

Swedish review: the 1920-1999 payee rule lived only in the routes. The
cash_accounts_payee_admin_only trigger now also refuses invoice_payee on
any other ledger (INVOICE_PAYEE_ACCOUNT_INVALID, 23514), whoever writes
it, and the backfill only targets giro/bank rows, so a company whose
single enabled cash_accounts row is a Stripe clearing account keeps its
legacy bankgiro in company_settings instead of landing it on 1686. pg
test covers insert and update on 1686 and 1910; the function was applied
to staging and probed.

Typecheck ratchet: main is red from two merges that landed with failing
Checks, and every branch that syncs it inherits the errors.
  - #2242 added POST(req) calls to the fiscal-periods route test without
    the route params argument withRouteContext handlers take (25 errors
    in the file, baseline 23). All 25 calls now pass
    createMockRouteParams({}).
  - #2247 made SyncResult.requestedFromDate and historyNarrowed required;
    the 13 mockedSync results in the enable-banking accounts-route test
    lacked them. They now carry a fixed date and historyNarrowed: false.
Both files' tests pass unchanged in behaviour.

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

* chore(migrations): move invoices_payment_cash_account to 20260903193000 after colliding with main's party_promotion

origin/main merged 20260903183000_party_promotion while this branch held
the same version. Staging's schema_migrations row must follow (pending:
the Supabase MCP was disconnected at the time of this commit).

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

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-03 21:06:45 +02:00

625 lines
24 KiB
TypeScript

import type { Invoice, Customer, CompanySettings, ReminderTextOverrides } from '@/types'
import { formatCurrency, formatDate, getCompanyDisplayName } from '@/lib/utils'
import { getAmountToPay } from '@/lib/invoices/rounding'
import { companyWithInvoicePaymentAccount } from '@/lib/invoices/payment-accounts'
import { applyPlaceholders, escapeHtml, sanitizeSubjectLine } from './user-text'
/**
* What the customer was asked to pay on the original invoice: the öre-rounded
* "Att betala" minus any ROT/RUT-avdrag (fakturamodellen: the deduction is a
* claim on Skatteverket, never on the customer). Reminders, dröjsmålsränta and
* the amount-to-pay line must all start from this figure, not invoice.total,
* or a privatperson is dunned for the SKV share and charged interest on it.
*/
export function reminderPrincipal(invoice: Invoice, company: CompanySettings): number {
return getAmountToPay(invoice, company).toPay
}
export interface ReminderEmailData {
invoice: Invoice
customer: Customer
company: CompanySettings
reminderLevel: 1 | 2 | 3
daysOverdue: number
actionUrl: string // URL for customer to mark as paid or dispute
// Dröjsmålsränta + lagstadgad påminnelseavgift (Räntelagen §6, Lag 1981:739).
// When the reminder is generated by the cron, these are computed and persisted
// on the invoice_reminders row and then passed in here.
//
// interestAmount is a share of the invoice total, so it carries the INVOICE
// currency. reminderFee is a fixed statutory krona amount and always carries
// SEK (see REMINDER_FEE_CURRENCY). The two are deliberately not summed here:
// the amount to pay is derived per currency by calculateReminderAmounts().
interestAmount: number
interestRate: number // annual rate as decimal (0.105 = 10.5%)
interestFromDate: string
interestDays: number
reminderFee: number // always SEK, never the invoice currency
}
/**
* The lagstadgad påminnelseavgift is a Swedish-krona statute: Lag (1981:739) om
* ersättning för inkassokostnader m.m. 2 §, with the amount fixed at 60 kr by
* förordning (1981:1057) 1 §. There is no conversion rule for a foreign-currency
* claim, and Accounted books the fee 1510/3990 in SEK regardless of the invoice
* currency (lib/bookkeeping/reminder-fee-entries.ts).
*
* So the fee is always quoted in SEK. Rendering "60" with the invoice's currency
* code would demand roughly ten times the statutory amount from a EUR customer
* and would not match the receivable recorded in the books.
*/
export const REMINDER_FEE_CURRENCY = 'SEK'
export interface ReminderAmounts {
/** Invoice currency (uppercased ISO code). Carries the invoice total + interest. */
currency: string
/** invoice.total + dröjsmålsränta, plus the fee only when the invoice is itself in SEK. */
totalDue: number
/**
* The påminnelseavgift in SEK when the invoice is in another currency, so it
* has to be demanded alongside rather than inside `totalDue`. 0 when the fee
* is already folded into `totalDue`.
*/
feeDueSeparately: number
}
/**
* Split the amount to pay per currency. Never returns a single scalar that mixes
* a foreign invoice currency with the SEK statutory fee.
*/
export function calculateReminderAmounts(input: {
invoiceTotal: number
interestAmount: number
reminderFee: number
currency?: string | null
}): ReminderAmounts {
const currency = (input.currency || REMINDER_FEE_CURRENCY).toUpperCase()
const feeSharesInvoiceCurrency = currency === REMINDER_FEE_CURRENCY
const fee = input.reminderFee > 0 ? Math.round(input.reminderFee * 100) / 100 : 0
const totalDue =
Math.round(
(input.invoiceTotal + input.interestAmount + (feeSharesInvoiceCurrency ? fee : 0)) * 100,
) / 100
return {
currency,
totalDue,
feeDueSeparately: feeSharesInvoiceCurrency ? 0 : fee,
}
}
/**
* Render the amount to pay. When the statutory fee is in a different currency
* than the invoice it is appended as its own amount ("1 010,00 € + 60 kr")
* instead of being folded into a misleading single figure.
*/
export function formatReminderTotalDue(amounts: ReminderAmounts): string {
const base = formatCurrency(amounts.totalDue, amounts.currency)
if (amounts.feeDueSeparately <= 0) {
return base
}
return `${base} + ${formatCurrency(amounts.feeDueSeparately, REMINDER_FEE_CURRENCY)}`
}
/** Shown whenever a SEK fee rides along with a foreign-currency invoice. */
export const REMINDER_FEE_CURRENCY_NOTE =
'Påminnelseavgiften är lagstadgad (Lag 1981:739) och anges i svenska kronor. '
+ 'Den räknas inte om till fakturans valuta utan betalas som ett separat belopp i SEK.'
// Reminder level configurations
const REMINDER_CONFIG = {
1: {
title: 'Vänlig påminnelse',
tone: 'friendly',
daysAfterDue: 15
},
2: {
title: 'Andra påminnelsen',
tone: 'firm',
daysAfterDue: 30
},
3: {
title: 'Slutlig påminnelse',
tone: 'urgent',
daysAfterDue: 45
}
} as const
export type ReminderLevelKey = 'level_1' | 'level_2' | 'level_3'
function levelKey(reminderLevel: 1 | 2 | 3): ReminderLevelKey {
return `level_${reminderLevel}` as ReminderLevelKey
}
// Placeholder keys available in company-editable reminder texts
// (company_settings.reminder_text_overrides). Rendered as a legend in the
// settings UI; kept here rather than in messages/*.json because ICU message
// syntax treats literal braces as interpolation.
export const REMINDER_EMAIL_PLACEHOLDER_KEYS = [
'fakturanummer',
'kundnamn',
'förnamn',
'företag',
'fakturadatum',
'förfallodatum',
'belopp',
'dagar',
] as const
/**
* Default subject/body per reminder level, in placeholder-pattern form.
* Single source of truth: the stock mail renders these same patterns through
* the same substitution pipeline as company overrides, so the settings-UI
* prefill is exactly what goes out and cannot drift from the send path.
*
* Level 3 is deliberately an inkassovarning (final notice before collection),
* as Swedish practice expects: it names the 8-day window and that the claim
* is handed to inkasso with added statutory costs (lag 1981:739). TEXT only:
* fee and interest math live in the reminder processor and are unaffected by
* anything here or in company overrides.
*
* The stock subject additionally gets ' (inkl. dröjsmålsränta)' appended when
* surcharges apply (see generateReminderEmailSubject); an override replaces
* the whole line and gets no automatic suffix.
*/
export const REMINDER_EMAIL_DEFAULT_TEXTS: Record<
ReminderLevelKey,
{ subject: string; body: string }
> = {
level_1: {
subject: 'Vänlig påminnelse: Faktura {fakturanummer} - {belopp}',
body:
'Vi vill påminna dig om att faktura {fakturanummer} förföll till betalning den {förfallodatum}. '
+ 'Om du redan har betalat kan du bortse från denna påminnelse.',
},
level_2: {
subject: 'Andra påminnelsen: Faktura {fakturanummer} - {belopp}',
body:
'Trots vår tidigare påminnelse har vi ännu inte mottagit betalning för faktura {fakturanummer} '
+ 'som förföll den {förfallodatum}.\n\n'
+ 'Vi ber dig vänligen att omgående reglera detta belopp för att undvika ytterligare åtgärder.',
},
level_3: {
subject: 'Slutlig påminnelse: Faktura {fakturanummer} - {belopp}',
body:
'Detta är en slutlig påminnelse och inkassovarning gällande faktura {fakturanummer}.\n\n'
+ 'Fakturan förföll till betalning den {förfallodatum} och vi har trots tidigare påminnelser '
+ 'ännu inte mottagit din betalning.\n\n'
+ 'Om full betalning inte har kommit oss tillhanda inom 8 dagar från detta meddelande '
+ 'överlämnas fordran till inkasso, vilket medför ytterligare kostnader för dig enligt '
+ 'lag (1981:739) om ersättning för inkassokostnader m.m.',
},
}
// Values for the fixed placeholder set. {belopp} is the amount to pay incl.
// surcharges via formatReminderTotalDue, so a foreign-currency invoice with a
// SEK fee renders the two-amount form here too, never one mixed scalar.
function buildReminderPlaceholderValues(data: ReminderEmailData): Record<string, string> {
const { invoice, customer, company, daysOverdue, interestAmount, reminderFee } = data
const fullName = (customer.name || '').trim()
const amounts = calculateReminderAmounts({
invoiceTotal: reminderPrincipal(invoice, company),
interestAmount,
reminderFee,
currency: invoice.currency,
})
return {
fakturanummer: invoice.invoice_number ?? '',
kundnamn: fullName,
förnamn: fullName ? fullName.split(' ')[0] : '',
företag: getCompanyDisplayName(company),
fakturadatum: formatDate(invoice.invoice_date),
förfallodatum: formatDate(invoice.due_date),
belopp: formatReminderTotalDue(amounts),
dagar: String(daysOverdue),
}
}
interface ResolvedReminderTexts {
subject?: string
body?: string
}
// Resolves the company's custom reminder texts for one level. Per-field
// fallback: missing / non-string / whitespace-only values return undefined
// and the caller renders the default pattern instead. Returns RAW substituted
// strings: escaping is the caller's job per output variant (HTML vs text vs
// subject). Defensive typeof checks: rows can be written outside Zod
// (scripts, SQL).
function resolveReminderTexts(
company: CompanySettings,
reminderLevel: 1 | 2 | 3,
values: Record<string, string>,
): ResolvedReminderTexts {
const overrides: ReminderTextOverrides | null | undefined = company.reminder_text_overrides
const levelTexts =
overrides && typeof overrides === 'object' ? overrides[levelKey(reminderLevel)] : undefined
if (!levelTexts || typeof levelTexts !== 'object') return {}
const pick = (v: unknown): string | undefined =>
typeof v === 'string' && v.trim() !== '' ? applyPlaceholders(v.trim(), values) : undefined
return {
subject: pick(levelTexts.subject),
body: pick(levelTexts.body),
}
}
// Effective body for one level: override if present, else the default
// pattern, both substituted through the same pipeline.
function resolveReminderBody(data: ReminderEmailData): string {
const values = buildReminderPlaceholderValues(data)
const custom = resolveReminderTexts(data.company, data.reminderLevel, values)
return (
custom.body
?? applyPlaceholders(REMINDER_EMAIL_DEFAULT_TEXTS[levelKey(data.reminderLevel)].body, values)
)
}
// Blank-line separated paragraphs -> <p> blocks; single newlines -> <br>.
// Escape FIRST so user-authored overrides cannot inject markup. The final
// level's opening paragraph keeps the red emphasis regardless of override:
// the inkassovarning must not look like a routine note.
function reminderBodyToHtml(body: string, reminderLevel: 1 | 2 | 3): string {
return body
.split(/(?:\r?\n){2,}/)
.map((paragraph, index) => {
const emphasis =
reminderLevel === 3 && index === 0 ? ' color: #dc2626; font-weight: 500;' : ''
const html = escapeHtml(paragraph).replace(/\r\n|\r|\n/g, '<br>')
return `<p style="margin: 0 0 15px 0;${emphasis}">${html}</p>`
})
.join('\n ')
}
/**
* Generate HTML email for payment reminder
*/
export function generateReminderEmailHtml(data: ReminderEmailData): string {
const {
invoice,
customer,
reminderLevel,
daysOverdue,
actionUrl,
interestAmount,
interestRate,
interestDays,
reminderFee,
} = data
// Payment details follow the invoice currency, same as the invoice email
// and PDF: a EUR reminder must never print the SEK account's IBAN.
const company = companyWithInvoicePaymentAccount(data.company, invoice.currency, invoice.payment_details ?? null)
const config = REMINDER_CONFIG[reminderLevel]
const interestRatePercent = (interestRate * 100).toLocaleString('sv-SE', {
minimumFractionDigits: 0,
maximumFractionDigits: 2,
})
const hasInterest = interestAmount > 0
const hasFee = reminderFee > 0
const hasSurcharges = hasInterest || hasFee
const amounts = calculateReminderAmounts({
invoiceTotal: reminderPrincipal(invoice, company),
interestAmount,
reminderFee,
currency: invoice.currency,
})
const feeInOtherCurrency = amounts.feeDueSeparately > 0
// Different styling based on urgency
const headerColor = reminderLevel === 3 ? '#dc2626' : reminderLevel === 2 ? '#ea580c' : '#2563eb'
const buttonColor = reminderLevel === 3 ? '#dc2626' : reminderLevel === 2 ? '#ea580c' : '#2563eb'
return `
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${config.title} - Faktura ${invoice.invoice_number}</title>
</head>
<body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; line-height: 1.6; color: #333; background-color: #f9fafb;">
<div style="max-width: 600px; margin: 0 auto; padding: 40px 20px;">
<div style="background: white; border-radius: 12px; padding: 40px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
<!-- Header -->
<div style="text-align: center; margin-bottom: 30px;">
<div style="display: inline-block; background: ${headerColor}15; color: ${headerColor}; padding: 8px 16px; border-radius: 20px; font-size: 12px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;">
${config.title}
</div>
</div>
<!-- Title -->
<h1 style="margin: 0 0 20px 0; font-size: 22px; font-weight: 600; color: #111; text-align: center;">
Faktura ${invoice.invoice_number} förföll för ${daysOverdue} dagar sedan
</h1>
<!-- Greeting and Message -->
<div style="margin-bottom: 30px;">
<p style="margin: 0 0 15px 0;">
Hej${customer.name ? ` ${customer.name.split(' ')[0]}` : ''},
</p>
${reminderBodyToHtml(resolveReminderBody(data), reminderLevel)}
</div>
<!-- Invoice Summary Box -->
<div style="background: #f8f9fa; border-radius: 8px; padding: 25px; margin-bottom: 30px; border-left: 4px solid ${headerColor};">
<table style="width: 100%; border-collapse: collapse;">
<tr>
<td style="padding: 8px 0; color: #666; font-size: 14px;">Fakturanummer:</td>
<td style="padding: 8px 0; text-align: right; font-weight: 500;">${invoice.invoice_number}</td>
</tr>
<tr>
<td style="padding: 8px 0; color: #666; font-size: 14px;">Fakturadatum:</td>
<td style="padding: 8px 0; text-align: right;">${formatDate(invoice.invoice_date)}</td>
</tr>
<tr>
<td style="padding: 8px 0; color: #666; font-size: 14px;">Förfallodatum:</td>
<td style="padding: 8px 0; text-align: right; color: #dc2626; font-weight: 500;">
${formatDate(invoice.due_date)}
</td>
</tr>
<tr>
<td colspan="2" style="padding: 15px 0 8px 0; border-top: 1px solid #e5e7eb;"></td>
</tr>
<tr>
<td style="padding: 8px 0; color: #666; font-size: 14px;">Ursprungligt belopp:</td>
<td style="padding: 8px 0; text-align: right; font-weight: 500;">${formatCurrency(reminderPrincipal(invoice, company), invoice.currency)}</td>
</tr>
${hasInterest ? `
<tr>
<td style="padding: 8px 0; color: #666; font-size: 14px;">
Dröjsmålsränta (${interestRatePercent}% per år, ${interestDays} dagar):
</td>
<td style="padding: 8px 0; text-align: right; font-weight: 500;">${formatCurrency(interestAmount, invoice.currency)}</td>
</tr>
` : ''}
${hasFee ? `
<tr>
<td style="padding: 8px 0; color: #666; font-size: 14px;">Påminnelseavgift:</td>
<td style="padding: 8px 0; text-align: right; font-weight: 500;">${formatCurrency(reminderFee, REMINDER_FEE_CURRENCY)}</td>
</tr>
` : ''}
${hasSurcharges ? `
<tr>
<td colspan="2" style="padding: 12px 0 8px 0; border-top: 1px solid #e5e7eb;"></td>
</tr>
` : ''}
<tr>
<td style="padding: 8px 0; font-size: 18px; font-weight: 600;">Att betala:</td>
<td style="padding: 8px 0; text-align: right; font-size: 18px; font-weight: 600; color: ${headerColor};">
${formatReminderTotalDue(amounts)}
</td>
</tr>
${feeInOtherCurrency ? `
<tr>
<td colspan="2" style="padding: 10px 0 0 0; color: #666; font-size: 12px; line-height: 1.5;">
${REMINDER_FEE_CURRENCY_NOTE}
</td>
</tr>
` : ''}
</table>
</div>
<!-- Payment Details -->
<div style="margin-bottom: 30px;">
<h2 style="margin: 0 0 15px 0; font-size: 16px; font-weight: 600; color: #111;">
Betalningsinformation
</h2>
<table style="width: 100%; border-collapse: collapse;">
${company.bank_name ? `
<tr>
<td style="padding: 6px 0; color: #666; font-size: 14px; width: 140px;">Bank:</td>
<td style="padding: 6px 0;">${company.bank_name}</td>
</tr>
` : ''}
${company.clearing_number && company.account_number ? `
<tr>
<td style="padding: 6px 0; color: #666; font-size: 14px;">Kontonummer:</td>
<td style="padding: 6px 0;">${company.clearing_number}-${company.account_number}</td>
</tr>
` : ''}
${company.iban ? `
<tr>
<td style="padding: 6px 0; color: #666; font-size: 14px;">IBAN:</td>
<td style="padding: 6px 0;">${company.iban}</td>
</tr>
` : ''}
${company.bic ? `
<tr>
<td style="padding: 6px 0; color: #666; font-size: 14px;">BIC/SWIFT:</td>
<td style="padding: 6px 0;">${company.bic}</td>
</tr>
` : ''}
<tr>
<td style="padding: 6px 0; color: #666; font-size: 14px;">Meddelande:</td>
<td style="padding: 6px 0; font-weight: 500;">${invoice.invoice_number}</td>
</tr>
</table>
</div>
<!-- Action Buttons -->
<div style="text-align: center; margin-bottom: 30px;">
<p style="margin: 0 0 20px 0; color: #666; font-size: 14px;">
Har du redan betalat eller har frågor om fakturan?
</p>
<a href="${actionUrl}" style="display: inline-block; background: ${buttonColor}; color: white; padding: 14px 28px; border-radius: 8px; text-decoration: none; font-weight: 500; font-size: 14px;">
Hantera faktura
</a>
</div>
<!-- Footer -->
<div style="padding-top: 20px; border-top: 1px solid #e5e7eb;">
<p style="margin: 0 0 10px 0; color: #666; font-size: 14px;">
Har du frågor? Svara direkt på detta mejl så hjälper vi dig.
</p>
<p style="margin: 0; color: #666; font-size: 14px;">
Med vänliga hälsningar,<br>
<strong>${getCompanyDisplayName(company)}</strong>
</p>
${company.org_number ? `
<p style="margin: 10px 0 0 0; color: #999; font-size: 12px;">
Org.nr: ${company.org_number}
${company.vat_number ? ` | VAT: ${company.vat_number}` : ''}
</p>
` : ''}
</div>
</div>
<!-- Unsubscribe note -->
<p style="text-align: center; margin-top: 20px; color: #999; font-size: 12px;">
Detta är ett automatiskt meddelande angående en obetald faktura.
</p>
</div>
</body>
</html>
`
}
/**
* Generate plain text email for payment reminder
*/
export function generateReminderEmailText(data: ReminderEmailData): string {
const {
invoice,
customer,
reminderLevel,
daysOverdue,
actionUrl,
interestAmount,
interestRate,
interestDays,
reminderFee,
} = data
// Payment details follow the invoice currency, same as the invoice email
// and PDF: a EUR reminder must never print the SEK account's IBAN.
const company = companyWithInvoicePaymentAccount(data.company, invoice.currency, invoice.payment_details ?? null)
const config = REMINDER_CONFIG[reminderLevel]
const interestRatePercent = (interestRate * 100).toLocaleString('sv-SE', {
minimumFractionDigits: 0,
maximumFractionDigits: 2,
})
const hasInterest = interestAmount > 0
const hasFee = reminderFee > 0
const amounts = calculateReminderAmounts({
invoiceTotal: reminderPrincipal(invoice, company),
interestAmount,
reminderFee,
currency: invoice.currency,
})
let text = `${config.title.toUpperCase()}\n`
text += `Faktura ${invoice.invoice_number} förföll för ${daysOverdue} dagar sedan\n`
text += `=`.repeat(50) + `\n\n`
text += `Hej${customer.name ? ` ${customer.name.split(' ')[0]}` : ''},\n\n`
text += `${resolveReminderBody(data)}\n\n`
text += `Fakturasammanfattning:\n`
text += `-`.repeat(30) + `\n`
text += `Fakturanummer: ${invoice.invoice_number}\n`
text += `Fakturadatum: ${formatDate(invoice.invoice_date)}\n`
text += `Förfallodatum: ${formatDate(invoice.due_date)}\n`
text += `Ursprungligt belopp: ${formatCurrency(reminderPrincipal(invoice, company), invoice.currency)}\n`
if (hasInterest) {
text += `Dröjsmålsränta (${interestRatePercent}% per år, ${interestDays} dagar): ${formatCurrency(interestAmount, invoice.currency)}\n`
}
if (hasFee) {
text += `Påminnelseavgift: ${formatCurrency(reminderFee, REMINDER_FEE_CURRENCY)}\n`
}
text += `Att betala: ${formatReminderTotalDue(amounts)}\n`
text += `-`.repeat(30) + `\n`
if (amounts.feeDueSeparately > 0) {
text += `${REMINDER_FEE_CURRENCY_NOTE}\n`
}
text += `\n`
text += `Betalningsinformation:\n`
if (company.bank_name) text += `Bank: ${company.bank_name}\n`
if (company.clearing_number && company.account_number) {
text += `Kontonummer: ${company.clearing_number}-${company.account_number}\n`
}
if (company.iban) text += `IBAN: ${company.iban}\n`
if (company.bic) text += `BIC/SWIFT: ${company.bic}\n`
text += `Meddelande: ${invoice.invoice_number}\n\n`
text += `Har du redan betalat eller har frågor om fakturan?\n`
text += `Hantera faktura: ${actionUrl}\n\n`
text += `Har du frågor? Svara direkt på detta mejl så hjälper vi dig.\n\n`
text += `Med vänliga hälsningar,\n`
text += `${getCompanyDisplayName(company)}\n`
if (company.org_number) {
text += `\nOrg.nr: ${company.org_number}`
if (company.vat_number) text += ` | VAT: ${company.vat_number}`
text += `\n`
}
return text
}
/**
* Generate email subject for payment reminder.
*
* When dröjsmålsränta or påminnelseavgift apply we surface them in the
* subject so the customer sees the true amount to pay before opening
* the email.
*/
export function generateReminderEmailSubject(data: ReminderEmailData): string {
const { company, reminderLevel, interestAmount, reminderFee } = data
const hasSurcharges = interestAmount > 0 || reminderFee > 0
// {belopp} comes from formatReminderTotalDue: a SEK fee on a foreign-currency
// invoice renders as "1 010,00 € + 60 kr", two amounts in two currencies,
// never one mixed scalar.
const values = buildReminderPlaceholderValues(data)
const custom = resolveReminderTexts(company, reminderLevel, values)
if (custom.subject !== undefined) {
// An override owns the whole line: no automatic surcharge suffix.
return sanitizeSubjectLine(custom.subject)
}
const suffix = hasSurcharges ? ' (inkl. dröjsmålsränta)' : ''
const stock = applyPlaceholders(
REMINDER_EMAIL_DEFAULT_TEXTS[levelKey(reminderLevel)].subject,
values,
)
return sanitizeSubjectLine(`${stock}${suffix}`)
}
/**
* Get the number of days after due date for each reminder level
*/
export type ReminderDaysConfig = Record<1 | 2 | 3, number>
type ReminderDaysSettings = Partial<
Pick<
CompanySettings,
'reminder_days_level_1' | 'reminder_days_level_2' | 'reminder_days_level_3'
>
>
export function getReminderDaysConfig(
settings?: ReminderDaysSettings | null,
): ReminderDaysConfig {
const defaults: ReminderDaysConfig = {
1: REMINDER_CONFIG[1].daysAfterDue,
2: REMINDER_CONFIG[2].daysAfterDue,
3: REMINDER_CONFIG[3].daysAfterDue,
}
const configured: ReminderDaysConfig = {
1: settings?.reminder_days_level_1 ?? defaults[1],
2: settings?.reminder_days_level_2 ?? defaults[2],
3: settings?.reminder_days_level_3 ?? defaults[3],
}
const valid =
Object.values(configured).every((days) => Number.isInteger(days) && days >= 1 && days <= 365)
&& configured[1] < configured[2]
&& configured[2] < configured[3]
return valid ? configured : defaults
}