* feat: multi-series SIE import, reusable FiscalYearSelector, library templates in picker - SIE import preserves each voucher's source series (B/C/I/V/...), essential for Fortnox migrations where series carry semantic meaning (kundfakturor, inbetalningar, etc.). Target numbering still goes through next_voucher_number per series; source (series, number) is stored in the migration mapping for BFNAR 2013:2 audit trail. - Execute route reads company_settings.default_voucher_series as the fallback for vouchers arriving without a series (SIE4I). - Extract shared FiscalYearSelector component; adopt in /reports and /bookkeeping. - Transaction TemplatePicker now surfaces user-created library templates (company + team scope) alongside the static registry, with a helper to convert simple library templates into the BookingTemplate shape. - Exclude 8999 "Årets resultat" from income statement financial section and monthly breakdown so year-end closing entries don't cancel the net result. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test: skip Bokio SIE regression when fixtures are absent /dev_docs is gitignored (contains anonymised customer exports), so the integration test can't find its input files in CI. Gate the suite on fixture presence so it still runs locally. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: address Greptile review feedback - convertLibraryToBookingTemplate: default entity_applicability to 'all' when the source template has no entity_type, so TemplatePicker doesn't silently hide it for companies with a set entity type. - FiscalYearSelector: fire onReady in the no-company early-return branch so consumers (e.g. ReportsPage) don't get stuck in a loading skeleton while the company context is still hydrating. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat: arcim inbox + smart-match extension + commit metadata Three threads, all gated off in extensions.config.json (invoice-inbox and inbox-smart-match are not in the enabled list for this PR). invoice-inbox: Gmail OAuth -> Resend Inbound (v2.0.0) - Remove gmail-scanner / gmail-helpers - Add resend-inbound.ts (webhook verify, attachment fetch) and inbox-provisioning.ts (per-company @arcim.io address with rotation) - Replace /gmail/* routes with /inbox/address and admin-only /inbox/rotate - Workspace UI: card layout + MatchBlock surfacing AI transaction matches - classify-document: tightened discount/total prompt; cap confidence at 50% when line items do not reconcile with amount_incl_vat - Manifest requires RESEND_API_KEY, RESEND_INBOUND_DOMAIN, RESEND_INBOUND_WEBHOOK_SECRET inbox-smart-match (new extension) - Event-driven AI matching of receipts to bank transactions - Listens on inbox_item.classified (match now) and transaction.synced (retro-match receipts waiting for a transaction) - Uses service-role client; processing_history append is scoped by company_id from the event payload commit metadata + audit plumbing - journal_entries gains commit_method and rubric_version columns - commit_journal_entry RPC accepts both (BFNAR 2013:2 behandlingshistorik) - processing-history PII detector strips UUID-shaped substrings before personnummer pattern matching (UUIDs were triggering false positives) - New generic inbox_item.classified event Migrations - arcim_inbox: company_inboxes table, resend_email_id, email_body_text, auto-provision trigger, drops obsolete email_connections - journal_entry_commit_metadata: new columns + updated RPC - inbox_attachment_composite: resend_attachment_id + composite unique index - inbox_smart_match: correlation_id, match_reasoning, expanded match_method CHECK, pending-match and correlation indexes Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
136 lines
4.5 KiB
TypeScript
136 lines
4.5 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
import type { JournalEntryStatus } from '@/types'
|
|
|
|
// Mock event bus
|
|
vi.mock('@/lib/events', () => ({
|
|
eventBus: { emit: vi.fn().mockResolvedValue([]) },
|
|
}))
|
|
|
|
import { commitEntry, getNextVoucherNumber } from '../engine'
|
|
|
|
describe('voucher number atomicity', () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
})
|
|
|
|
it('getNextVoucherNumber returns incrementing numbers from RPC', async () => {
|
|
let callCount = 0
|
|
const supabase = {
|
|
rpc: vi.fn().mockImplementation(() => {
|
|
callCount++
|
|
return Promise.resolve({ data: callCount, error: null })
|
|
}),
|
|
}
|
|
|
|
const n1 = await getNextVoucherNumber(supabase as never, 'co-1', 'fp-1', 'A')
|
|
const n2 = await getNextVoucherNumber(supabase as never, 'co-1', 'fp-1', 'A')
|
|
const n3 = await getNextVoucherNumber(supabase as never, 'co-1', 'fp-1', 'A')
|
|
|
|
expect(n1).toBe(1)
|
|
expect(n2).toBe(2)
|
|
expect(n3).toBe(3)
|
|
expect(supabase.rpc).toHaveBeenCalledTimes(3)
|
|
})
|
|
|
|
it('getNextVoucherNumber throws on RPC error', async () => {
|
|
const supabase = {
|
|
rpc: vi.fn().mockResolvedValue({ data: null, error: { message: 'connection lost' } }),
|
|
}
|
|
|
|
await expect(
|
|
getNextVoucherNumber(supabase as never, 'co-1', 'fp-1', 'A')
|
|
).rejects.toThrow('Failed to get next voucher number: connection lost')
|
|
})
|
|
|
|
/**
|
|
* commitEntry uses the atomic commit_journal_entry RPC which increments the
|
|
* voucher sequence and updates the entry status in one transaction.
|
|
* If the RPC fails (e.g., balance trigger rejection), the sequence increment
|
|
* rolls back — no burned number, no gap.
|
|
*/
|
|
it('commitEntry RPC failure does not burn a sequence number', async () => {
|
|
const supabase = {
|
|
from: vi.fn(),
|
|
rpc: vi.fn().mockResolvedValue({
|
|
data: null,
|
|
error: { message: 'Journal entry is not balanced: debit=1000 credit=500' },
|
|
}),
|
|
}
|
|
|
|
await expect(
|
|
commitEntry(supabase as never, 'co-1', 'user-1', 'entry-1')
|
|
).rejects.toThrow('Failed to commit journal entry: Journal entry is not balanced')
|
|
|
|
// The atomic RPC was called — it failed, rolling back both the
|
|
// sequence increment and the status update. No burned number.
|
|
expect(supabase.rpc).toHaveBeenCalledWith('commit_journal_entry', {
|
|
p_company_id: 'co-1',
|
|
p_entry_id: 'entry-1',
|
|
p_commit_method: null,
|
|
p_rubric_version: null,
|
|
})
|
|
|
|
// from() was never called — the RPC handles everything atomically
|
|
expect(supabase.from).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('commitEntry succeeds via atomic RPC and returns posted entry', async () => {
|
|
const postedEntry = {
|
|
id: 'entry-1',
|
|
company_id: 'co-1',
|
|
fiscal_period_id: 'fp-1',
|
|
voucher_series: 'A',
|
|
voucher_number: 3,
|
|
status: 'posted' as JournalEntryStatus,
|
|
lines: [],
|
|
}
|
|
|
|
const supabase = {
|
|
from: vi.fn().mockImplementation(() => ({
|
|
select: vi.fn().mockReturnValue({
|
|
eq: vi.fn().mockReturnValue({
|
|
single: vi.fn().mockResolvedValue({ data: postedEntry, error: null }),
|
|
}),
|
|
}),
|
|
})),
|
|
// Atomic RPC returns the assigned voucher number
|
|
rpc: vi.fn().mockResolvedValue({ data: [{ voucher_number: 3 }], error: null }),
|
|
}
|
|
|
|
const result = await commitEntry(supabase as never, 'co-1', 'user-1', 'entry-1')
|
|
|
|
expect(result.voucher_number).toBe(3)
|
|
expect(result.status).toBe('posted')
|
|
expect(supabase.rpc).toHaveBeenCalledWith('commit_journal_entry', {
|
|
p_company_id: 'co-1',
|
|
p_entry_id: 'entry-1',
|
|
p_commit_method: null,
|
|
p_rubric_version: null,
|
|
})
|
|
// from() called once to fetch the complete entry with lines
|
|
expect(supabase.from).toHaveBeenCalledWith('journal_entries')
|
|
})
|
|
|
|
/**
|
|
* getNextVoucherNumber is still used by reverseEntry and storno-service.
|
|
* Those flows INSERT a new entry (not UPDATE a draft), so the atomic
|
|
* commit_journal_entry RPC doesn't apply. Burned numbers can still occur
|
|
* in reversal/correction flows if the INSERT fails after the counter
|
|
* increments. This is documented and expected.
|
|
*/
|
|
it('getNextVoucherNumber remains available for reversal/storno flows', async () => {
|
|
const supabase = {
|
|
rpc: vi.fn().mockResolvedValue({ data: 7, error: null }),
|
|
}
|
|
|
|
const num = await getNextVoucherNumber(supabase as never, 'co-1', 'fp-1', 'B')
|
|
|
|
expect(num).toBe(7)
|
|
expect(supabase.rpc).toHaveBeenCalledWith('next_voucher_number', {
|
|
p_company_id: 'co-1',
|
|
p_fiscal_period_id: 'fp-1',
|
|
p_series: 'B',
|
|
})
|
|
})
|
|
})
|