feat: remove AI extensions, restructure settings, and add atomic voucher commits (#157)
Remove AI-dependent extensions (ai-chat, ai-categorization, receipt-ocr, invoice-inbox) and their infrastructure (lib/ai/*, ai-consent, LangChain/ Anthropic/OpenAI deps) to simplify core and reduce bundle size. Restructure monolithic settings page into dedicated sub-pages (company, bookkeeping, invoicing, tax, banking, api, account, team, templates) with shared layout and sidebar navigation. Add atomic commit_journal_entry RPC so voucher number increment and status update happen in a single transaction — prevents burned numbers on constraint failures. Add continuity check report and voucher gap explanation tracking. Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
e89f2c402d
commit
d0b3f21bde
@@ -0,0 +1,294 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
// ============================================================
|
||||
// Mock Supabase — table-keyed result queues
|
||||
// ============================================================
|
||||
|
||||
type MockResult = { data?: unknown; error?: unknown; count?: number }
|
||||
let mockResults: Record<string, MockResult[]>
|
||||
|
||||
function makeBuilder(tableName: string) {
|
||||
const b: Record<string, unknown> = {}
|
||||
for (const m of ['select', 'eq', 'in', 'lt', 'neq', 'range', 'update']) {
|
||||
b[m] = vi.fn().mockReturnValue(b)
|
||||
}
|
||||
const consume = (): MockResult => {
|
||||
const queue = mockResults[tableName]
|
||||
if (!queue || queue.length === 0) return { data: null, error: null }
|
||||
return queue.shift()!
|
||||
}
|
||||
b.single = vi.fn().mockImplementation(async () => consume())
|
||||
b.then = (resolve: (v: unknown) => void) => resolve(consume())
|
||||
return b
|
||||
}
|
||||
|
||||
function makeClient() {
|
||||
return {
|
||||
from: vi.fn().mockImplementation((table: string) => makeBuilder(table)),
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any
|
||||
}
|
||||
|
||||
import { validateBalanceContinuity } from '../continuity-check'
|
||||
|
||||
let supabase: ReturnType<typeof makeClient>
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockResults = {}
|
||||
supabase = makeClient()
|
||||
})
|
||||
|
||||
describe('validateBalanceContinuity', () => {
|
||||
it('returns valid for first period (no previous_period_id)', async () => {
|
||||
mockResults = {
|
||||
fiscal_periods: [
|
||||
{ data: { id: 'p1', name: 'FY2024', period_start: '2024-01-01', previous_period_id: null, opening_balance_entry_id: null } },
|
||||
],
|
||||
}
|
||||
|
||||
const result = await validateBalanceContinuity(supabase, 'company-1', 'p1')
|
||||
|
||||
expect(result.valid).toBe(true)
|
||||
expect(result.discrepancies).toEqual([])
|
||||
expect(result.checked_accounts).toBe(0)
|
||||
expect(result.previous_period_name).toBeNull()
|
||||
})
|
||||
|
||||
it('returns valid when IB matches UB', async () => {
|
||||
mockResults = {
|
||||
fiscal_periods: [
|
||||
// Target period
|
||||
{ data: { id: 'p2', name: 'FY2025', period_start: '2025-01-01', previous_period_id: 'p1', opening_balance_entry_id: 'ob-1' } },
|
||||
// Previous period (for name)
|
||||
{ data: { id: 'p1', name: 'FY2024' } },
|
||||
// Previous period (for generateTrialBalance)
|
||||
{ data: { period_start: '2024-01-01', opening_balance_entry_id: null } },
|
||||
],
|
||||
journal_entry_lines: [
|
||||
// Previous period OB (fallback — no OB entry)
|
||||
{ data: [] },
|
||||
// Previous period lines (trial balance)
|
||||
{
|
||||
data: [
|
||||
{ account_number: '1930', debit_amount: 50000, credit_amount: 0 },
|
||||
{ account_number: '2099', debit_amount: 0, credit_amount: 30000 },
|
||||
{ account_number: '1510', debit_amount: 10000, credit_amount: 0 },
|
||||
],
|
||||
},
|
||||
// Current period OB entry lines (getOpeningBalances)
|
||||
{
|
||||
data: [
|
||||
{ account_number: '1930', debit_amount: 50000, credit_amount: 0 },
|
||||
{ account_number: '2099', debit_amount: 0, credit_amount: 30000 },
|
||||
{ account_number: '1510', debit_amount: 10000, credit_amount: 0 },
|
||||
],
|
||||
},
|
||||
],
|
||||
chart_of_accounts: [
|
||||
{
|
||||
data: [
|
||||
{ account_number: '1510', account_name: 'Kundfordringar', account_class: 1 },
|
||||
{ account_number: '1930', account_name: 'Företagskonto', account_class: 1 },
|
||||
{ account_number: '2099', account_name: 'Årets resultat', account_class: 2 },
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const result = await validateBalanceContinuity(supabase, 'company-1', 'p2')
|
||||
|
||||
expect(result.valid).toBe(true)
|
||||
expect(result.discrepancies).toEqual([])
|
||||
expect(result.checked_accounts).toBe(3)
|
||||
expect(result.period_name).toBe('FY2025')
|
||||
expect(result.previous_period_name).toBe('FY2024')
|
||||
})
|
||||
|
||||
it('detects discrepancy in one account', async () => {
|
||||
mockResults = {
|
||||
fiscal_periods: [
|
||||
{ data: { id: 'p2', name: 'FY2025', period_start: '2025-01-01', previous_period_id: 'p1', opening_balance_entry_id: 'ob-1' } },
|
||||
{ data: { id: 'p1', name: 'FY2024' } },
|
||||
{ data: { period_start: '2024-01-01', opening_balance_entry_id: null } },
|
||||
],
|
||||
journal_entry_lines: [
|
||||
{ data: [] },
|
||||
// Previous UB: 1930 = 50000 debit
|
||||
{
|
||||
data: [
|
||||
{ account_number: '1930', debit_amount: 50000, credit_amount: 0 },
|
||||
{ account_number: '2099', debit_amount: 0, credit_amount: 50000 },
|
||||
],
|
||||
},
|
||||
// Current IB: 1930 = 49000 debit (mismatch!)
|
||||
{
|
||||
data: [
|
||||
{ account_number: '1930', debit_amount: 49000, credit_amount: 0 },
|
||||
{ account_number: '2099', debit_amount: 0, credit_amount: 50000 },
|
||||
],
|
||||
},
|
||||
],
|
||||
chart_of_accounts: [
|
||||
{
|
||||
data: [
|
||||
{ account_number: '1930', account_name: 'Företagskonto', account_class: 1 },
|
||||
{ account_number: '2099', account_name: 'Årets resultat', account_class: 2 },
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const result = await validateBalanceContinuity(supabase, 'company-1', 'p2')
|
||||
|
||||
expect(result.valid).toBe(false)
|
||||
expect(result.discrepancies).toHaveLength(1)
|
||||
expect(result.discrepancies[0].account_number).toBe('1930')
|
||||
expect(result.discrepancies[0].previous_ub_net).toBe(50000)
|
||||
expect(result.discrepancies[0].current_ib_net).toBe(49000)
|
||||
expect(result.discrepancies[0].difference).toBe(1000)
|
||||
})
|
||||
|
||||
it('detects account present in UB but not IB', async () => {
|
||||
mockResults = {
|
||||
fiscal_periods: [
|
||||
{ data: { id: 'p2', name: 'FY2025', period_start: '2025-01-01', previous_period_id: 'p1', opening_balance_entry_id: 'ob-1' } },
|
||||
{ data: { id: 'p1', name: 'FY2024' } },
|
||||
{ data: { period_start: '2024-01-01', opening_balance_entry_id: null } },
|
||||
],
|
||||
journal_entry_lines: [
|
||||
{ data: [] },
|
||||
// Previous UB has 1510 and 2440
|
||||
{
|
||||
data: [
|
||||
{ account_number: '1510', debit_amount: 10000, credit_amount: 0 },
|
||||
{ account_number: '2440', debit_amount: 0, credit_amount: 10000 },
|
||||
],
|
||||
},
|
||||
// Current IB only has 1510 (2440 missing)
|
||||
{
|
||||
data: [
|
||||
{ account_number: '1510', debit_amount: 10000, credit_amount: 0 },
|
||||
],
|
||||
},
|
||||
],
|
||||
chart_of_accounts: [
|
||||
{
|
||||
data: [
|
||||
{ account_number: '1510', account_name: 'Kundfordringar', account_class: 1 },
|
||||
{ account_number: '2440', account_name: 'Leverantörsskulder', account_class: 2 },
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const result = await validateBalanceContinuity(supabase, 'company-1', 'p2')
|
||||
|
||||
expect(result.valid).toBe(false)
|
||||
expect(result.discrepancies).toHaveLength(1)
|
||||
expect(result.discrepancies[0].account_number).toBe('2440')
|
||||
expect(result.discrepancies[0].previous_ub_net).toBe(-10000)
|
||||
expect(result.discrepancies[0].current_ib_net).toBe(0)
|
||||
})
|
||||
|
||||
it('detects account present in IB but not UB', async () => {
|
||||
mockResults = {
|
||||
fiscal_periods: [
|
||||
{ data: { id: 'p2', name: 'FY2025', period_start: '2025-01-01', previous_period_id: 'p1', opening_balance_entry_id: 'ob-1' } },
|
||||
{ data: { id: 'p1', name: 'FY2024' } },
|
||||
{ data: { period_start: '2024-01-01', opening_balance_entry_id: null } },
|
||||
],
|
||||
journal_entry_lines: [
|
||||
{ data: [] },
|
||||
// Previous UB: only 1930
|
||||
{
|
||||
data: [
|
||||
{ account_number: '1930', debit_amount: 50000, credit_amount: 0 },
|
||||
],
|
||||
},
|
||||
// Current IB: 1930 + 1510 (1510 shouldn't be here)
|
||||
{
|
||||
data: [
|
||||
{ account_number: '1930', debit_amount: 50000, credit_amount: 0 },
|
||||
{ account_number: '1510', debit_amount: 5000, credit_amount: 0 },
|
||||
],
|
||||
},
|
||||
],
|
||||
chart_of_accounts: [
|
||||
{
|
||||
data: [
|
||||
{ account_number: '1930', account_name: 'Företagskonto', account_class: 1 },
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const result = await validateBalanceContinuity(supabase, 'company-1', 'p2')
|
||||
|
||||
expect(result.valid).toBe(false)
|
||||
expect(result.discrepancies).toHaveLength(1)
|
||||
expect(result.discrepancies[0].account_number).toBe('1510')
|
||||
expect(result.discrepancies[0].previous_ub_net).toBe(0)
|
||||
expect(result.discrepancies[0].current_ib_net).toBe(5000)
|
||||
})
|
||||
|
||||
it('treats differences within 0.01 SEK tolerance as valid', async () => {
|
||||
mockResults = {
|
||||
fiscal_periods: [
|
||||
{ data: { id: 'p2', name: 'FY2025', period_start: '2025-01-01', previous_period_id: 'p1', opening_balance_entry_id: 'ob-1' } },
|
||||
{ data: { id: 'p1', name: 'FY2024' } },
|
||||
{ data: { period_start: '2024-01-01', opening_balance_entry_id: null } },
|
||||
],
|
||||
journal_entry_lines: [
|
||||
{ data: [] },
|
||||
{
|
||||
data: [
|
||||
{ account_number: '1930', debit_amount: 50000.005, credit_amount: 0 },
|
||||
],
|
||||
},
|
||||
{
|
||||
data: [
|
||||
{ account_number: '1930', debit_amount: 50000, credit_amount: 0 },
|
||||
],
|
||||
},
|
||||
],
|
||||
chart_of_accounts: [
|
||||
{
|
||||
data: [
|
||||
{ account_number: '1930', account_name: 'Företagskonto', account_class: 1 },
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const result = await validateBalanceContinuity(supabase, 'company-1', 'p2')
|
||||
|
||||
expect(result.valid).toBe(true)
|
||||
expect(result.discrepancies).toEqual([])
|
||||
})
|
||||
|
||||
it('throws when period not found', async () => {
|
||||
mockResults = {
|
||||
fiscal_periods: [
|
||||
{ data: null, error: { message: 'not found' } },
|
||||
],
|
||||
}
|
||||
|
||||
await expect(
|
||||
validateBalanceContinuity(supabase, 'company-1', 'nonexistent')
|
||||
).rejects.toThrow('Fiscal period not found')
|
||||
})
|
||||
|
||||
it('throws when previous period not found', async () => {
|
||||
mockResults = {
|
||||
fiscal_periods: [
|
||||
{ data: { id: 'p2', name: 'FY2025', period_start: '2025-01-01', previous_period_id: 'p1', opening_balance_entry_id: null } },
|
||||
{ data: null, error: { message: 'not found' } },
|
||||
],
|
||||
}
|
||||
|
||||
await expect(
|
||||
validateBalanceContinuity(supabase, 'company-1', 'p2')
|
||||
).rejects.toThrow('Previous fiscal period not found')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,124 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import type { ContinuityCheckResult, ContinuityDiscrepancy } from '@/types'
|
||||
import { generateTrialBalance } from './trial-balance'
|
||||
import { getOpeningBalances } from './opening-balances'
|
||||
|
||||
/**
|
||||
* Validate that a fiscal period's opening balances (IB) match the previous
|
||||
* period's closing balances (UB) for all balance sheet accounts (class 1-2).
|
||||
*
|
||||
* Uses the same data paths as the actual reports: generateTrialBalance() for
|
||||
* UB and getOpeningBalances() for IB, so a passing check proves the reports
|
||||
* are consistent.
|
||||
*
|
||||
* Tolerance: 0.01 SEK per account — covers IEEE 754 rounding drift from
|
||||
* intermediate Math.round() calls, NOT Swedish öresavrundning (abolished 2010).
|
||||
*/
|
||||
export async function validateBalanceContinuity(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
fiscalPeriodId: string
|
||||
): Promise<ContinuityCheckResult> {
|
||||
// Fetch target period
|
||||
const { data: period, error: periodError } = await supabase
|
||||
.from('fiscal_periods')
|
||||
.select('id, name, period_start, previous_period_id, opening_balance_entry_id')
|
||||
.eq('id', fiscalPeriodId)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
if (periodError || !period) {
|
||||
throw new Error('Fiscal period not found')
|
||||
}
|
||||
|
||||
// First period — nothing to compare against
|
||||
if (!period.previous_period_id) {
|
||||
return {
|
||||
valid: true,
|
||||
period_name: period.name,
|
||||
previous_period_name: null,
|
||||
discrepancies: [],
|
||||
checked_accounts: 0,
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch previous period name
|
||||
const { data: prevPeriod } = await supabase
|
||||
.from('fiscal_periods')
|
||||
.select('id, name')
|
||||
.eq('id', period.previous_period_id)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
if (!prevPeriod) {
|
||||
throw new Error('Previous fiscal period not found')
|
||||
}
|
||||
|
||||
// Previous period UB: trial balance filtered to class 1-2
|
||||
const { rows: trialRows } = await generateTrialBalance(
|
||||
supabase,
|
||||
companyId,
|
||||
prevPeriod.id
|
||||
)
|
||||
|
||||
const previousUB = new Map<string, { net: number; name: string }>()
|
||||
for (const row of trialRows) {
|
||||
if (row.account_class >= 1 && row.account_class <= 2) {
|
||||
const net = Math.round((row.closing_debit - row.closing_credit) * 100) / 100
|
||||
if (Math.abs(net) >= 0.005) {
|
||||
previousUB.set(row.account_number, { net, name: row.account_name })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Current period IB
|
||||
const { balances: ibBalances } = await getOpeningBalances(supabase, companyId, period)
|
||||
|
||||
const currentIB = new Map<string, number>()
|
||||
for (const [accountNumber, bal] of ibBalances) {
|
||||
// Only check balance sheet accounts
|
||||
const accountClass = parseInt(accountNumber[0]) || 0
|
||||
if (accountClass >= 1 && accountClass <= 2) {
|
||||
const net = Math.round((bal.debit - bal.credit) * 100) / 100
|
||||
if (Math.abs(net) >= 0.005) {
|
||||
currentIB.set(accountNumber, net)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Compare all accounts from both sides
|
||||
const allAccounts = new Set([...previousUB.keys(), ...currentIB.keys()])
|
||||
const discrepancies: ContinuityDiscrepancy[] = []
|
||||
|
||||
// Get account names for IB-only accounts
|
||||
const accountNames = new Map<string, string>()
|
||||
for (const [num, data] of previousUB) {
|
||||
accountNames.set(num, data.name)
|
||||
}
|
||||
|
||||
for (const accountNumber of allAccounts) {
|
||||
const ubNet = previousUB.get(accountNumber)?.net ?? 0
|
||||
const ibNet = currentIB.get(accountNumber) ?? 0
|
||||
const difference = Math.round((ubNet - ibNet) * 100) / 100
|
||||
|
||||
if (Math.abs(difference) > 0.01) {
|
||||
discrepancies.push({
|
||||
account_number: accountNumber,
|
||||
account_name: accountNames.get(accountNumber) ?? `Konto ${accountNumber}`,
|
||||
previous_ub_net: ubNet,
|
||||
current_ib_net: ibNet,
|
||||
difference,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
discrepancies.sort((a, b) => a.account_number.localeCompare(b.account_number))
|
||||
|
||||
return {
|
||||
valid: discrepancies.length === 0,
|
||||
period_name: period.name,
|
||||
previous_period_name: prevPeriod.name,
|
||||
discrepancies,
|
||||
checked_accounts: allAccounts.size,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user