Files
accounted/lib/invoices/__tests__/reminder-processor.test.ts
T
Jakob WennbergandClaude Opus 4.7 cc351158f8 Invoicing & account-security polish bundle (#550)
* feat: invoicing & account-security polish bundle

Five independent improvements bundled to ship together:

- BankID/password lockout fix: BankID-only users could enroll MFA and
  brick themselves (Supabase requires AAL2 to change password or unenroll
  MFA, and AAL2 needs a password sign-in). New app_metadata.has_password
  flag tracks this; middleware gates /mfa/enroll behind it, /account/set-
  password is the unlock path, SecuritySettings shows a banner, and
  /api/account/password is the single write path that flips the flag.
  Backfill script for existing users.

- Swish invoice payment method: company_settings.swish + invoice_show_swish
  columns, validation in lib/api/schemas.ts (accepts 123XXXXXXX företag or
  07XXXXXXXX mobile, strips whitespace/hyphens), rendered on invoice PDFs.

- Send-reminders kill switch: per-company company_settings.send_invoice_
  reminders toggle in PdfPrintSettings/Automatisering. Reminder processor
  also tightened: positive status allowlist (sent + overdue) so terminal
  statuses can never match; skip when customer already responded via
  reminder link; race-window re-check before send.

- First-invoice logo prompt: one-shot dialog when creating the first
  invoice without a logo (issue #520). Self-limits via head-only count.

- SIE export opening-balance fallback: route IB through getOpeningBalances
  so the compute_prior_opening_balances RPC supplies #IB after multi-year
  imports where opening_balance_entry_id is intentionally NULL. Previously
  #IB silently went to zero and #UB collapsed to current-period movements.

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

* fix(account-polish): address PR review feedback

- BankID-link path (extensions/general/tic/index.ts): read-merge-write
  app_metadata instead of passing { bankid_linked: true } alone.
  updateUserById REPLACES app_metadata wholesale, so the previous code
  would have wiped has_password for any user who later linked BankID,
  causing the set-password banner to (incorrectly) reappear and blocking
  the standard MFA enrollment button. The comment is now corrected.

- Middleware (lib/supabase/middleware.ts): thread inner returnTo through
  the /mfa/enroll → /account/set-password redirect so the user lands on
  their original destination after the full chain completes, not on /.

- safeReturnTo helper (lib/auth/safe-return-to.ts): replace the
  starts-with-/-but-not-// guard on mfa/enroll and set-password pages.
  The previous guard let /\evil.com and /@evil.com through. The new
  helper parses against a synthetic base origin and verifies it matches.

- set-password page (app/(auth)/account/set-password/page.tsx): remove
  CLAUDE.md design system violations — bg-gradient-to-b on page bg,
  inline shadow-md style on the card, space-y-5, font-medium on the h1,
  rounded-xl on the card. Flat surface, hairline border, font-display
  h1 per the design tokens.

- Swish dedup (lib/payments/swish.ts): extract normaliseSwish() and
  isValidSwish() helpers and use them in lib/api/schemas.ts,
  components/settings/BankDetailsForm.tsx, and the invoicing settings
  page. Single source of truth for the regex.

- Password route (app/api/account/password/route.ts): emit a structured
  success log so the audit pipeline can detect password-set events, not
  just failures.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 16:44:09 +02:00

140 lines
4.1 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/service', () => ({
getEmailService: () => ({
sendEmail: vi.fn().mockResolvedValue({ success: true }),
}),
}))
import {
processOverdueReminders,
determineReminderLevel,
calculateDaysOverdue,
} from '../reminder-processor'
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()
})
})
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')
})
})