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>
This commit is contained in:
co-authored by
Claude Opus 4.7
parent
2879f6ed17
commit
cc351158f8
@@ -1129,6 +1129,48 @@ describe('UpdateSettingsSchema', () => {
|
||||
const result = UpdateSettingsSchema.safeParse({ invoice_default_days: 30.5 })
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
|
||||
describe('swish', () => {
|
||||
it('accepts a Swish-företag number (123XXXXXXX)', () => {
|
||||
const result = UpdateSettingsSchema.safeParse({ swish: '1234567890' })
|
||||
expect(result.success).toBe(true)
|
||||
if (result.success) expect(result.data.swish).toBe('1234567890')
|
||||
})
|
||||
|
||||
it('accepts a Swedish mobile number (07XXXXXXXX)', () => {
|
||||
const result = UpdateSettingsSchema.safeParse({ swish: '0701234567' })
|
||||
expect(result.success).toBe(true)
|
||||
if (result.success) expect(result.data.swish).toBe('0701234567')
|
||||
})
|
||||
|
||||
it('strips whitespace and hyphens before validating', () => {
|
||||
const result = UpdateSettingsSchema.safeParse({ swish: '123 456 78 90' })
|
||||
expect(result.success).toBe(true)
|
||||
if (result.success) expect(result.data.swish).toBe('1234567890')
|
||||
})
|
||||
|
||||
it('rejects a non-Swish-företag, non-mobile number', () => {
|
||||
const result = UpdateSettingsSchema.safeParse({ swish: '0123456789' })
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
|
||||
it('accepts empty string for clearing the value', () => {
|
||||
const result = UpdateSettingsSchema.safeParse({ swish: '' })
|
||||
expect(result.success).toBe(true)
|
||||
})
|
||||
|
||||
it('accepts invoice_show_swish toggle', () => {
|
||||
const result = UpdateSettingsSchema.safeParse({ invoice_show_swish: false })
|
||||
expect(result.success).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('send_invoice_reminders', () => {
|
||||
it('accepts the kill-switch toggle', () => {
|
||||
const result = UpdateSettingsSchema.safeParse({ send_invoice_reminders: false })
|
||||
expect(result.success).toBe(true)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
// ============================================================
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from 'zod'
|
||||
import { normaliseSwish, isValidSwish } from '@/lib/payments/swish'
|
||||
|
||||
// ============================================================
|
||||
// Shared primitives
|
||||
@@ -481,6 +482,16 @@ export const UpdateSettingsSchema = z.object({
|
||||
account_number: z.string().regex(/^\d{6,12}$/, 'Kontonummer måste vara 6-12 siffror').optional().or(z.literal('')),
|
||||
bankgiro: z.string().regex(/^(\d{3,4}-\d{4}|\d{7,8})$/, 'Ogiltigt bankgironummer (7-8 siffror)').nullable().optional().or(z.literal('')),
|
||||
plusgiro: z.string().regex(/^\d{1,7}-\d{1}$/, 'Ogiltigt plusgironummer').nullable().optional().or(z.literal('')),
|
||||
swish: z.string()
|
||||
.transform(normaliseSwish)
|
||||
.pipe(
|
||||
z.string().refine(
|
||||
isValidSwish,
|
||||
'Ogiltigt Swish-nummer (företagsnummer 123XXXXXXX eller mobilnummer 07XXXXXXXX)',
|
||||
),
|
||||
)
|
||||
.nullable()
|
||||
.optional(),
|
||||
iban: z.string().optional(),
|
||||
bic: z.string().optional(),
|
||||
accounting_method: AccountingMethodSchema.optional(),
|
||||
@@ -503,11 +514,14 @@ export const UpdateSettingsSchema = z.object({
|
||||
invoice_show_ocr: z.boolean().optional(),
|
||||
invoice_show_bankgiro: z.boolean().optional(),
|
||||
invoice_show_plusgiro: z.boolean().optional(),
|
||||
invoice_show_swish: z.boolean().optional(),
|
||||
invoice_show_logo: z.boolean().optional(),
|
||||
invoice_show_company_name: z.boolean().optional(),
|
||||
invoice_company_name_position: z.enum(['header', 'footer']).optional(),
|
||||
invoice_late_fee_text: z.string().nullable().optional(),
|
||||
invoice_credit_terms_text: z.string().nullable().optional(),
|
||||
// Automation
|
||||
send_invoice_reminders: z.boolean().optional(),
|
||||
// AI agent flow
|
||||
ai_flow_enabled: z.boolean().optional(),
|
||||
// Salary payment file
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { userHasPassword } from '../has-password'
|
||||
|
||||
describe('userHasPassword', () => {
|
||||
it('returns true when has_password === true', () => {
|
||||
expect(userHasPassword({ app_metadata: { has_password: true } })).toBe(true)
|
||||
})
|
||||
|
||||
it('returns false when has_password === false', () => {
|
||||
expect(userHasPassword({ app_metadata: { has_password: false } })).toBe(false)
|
||||
})
|
||||
|
||||
it('returns false when flag is missing but bankid_linked === true', () => {
|
||||
expect(userHasPassword({ app_metadata: { bankid_linked: true } })).toBe(false)
|
||||
})
|
||||
|
||||
it('returns true when flag is missing and bankid_linked is not true (legacy email/password user)', () => {
|
||||
expect(userHasPassword({ app_metadata: {} })).toBe(true)
|
||||
expect(userHasPassword({ app_metadata: { bankid_linked: false } })).toBe(true)
|
||||
})
|
||||
|
||||
it('returns true when app_metadata is missing entirely', () => {
|
||||
expect(userHasPassword({ app_metadata: undefined as unknown as Record<string, unknown> })).toBe(true)
|
||||
})
|
||||
|
||||
it('prefers explicit has_password over bankid_linked (BankID user who later set a password)', () => {
|
||||
expect(
|
||||
userHasPassword({ app_metadata: { bankid_linked: true, has_password: true } }),
|
||||
).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { safeReturnTo } from '../safe-return-to'
|
||||
|
||||
describe('safeReturnTo', () => {
|
||||
it('returns the value when it is a same-origin relative path', () => {
|
||||
expect(safeReturnTo('/settings/account', '/')).toBe('/settings/account')
|
||||
expect(safeReturnTo('/invoices/new', '/')).toBe('/invoices/new')
|
||||
})
|
||||
|
||||
it('preserves search and hash', () => {
|
||||
expect(safeReturnTo('/invoices?status=overdue', '/')).toBe('/invoices?status=overdue')
|
||||
expect(safeReturnTo('/settings/account#mfa', '/')).toBe('/settings/account#mfa')
|
||||
})
|
||||
|
||||
it('returns the fallback for missing or empty values', () => {
|
||||
expect(safeReturnTo(null, '/home')).toBe('/home')
|
||||
expect(safeReturnTo(undefined, '/home')).toBe('/home')
|
||||
expect(safeReturnTo('', '/home')).toBe('/home')
|
||||
})
|
||||
|
||||
it('rejects absolute URLs', () => {
|
||||
expect(safeReturnTo('https://evil.com/path', '/')).toBe('/')
|
||||
expect(safeReturnTo('http://evil.com', '/')).toBe('/')
|
||||
})
|
||||
|
||||
it('rejects protocol-relative URLs', () => {
|
||||
expect(safeReturnTo('//evil.com/path', '/')).toBe('/')
|
||||
})
|
||||
|
||||
it('rejects the /\\evil.com browser-quirk form', () => {
|
||||
expect(safeReturnTo('/\\evil.com', '/')).toBe('/')
|
||||
})
|
||||
|
||||
it('rejects the /@user@host form some clients resolve off-origin', () => {
|
||||
expect(safeReturnTo('/@evil.com', '/')).toBe('/')
|
||||
})
|
||||
|
||||
it('rejects values that do not start with /', () => {
|
||||
expect(safeReturnTo('settings', '/')).toBe('/')
|
||||
expect(safeReturnTo('javascript:alert(1)', '/')).toBe('/')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { User } from '@supabase/supabase-js'
|
||||
|
||||
/**
|
||||
* True iff the user has set a password they actually know.
|
||||
*
|
||||
* Source of truth: `app_metadata.has_password` (server-only, set by us — clients
|
||||
* cannot fake it through `updateUser`).
|
||||
*
|
||||
* - BankID signup writes `has_password: false` (they got a random server-side
|
||||
* password they will never see).
|
||||
* - Email/password signup doesn't set the flag — we infer `true` because the
|
||||
* user supplied a password to reach signUp at all.
|
||||
* - The flag flips to `true` after a successful POST /api/account/password.
|
||||
*/
|
||||
export function userHasPassword(user: Pick<User, 'app_metadata'>): boolean {
|
||||
const meta = user.app_metadata ?? {}
|
||||
if (meta.has_password === true) return true
|
||||
if (meta.has_password === false) return false
|
||||
return meta.bankid_linked !== true
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Validate that a returnTo query param is a same-origin relative path.
|
||||
*
|
||||
* The previous guard only rejected protocol-relative URLs (`//evil.com`),
|
||||
* but `/\evil.com`, `/?@evil.com`, and various other forms can still
|
||||
* redirect off-origin in some browsers. Parse with a real URL and verify
|
||||
* the origin matches.
|
||||
*
|
||||
* Returns the normalised path-with-search-and-hash on success, or the
|
||||
* provided `fallback` if `value` is missing, malformed, or off-origin.
|
||||
*/
|
||||
export function safeReturnTo(value: string | null | undefined, fallback: string): string {
|
||||
if (!value) return fallback
|
||||
if (!value.startsWith('/')) return fallback
|
||||
// Reject protocol-relative and the two known browser-quirk forms.
|
||||
if (value.startsWith('//') || value.startsWith('/\\') || value.startsWith('/@')) {
|
||||
return fallback
|
||||
}
|
||||
try {
|
||||
const base = 'https://gnubok.invalid'
|
||||
const parsed = new URL(value, base)
|
||||
if (parsed.origin !== base) return fallback
|
||||
return parsed.pathname + parsed.search + parsed.hash
|
||||
} catch {
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
@@ -91,11 +91,11 @@ describe('processOverdueReminders — credit-note filter', () => {
|
||||
expect(isCall?.args[1]).toBeNull()
|
||||
})
|
||||
|
||||
it('combines the credit-note filter with status=sent and due_date cutoff', async () => {
|
||||
it('combines the credit-note filter with status allowlist and due_date cutoff', async () => {
|
||||
await processOverdueReminders()
|
||||
|
||||
const eqStatus = chainCalls.find(
|
||||
(c) => c.method === 'eq' && c.args[0] === 'status',
|
||||
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',
|
||||
@@ -104,8 +104,36 @@ describe('processOverdueReminders — credit-note filter', () => {
|
||||
(c) => c.method === 'lte' && c.args[0] === 'due_date',
|
||||
)
|
||||
|
||||
expect(eqStatus?.args[1]).toBe('sent')
|
||||
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')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -609,6 +609,12 @@ export function InvoicePDF({ invoice, customer, items, company, originalInvoiceN
|
||||
<Text style={styles.paymentValue}>{company.plusgiro}</Text>
|
||||
</View>
|
||||
)}
|
||||
{company.swish && (company.invoice_show_swish ?? true) && (
|
||||
<View style={styles.paymentRow}>
|
||||
<Text style={styles.paymentLabel}>Swish:</Text>
|
||||
<Text style={styles.paymentValue}>{company.swish}</Text>
|
||||
</View>
|
||||
)}
|
||||
{company.iban && (
|
||||
<View style={styles.paymentRow}>
|
||||
<Text style={styles.paymentLabel}>IBAN:</Text>
|
||||
|
||||
@@ -136,13 +136,16 @@ export async function processOverdueReminders(): Promise<ProcessRemindersResult>
|
||||
const cutoffDate = new Date()
|
||||
cutoffDate.setDate(cutoffDate.getDate() - minOverdueDays)
|
||||
|
||||
// Positive allowlist — inherently excludes 'paid', 'partially_paid', 'cancelled', 'credited'.
|
||||
// Including 'overdue' ensures level-2 / level-3 reminders re-fire after the first reminder
|
||||
// flips status to 'overdue' (see status update below).
|
||||
const { data: overdueInvoices, error: invoiceError } = await supabase
|
||||
.from('invoices')
|
||||
.select(`
|
||||
*,
|
||||
customer:customers(*)
|
||||
`)
|
||||
.eq('status', 'sent')
|
||||
.in('status', ['sent', 'overdue'])
|
||||
.is('credited_invoice_id', null)
|
||||
.lte('due_date', cutoffDate.toISOString().split('T')[0])
|
||||
.order('due_date', { ascending: true })
|
||||
@@ -172,9 +175,21 @@ export async function processOverdueReminders(): Promise<ProcessRemindersResult>
|
||||
// Get existing reminders for this invoice
|
||||
const { data: existingReminders } = await supabase
|
||||
.from('invoice_reminders')
|
||||
.select('reminder_level')
|
||||
.select('reminder_level, response_type')
|
||||
.eq('invoice_id', invoice.id)
|
||||
|
||||
// Skip if customer already responded (marked paid OR disputed) — they've
|
||||
// told us they don't want another reminder. The business owner still needs
|
||||
// to record the actual payment (mark-paid / match-invoice) to flip status
|
||||
// and post the journal entry; we don't do that here because the customer
|
||||
// action is unauthenticated and posting a JE without a verified payment
|
||||
// would put the books out of sync.
|
||||
const customerResponded = existingReminders?.some(r => r.response_type !== null)
|
||||
if (customerResponded) {
|
||||
log.info(`Skipping invoice ${invoice.invoice_number}: customer already responded via reminder link`)
|
||||
continue
|
||||
}
|
||||
|
||||
const existingLevels = existingReminders?.map(r => r.reminder_level) || []
|
||||
const daysOverdue = calculateDaysOverdue(invoice.due_date)
|
||||
const reminderLevel = determineReminderLevel(daysOverdue, existingLevels)
|
||||
@@ -205,6 +220,26 @@ export async function processOverdueReminders(): Promise<ProcessRemindersResult>
|
||||
continue
|
||||
}
|
||||
|
||||
// Per-company kill switch (settings → Fakturering → "Skicka automatiska påminnelser")
|
||||
if (company.send_invoice_reminders === false) {
|
||||
log.info(`Skipping invoice ${invoice.invoice_number}: automatic reminders disabled for company ${invoice.company_id}`)
|
||||
continue
|
||||
}
|
||||
|
||||
// Race-window guard — re-check invoice status immediately before sending.
|
||||
// The cron runs at 08:00; a payment match arriving during the run shouldn't
|
||||
// produce a reminder for an already-paid invoice.
|
||||
const { data: currentInvoice } = await supabase
|
||||
.from('invoices')
|
||||
.select('status')
|
||||
.eq('id', invoice.id)
|
||||
.single()
|
||||
|
||||
if (!currentInvoice || !['sent', 'overdue'].includes(currentInvoice.status as string)) {
|
||||
log.info(`Skipping invoice ${invoice.invoice_number}: status changed to ${currentInvoice?.status ?? 'unknown'} mid-run`)
|
||||
continue
|
||||
}
|
||||
|
||||
// Create reminder record first (to get action token)
|
||||
const { data: reminderRecord, error: reminderError } = await supabase
|
||||
.from('invoice_reminders')
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { normaliseSwish, isValidSwish } from '../swish'
|
||||
|
||||
describe('normaliseSwish', () => {
|
||||
it('strips whitespace and hyphens', () => {
|
||||
expect(normaliseSwish('123 456 78 90')).toBe('1234567890')
|
||||
expect(normaliseSwish('070-123 45 67')).toBe('0701234567')
|
||||
expect(normaliseSwish(' 1234567890 ')).toBe('1234567890')
|
||||
})
|
||||
|
||||
it('returns empty string for null/undefined/empty', () => {
|
||||
expect(normaliseSwish(null)).toBe('')
|
||||
expect(normaliseSwish(undefined)).toBe('')
|
||||
expect(normaliseSwish('')).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('isValidSwish', () => {
|
||||
it('accepts Swish Företag numbers (123XXXXXXX)', () => {
|
||||
expect(isValidSwish('1234567890')).toBe(true)
|
||||
expect(isValidSwish('1230000000')).toBe(true)
|
||||
})
|
||||
|
||||
it('accepts Swedish mobile numbers (07XXXXXXXX)', () => {
|
||||
expect(isValidSwish('0701234567')).toBe(true)
|
||||
expect(isValidSwish('0700000000')).toBe(true)
|
||||
})
|
||||
|
||||
it('accepts empty string for clearing the field', () => {
|
||||
expect(isValidSwish('')).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects non-conforming numbers', () => {
|
||||
expect(isValidSwish('0123456789')).toBe(false)
|
||||
expect(isValidSwish('1239')).toBe(false)
|
||||
expect(isValidSwish('12345678901')).toBe(false)
|
||||
expect(isValidSwish('123abc4567')).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Swish number normalisation + validation.
|
||||
*
|
||||
* Two accepted shapes:
|
||||
* - Swish Företag: `123XXXXXXX` (10 digits starting with `123`)
|
||||
* - Swedish mobile: `07XXXXXXXX` (10 digits starting with `07`)
|
||||
*
|
||||
* Whitespace and hyphens are stripped before validation so users can paste
|
||||
* formatted numbers (`123 456 78 90` or `070-123 45 67`) and have them
|
||||
* canonicalised.
|
||||
*/
|
||||
|
||||
const SWISH_FORETAG = /^123\d{7}$/
|
||||
const SWEDISH_MOBILE = /^07\d{8}$/
|
||||
|
||||
export function normaliseSwish(value: string | null | undefined): string {
|
||||
if (!value) return ''
|
||||
return value.replace(/[\s-]/g, '')
|
||||
}
|
||||
|
||||
export function isValidSwish(normalised: string): boolean {
|
||||
return normalised === '' || SWISH_FORETAG.test(normalised) || SWEDISH_MOBILE.test(normalised)
|
||||
}
|
||||
@@ -20,6 +20,10 @@ function makeBuilder() {
|
||||
function makeClient() {
|
||||
return {
|
||||
from: vi.fn().mockImplementation(() => makeBuilder()),
|
||||
// `rpc` drains the same queue so tests can intersperse RPC + table fetches.
|
||||
// SIE export calls `compute_prior_opening_balances` via getOpeningBalances
|
||||
// whenever `opening_balance_entry_id` is null (the multi-year-import path).
|
||||
rpc: vi.fn().mockImplementation(async () => results[resultIdx++] ?? { data: null, error: null }),
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any
|
||||
}
|
||||
@@ -67,6 +71,8 @@ describe('generateSIEExport', () => {
|
||||
{ data: [], error: null },
|
||||
// 5: projects (empty)
|
||||
{ data: [], error: null },
|
||||
// 6: compute_prior_opening_balances RPC (empty — no IB)
|
||||
{ data: [], error: null },
|
||||
]
|
||||
|
||||
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
|
||||
@@ -90,6 +96,7 @@ describe('generateSIEExport', () => {
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null }, // RPC fallback
|
||||
]
|
||||
|
||||
const output = await generateSIEExport(supabase, 'company-1', {
|
||||
@@ -114,6 +121,7 @@ describe('generateSIEExport', () => {
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null }, // RPC fallback
|
||||
]
|
||||
|
||||
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
|
||||
@@ -150,6 +158,7 @@ describe('generateSIEExport', () => {
|
||||
},
|
||||
{ data: [], error: null }, // cost_centers
|
||||
{ data: [], error: null }, // projects
|
||||
{ data: [], error: null }, // RPC fallback
|
||||
]
|
||||
|
||||
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
|
||||
@@ -180,6 +189,7 @@ describe('generateSIEExport', () => {
|
||||
],
|
||||
error: null,
|
||||
},
|
||||
{ data: [], error: null }, // RPC fallback
|
||||
]
|
||||
|
||||
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
|
||||
@@ -214,6 +224,7 @@ describe('generateSIEExport', () => {
|
||||
},
|
||||
{ data: [{ code: 'CC1', name: 'Avdelning 1', is_active: true }], error: null },
|
||||
{ data: [{ code: 'P001', name: 'Projekt Alpha', is_active: true }], error: null },
|
||||
{ data: [], error: null }, // RPC fallback
|
||||
]
|
||||
|
||||
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
|
||||
@@ -247,6 +258,7 @@ describe('generateSIEExport', () => {
|
||||
},
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null }, // RPC fallback
|
||||
]
|
||||
|
||||
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
|
||||
@@ -283,6 +295,7 @@ describe('generateSIEExport', () => {
|
||||
},
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null }, // RPC fallback
|
||||
]
|
||||
|
||||
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
|
||||
@@ -298,6 +311,7 @@ describe('generateSIEExport', () => {
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null }, // RPC fallback
|
||||
]
|
||||
|
||||
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
|
||||
@@ -321,6 +335,7 @@ describe('generateSIEExport', () => {
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null }, // RPC fallback
|
||||
]
|
||||
|
||||
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
|
||||
@@ -337,6 +352,7 @@ describe('generateSIEExport', () => {
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null }, // RPC fallback
|
||||
]
|
||||
|
||||
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
|
||||
@@ -344,4 +360,67 @@ describe('generateSIEExport', () => {
|
||||
expect(output).not.toContain('#DIM')
|
||||
expect(output).not.toContain('#OBJEKT')
|
||||
})
|
||||
|
||||
it('emits #IB from compute_prior_opening_balances RPC fallback when opening_balance_entry_id is null', async () => {
|
||||
// Reproduces the user-reported bug: after a multi-year SIE import the
|
||||
// continuation-import guard intentionally leaves opening_balance_entry_id
|
||||
// NULL, and previously the SIE export silently produced zero #IB records,
|
||||
// collapsing #UB to current-period movements only. The fix wires SIE
|
||||
// export to getOpeningBalances() so the RPC backs up the missing link.
|
||||
results = [
|
||||
// period — note: no opening_balance_entry_id, so getOpeningBalances
|
||||
// falls through to the RPC path
|
||||
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31', opening_balance_entry_id: null }, error: null },
|
||||
{ data: null, error: null }, // prevPeriod
|
||||
{ data: [], error: null }, // accounts
|
||||
{ data: [], error: null }, // journal_entries (no movements this period)
|
||||
{ data: [], error: null }, // cost_centers
|
||||
{ data: [], error: null }, // projects
|
||||
// RPC fallback returns prior IBs derived from historical journal lines
|
||||
{
|
||||
data: [
|
||||
{ account_number: '1930', debit: 50000, credit: 0 },
|
||||
{ account_number: '2440', debit: 0, credit: 50000 },
|
||||
],
|
||||
error: null,
|
||||
},
|
||||
]
|
||||
|
||||
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
|
||||
|
||||
expect(output).toContain('#IB 0 1930 50000.00')
|
||||
expect(output).toContain('#IB 0 2440 -50000.00')
|
||||
// UB = IB + period movements (zero this period), so #UB mirrors #IB
|
||||
expect(output).toContain('#UB 0 1930 50000.00')
|
||||
expect(output).toContain('#UB 0 2440 -50000.00')
|
||||
})
|
||||
|
||||
it('reads #IB from explicit opening_balance_entry_id when set', async () => {
|
||||
// When opening_balance_entry_id is set, getOpeningBalances uses the
|
||||
// journal_entry_lines path (fetchAllRows) instead of the RPC, so the
|
||||
// queue here serves the line rows rather than RPC rows.
|
||||
results = [
|
||||
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31', opening_balance_entry_id: 'ob-entry-1' }, error: null },
|
||||
{ data: null, error: null }, // prevPeriod
|
||||
{ data: [], error: null }, // accounts
|
||||
{ data: [], error: null }, // journal_entries
|
||||
{ data: [], error: null }, // cost_centers
|
||||
{ data: [], error: null }, // projects
|
||||
// fetchAllRows page 1 — explicit OB entry lines
|
||||
{
|
||||
data: [
|
||||
{ account_number: '1930', debit_amount: 12000, credit_amount: 0 },
|
||||
{ account_number: '2440', debit_amount: 0, credit_amount: 12000 },
|
||||
],
|
||||
error: null,
|
||||
},
|
||||
]
|
||||
|
||||
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
|
||||
|
||||
expect(output).toContain('#IB 0 1930 12000.00')
|
||||
expect(output).toContain('#IB 0 2440 -12000.00')
|
||||
expect(output).toContain('#UB 0 1930 12000.00')
|
||||
expect(output).toContain('#UB 0 2440 -12000.00')
|
||||
})
|
||||
})
|
||||
|
||||
+16
-19
@@ -1,6 +1,7 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
||||
import { getBranding } from '@/lib/branding/service'
|
||||
import { getOpeningBalances } from './opening-balances'
|
||||
import type { SIEExportOptions, JournalEntry, JournalEntryLine, BASAccount } from '@/types'
|
||||
|
||||
function sanitizeProgramName(str: string): string {
|
||||
@@ -136,27 +137,23 @@ export async function generateSIEExport(
|
||||
}
|
||||
|
||||
// === Opening balances (IB) ===
|
||||
// Collect IB per account for UB calculation (UB = IB + movements)
|
||||
// Routes through getOpeningBalances() so we get the same fallback as trial
|
||||
// balance / balance sheet: when opening_balance_entry_id is NULL — which is
|
||||
// expected after continuation SIE imports (sie-import.ts skips creating an
|
||||
// IB entry once prior posted activity exists) — the compute_prior_opening_
|
||||
// balances RPC derives IB from earlier journal lines instead of silently
|
||||
// emitting zero #IB records and producing wrong #UB values.
|
||||
const openingBalancesByAccount = new Map<string, number>()
|
||||
const { balances: obBalances } = await getOpeningBalances(supabase, companyId, {
|
||||
period_start: period.period_start,
|
||||
opening_balance_entry_id: period.opening_balance_entry_id ?? null,
|
||||
})
|
||||
|
||||
if (period.opening_balance_entry_id) {
|
||||
const { data: obEntry } = await supabase
|
||||
.from('journal_entries')
|
||||
.select('*, lines:journal_entry_lines(*)')
|
||||
.eq('id', period.opening_balance_entry_id)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
if (obEntry?.lines) {
|
||||
for (const line of (obEntry.lines as JournalEntryLine[])) {
|
||||
const amount = (Number(line.debit_amount) || 0) - (Number(line.credit_amount) || 0)
|
||||
lines.push(`#IB 0 ${line.account_number} ${formatAmount(amount)}`)
|
||||
openingBalancesByAccount.set(
|
||||
line.account_number,
|
||||
(openingBalancesByAccount.get(line.account_number) || 0) + amount
|
||||
)
|
||||
}
|
||||
}
|
||||
for (const [accountNumber, { debit, credit }] of obBalances) {
|
||||
const amount = Math.round(((Number(debit) || 0) - (Number(credit) || 0)) * 100) / 100
|
||||
if (amount === 0) continue
|
||||
lines.push(`#IB 0 ${accountNumber} ${formatAmount(amount)}`)
|
||||
openingBalancesByAccount.set(accountNumber, amount)
|
||||
}
|
||||
|
||||
// === Journal entries (VER + TRANS) ===
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createServerClient } from '@supabase/ssr'
|
||||
import { NextResponse, type NextRequest } from 'next/server'
|
||||
import { shouldEnforceMfa } from '@/lib/auth/mfa'
|
||||
import { userHasPassword } from '@/lib/auth/has-password'
|
||||
|
||||
export async function updateSession(request: NextRequest) {
|
||||
let supabaseResponse = NextResponse.next({
|
||||
@@ -89,11 +90,40 @@ export async function updateSession(request: NextRequest) {
|
||||
return NextResponse.redirect(url)
|
||||
}
|
||||
|
||||
// MFA pages — accessible to authenticated users (AAL1+), skip MFA enforcement
|
||||
// /mfa/enroll: gate behind has-password. BankID-only users who reach this
|
||||
// page can lock themselves out — Supabase requires AAL2 to change password
|
||||
// or unenroll MFA, and AAL2 needs a prior password sign-in. Force them to
|
||||
// set a password first. The /account/set-password page does that and routes
|
||||
// back here via ?returnTo. Thread the inner returnTo through so the user
|
||||
// ends up on their original destination after the full chain completes.
|
||||
if (pathname.startsWith('/mfa/enroll')) {
|
||||
if (!userHasPassword(user)) {
|
||||
const innerReturnTo = request.nextUrl.searchParams.get('returnTo')
|
||||
const mfaTarget = `/mfa/enroll${
|
||||
innerReturnTo ? `?returnTo=${encodeURIComponent(innerReturnTo)}` : ''
|
||||
}`
|
||||
return NextResponse.redirect(
|
||||
new URL(
|
||||
`/account/set-password?returnTo=${encodeURIComponent(mfaTarget)}`,
|
||||
request.url,
|
||||
),
|
||||
)
|
||||
}
|
||||
return supabaseResponse
|
||||
}
|
||||
|
||||
// Other MFA pages — accessible to authenticated users (AAL1+), skip MFA enforcement
|
||||
if (pathname.startsWith('/mfa/')) {
|
||||
return supabaseResponse
|
||||
}
|
||||
|
||||
// /account/set-password is the escape hatch from the BankID/MFA lockout
|
||||
// and must be reachable even when the user has no company yet (e.g. mid-
|
||||
// onboarding) and is at AAL1.
|
||||
if (pathname.startsWith('/account/set-password')) {
|
||||
return supabaseResponse
|
||||
}
|
||||
|
||||
// MFA enforcement (application-side only, not RLS)
|
||||
if (shouldEnforceMfa(user)) {
|
||||
const { data: aal } = await supabase.auth.mfa.getAuthenticatorAssuranceLevel()
|
||||
|
||||
Reference in New Issue
Block a user