Files
accounted/lib/invoices/__tests__/reminder-processor.test.ts
T
MattssonandClaude Fable 5 0040cadacc feat(invoicing): opt-in invoice email from the company's own sending domain (#1802)
* feat(invoicing): opt-in invoice email from the company's own sending domain

Companies holding the custom_sender_domain capability grant can register
their own domain (Resend sending-only profile), publish DKIM/SPF, and once
verified every invoice email (send, reminders, recurring, payment
confirmation, MCP/v1 sends) leaves as "<name> <faktura@their-domain>"
instead of the platform sender. Reply-To is unchanged.

- New table company_sending_domains (RLS: members read, owner/admin write;
  audit trigger), types, archive-export classification.
- New capability key custom_sender_domain: manually granted per company,
  deliberately outside PAID_CAPABILITIES (never trial-seeded, never written
  by the Stripe sync). Without the grant the settings section is hidden and
  nothing changes.
- Email extension: sending-domain routes (GET/POST/PATCH/DELETE, verify),
  Resend domain lifecycle without orphan adoption, domain.updated handling
  on the delivery webhook, explicit From support in the Resend adapter.
- Core resolveInvoiceSender(): verified + enabled + entitled, else the
  platform sender; never throws.
- Settings -> Invoicing: "Avsändare vid fakturautskick" section (sv/en).
- Unit tests for the resolver, domain helpers, routes, From header; pg-real
  test for RLS and constraints.

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

* fix(invoicing): harden sending-domain writes, sender fallback, review findings

Skeptic refutations:
- Tenant JWTs could insert/update company_sending_domains with status =
  'verified' and an arbitrary domain through PostgREST (RLS only checked
  membership), then send invoice mail as that domain. New migration
  20260822130000 adds a BEFORE trigger: tenants may only open a pending
  claim and edit sender_local_part/sender_name/enabled; domain and
  verification state are service-role only. claim/verify helpers now take
  a service-role writer for those columns; the route's RLS client still
  does the insert.
- A company domain Resend later rejects made every invoice send fail: the
  Resend adapter retries once as the platform sender when an explicit
  company From is rejected (nothing was sent, so no double send).

Review findings:
- domain.updated webhook: discriminated outcome; DB errors answer 500 so
  Svix retries, unknown domains are acknowledged.
- Display names are RFC 5322-quoted only when they carry specials.
- Sender local part is a strict dot-atom (no trailing/consecutive dots),
  in code and in the CHECK constraint; resend_domain_id index is UNIQUE.
- IME composition guard on the claim input; event bus reset in tests;
  settings section skips its request for non-admins.

Deferred (needs a product call): persisting the effective From address in
the invoice delivery log touches the hardened evidence triggers; recorded
in DECISIONS.md.

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

* fix(invoicing): bind sending-domain verification to the claimed domain; fix pg test

Skeptic re-check found a TOCTOU: during the claim's Resend round-trip a
tenant could delete and re-insert its pending row under the same id with a
reserved domain, and the service-role writer updated by id alone. Now:
- the claim's verification-state write filters on (id, company_id, domain,
  resend_domain_id IS NULL) and rolls back on zero rows;
- verify and the domain.updated webhook compare Resend's domain name with
  the row before writing verified;
- resolveInvoiceSender refuses reserved platform domains and non-hostnames
  at send time (reserved-domain logic moved to lib/email/domain-name.ts and
  shared with the claim validator).

pg-real: the case-insensitive uniqueness assertion now expects the
domain_shape CHECK (lowercase enforced) for an uppercase variant and the
unique index for a same-case duplicate.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-23 00:07:30 +02:00

176 lines
5.3 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest'
const chainCalls: Array<{ method: string; args: unknown[] }> = []
vi.mock('@supabase/ssr', () => {
const buildChain = (): unknown =>
new Proxy(
{},
{
get(_t, prop) {
if (prop === 'then') {
return (resolve: (v: unknown) => void) =>
resolve({ data: [], error: null, count: null })
}
return (...args: unknown[]) => {
chainCalls.push({ method: String(prop), args })
return buildChain()
}
},
},
)
return {
createServerClient: vi.fn(() => ({
from: vi.fn(() => buildChain()),
rpc: vi.fn(() => buildChain()),
})),
}
})
vi.mock('@/lib/email/invoice-sender', () => ({
resolveInvoiceSender: vi.fn().mockResolvedValue(undefined),
}))
vi.mock('@/lib/email/service', () => ({
getEmailService: () => ({
sendEmail: vi.fn().mockResolvedValue({ success: true }),
}),
}))
import {
processOverdueReminders,
determineReminderLevel,
calculateDaysOverdue,
} from '../reminder-processor'
import { getReminderDaysConfig } from '@/lib/email/reminder-templates'
describe('determineReminderLevel', () => {
it('returns null below the level-1 threshold', () => {
expect(determineReminderLevel(10, [])).toBeNull()
})
it('returns 1 at 15 days overdue', () => {
expect(determineReminderLevel(15, [])).toBe(1)
})
it('returns 2 at 30 days when level 1 already sent', () => {
expect(determineReminderLevel(30, [1])).toBe(2)
})
it('returns 3 at 45 days when 1 and 2 already sent', () => {
expect(determineReminderLevel(45, [1, 2])).toBe(3)
})
it('returns null when all levels have been sent', () => {
expect(determineReminderLevel(60, [1, 2, 3])).toBeNull()
})
it('uses a company-specific schedule', () => {
const config = { 1: 7, 2: 21, 3: 35 } as const
expect(determineReminderLevel(6, [], config)).toBeNull()
expect(determineReminderLevel(7, [], config)).toBe(1)
expect(determineReminderLevel(21, [1], config)).toBe(2)
expect(determineReminderLevel(35, [1, 2], config)).toBe(3)
})
})
describe('getReminderDaysConfig', () => {
it('returns the existing defaults when no company settings are supplied', () => {
expect(getReminderDaysConfig()).toEqual({ 1: 15, 2: 30, 3: 45 })
})
it('returns configured company thresholds', () => {
expect(getReminderDaysConfig({
reminder_days_level_1: 5,
reminder_days_level_2: 10,
reminder_days_level_3: 20,
})).toEqual({ 1: 5, 2: 10, 3: 20 })
})
it('falls back to defaults for an invalid stored schedule', () => {
expect(getReminderDaysConfig({
reminder_days_level_1: 30,
reminder_days_level_2: 20,
reminder_days_level_3: 45,
})).toEqual({ 1: 15, 2: 30, 3: 45 })
})
})
describe('calculateDaysOverdue', () => {
it('returns a positive number for a past due date', () => {
const tenDaysAgo = new Date()
tenDaysAgo.setDate(tenDaysAgo.getDate() - 10)
const days = calculateDaysOverdue(tenDaysAgo.toISOString().split('T')[0])
expect(days).toBeGreaterThanOrEqual(9)
expect(days).toBeLessThanOrEqual(10)
})
})
describe('processOverdueReminders: credit-note filter', () => {
beforeEach(() => {
chainCalls.length = 0
})
it('excludes credit notes via .is("credited_invoice_id", null)', async () => {
await processOverdueReminders()
const isCall = chainCalls.find(
(c) => c.method === 'is' && c.args[0] === 'credited_invoice_id',
)
expect(
isCall,
'overdue-invoice query must filter out credit notes: credit notes have a negative total and must never trigger a payment reminder (e.g. KR-F2026002)',
).toBeDefined()
expect(isCall?.args[1]).toBeNull()
})
it('combines the credit-note filter with status allowlist and due_date cutoff', async () => {
await processOverdueReminders()
const inStatus = chainCalls.find(
(c) => c.method === 'in' && c.args[0] === 'status',
)
const isCreditedNull = chainCalls.find(
(c) => c.method === 'is' && c.args[0] === 'credited_invoice_id',
)
const lteDueDate = chainCalls.find(
(c) => c.method === 'lte' && c.args[0] === 'due_date',
)
expect(inStatus?.args[1]).toEqual(['sent', 'overdue'])
expect(isCreditedNull?.args[1]).toBeNull()
expect(lteDueDate).toBeDefined()
})
it('uses a positive allowlist (sent + overdue) so paid / partially_paid / cancelled / credited can never match', async () => {
await processOverdueReminders()
const inStatus = chainCalls.find(
(c) => c.method === 'in' && c.args[0] === 'status',
)
expect(inStatus?.args[1]).toEqual(['sent', 'overdue'])
// Defense in depth: ensure no .eq('status', terminal) somehow snuck in.
const eqTerminal = chainCalls.find(
(c) =>
c.method === 'eq' &&
c.args[0] === 'status' &&
['paid', 'partially_paid', 'cancelled', 'credited'].includes(
c.args[1] as string,
),
)
expect(eqTerminal).toBeUndefined()
})
it('includes overdue in the allowlist so level-2 and level-3 reminders re-fire after the first reminder flips status', async () => {
await processOverdueReminders()
const inStatus = chainCalls.find(
(c) => c.method === 'in' && c.args[0] === 'status',
)
expect(inStatus?.args[1]).toContain('overdue')
})
})