* fix(errors): close remaining raw-message leaks after #1048 (#337) Follow-up to PR #1048. No user-visible toast or response field can now carry a raw engine or DB message; everything maps through getErrorMessage or the structured-errors registry. - get-error-message: only normalize a code-carrying Error instance into the structured path when the registry knows the code; unknown codes (Node system errors, stray third-party codes, Error-wrapped Postgres SQLSTATEs) fall through to pattern match, Swedish check, Postgres map and the status/context/generic fallbacks instead of returning the raw message. New Swedish-detection pattern for "ar last" phrases and a known-pattern row for "already has a journal entry". - structured-errors: add CANNOT_EDIT_NON_DRAFT (409) and MANDATORY_DIMENSION_MISSING (400) rows, plus common Node network codes (ECONNREFUSED, ECONNRESET, ETIMEDOUT, ENOTFOUND, EAI_AGAIN, EPIPE) as retryable 503 transients with a Swedish message. - pending-operations commit + bulk-commit routes: map executor error strings through getErrorMessage before responding (raw stays in logs); Swedish passes through, English falls to status-appropriate Swedish. - pending page: toast via getErrorMessage, fixing raw English toasts and "[object Object]" for structured envelopes on commit/bulk/reject. - transactions book + journal-entries routes: untyped catch and DB list errors no longer return err.message; mapped or static Swedish instead. - invoice send + issue-credit-note: partial_failures reasons are now Swedish (raw provider/DB text logged, never returned). - Tests: new unknown-code/Error-instance suite, registry rows asserted, route tests updated off the pinned raw-English expectations. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(skatteverket): target the räkenskapsår for yearly VAT redovisningsperiod A yearly filer with a broken fiscal year has a Skatteverket period ending in its FY-end month, not December, and the panel's year state is never maintained in yearly mode (the year picker is replaced by the räkenskapsår selector), so calls targeted the wrong period even for calendar-FY companies filing after year end. The selected fiscal period now rides through the whole chain: panel query strings, draft/validate/ submit bodies, buildMomsuppgift (which resolves the FY bounds so the period id and the figures describe the same räkenskapsår), and the staged-commit path. MCP callers without a fiscal period keep the calendar fallback. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(deadlines): group same-day skattekonto deadlines into one card Moms, AGI and preliminärskatt legally share the skattekonto date (den 12:e), so a small monthly-moms employer saw 2-3 near-identical rows per month. Two or more pending system rows of the skattekonto family on the same due date now render as one grouped card with the date block once and each obligation as a sub-row keeping its own confirm-to-complete flow. Presentation only: rows, statuses, ICS feed unchanged. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(deadlines): KU + ROT/RUT + long-tail opt-in deadlines, rolling horizon Follow-ups from the #1028 audit left out of the #1057-#1060 fix stack, each with its own condition modeling: - kontrolluppgifter (KU10/KU20/KU31), due 31 Jan (SFL 24 kap. 1 §): opt-in flag suggested from ledger signals (2898 utdelning, 2393/2893 ägarlån; deliberately not 2091, see DECISIONS.md), AB only, mirroring the #1059 EU-sales suggest-and-confirm pattern. - rot_rut_begaran, due 31 Jan after the payment year (Lag 2009:194 8 §): rows generated only for years with actually PAID ROT/RUT invoices, resolved inside the generator; invoice-derived suggestion. - Long tail, explicit opt-in ('Fler deadlines'): OSS quarterly and IOSS monthly with a skipBankingDayAdjustment config flag (EU-law dates stand on weekends), Intrastat (10th banking day of the following month), punktskatt (ordinary skattedeklaration schedule), and fyllnadsinbetalning (12th of 2nd month over 30k / 3rd of 5th month, SFL 62:8 + 65 kap.). Kvarskatt deferred: needs a slutskattebesked date the app does not hold. - Rolling generation horizon: recurring types ~6 months ahead, annual 12 months, mirrored in the backfill expectation keys so the nightly cron never thrashes; regeneration now preserves manual in_progress status; one-time cleanup migration removes existing far-future rows. Migrations also applied to the staging branch, together with the previously missing 20260717xxxxxx deadline migrations (staging had drifted and lacked dismissed_at). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(arsredovisning): keep narrative editable after year-end close The narrative save endpoint refused writes whenever the fiscal period was closed/locked, but Verkstall bokslut closes the period before the arsredovisning text is ever written, so every legitimate save failed with PERIOD_LOCKED and the PDF fell back to placeholder text. The narrative is arsredovisning document text (ARL 6 kap.), not journal rakenskapsinformation, so the bookkeeping period lock does not apply. Saves are now refused only once a Bolagsverket submission for the period is registrerad (ARSREDOVISNING_REGISTERED, 409); the filed artifact was already frozen separately by the submissions immutability trigger. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(skatteverket): surface dead SKV connections and nudge reconnect Prod has ~70 companies that connected Skatteverket before the post-connect sync fix (#1010) and silently never synced skattekonto: the only reconnect prompt lived in the settings panel nobody revisits. - transactions-page banner when the connection is needs_reconsent or expired without refresh, linking to /settings/tax - pre-connect note in the connect panel: approve ALL behorigheter on Skatteverket's consent page (previously only shown after a failure) - wire the inert skattekonto.connection.expired event to an email nudge to the token owner; one send per consent episode via claim-first dedup in notification_log (type skv_connection_expired, partial unique index in migration 20260720090000, applied to staging) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(archive): per-year behandlingshistorik covers late-booked vouchers + Drive backup disclaimer The per-fiscal-year archive filtered audit rows by created_at within the period, dropping treatment history for bokslut entries, stornos and SIE imports booked after year end (BFNAR 2013:2 kap 8). The year archive now unions the date window with every audit row touching the period's journal entries and lines, deduped by audit id; line rows (company_id NULL by trigger design) are admitted via a scoped OR and reachable on the service-role backup path. ARCHIVE_FORMAT_VERSION 2->3 forces a one-time Drive re-upload so existing archives pick up the complete history. The Drive card on /import Exportera and the LASMIG texts now state the Drive copy is a convenience backup, not the BFL 7 kap legal archive. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(decisions): clarify Arsredovisning narrative save behavior on submission status * feat(invoices): gate payment links behind invoice settings opt-in The payment-link section (manual URL field + Stripe auto-create toggle) was visible on every invoice and auto-created Stripe links on send for any connected company. It is now opt-in per company: - new company_settings.invoice_payment_links_enabled, default false for everyone (no grandfathering of Stripe-connected companies) - invoice editor hides the whole section unless enabled; a draft that already carries a link still shows it so old links stay clearable - enforced server-side in maybeCreatePaymentLinkForInvoice (after the provider lookup, so the extension-free core build never queries), so dashboard, v1, MCP and recurring sends all obey it - new toggle on Settings -> Invoicing, saves instantly; sv/en strings Migration applied to the staging branch; prod gets it on merge. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(tests): add invoice_payment_links_enabled to company settings fixture The makeCompanySettings fixture missed the new required boolean, failing the core-only build's type check of tests/helpers.ts. Default false, matching the migration default. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Signed-off-by: Emil <emilmattsson14@gmail.com> * fix(review): address CodeRabbit, compliance and Swedish review findings Round 2 of PR #1076 review feedback, one change per accepted finding: - pending page: res.json() safe fallback in both commit paths so a non-JSON proxy response cannot surface a raw parser error - bulk-commit: map operation status enums to Swedish display labels in the 'Redan hanterad' skip message - payment-link settings: disable the toggle while a save is in flight to prevent out-of-order PUT responses - deadlines group card: route all UI strings through next-intl (deadlines namespace, sv + en) - archive export: scope the period audit entry lookup to posted/reversed, matching the rest of the export - error tests: assert the exact registry English message for ECONNREFUSED to lock the no-leakage contract - signal routes: log.warn when best-effort lookups swallow a Supabase error (forensics), keep fail-closed behavior - narrative route: document that 'avslutad' submissions deliberately stay editable (never registered at Bolagsverket) - VAT: yearly declarations without an explicit fiscalPeriodId now resolve the räkenskapsår ending in the target year from fiscal_periods instead of assuming a calendar FY (SFL 26 kap 10-11 §§); calendar fallback only when no fiscal period exists - deadlines: IOSS deadline no longer requires vat_registered (Art. 369s has no Swedish VAT registration prerequisite) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Signed-off-by: Emil <emilmattsson14@gmail.com> --------- Signed-off-by: Emil <emilmattsson14@gmail.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
745 lines
26 KiB
TypeScript
745 lines
26 KiB
TypeScript
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
import JSZip from 'jszip'
|
|
import {
|
|
generateFullArchive,
|
|
generateBaseDataArchive,
|
|
estimateArchiveSize,
|
|
MASTER_DATA_DUMP_TABLES,
|
|
} from '../full-archive-export'
|
|
import { createQueuedMockSupabase } from '@/tests/helpers'
|
|
import { getAuditLog } from '@/lib/core/audit/audit-service'
|
|
import type { AuditLogEntry } from '@/types'
|
|
|
|
vi.mock('../sie-export', () => ({
|
|
generateSIEExport: vi.fn().mockResolvedValue('#FLAGGA 0\n#PROGRAM "ERPBase"'),
|
|
}))
|
|
|
|
vi.mock('../trial-balance', () => ({
|
|
generateTrialBalance: vi.fn().mockResolvedValue({
|
|
rows: [], totalDebit: 0, totalCredit: 0, isBalanced: true,
|
|
}),
|
|
}))
|
|
|
|
vi.mock('../income-statement', () => ({
|
|
generateIncomeStatement: vi.fn().mockResolvedValue({
|
|
revenue_sections: [], total_revenue: 0,
|
|
expense_sections: [], total_expenses: 0,
|
|
financial_sections: [], total_financial: 0,
|
|
net_result: 0, period: { start: '2024-01-01', end: '2024-12-31' },
|
|
}),
|
|
}))
|
|
|
|
vi.mock('../balance-sheet', () => ({
|
|
generateBalanceSheet: vi.fn().mockResolvedValue({
|
|
asset_sections: [], equity_liability_sections: [],
|
|
total_assets: 0, total_equity_liabilities: 0,
|
|
period: { start: '2024-01-01', end: '2024-12-31' },
|
|
}),
|
|
}))
|
|
|
|
vi.mock('../general-ledger', () => ({
|
|
generateGeneralLedger: vi.fn().mockResolvedValue({
|
|
accounts: [], period: { start: '2024-01-01', end: '2024-12-31' },
|
|
}),
|
|
}))
|
|
|
|
vi.mock('../journal-register', () => ({
|
|
generateJournalRegister: vi.fn().mockResolvedValue({
|
|
entries: [], total_entries: 0, total_debit: 0, total_credit: 0,
|
|
period: { start: '2024-01-01', end: '2024-12-31' },
|
|
}),
|
|
}))
|
|
|
|
vi.mock('../vat-declaration', () => ({
|
|
calculateVatDeclaration: vi.fn().mockResolvedValue({
|
|
period: { type: 'yearly', year: 2024, period: 1, start: '2024-01-01', end: '2024-12-31' },
|
|
rutor: {
|
|
ruta05: 0, ruta06: 0, ruta07: 0,
|
|
ruta10: 0, ruta11: 0, ruta12: 0,
|
|
ruta39: 0, ruta40: 0, ruta48: 0, ruta49: 0,
|
|
},
|
|
invoiceCount: 0, transactionCount: 0,
|
|
breakdown: {
|
|
invoices: { ruta05: 0, ruta06: 0, ruta07: 0, ruta10: 0, ruta11: 0, ruta12: 0, ruta39: 0, ruta40: 0, base25: 0, base12: 0, base6: 0 },
|
|
transactions: { ruta48: 0 },
|
|
receipts: { ruta48: 0 },
|
|
},
|
|
}),
|
|
}))
|
|
|
|
vi.mock('@/lib/core/audit/audit-service', () => ({
|
|
getAuditLog: vi.fn().mockResolvedValue({ data: [], count: 0 }),
|
|
}))
|
|
|
|
const mockGetAuditLog = vi.mocked(getAuditLog)
|
|
|
|
const COMPANY_ROW = {
|
|
company_name: 'Test AB',
|
|
org_number: '5566778899',
|
|
moms_period: 'quarterly',
|
|
}
|
|
|
|
const PERIOD_2024 = {
|
|
id: 'period-2024',
|
|
period_start: '2024-01-01',
|
|
period_end: '2024-12-31',
|
|
opening_balance_entry_id: null,
|
|
}
|
|
|
|
const PERIOD_2023 = {
|
|
id: 'period-2023',
|
|
period_start: '2023-01-01',
|
|
period_end: '2023-12-31',
|
|
opening_balance_entry_id: null,
|
|
}
|
|
|
|
describe('generateFullArchive', () => {
|
|
let supabase: ReturnType<typeof createQueuedMockSupabase>['supabase']
|
|
let enqueueMany: ReturnType<typeof createQueuedMockSupabase>['enqueueMany']
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
mockGetAuditLog.mockResolvedValue({ data: [], count: 0 })
|
|
const mock = createQueuedMockSupabase()
|
|
supabase = mock.supabase
|
|
enqueueMany = mock.enqueueMany
|
|
})
|
|
|
|
describe('scope: period', () => {
|
|
it('generates a ZIP with expected file structure', async () => {
|
|
enqueueMany([
|
|
{ data: COMPANY_ROW }, // company_settings
|
|
{ data: PERIOD_2024 }, // fiscal_periods (single)
|
|
{ data: [] }, // document_attachments
|
|
])
|
|
|
|
const buffer = await generateFullArchive(supabase as any, 'company-1', {
|
|
scope: 'period',
|
|
period_id: PERIOD_2024.id,
|
|
})
|
|
|
|
const zip = await JSZip.loadAsync(buffer)
|
|
|
|
expect(zip.file('bokforing.se')).not.toBeNull()
|
|
expect(zip.file('rapporter/saldobalans.json')).not.toBeNull()
|
|
expect(zip.file('rapporter/resultatrakning.json')).not.toBeNull()
|
|
expect(zip.file('rapporter/balansrakning.json')).not.toBeNull()
|
|
expect(zip.file('rapporter/huvudbok.json')).not.toBeNull()
|
|
expect(zip.file('rapporter/grundbok.json')).not.toBeNull()
|
|
expect(zip.file('rapporter/momsdeklaration.json')).not.toBeNull()
|
|
expect(zip.file('dokument/manifest.json')).not.toBeNull()
|
|
expect(zip.file('revision/behandlingshistorik.json')).not.toBeNull()
|
|
expect(zip.file('revision/systemdokumentation.json')).not.toBeNull()
|
|
// Human-readable layer: CSV twins + the Swedish README.
|
|
expect(zip.file('rapporter/saldobalans.csv')).not.toBeNull()
|
|
expect(zip.file('rapporter/resultatrakning.csv')).not.toBeNull()
|
|
expect(zip.file('rapporter/balansrakning.csv')).not.toBeNull()
|
|
expect(zip.file('rapporter/huvudbok.csv')).not.toBeNull()
|
|
const readme = zip.file('LÄSMIG.txt')
|
|
expect(readme).not.toBeNull()
|
|
const readmeText = await readme!.async('text')
|
|
expect(readmeText).toContain('Test AB')
|
|
expect(readmeText).toContain('Räkenskapsår')
|
|
})
|
|
|
|
it('handles missing documents gracefully', async () => {
|
|
enqueueMany([
|
|
{ data: COMPANY_ROW },
|
|
{ data: PERIOD_2024 },
|
|
{
|
|
data: [
|
|
{
|
|
id: 'doc-1',
|
|
file_name: 'receipt.pdf',
|
|
storage_path: 'documents/user-1/receipt.pdf',
|
|
journal_entry_id: 'entry-1',
|
|
journal_entries: {
|
|
voucher_number: 17,
|
|
voucher_series: 'A',
|
|
entry_date: '2024-03-15',
|
|
},
|
|
},
|
|
],
|
|
},
|
|
{ data: [{ id: 'entry-1', fiscal_period_id: PERIOD_2024.id }] },
|
|
])
|
|
|
|
supabase.storage.from = vi.fn().mockReturnValue({
|
|
download: vi.fn().mockResolvedValue({
|
|
data: null,
|
|
error: { message: 'File not found' },
|
|
}),
|
|
})
|
|
|
|
const buffer = await generateFullArchive(supabase as any, 'company-1', {
|
|
scope: 'period',
|
|
period_id: PERIOD_2024.id,
|
|
})
|
|
|
|
const zip = await JSZip.loadAsync(buffer)
|
|
const manifestFile = zip.file('dokument/manifest.json')
|
|
expect(manifestFile).not.toBeNull()
|
|
|
|
const manifest = JSON.parse(await manifestFile!.async('text'))
|
|
expect(manifest).toHaveLength(1)
|
|
expect(manifest[0].status).toBe('error')
|
|
expect(manifest[0].error).toBe('File not found')
|
|
expect(manifest[0].fiscal_period_id).toBe(PERIOD_2024.id)
|
|
// New manifest fields populated even on error (path is computed before download)
|
|
expect(manifest[0].voucher_number).toBe('A17')
|
|
expect(manifest[0].entry_date).toBe('2024-03-15')
|
|
expect(manifest[0].zip_path).toBe('dokument/2024/A17_receipt.pdf')
|
|
})
|
|
|
|
it('skips documents when include_documents is false', async () => {
|
|
enqueueMany([
|
|
{ data: COMPANY_ROW },
|
|
{ data: PERIOD_2024 },
|
|
])
|
|
|
|
const buffer = await generateFullArchive(supabase as any, 'company-1', {
|
|
scope: 'period',
|
|
period_id: PERIOD_2024.id,
|
|
include_documents: false,
|
|
})
|
|
|
|
const zip = await JSZip.loadAsync(buffer)
|
|
|
|
expect(zip.file('dokument/manifest.json')).toBeNull()
|
|
expect(zip.file('bokforing.se')).not.toBeNull()
|
|
expect(zip.file('revision/behandlingshistorik.json')).not.toBeNull()
|
|
})
|
|
|
|
it('throws when fiscal period not found', async () => {
|
|
enqueueMany([
|
|
{ data: COMPANY_ROW },
|
|
{ data: null },
|
|
])
|
|
|
|
await expect(
|
|
generateFullArchive(supabase as any, 'company-1', {
|
|
scope: 'period',
|
|
period_id: 'nonexistent',
|
|
})
|
|
).rejects.toThrow('Fiscal period not found')
|
|
})
|
|
|
|
it('filters audit trail by period dates', async () => {
|
|
enqueueMany([
|
|
{ data: COMPANY_ROW },
|
|
{ data: PERIOD_2024 },
|
|
{ data: [] },
|
|
])
|
|
|
|
await generateFullArchive(supabase as any, 'company-1', {
|
|
scope: 'period',
|
|
period_id: PERIOD_2024.id,
|
|
})
|
|
|
|
expect(mockGetAuditLog).toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
'company-1',
|
|
expect.objectContaining({
|
|
from_date: PERIOD_2024.period_start,
|
|
to_date: `${PERIOD_2024.period_end}T23:59:59.999Z`,
|
|
})
|
|
)
|
|
})
|
|
|
|
it("includes audit rows for the period's entries booked outside the window", async () => {
|
|
// Bokslut reality: the FY2024 year-end entry is committed in March 2025,
|
|
// so its audit rows fall outside the period's date window. The year's
|
|
// archive must still carry them (BFNAR 2013:2 kap 8).
|
|
const inWindow: AuditLogEntry = {
|
|
id: 'audit-1',
|
|
user_id: 'user-1',
|
|
company_id: 'company-1',
|
|
action: 'INSERT',
|
|
table_name: 'journal_entries',
|
|
record_id: 'e-1',
|
|
actor_id: 'user-1',
|
|
actor_type: null,
|
|
actor_label: null,
|
|
old_state: null,
|
|
new_state: null,
|
|
description: 'Created journal_entries record',
|
|
created_at: '2024-06-01T10:00:00Z',
|
|
}
|
|
const outOfWindowCommit: AuditLogEntry = {
|
|
...inWindow,
|
|
id: 'audit-2',
|
|
action: 'COMMIT',
|
|
description: 'Committed journal entry A55',
|
|
created_at: '2025-03-15T09:00:00Z',
|
|
}
|
|
// Line audit rows carry company_id NULL (write_audit_log finds no
|
|
// company_id column on journal_entry_lines).
|
|
const lineRow: AuditLogEntry = {
|
|
...inWindow,
|
|
id: 'audit-3',
|
|
company_id: null,
|
|
table_name: 'journal_entry_lines',
|
|
record_id: 'l-1',
|
|
created_at: '2025-03-15T09:00:01Z',
|
|
}
|
|
|
|
mockGetAuditLog.mockResolvedValue({ data: [inWindow], count: 1 })
|
|
|
|
enqueueMany([
|
|
{ data: COMPANY_ROW }, // company_settings
|
|
{ data: PERIOD_2024 }, // fiscal_periods
|
|
{ data: [] }, // document_attachments
|
|
{ data: [{ id: 'e-1' }] }, // journal_entries ids for the period
|
|
{ data: [{ id: 'l-1' }] }, // journal_entry_lines ids
|
|
// audit_log by record id: returns the in-window row again (dedupe)
|
|
// plus the two out-of-window rows
|
|
{ data: [inWindow, outOfWindowCommit, lineRow] },
|
|
])
|
|
|
|
const buffer = await generateFullArchive(supabase as any, 'company-1', {
|
|
scope: 'period',
|
|
period_id: PERIOD_2024.id,
|
|
})
|
|
|
|
const zip = await JSZip.loadAsync(buffer)
|
|
const history = JSON.parse(
|
|
await zip.file('revision/behandlingshistorik.json')!.async('text')
|
|
) as Array<{ id: string }>
|
|
|
|
// Deduped: audit-1 appears once despite arriving via both fetches.
|
|
expect(history).toHaveLength(3)
|
|
const ids = history.map((h) => h.id)
|
|
expect(ids).toContain('audit-2')
|
|
expect(ids).toContain('audit-3')
|
|
// Newest first, matching getAuditLog's output order.
|
|
expect(ids[0]).toBe('audit-3')
|
|
expect(ids[2]).toBe('audit-1')
|
|
})
|
|
})
|
|
|
|
describe('scope: all', () => {
|
|
it('generates per-period SIE files and report subfolders', async () => {
|
|
enqueueMany([
|
|
{ data: COMPANY_ROW },
|
|
{ data: [PERIOD_2023, PERIOD_2024] }, // fiscal_periods (list for fetchAllPeriods)
|
|
{ data: [] }, // document_attachments
|
|
])
|
|
|
|
const buffer = await generateFullArchive(supabase as any, 'company-1', {
|
|
scope: 'all',
|
|
})
|
|
|
|
const zip = await JSZip.loadAsync(buffer)
|
|
|
|
expect(zip.file('sie/2023-01-01_2023-12-31.se')).not.toBeNull()
|
|
expect(zip.file('sie/2024-01-01_2024-12-31.se')).not.toBeNull()
|
|
expect(zip.file('rapporter/2023-01-01_2023-12-31/saldobalans.json')).not.toBeNull()
|
|
expect(zip.file('rapporter/2024-01-01_2024-12-31/saldobalans.json')).not.toBeNull()
|
|
expect(zip.file('rapporter/2024-01-01_2024-12-31/saldobalans.csv')).not.toBeNull()
|
|
expect(zip.file('rapporter/2024-01-01_2024-12-31/huvudbok.csv')).not.toBeNull()
|
|
expect(zip.file('revision/behandlingshistorik.json')).not.toBeNull()
|
|
expect(zip.file('revision/systemdokumentation.json')).not.toBeNull()
|
|
const readmeText = await zip.file('LÄSMIG.txt')!.async('text')
|
|
expect(readmeText).toContain('Hela bokföringen')
|
|
// No root bokforing.se in all-mode
|
|
expect(zip.file('bokforing.se')).toBeNull()
|
|
})
|
|
|
|
it('does not filter audit trail by date in all-mode', async () => {
|
|
enqueueMany([
|
|
{ data: COMPANY_ROW },
|
|
{ data: [PERIOD_2024] },
|
|
{ data: [] },
|
|
])
|
|
|
|
await generateFullArchive(supabase as any, 'company-1', { scope: 'all' })
|
|
|
|
const call = mockGetAuditLog.mock.calls[0]
|
|
expect(call[2]).not.toHaveProperty('from_date')
|
|
expect(call[2]).not.toHaveProperty('to_date')
|
|
})
|
|
|
|
it('tags each document with its fiscal_period_id across periods', async () => {
|
|
enqueueMany([
|
|
{ data: COMPANY_ROW },
|
|
{ data: [PERIOD_2023, PERIOD_2024] },
|
|
{
|
|
data: [
|
|
{
|
|
id: 'doc-2023',
|
|
file_name: 'r23.pdf',
|
|
storage_path: 'p/r23.pdf',
|
|
journal_entry_id: 'e-2023',
|
|
journal_entries: { voucher_number: 7, voucher_series: 'A', entry_date: '2023-06-01' },
|
|
},
|
|
{
|
|
id: 'doc-2024',
|
|
file_name: 'r24.pdf',
|
|
storage_path: 'p/r24.pdf',
|
|
journal_entry_id: 'e-2024',
|
|
journal_entries: { voucher_number: 12, voucher_series: 'B', entry_date: '2024-08-20' },
|
|
},
|
|
],
|
|
},
|
|
{
|
|
data: [
|
|
{ id: 'e-2023', fiscal_period_id: PERIOD_2023.id },
|
|
{ id: 'e-2024', fiscal_period_id: PERIOD_2024.id },
|
|
],
|
|
},
|
|
])
|
|
|
|
const buffer = await generateFullArchive(supabase as any, 'company-1', {
|
|
scope: 'all',
|
|
})
|
|
|
|
const zip = await JSZip.loadAsync(buffer)
|
|
const manifestFile = zip.file('dokument/manifest.json')
|
|
expect(manifestFile).not.toBeNull()
|
|
|
|
const manifest = JSON.parse(await manifestFile!.async('text'))
|
|
expect(manifest).toHaveLength(2)
|
|
const byId = Object.fromEntries(
|
|
(
|
|
manifest as Array<{
|
|
document_id: string
|
|
fiscal_period_id: string | null
|
|
voucher_number: string | null
|
|
zip_path: string | null
|
|
}>
|
|
).map((m) => [m.document_id, m])
|
|
)
|
|
expect(byId['doc-2023'].fiscal_period_id).toBe(PERIOD_2023.id)
|
|
expect(byId['doc-2024'].fiscal_period_id).toBe(PERIOD_2024.id)
|
|
expect(byId['doc-2023'].voucher_number).toBe('A7')
|
|
expect(byId['doc-2024'].voucher_number).toBe('B12')
|
|
expect(byId['doc-2023'].zip_path).toBe('dokument/2023/A7_r23.pdf')
|
|
expect(byId['doc-2024'].zip_path).toBe('dokument/2024/B12_r24.pdf')
|
|
|
|
// Files actually written under the new path
|
|
expect(zip.file('dokument/2023/A7_r23.pdf')).not.toBeNull()
|
|
expect(zip.file('dokument/2024/B12_r24.pdf')).not.toBeNull()
|
|
})
|
|
|
|
it('routes draft entries and orphans to dokument/_okopplade and disambiguates collisions', async () => {
|
|
enqueueMany([
|
|
{ data: COMPANY_ROW },
|
|
{ data: [PERIOD_2024] },
|
|
{
|
|
data: [
|
|
// True orphan: uploaded but never linked to any entry. Backups
|
|
// must still carry it (inbox items are räkenskapsinformation).
|
|
{
|
|
id: 'doc-orphan',
|
|
file_name: 'inbox.pdf',
|
|
storage_path: 'p/inbox.pdf',
|
|
journal_entry_id: null,
|
|
journal_entries: null,
|
|
},
|
|
// Draft entry: journal_entry_id present but voucher_number is null
|
|
{
|
|
id: 'doc-draft',
|
|
file_name: 'invoice.pdf',
|
|
storage_path: 'p/invoice.pdf',
|
|
journal_entry_id: 'e-draft',
|
|
journal_entries: { voucher_number: null, voucher_series: 'A', entry_date: null },
|
|
},
|
|
// Two posted docs that collide on the same voucher+filename
|
|
{
|
|
id: 'doc-collide-1234abcd-ee',
|
|
file_name: 'kvitto.pdf',
|
|
storage_path: 'p/kvitto-1.pdf',
|
|
journal_entry_id: 'e-posted',
|
|
journal_entries: { voucher_number: 5, voucher_series: 'A', entry_date: '2024-05-01' },
|
|
},
|
|
{
|
|
id: 'doc-collide-5678efgh-ff',
|
|
file_name: 'kvitto.pdf',
|
|
storage_path: 'p/kvitto-2.pdf',
|
|
journal_entry_id: 'e-posted',
|
|
journal_entries: { voucher_number: 5, voucher_series: 'A', entry_date: '2024-05-01' },
|
|
},
|
|
],
|
|
},
|
|
// entryIdToPeriodId map: draft and posted both resolve to PERIOD_2024
|
|
{
|
|
data: [
|
|
{ id: 'e-draft', fiscal_period_id: PERIOD_2024.id },
|
|
{ id: 'e-posted', fiscal_period_id: PERIOD_2024.id },
|
|
],
|
|
},
|
|
])
|
|
|
|
const buffer = await generateFullArchive(supabase as any, 'company-1', {
|
|
scope: 'all',
|
|
})
|
|
|
|
const zip = await JSZip.loadAsync(buffer)
|
|
const manifest = JSON.parse(await zip.file('dokument/manifest.json')!.async('text')) as Array<{
|
|
document_id: string
|
|
voucher_number: string | null
|
|
zip_path: string | null
|
|
}>
|
|
const byId = Object.fromEntries(manifest.map((m) => [m.document_id, m]))
|
|
|
|
// Unlinked orphan -> _okopplade, included in the backup
|
|
expect(byId['doc-orphan'].voucher_number).toBeNull()
|
|
expect(byId['doc-orphan'].zip_path).toBe('dokument/_okopplade/inbox.pdf')
|
|
|
|
// Draft -> _okopplade, no voucher prefix
|
|
expect(byId['doc-draft'].voucher_number).toBeNull()
|
|
expect(byId['doc-draft'].zip_path).toBe('dokument/_okopplade/invoice.pdf')
|
|
|
|
// First posted doc gets the canonical path
|
|
expect(byId['doc-collide-1234abcd-ee'].zip_path).toBe('dokument/2024/A5_kvitto.pdf')
|
|
// Second posted doc gets the id-suffix disambiguation before the extension
|
|
expect(byId['doc-collide-5678efgh-ff'].zip_path).toBe(
|
|
'dokument/2024/A5_kvitto_doc-coll.pdf'
|
|
)
|
|
|
|
// All files exist in the ZIP
|
|
expect(zip.file('dokument/_okopplade/inbox.pdf')).not.toBeNull()
|
|
expect(zip.file('dokument/_okopplade/invoice.pdf')).not.toBeNull()
|
|
expect(zip.file('dokument/2024/A5_kvitto.pdf')).not.toBeNull()
|
|
expect(zip.file('dokument/2024/A5_kvitto_doc-coll.pdf')).not.toBeNull()
|
|
})
|
|
|
|
it('throws when no fiscal periods exist', async () => {
|
|
enqueueMany([
|
|
{ data: COMPANY_ROW },
|
|
{ data: [] },
|
|
])
|
|
|
|
await expect(
|
|
generateFullArchive(supabase as any, 'company-1', { scope: 'all' })
|
|
).rejects.toThrow('No fiscal periods found')
|
|
})
|
|
|
|
it('includes imported SIE source files and master-data dumps in all-mode', async () => {
|
|
const importRow = {
|
|
id: 'import-1',
|
|
filename: 'original.se',
|
|
file_hash: 'abc123',
|
|
file_storage_path: 'company-1/import-1.se',
|
|
org_number: '5560000000',
|
|
company_name: 'Test AB',
|
|
sie_type: 4,
|
|
fiscal_year_start: '2024-01-01',
|
|
fiscal_year_end: '2024-12-31',
|
|
accounts_count: 42,
|
|
transactions_count: 120,
|
|
status: 'completed',
|
|
fiscal_period_id: PERIOD_2024.id,
|
|
imported_at: '2024-11-01T10:00:00Z',
|
|
created_at: '2024-11-01T09:55:00Z',
|
|
}
|
|
|
|
// Master-data dump runs sequentially over MASTER_DATA_DUMP_TABLES.
|
|
// Direct tables issue one query; via-tables issue a parent-id query and,
|
|
// when parents exist, one chunked child query.
|
|
const masterDataQueue = MASTER_DATA_DUMP_TABLES.flatMap((t): { data: unknown }[] => {
|
|
if (t.name === 'customers') {
|
|
return [{ data: [{ id: 'cust-1', name: 'Acme AB' }] }]
|
|
}
|
|
if (t.name === 'invoice_items') {
|
|
return [
|
|
{ data: [{ id: 'inv-1' }] }, // parent ids (invoices)
|
|
{ data: [{ id: 'item-1', invoice_id: 'inv-1', description: 'Konsulttid' }] },
|
|
]
|
|
}
|
|
if (t.via) return [{ data: [] }] // no parents -> no child query
|
|
if (t.name === 'company_settings') return [{ data: [COMPANY_ROW] }]
|
|
return [{ data: [] }]
|
|
})
|
|
|
|
enqueueMany([
|
|
{ data: COMPANY_ROW }, // fetchCompany
|
|
{ data: [PERIOD_2024] }, // fetchAllPeriods
|
|
{ data: [] }, // document_attachments
|
|
{ data: [importRow] }, // sie_imports
|
|
{ data: [{ source_account: '9999', target_account: '1510' }] }, // sie_account_mappings
|
|
...masterDataQueue,
|
|
])
|
|
|
|
const buffer = await generateFullArchive(supabase as any, 'company-1', {
|
|
scope: 'all',
|
|
})
|
|
const zip = await JSZip.loadAsync(buffer)
|
|
|
|
const originalFile = zip.file('sie/original/import-1_original.se')
|
|
expect(originalFile).not.toBeNull()
|
|
|
|
const manifestFile = zip.file('sie/original/manifest.json')
|
|
expect(manifestFile).not.toBeNull()
|
|
const manifest = JSON.parse(await manifestFile!.async('text'))
|
|
expect(manifest[0].import_id).toBe('import-1')
|
|
expect(manifest[0].status).toBe('downloaded')
|
|
|
|
const imports = JSON.parse(await zip.file('sie/imports.json')!.async('text'))
|
|
expect(imports[0].filename).toBe('original.se')
|
|
expect(zip.file('sie/account_mappings.json')).not.toBeNull()
|
|
|
|
// Every table in the dump contract gets a file, even when empty.
|
|
for (const t of MASTER_DATA_DUMP_TABLES) {
|
|
expect(zip.file(`data/${t.file}`), `data/${t.file}`).not.toBeNull()
|
|
}
|
|
|
|
const customers = JSON.parse(await zip.file('data/customers.json')!.async('text'))
|
|
expect(customers).toEqual([{ id: 'cust-1', name: 'Acme AB' }])
|
|
|
|
// Child table fetched via parent ids (invoice_items has no company_id).
|
|
const items = JSON.parse(await zip.file('data/invoice_items.json')!.async('text'))
|
|
expect(items).toEqual([
|
|
{ id: 'item-1', invoice_id: 'inv-1', description: 'Konsulttid' },
|
|
])
|
|
})
|
|
|
|
it('skips raw SIE blobs when include_documents is false but keeps metadata', async () => {
|
|
enqueueMany([
|
|
{ data: COMPANY_ROW },
|
|
{ data: [PERIOD_2024] },
|
|
{
|
|
data: [
|
|
{
|
|
id: 'import-1',
|
|
filename: 'x.se',
|
|
file_hash: 'h',
|
|
file_storage_path: 'company-1/import-1.se',
|
|
status: 'completed',
|
|
imported_at: '2024-11-01T10:00:00Z',
|
|
created_at: '2024-11-01T09:55:00Z',
|
|
},
|
|
],
|
|
}, // sie_imports
|
|
{ data: [] }, // sie_account_mappings
|
|
])
|
|
|
|
const buffer = await generateFullArchive(supabase as any, 'company-1', {
|
|
scope: 'all',
|
|
include_documents: false,
|
|
})
|
|
const zip = await JSZip.loadAsync(buffer)
|
|
|
|
expect(zip.file('sie/imports.json')).not.toBeNull()
|
|
expect(zip.file('sie/account_mappings.json')).not.toBeNull()
|
|
expect(zip.file('sie/original/import-1_x.se')).toBeNull()
|
|
expect(zip.file('sie/original/manifest.json')).toBeNull()
|
|
expect(zip.file('data/customers.json')).not.toBeNull()
|
|
})
|
|
})
|
|
})
|
|
|
|
describe('generateBaseDataArchive', () => {
|
|
let supabase: ReturnType<typeof createQueuedMockSupabase>['supabase']
|
|
let enqueueMany: ReturnType<typeof createQueuedMockSupabase>['enqueueMany']
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
mockGetAuditLog.mockResolvedValue({ data: [], count: 0 })
|
|
const mock = createQueuedMockSupabase()
|
|
supabase = mock.supabase
|
|
enqueueMany = mock.enqueueMany
|
|
})
|
|
|
|
it('bundles unlinked documents, master data, SIE sources and the audit trail', async () => {
|
|
const masterDataQueue = MASTER_DATA_DUMP_TABLES.flatMap((t): { data: unknown }[] => {
|
|
if (t.name === 'customers') return [{ data: [{ id: 'cust-1', name: 'Acme AB' }] }]
|
|
if (t.via) return [{ data: [] }]
|
|
return [{ data: [] }]
|
|
})
|
|
|
|
enqueueMany([
|
|
{ data: COMPANY_ROW }, // fetchCompany
|
|
{ data: [PERIOD_2024] }, // fetchAllPeriods
|
|
{
|
|
data: [
|
|
// Orphan: goes into Grunddata.
|
|
{
|
|
id: 'doc-orphan',
|
|
file_name: 'inbox.pdf',
|
|
storage_path: 'p/inbox.pdf',
|
|
journal_entry_id: null,
|
|
journal_entries: null,
|
|
},
|
|
// Linked to a posted entry: belongs to the period archive, not here.
|
|
{
|
|
id: 'doc-linked',
|
|
file_name: 'kvitto.pdf',
|
|
storage_path: 'p/kvitto.pdf',
|
|
journal_entry_id: 'e-1',
|
|
journal_entries: { voucher_number: 5, voucher_series: 'A', entry_date: '2024-05-01' },
|
|
},
|
|
],
|
|
}, // document_attachments
|
|
{ data: [{ id: 'e-1', fiscal_period_id: PERIOD_2024.id }] }, // entry->period map
|
|
{ data: [] }, // sie_imports
|
|
{ data: [] }, // sie_account_mappings
|
|
...masterDataQueue,
|
|
])
|
|
|
|
const buffer = await generateBaseDataArchive(supabase as any, 'company-1')
|
|
const zip = await JSZip.loadAsync(buffer)
|
|
|
|
const manifest = JSON.parse(await zip.file('dokument/manifest.json')!.async('text'))
|
|
expect(manifest).toHaveLength(1)
|
|
expect(manifest[0].document_id).toBe('doc-orphan')
|
|
expect(zip.file('dokument/_okopplade/inbox.pdf')).not.toBeNull()
|
|
|
|
expect(zip.file('data/customers.json')).not.toBeNull()
|
|
expect(zip.file('sie/imports.json')).not.toBeNull()
|
|
expect(zip.file('revision/behandlingshistorik.json')).not.toBeNull()
|
|
expect(zip.file('revision/systemdokumentation.json')).not.toBeNull()
|
|
|
|
const readme = await zip.file('LÄSMIG.txt')!.async('text')
|
|
expect(readme).toContain('Grunddata')
|
|
// Period-scoped content stays out of Grunddata.
|
|
expect(zip.file('bokforing.se')).toBeNull()
|
|
expect(zip.file('rapporter/saldobalans.json')).toBeNull()
|
|
})
|
|
})
|
|
|
|
describe('estimateArchiveSize', () => {
|
|
let supabase: ReturnType<typeof createQueuedMockSupabase>['supabase']
|
|
let enqueueMany: ReturnType<typeof createQueuedMockSupabase>['enqueueMany']
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
const mock = createQueuedMockSupabase()
|
|
supabase = mock.supabase
|
|
enqueueMany = mock.enqueueMany
|
|
})
|
|
|
|
it('sums document file_size_bytes in all-mode plus overhead', async () => {
|
|
enqueueMany([
|
|
{
|
|
data: [
|
|
{ file_size_bytes: 1_000_000, journal_entry_id: 'e1' },
|
|
{ file_size_bytes: 2_500_000, journal_entry_id: 'e2' },
|
|
],
|
|
count: 2,
|
|
},
|
|
])
|
|
|
|
const result = await estimateArchiveSize(supabase as any, 'company-1', 'all')
|
|
|
|
expect(result.document_bytes).toBe(3_500_000)
|
|
expect(result.document_count).toBe(2)
|
|
// overhead is +8 MB
|
|
expect(result.total_bytes).toBe(3_500_000 + 8 * 1024 * 1024)
|
|
})
|
|
|
|
it('returns overhead only when no documents in scope', async () => {
|
|
enqueueMany([
|
|
{ data: [], count: 0 }, // journal_entries for periodEntryIds
|
|
{ data: [], count: 0 }, // document_attachments
|
|
])
|
|
|
|
const result = await estimateArchiveSize(supabase as any, 'company-1', 'period', 'p-1')
|
|
|
|
expect(result.document_bytes).toBe(0)
|
|
expect(result.document_count).toBe(0)
|
|
expect(result.total_bytes).toBe(8 * 1024 * 1024)
|
|
})
|
|
})
|