fix: make out-of-order SIE opening balances atomic (#1334)

* fix: preserve SIE IB on out-of-order imports

* fix: make SIE opening balance replacement atomic

* test: seed accounts for atomic IB pg coverage

* test: complete atomic IB pg fixtures

* fix(import): avoid IB resync across fiscal-year gaps

* test(import): mirror PostgREST date values in pg adapter

* fix(import): address opening balance review feedback
This commit is contained in:
Mattsson
2026-08-02 20:39:29 +02:00
committed by GitHub
parent 8a2498a987
commit 18cdba3574
11 changed files with 2869 additions and 55 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,185 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { eventBus } from '@/lib/events'
import { replaceOpeningBalanceEntry } from '../engine'
import {
AccountsNotInChartError,
BookkeepingDatabaseError,
JournalEntryNotBalancedError,
} from '../errors'
vi.mock('@/lib/events', () => ({
eventBus: { emit: vi.fn().mockResolvedValue([]) },
}))
vi.mock('@/lib/bookkeeping/account-backfill', () => ({
backfillStandardBASAccounts: vi.fn().mockResolvedValue([]),
}))
function thenableChain(result: unknown) {
const chain: Record<string, unknown> = {}
for (const method of ['select', 'eq', 'in']) {
chain[method] = vi.fn().mockReturnValue(chain)
}
chain.then = (resolve: (value: unknown) => void) => resolve(result)
return chain
}
const input = {
fiscal_period_id: 'period-2026',
entry_date: '2026-01-01',
description: 'Replacement opening balance',
source_type: 'opening_balance' as const,
voucher_series: 'A',
lines: [
{ account_number: '1930', debit_amount: 150, credit_amount: 0 },
{ account_number: '2010', debit_amount: 0, credit_amount: 150 },
],
}
describe('replaceOpeningBalanceEntry', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('passes resolved lines to the atomic RPC and emits committed/reversed events', async () => {
const entries = [
{ id: 'old-entry', status: 'reversed', lines: [] },
{ id: 'new-entry', status: 'posted', source_type: 'opening_balance', lines: [] },
{ id: 'storno-entry', status: 'posted', source_type: 'storno', lines: [] },
]
const rpc = vi.fn().mockResolvedValue({
data: [{
new_entry_id: 'new-entry',
storno_entry_id: 'storno-entry',
new_voucher_number: 2,
storno_voucher_number: 3,
}],
error: null,
})
const supabase = {
rpc,
from: vi.fn().mockImplementation((table: string) => {
if (table === 'chart_of_accounts') {
return thenableChain({
data: [
{ id: 'account-1930', account_number: '1930' },
{ id: 'account-2010', account_number: '2010' },
],
error: null,
})
}
if (table === 'journal_entries') {
return thenableChain({ data: entries, error: null })
}
throw new Error(`Unexpected table: ${table}`)
}),
}
const result = await replaceOpeningBalanceEntry(
supabase as never,
'company-1',
'user-1',
'old-entry',
input,
)
expect(result).toEqual({
newEntryId: 'new-entry',
stornoEntryId: 'storno-entry',
newVoucherNumber: 2,
stornoVoucherNumber: 3,
})
expect(rpc).toHaveBeenCalledWith('commit_opening_balance_replacement', expect.objectContaining({
p_company_id: 'company-1',
p_period_id: 'period-2026',
p_expected_old_entry_id: 'old-entry',
p_user_id: 'user-1',
p_entry_date: '2026-01-01',
p_voucher_series: 'A',
p_lines: [
expect.objectContaining({
account_number: '1930',
account_id: 'account-1930',
debit_amount: 150,
credit_amount: 0,
}),
expect.objectContaining({
account_number: '2010',
account_id: 'account-2010',
debit_amount: 0,
credit_amount: 150,
}),
],
}))
expect(eventBus.emit).toHaveBeenCalledTimes(3)
expect(eventBus.emit).toHaveBeenCalledWith(expect.objectContaining({
type: 'journal_entry.reversed',
}))
})
it('rejects an unbalanced replacement before calling the RPC', async () => {
const rpc = vi.fn()
await expect(replaceOpeningBalanceEntry(
{ rpc } as never,
'company-1',
'user-1',
'old-entry',
{
...input,
lines: [
{ account_number: '1930', debit_amount: 150, credit_amount: 0 },
{ account_number: '2010', debit_amount: 0, credit_amount: 149 },
],
},
)).rejects.toBeInstanceOf(JournalEntryNotBalancedError)
expect(rpc).not.toHaveBeenCalled()
})
it('rejects lines whose accounts are absent from the chart', async () => {
const rpc = vi.fn()
const from = vi.fn().mockImplementation((table: string) => {
if (table !== 'chart_of_accounts') throw new Error(`Unexpected table: ${table}`)
return thenableChain({ data: [], error: null })
})
await expect(replaceOpeningBalanceEntry(
{ rpc, from } as never,
'company-1',
'user-1',
'old-entry',
input,
)).rejects.toBeInstanceOf(AccountsNotInChartError)
expect(rpc).not.toHaveBeenCalled()
})
it('surfaces an atomic RPC failure without attempting a partial journal write', async () => {
const rpc = vi.fn().mockResolvedValue({
data: null,
error: { message: 'Opening balance changed concurrently', code: '40001' },
})
const from = vi.fn().mockImplementation((table: string) => {
if (table !== 'chart_of_accounts') throw new Error(`Unexpected table: ${table}`)
return thenableChain({
data: [
{ id: 'account-1930', account_number: '1930' },
{ id: 'account-2010', account_number: '2010' },
],
error: null,
})
})
await expect(replaceOpeningBalanceEntry(
{ rpc, from } as never,
'company-1',
'user-1',
'old-entry',
input,
)).rejects.toBeInstanceOf(BookkeepingDatabaseError)
expect(rpc).toHaveBeenCalledTimes(1)
expect(from).toHaveBeenCalledTimes(1)
})
})
+184 -3
View File
@@ -191,8 +191,7 @@ export async function findFiscalPeriod(
* Build line insert objects from input lines, resolving account IDs and
* including tax_code and the dimensions bag
*/
function buildLineInserts(
entryId: string,
function buildLineValues(
lines: CreateJournalEntryLineInput[],
accountIdMap: Map<string, string>
) {
@@ -202,7 +201,6 @@ function buildLineInserts(
// (20260702230000): writing them explicitly would error.
const dimensions = normalizeLineDimensions(line)
return {
journal_entry_id: entryId,
account_number: line.account_number,
account_id: accountIdMap.get(line.account_number) || null,
debit_amount: Math.round((line.debit_amount || 0) * 100) / 100,
@@ -218,6 +216,17 @@ function buildLineInserts(
})
}
function buildLineInserts(
entryId: string,
lines: CreateJournalEntryLineInput[],
accountIdMap: Map<string, string>
) {
return buildLineValues(lines, accountIdMap).map((line) => ({
journal_entry_id: entryId,
...line,
}))
}
/**
* Create a draft journal entry with lines (no voucher number assigned yet)
* The entry stays in 'draft' status until commitEntry() is called.
@@ -713,6 +722,178 @@ export async function createJournalEntry(
}
}
export interface OpeningBalanceReplacementResult {
newEntryId: string
stornoEntryId: string
newVoucherNumber: number
stornoVoucherNumber: number
}
/**
* Atomically replace a period's posted opening balance with a new engine
* voucher and a storno of the old voucher. The database function owns the
* period row lock, authorization, compare-and-swap check, voucher commits,
* status transition, and pointer swap in one transaction.
*/
export async function replaceOpeningBalanceEntry(
supabase: SupabaseClient,
companyId: string,
userId: string,
expectedOldEntryId: string,
input: CreateJournalEntryInput,
): Promise<OpeningBalanceReplacementResult> {
if (input.source_type !== 'opening_balance') {
throw new BookkeepingDatabaseError(
'replace_opening_balance',
'Replacement entry must use source_type opening_balance',
)
}
const balance = validateBalance(input.lines)
if (!balance.valid) {
throw new JournalEntryNotBalancedError(
balance.totalDebit,
balance.totalCredit,
'draft',
)
}
await validateEntryDimensions(supabase, companyId, input.lines)
const accountIdMap = await resolveAccountIds(supabase, companyId, input.lines)
const accountNumbers = [...new Set(input.lines.map((line) => line.account_number))]
let missingAccounts = accountNumbers.filter((number) => !accountIdMap.has(number))
if (missingAccounts.length > 0) {
const seeded = await backfillStandardBASAccounts(
supabase,
companyId,
userId,
missingAccounts,
)
if (seeded.length > 0) {
const refreshed = await resolveAccountIds(supabase, companyId, input.lines)
for (const [number, id] of refreshed) accountIdMap.set(number, id)
missingAccounts = accountNumbers.filter((number) => !accountIdMap.has(number))
}
if (missingAccounts.length > 0) {
throw new AccountsNotInChartError(missingAccounts)
}
}
const voucherSeries = input.voucher_series
?? await resolveSeriesFromSettings(supabase, companyId, 'opening_balance')
const preparedLines = buildLineValues(input.lines, accountIdMap)
const actor = getActor()
const { data, error } = await supabase.rpc('commit_opening_balance_replacement', {
p_company_id: companyId,
p_period_id: input.fiscal_period_id,
p_expected_old_entry_id: expectedOldEntryId,
p_user_id: userId,
p_entry_date: input.entry_date,
p_description: input.description,
p_voucher_series: voucherSeries,
p_lines: preparedLines,
p_actor_type: actor?.type ?? null,
p_actor_label: actor?.label ?? null,
})
if (error) {
log.error('commit_opening_balance_replacement RPC failed', error, {
operation: 'replace_opening_balance',
companyId,
userId,
entityType: 'journal_entry',
entityId: expectedOldEntryId,
fiscalPeriodId: input.fiscal_period_id,
pgCode: (error as { code?: string }).code,
pgDetails: (error as { details?: string }).details,
pgHint: (error as { hint?: string }).hint,
})
throw new BookkeepingDatabaseError('replace_opening_balance', error.message)
}
type RpcRow = {
new_entry_id: string
storno_entry_id: string
new_voucher_number: number
storno_voucher_number: number
}
const row = (Array.isArray(data) ? data[0] : data) as RpcRow | null
if (!row?.new_entry_id || !row.storno_entry_id) {
throw new BookkeepingDatabaseError(
'replace_opening_balance',
'Atomic replacement returned no journal entry ids',
)
}
const result: OpeningBalanceReplacementResult = {
newEntryId: row.new_entry_id,
stornoEntryId: row.storno_entry_id,
newVoucherNumber: row.new_voucher_number,
stornoVoucherNumber: row.storno_voucher_number,
}
const { data: entries, error: entriesError } = await supabase
.from('journal_entries')
.select('*, lines:journal_entry_lines(*)')
.eq('company_id', companyId)
.in('id', [expectedOldEntryId, result.newEntryId, result.stornoEntryId])
if (entriesError) {
log.error('atomic opening balance replacement committed but entry refresh failed', entriesError, {
companyId,
entityId: result.newEntryId,
})
return result
}
const byId = new Map(
((entries ?? []) as JournalEntry[]).map((entry) => [entry.id, entry]),
)
const originalEntry = byId.get(expectedOldEntryId)
const newEntry = byId.get(result.newEntryId)
const stornoEntry = byId.get(result.stornoEntryId)
if (!originalEntry || !newEntry || !stornoEntry) {
log.error(
'atomic opening balance replacement committed but event entries are missing',
new Error('journal entry refresh returned incomplete replacement data'),
{
companyId,
expectedOldEntryId,
newEntryId: result.newEntryId,
stornoEntryId: result.stornoEntryId,
missingOriginalEntry: !originalEntry,
missingNewEntry: !newEntry,
missingStornoEntry: !stornoEntry,
},
)
}
if (newEntry) {
await eventBus.emit({
type: 'journal_entry.committed',
payload: { entry: newEntry, userId, companyId },
})
}
if (stornoEntry) {
await eventBus.emit({
type: 'journal_entry.committed',
payload: { entry: stornoEntry, userId, companyId },
})
}
if (originalEntry && stornoEntry) {
await eventBus.emit({
type: 'journal_entry.reversed',
payload: { originalEntry, reversalEntry: stornoEntry, userId, companyId },
})
}
return result
}
/**
* Get the current date in Swedish timezone (Europe/Stockholm).
* Avoids UTC date shift when server runs in a different timezone.
+1
View File
@@ -292,6 +292,7 @@ export type BookkeepingOperation =
| 'create_reversal_entry'
| 'create_reversal_lines'
| 'post_reversal_entry'
| 'replace_opening_balance'
| 'create_corrected_entry'
| 'create_corrected_lines'
| 'post_corrected_entry'
@@ -13,14 +13,14 @@
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { executeSIEImport } from '../sie-import'
import { createJournalEntry } from '@/lib/bookkeeping/engine'
import { createJournalEntry, replaceOpeningBalanceEntry } from '@/lib/bookkeeping/engine'
import { findUntransferredResults } from '@/lib/reports/imbalance-diagnosis'
import type { ParsedSIEFile, AccountMapping } from '../types'
import type { SupabaseClient } from '@supabase/supabase-js'
vi.mock('@/lib/bookkeeping/engine', () => ({
createJournalEntry: vi.fn(async () => ({ id: 'ob-entry-1' })),
reverseEntry: vi.fn(),
replaceOpeningBalanceEntry: vi.fn(),
}))
vi.mock('@/lib/reports/imbalance-diagnosis', () => ({
@@ -131,7 +131,7 @@ function makeMapping(source: string, target: string): AccountMapping {
}
}
function standardQueues() {
function standardQueues(): Record<string, QueuedResult[]> {
return {
sie_imports: [
{ data: null }, // checkDuplicateImport: no duplicate
@@ -280,6 +280,228 @@ describe('executeSIEImport: derived IB from #UB -1 (issue #675)', () => {
expect(createJournalEntry).not.toHaveBeenCalled()
expect(result.openingBalanceEntryId).toBeNull()
})
it('keeps an earlier-year IB and resyncs the already-imported successor', async () => {
const queues = standardQueues()
queues.fiscal_periods = [
{ data: { id: 'fp-2025' } },
{ data: { opening_balances_set: false, opening_balance_entry_id: null } },
{}, // Link the new 2025 IB.
{
data: {
id: 'fp-2026',
name: 'Räkenskapsår 2026',
period_start: '2026-01-01',
period_end: '2026-12-31',
is_closed: false,
locked_at: null,
opening_balance_entry_id: 'ib-2026-old',
opening_balances_set: true,
},
},
]
queues.journal_entries = [
// The chronological activity check excludes the already-imported 2026
// entries when deciding whether the 2025 #IB is legitimate.
{ count: 0 },
]
vi.mocked(createJournalEntry).mockResolvedValueOnce({
id: 'ib-2025',
} as Awaited<ReturnType<typeof createJournalEntry>>)
vi.mocked(replaceOpeningBalanceEntry).mockResolvedValueOnce({
newEntryId: 'ib-2026-new',
stornoEntryId: 'storno-2026-old',
newVoucherNumber: 2,
stornoVoucherNumber: 3,
})
const parsed = makeParsedFile({
header: {
...makeParsedFile().header,
fiscalYears: [{ yearIndex: 0, start: '2025-01-01', end: '2025-12-31' }],
},
openingBalances: [
{ yearIndex: 0, account: '1930', amount: 100 },
{ yearIndex: 0, account: '2010', amount: -100 },
],
closingBalances: [
{ yearIndex: 0, account: '1930', amount: 150 },
{ yearIndex: 0, account: '2010', amount: -150 },
],
stats: {
totalAccounts: 2,
totalVouchers: 0,
totalTransactionLines: 0,
fiscalYearStart: '2025-01-01',
fiscalYearEnd: '2025-12-31',
},
})
const result = await executeSIEImport(
buildRoutingSupabase(queues),
'company-1',
'user-1',
parsed,
standardMappings,
standardOptions,
)
expect(result.success).toBe(true)
expect(result.openingBalanceEntryId).toBe('ib-2025')
expect(result.nextPeriodIBResync).toEqual({
nextPeriodId: 'fp-2026',
nextPeriodName: 'Räkenskapsår 2026',
stornoEntryId: 'storno-2026-old',
newOpeningBalanceEntryId: 'ib-2026-new',
})
expect(result.warnings.join(' ')).toMatch(/Räkenskapsår 2026.*synkades om/)
expect(vi.mocked(createJournalEntry).mock.calls[0][3]).toMatchObject({
fiscal_period_id: 'fp-2025',
source_type: 'opening_balance',
entry_date: '2025-01-01',
})
expect(replaceOpeningBalanceEntry).toHaveBeenCalledWith(
expect.anything(),
'company-1',
'user-1',
'ib-2026-old',
expect.objectContaining({
fiscal_period_id: 'fp-2026',
source_type: 'opening_balance',
entry_date: '2026-01-01',
}),
)
expect(vi.mocked(replaceOpeningBalanceEntry).mock.calls[0]?.[4]).not.toHaveProperty(
'voucher_series',
)
})
it('warns without changing a locked successor opening balance', async () => {
const queues = standardQueues()
queues.fiscal_periods = [
{ data: { id: 'fp-2025' } },
{ data: { opening_balances_set: false, opening_balance_entry_id: null } },
{}, // Link the new 2025 IB.
{
data: {
id: 'fp-2026',
name: 'Räkenskapsår 2026',
period_start: '2026-01-01',
period_end: '2026-12-31',
is_closed: false,
locked_at: '2026-07-01T00:00:00Z',
opening_balance_entry_id: 'ib-2026-old',
opening_balances_set: true,
},
},
]
queues.journal_entries = [{ count: 0 }]
vi.mocked(createJournalEntry).mockResolvedValueOnce({
id: 'ib-2025',
} as Awaited<ReturnType<typeof createJournalEntry>>)
const parsed = makeParsedFile({
header: {
...makeParsedFile().header,
fiscalYears: [{ yearIndex: 0, start: '2025-01-01', end: '2025-12-31' }],
},
openingBalances: [
{ yearIndex: 0, account: '1930', amount: 100 },
{ yearIndex: 0, account: '2010', amount: -100 },
],
closingBalances: [
{ yearIndex: 0, account: '1930', amount: 150 },
{ yearIndex: 0, account: '2010', amount: -150 },
],
stats: {
totalAccounts: 2,
totalVouchers: 0,
totalTransactionLines: 0,
fiscalYearStart: '2025-01-01',
fiscalYearEnd: '2025-12-31',
},
})
const result = await executeSIEImport(
buildRoutingSupabase(queues),
'company-1',
'user-1',
parsed,
standardMappings,
standardOptions,
)
expect(result.success).toBe(true)
expect(result.openingBalanceEntryId).toBe('ib-2025')
expect(result.nextPeriodIBResync).toBeUndefined()
expect(result.nextPeriodIBResyncSkipped).toEqual({
reason: 'locked',
nextPeriodName: 'Räkenskapsår 2026',
})
expect(result.warnings.join(' ')).toMatch(/Räkenskapsår 2026.*är låst/)
expect(createJournalEntry).toHaveBeenCalledTimes(1)
expect(replaceOpeningBalanceEntry).not.toHaveBeenCalled()
})
it('still rejects a file whose vouchers cross the target fiscal-period boundary', async () => {
const queues = standardQueues()
queues.fiscal_periods = [
{ data: { id: 'fp-2025' } },
{ data: { opening_balances_set: false, opening_balance_entry_id: null } },
{}, // Link the 2025 IB before transaction-range validation.
{ data: { period_start: '2025-01-01', period_end: '2025-12-31' } },
]
queues.journal_entries = [{ count: 0 }]
vi.mocked(createJournalEntry).mockResolvedValueOnce({
id: 'ib-2025',
} as Awaited<ReturnType<typeof createJournalEntry>>)
const parsed = makeParsedFile({
header: {
...makeParsedFile().header,
fiscalYears: [{ yearIndex: 0, start: '2025-01-01', end: '2025-12-31' }],
},
openingBalances: [
{ yearIndex: 0, account: '1930', amount: 100 },
{ yearIndex: 0, account: '2010', amount: -100 },
],
closingBalances: [],
vouchers: [
{
series: 'A',
number: 1,
date: new Date(2026, 0, 2),
description: 'Voucher from another fiscal year',
lines: [
{ account: '1930', amount: 10 },
{ account: '2010', amount: -10 },
],
},
],
stats: {
totalAccounts: 2,
totalVouchers: 1,
totalTransactionLines: 2,
fiscalYearStart: '2025-01-01',
fiscalYearEnd: '2025-12-31',
},
})
const result = await executeSIEImport(
buildRoutingSupabase(queues),
'company-1',
'user-1',
parsed,
standardMappings,
standardOptions,
)
expect(result.success).toBe(false)
expect(result.errors.join(' ')).toMatch(/datum utanför räkenskapsåret/)
expect(result.errors.join(' ')).toMatch(/flera år i samma fil stöds inte/)
})
})
// --- Untransferred prior-year results (post-import walk) ---
File diff suppressed because it is too large Load Diff
+53 -6
View File
@@ -565,6 +565,30 @@ describe('ensureFiscalPeriod validation', () => {
).rejects.toThrow(/överlappar men matchar inte/)
})
it('relinks the immediate successor when an earlier period is imported later', async () => {
const { supabase, enqueueMany, findCalls } = createQueuedMockSupabase()
enqueueMany([
{ data: null, error: null },
{ data: [], error: null },
{ data: [], error: null },
{ data: { id: 'fp-2025' }, error: null },
{ data: [{ id: 'fp-2026' }], error: null },
{ data: null, error: null },
])
const id = await ensureFiscalPeriod(
supabase as unknown as Supabase,
'company-id',
'2025-01-01',
'2025-12-31',
)
expect(id).toBe('fp-2025')
expect(findCalls('fiscal_periods', 'update')).toContainEqual([
{ previous_period_id: 'fp-2025' },
])
})
// BFL 3 kap. caps any räkenskapsår at 18 months (12 is the norm; 18 is the
// ceiling for a förlängt/omlagt year). #RAR used to be validated for start
// and end DAY only, so a 24-month räkenskapsår from a foreign system
@@ -841,6 +865,10 @@ describe('companyHasPriorActivity', () => {
capturedFilters[`in:${col}`] = val
return chain
},
lte: (col: string, val: unknown) => {
capturedFilters[`lte:${col}`] = val
return chain
},
then: (resolve: (v: { count: number; error: null }) => void) =>
resolve({ count, error: null }),
}
@@ -853,7 +881,11 @@ describe('companyHasPriorActivity', () => {
it('returns false when the company has no prior posted entries', async () => {
const { supabase } = buildCountingSupabase(0)
const result = await companyHasPriorActivity(supabase as unknown as Supabase, 'company-1')
const result = await companyHasPriorActivity(
supabase as unknown as Supabase,
'company-1',
'2025-12-31',
)
expect(result).toBe(false)
})
@@ -861,7 +893,11 @@ describe('companyHasPriorActivity', () => {
it('returns true when the company has prior posted non-IB entries', async () => {
const { supabase } = buildCountingSupabase(42)
const result = await companyHasPriorActivity(supabase as unknown as Supabase, 'company-1')
const result = await companyHasPriorActivity(
supabase as unknown as Supabase,
'company-1',
'2025-12-31',
)
expect(result).toBe(true)
})
@@ -869,11 +905,16 @@ describe('companyHasPriorActivity', () => {
it('excludes opening_balance and storno entries, and only counts posted', async () => {
const { supabase, capturedFilters } = buildCountingSupabase(0)
await companyHasPriorActivity(supabase as unknown as Supabase, 'company-1')
await companyHasPriorActivity(
supabase as unknown as Supabase,
'company-1',
'2025-12-31',
)
expect(capturedFilters['neq:source_type']).toEqual(['opening_balance', 'storno'])
expect(capturedFilters['eq:status']).toBe('posted')
expect(capturedFilters['eq:company_id']).toBe('company-1')
expect(capturedFilters['lte:entry_date']).toBe('2025-12-31')
})
it('treats null/undefined count as zero', async () => {
@@ -884,8 +925,10 @@ describe('companyHasPriorActivity', () => {
neq: () => ({
neq: () => ({
eq: () => ({
then: (resolve: (v: { count: null; error: null }) => void) =>
resolve({ count: null, error: null }),
lte: () => ({
then: (resolve: (v: { count: null; error: null }) => void) =>
resolve({ count: null, error: null }),
}),
}),
}),
}),
@@ -894,7 +937,11 @@ describe('companyHasPriorActivity', () => {
}),
}
const result = await companyHasPriorActivity(supabase as unknown as Supabase, 'company-1')
const result = await companyHasPriorActivity(
supabase as unknown as Supabase,
'company-1',
'2025-12-31',
)
expect(result).toBe(false)
})
+50 -43
View File
@@ -9,7 +9,7 @@
import type { SupabaseClient } from '@supabase/supabase-js'
import { normalizeLineDimensions } from '@/lib/bookkeeping/dimension-resolver'
import { importDimensionRegistry } from './sie-dimensions'
import { createJournalEntry, reverseEntry } from '@/lib/bookkeeping/engine'
import { createJournalEntry, replaceOpeningBalanceEntry } from '@/lib/bookkeeping/engine'
import type {
ParsedSIEFile,
AccountMapping,
@@ -735,9 +735,10 @@ async function createOpeningBalanceEntry(
}
/**
* Returns true when the company already has at least one posted (or reversed)
* non-IB journal entry, i.e. this is a continuation import, not the first
* ever SIE upload for the company.
* Returns true when the company already has at least one posted non-IB
* journal entry dated no later than the target fiscal period, i.e. this is a
* continuation import rather than the first SIE upload for that point in the
* company's chronology.
*
* Used to gate IB-entry creation: when a company is already live, each year's
* #IB equals the prior year's UB, which is the sum of already-imported
@@ -746,7 +747,8 @@ async function createOpeningBalanceEntry(
*/
export async function companyHasPriorActivity(
supabase: SupabaseClient,
companyId: string
companyId: string,
targetPeriodEnd: string,
): Promise<boolean> {
// Only count currently-effective real activity. Excluding 'reversed' drops
// cancelled originals; excluding source_type 'storno' drops their matching
@@ -760,6 +762,9 @@ export async function companyHasPriorActivity(
.neq('source_type', 'opening_balance')
.neq('source_type', 'storno')
.eq('status', 'posted')
// Keep same-period activity in the continuation guard, but ignore a
// later year that happened to be imported first.
.lte('entry_date', targetPeriodEnd)
return (count ?? 0) > 0
}
@@ -839,6 +844,21 @@ export async function resyncNextPeriodOpeningBalance(
return { resynced: false, reason: 'no_next_period' }
}
const importedPeriodEnd = new Date(`${justImportedPeriodEnd}T00:00:00Z`)
importedPeriodEnd.setUTCDate(importedPeriodEnd.getUTCDate() + 1)
const expectedNextPeriodStart = importedPeriodEnd.toISOString().slice(0, 10)
if (nextPeriod.period_start !== expectedNextPeriodStart) {
// A later period separated by a gap has its own authoritative IB. It must
// not be replaced with a non-adjacent year's UB while the middle year is
// still missing.
return {
resynced: false,
reason: 'next_period_not_adjacent',
nextPeriodName: nextPeriod.name,
}
}
if (!nextPeriod.opening_balance_entry_id) {
// No existing IB on the next period: caller has nothing to resync; the
// user's first IB for the next period will be derived from the import
@@ -909,52 +929,26 @@ export async function resyncNextPeriodOpeningBalance(
}
}
// Ordering note: create the new IB FIRST, then storno the old one. If we
// stornoed first and the createJournalEntry call failed, the next period
// would be left with a reversed IB and nothing to replace it, and
// executeSIEImport swallows our error as a non-fatal warning. By creating
// first we guarantee the worst case is "new IB exists but not yet linked",
// which getOpeningBalances() can still reason about.
// Build the new IB entry on the next period.
const newEntry = await createJournalEntry(supabase, companyId, userId, {
fiscal_period_id: nextPeriod.id,
entry_date: nextPeriod.period_start as string,
description: 'Ingående balanser (resynk efter prior-year SIE-import)',
source_type: 'opening_balance',
voucher_series: 'A',
lines: newLines,
})
// Atomically swap the period FK pointer (two-step around the
// immutability trigger).
const { error: relinkError } = await supabase.rpc('replace_period_opening_balance_link', {
p_company_id: companyId,
p_period_id: nextPeriod.id,
p_new_entry_id: newEntry.id,
})
if (relinkError) {
throw new Error(`Failed to relink opening balance on next period: ${relinkError.message}`)
}
// Now that the period points at the new IB, storno the old one. If this
// throws, the period is already on the correct entry: the orphaned old
// entry shows up as a stray verifikat but the FK stays consistent.
const storno = await reverseEntry(
const replacement = await replaceOpeningBalanceEntry(
supabase,
companyId,
userId,
nextPeriod.opening_balance_entry_id,
nextPeriod.period_start as string,
{
fiscal_period_id: nextPeriod.id,
entry_date: nextPeriod.period_start as string,
description: 'Ingående balanser (resynk efter prior-year SIE-import)',
source_type: 'opening_balance',
lines: newLines,
},
)
return {
resynced: true,
nextPeriodId: nextPeriod.id,
nextPeriodName: nextPeriod.name,
stornoEntryId: storno.id,
newOpeningBalanceEntryId: newEntry.id,
stornoEntryId: replacement.stornoEntryId,
newOpeningBalanceEntryId: replacement.newEntryId,
}
}
@@ -2199,7 +2193,11 @@ export async function executeSIEImport(
// first-ever import creates the legitimate pre-system IB; subsequent
// imports must rely on the prior entries to derive opening balances
// on the fly (via getOpeningBalances() fallback).
const isContinuationImport = await companyHasPriorActivity(supabase, companyId)
const isContinuationImport = await companyHasPriorActivity(
supabase,
companyId,
fiscalYearEnd,
)
if (isContinuationImport) {
result.warnings.push(
@@ -2464,7 +2462,16 @@ export async function executeSIEImport(
// exists with its own opening_balance entry, the customer is doing a
// prior-year backfill. Sync the next period's IB to match the UB we
// just imported so reports stay consistent.
if (result.success && fiscalYearEnd && result.fiscalPeriodId && parsed.closingBalances.length > 0) {
// result.success is finalized below, after diagnostics and documentation.
// Use the same error condition here so this block is reachable, but require
// a target-period entry so a no-op file cannot succeed through resync alone.
if (
result.errors.length === 0 &&
result.journalEntriesCreated > 0 &&
fiscalYearEnd &&
result.fiscalPeriodId &&
parsed.closingBalances.length > 0
) {
try {
const resync = await resyncNextPeriodOpeningBalance(
supabase,