Files
accounted/lib/email/reminder-templates.ts
T
MattssonandClaude Opus 4.7 32d9978f1b Fix/chrome pdf preview csp (#572)
* feat: add option to exclude year-end closing entries in SIE export and related reports

* delete docs

* fix: allow Chrome's PDF viewer in verifikat document preview

The /api/documents/:id/inline route shipped with
`object-src 'none'` in its CSP, which blocked Chrome's built-in PDF
viewer (it renders inline PDFs via an internal <embed>). Users on
Chrome saw "Det här innehållet har blockerats" when expanding a PDF
attachment in the bookkeeping view; Firefox (PDF.js) and Edge (own
viewer) were unaffected, and JPGs worked because <img> isn't subject
to object-src.

Drops the CSP for this route to the minimum needed for embeddability:
`frame-ancestors 'self'`. X-Content-Type-Options: nosniff plus the
fixed Content-Type from the handler already block MIME confusion;
X-Frame-Options: SAMEORIGIN + frame-ancestors still block clickjacking.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(auth): add webmail deep link to email confirmation screens

Mirrors Stripe's signup UX: after asking the user to verify their email,
detect their webmail provider from the domain and show a button that
opens the inbox in a new tab. Gmail gets a from:<sender> search
pre-populated; Outlook/Yahoo/iCloud/Proton open the inbox directly.
Unknown / custom domains fall back to the existing copy.

Sender address is configurable via NEXT_PUBLIC_BRANDING_AUTH_EMAIL_FROM
(default noreply@gnubok.se) so white-label installs can match their
Supabase Auth SMTP config.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(auth): unblock first-time password set for BankID users with MFA

Supabase rejects updateUser({password}) and mfa.unenroll with "AAL2 session
is required" whenever a TOTP factor is enrolled. BankID magic-link logins
produce AAL1, and middleware skips MFA enforcement for bankid_linked users,
so they had no path to AAL2 — leaving them unable to set a backup password
or disable MFA without going through the email-recovery escape hatch.

- /api/account/password: branch on app_metadata.has_password. First-time set
  writes via service.auth.admin.updateUserById (no existing credential to
  protect, AAL2 guard does not apply). Change-password keeps the user-session
  updateUser so AAL2 still fires for credential rotation.
- /mfa/verify: accept a safeReturnTo query param and route there after
  successful verify, so step-up flows can land back where they came from.
- SecuritySettings: detect the AAL2 error from both change-password and
  mfa.unenroll and redirect through /mfa/verify?returnTo=/settings/account
  instead of toasting a dead-end error.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* Add tests and rounding utility for öre precision in bokslut calculations

- Implemented `roundOre` function for rounding SEK amounts to two decimal places, ensuring consistent monetary calculations.
- Introduced `ORE_TOLERANCE` constant for comparing rounded amounts, facilitating invariant checks in financial entries.
- Created comprehensive tests for `roundOre`, covering typical cases, edge cases, and idempotency.
- Added year-end invariants tests to verify database-level guarantees for closing entries, ensuring they balance to the öre and reject discrepancies.
- Developed end-to-end tests for the dispositions chain, validating the correctness of calculations across various scenarios.

* fix: update PDF rendering to remove Swish QR code generation and set default to disable Swish visibility

* fix: enhance security by rejecting data URIs in safeReturnTo function tests

* fix: improve rounding logic in roundOre function and add customer_type migration

* fix: add customer_type column to customers and enforce CHECK constraint

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 22:29:41 +02:00

365 lines
14 KiB
TypeScript

import type { Invoice, Customer, CompanySettings } from '@/types'
import { formatCurrency, formatDate, getCompanyDisplayName, getCompanyPrimaryName } from '@/lib/utils'
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: number
interestRate: number // annual rate as decimal (0.105 = 10.5%)
interestFromDate: string
interestDays: number
reminderFee: number
totalDue: number // invoice.total + interestAmount + reminderFee
}
// 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
/**
* Generate HTML email for payment reminder
*/
export function generateReminderEmailHtml(data: ReminderEmailData): string {
const {
invoice,
customer,
company,
reminderLevel,
daysOverdue,
actionUrl,
interestAmount,
interestRate,
interestDays,
reminderFee,
totalDue,
} = data
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
// 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>
${reminderLevel === 1 ? `
<p style="margin: 0 0 15px 0;">
Vi vill påminna dig om att faktura ${invoice.invoice_number} förföll till betalning den ${formatDate(invoice.due_date)}.
Om du redan har betalat kan du bortse från denna påminnelse.
</p>
` : reminderLevel === 2 ? `
<p style="margin: 0 0 15px 0;">
Trots vår tidigare påminnelse har vi ännu inte mottagit betalning för faktura ${invoice.invoice_number}
som förföll den ${formatDate(invoice.due_date)}.
</p>
<p style="margin: 0 0 15px 0;">
Vi ber dig vänligen att omgående reglera detta belopp för att undvika ytterligare åtgärder.
</p>
` : `
<p style="margin: 0 0 15px 0; color: #dc2626; font-weight: 500;">
Detta är vår slutliga påminnelse gällande faktura ${invoice.invoice_number}.
</p>
<p style="margin: 0 0 15px 0;">
Fakturan förföll till betalning den ${formatDate(invoice.due_date)} och vi har ännu inte mottagit betalning
trots tidigare påminnelser.
</p>
<p style="margin: 0 0 15px 0;">
Om betalning inte inkommer inom 7 dagar kommer ärendet att överlämnas för vidare hantering.
</p>
`}
</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(invoice.total, 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, invoice.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};">
${formatCurrency(totalDue, invoice.currency)}
</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>${getCompanyPrimaryName(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,
company,
reminderLevel,
daysOverdue,
actionUrl,
interestAmount,
interestRate,
interestDays,
reminderFee,
totalDue,
} = data
const config = REMINDER_CONFIG[reminderLevel]
const interestRatePercent = (interestRate * 100).toLocaleString('sv-SE', {
minimumFractionDigits: 0,
maximumFractionDigits: 2,
})
const hasInterest = interestAmount > 0
const hasFee = reminderFee > 0
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`
if (reminderLevel === 1) {
text += `Vi vill påminna dig om att faktura ${invoice.invoice_number} förföll till betalning den ${formatDate(invoice.due_date)}.\n`
text += `Om du redan har betalat kan du bortse från denna påminnelse.\n\n`
} else if (reminderLevel === 2) {
text += `Trots vår tidigare påminnelse har vi ännu inte mottagit betalning för faktura ${invoice.invoice_number} som förföll den ${formatDate(invoice.due_date)}.\n\n`
text += `Vi ber dig vänligen att omgående reglera detta belopp för att undvika ytterligare åtgärder.\n\n`
} else {
text += `DETTA ÄR VÅR SLUTLIGA PÅMINNELSE\n\n`
text += `Fakturan förföll till betalning den ${formatDate(invoice.due_date)} och vi har ännu inte mottagit betalning trots tidigare påminnelser.\n\n`
text += `Om betalning inte inkommer inom 7 dagar kommer ärendet att överlämnas för vidare hantering.\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(invoice.total, 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, invoice.currency)}\n`
}
text += `Att betala: ${formatCurrency(totalDue, invoice.currency)}\n`
text += `-`.repeat(30) + `\n\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 { invoice, reminderLevel, totalDue, interestAmount, reminderFee } = data
const config = REMINDER_CONFIG[reminderLevel]
const hasSurcharges = interestAmount > 0 || reminderFee > 0
const amount = hasSurcharges ? totalDue : invoice.total
const suffix = hasSurcharges ? ' (inkl. dröjsmålsränta)' : ''
return `${config.title}: Faktura ${invoice.invoice_number} - ${formatCurrency(amount, invoice.currency)}${suffix}`
}
/**
* Get the number of days after due date for each reminder level
*/
export function getReminderDaysConfig(): Record<1 | 2 | 3, number> {
return {
1: REMINDER_CONFIG[1].daysAfterDue,
2: REMINDER_CONFIG[2].daysAfterDue,
3: REMINDER_CONFIG[3].daysAfterDue
}
}