fix: Swedish VAT/SIE compliance, storno hardening, document integrity (#209)

* feat: add INK2 declaration improvements, invoice delivery date, and Swedish compliance skills

Expand INK2 engine with full INK2S/INK2R support and improved SRU generation.
Add delivery_date field to invoices and corresponding PDF/migration support.
Add Claude skills for Swedish asset accounting, invoice compliance, SIE import/export, SRU filing, and tax planning.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address PR review — map BAS 4500–4899, strip CRLF in SRU, document P3

- Map BAS accounts 4500–4599 (legoarbeten), 4700–4899 (diverse
  varuinköpskostnader) to SRU 7512 so they are not silently dropped
  from INK2R declarations
- Strip \r\n in sanitizeString to prevent CRLF injection in SRU fields
- Document P3 period suffix limitation for brutet räkenskapsår

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: correct BAS 4500-4599, 4700-4899 mapping from 7512 to 7511

Per the official BAS-to-SRU mapping, these account ranges are cost of
goods (legoarbeten, inkurans, svinn) and belong under 7511 (Råvaror
och förnödenheter), not 7512 (Handelsvaror). 7512 remains 4600-4699.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: Swedish VAT compliance — representation VAT, domestic RC, full BAS 26xx mapping, SIE encoding

- Representation expenses now default to reduced_12 VAT (ML 13 kap 24-25 §§);
  income tax deduction was abolished 2017 but VAT deduction at 12% remains
- Domestic reverse charge (byggtjänster etc.) uses 2647 instead of 2645,
  with distinct line descriptions for Swedish vs EU/non-EU RC
- VAT declaration maps all BAS 26xx variant accounts (egna uttag 2612/2622/2632,
  uthyrning 2613/2623/2633, VMB 2616/2626/2636, import 2615/2625/2635,
  domestic RC 2647, frivillig skattskyldighet 2642) and revenue variants
  (3108/3105/3004/3100) to correct momsdeklaration rutor
- SIE parser: remove unreliable #FORMAT PC8 encoding detection (most software
  exports UTF-8 with PC8 header), parse #FLAGGA for import-already-done warning,
  default SIE type to 1 when absent, fix RTRANS/BTRANS documentation
- SIE export: add #RAR -1 (previous fiscal year), fix UB = IB + movements
- Error messages: add pattern matching for locked period trigger errors

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address Greptile review — update ruta49 JSDoc, use null sentinel in error map

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: harden storno CAS guard, document integrity, and BFNAR archive compliance

- Storno: defer original→reversed until both entries succeed, add CAS guard
  for concurrent reversals, use cancelEntry() instead of delete
- Document: add document.accessed event, enrich archive manifest with metadata,
  add BFNAR 2013:2 systemdokumentation to full archive export
- Verify cron: run daily, configurable batch size, include company_id in audit
- Migrations: integrity audit actions, document version chain, metadata
  immutability, audit deletions, fix immutability for posted/cancelled

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address Greptile review — allow is_current_version in immutability trigger, log cancelEntry errors

- Remove is_current_version from blocked fields in enforce_document_metadata_immutability
  trigger so create_document_version RPC can supersede documents linked to posted entries
- Add error logging to cancelEntry for observability on cleanup failures

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-04-09 16:12:03 +02:00
committed by GitHub
co-authored by Claude Opus 4.6
parent 6ccd4f429c
commit b484e9a7b4
17 changed files with 1214 additions and 47 deletions
+82 -8
View File
@@ -16,8 +16,16 @@ export interface FullArchiveOptions {
}
interface DocumentManifestEntry {
document_id: string
file_name: string
storage_path: string
sha256_hash: string
journal_entry_id: string | null
version: number
digitization_date: string | null
upload_source: string | null
mime_type: string | null
file_size_bytes: number | null
status: 'downloaded' | 'missing' | 'error'
error?: string
}
@@ -110,7 +118,7 @@ export async function generateFullArchive(
// Fetch document attachments linked to journal entries in this period
const { data: documents } = await supabase
.from('document_attachments')
.select('id, file_name, storage_path, journal_entry_id')
.select('id, file_name, storage_path, journal_entry_id, sha256_hash, version, digitization_date, upload_source, mime_type, file_size_bytes')
.eq('company_id', companyId)
.not('journal_entry_id', 'is', null)
@@ -129,6 +137,19 @@ export async function generateFullArchive(
)
for (const doc of periodDocuments) {
const baseManifest = {
document_id: doc.id,
file_name: doc.file_name,
storage_path: doc.storage_path,
sha256_hash: doc.sha256_hash,
journal_entry_id: doc.journal_entry_id,
version: doc.version,
digitization_date: doc.digitization_date,
upload_source: doc.upload_source,
mime_type: doc.mime_type,
file_size_bytes: doc.file_size_bytes,
}
try {
const { data: fileData, error } = await supabase.storage
.from('documents')
@@ -136,8 +157,7 @@ export async function generateFullArchive(
if (error || !fileData) {
manifest.push({
file_name: doc.file_name,
storage_path: doc.storage_path,
...baseManifest,
status: 'error',
error: error?.message || 'Download returned no data',
})
@@ -145,16 +165,16 @@ export async function generateFullArchive(
}
const buffer = await fileData.arrayBuffer()
dokument.file(doc.file_name, buffer)
// Prefix with document ID to prevent duplicate filename collisions
const zipFileName = `${doc.id}_${doc.file_name}`
dokument.file(zipFileName, buffer)
manifest.push({
file_name: doc.file_name,
storage_path: doc.storage_path,
...baseManifest,
status: 'downloaded',
})
} catch (err) {
manifest.push({
file_name: doc.file_name,
storage_path: doc.storage_path,
...baseManifest,
status: 'error',
error: err instanceof Error ? err.message : 'Unknown error',
})
@@ -187,5 +207,59 @@ export async function generateFullArchive(
revision.file('behandlingshistorik.json', JSON.stringify(allAuditEntries, null, 2))
// 5. Systemdokumentation (BFNAR 2013:2 kap 8)
const [accountsResult, voucherSeriesResult] = await Promise.all([
supabase
.from('chart_of_accounts')
.select('account_number, account_name, account_type, is_active')
.eq('company_id', companyId)
.order('account_number'),
supabase
.from('voucher_sequences')
.select('voucher_series, last_number')
.eq('company_id', companyId)
.eq('fiscal_period_id', period_id),
])
const systemdokumentation = {
system: {
name: 'gnubok',
description: 'Bokforingssystem for enskild firma och aktiebolag',
url: process.env.NEXT_PUBLIC_APP_URL || '',
},
kontoplan: {
standard: 'BAS 2026',
accounts: accountsResult.data || [],
},
verifikationsserier: (voucherSeriesResult.data || []).map((vs: { voucher_series: string; last_number: number }) => ({
serie: vs.voucher_series,
senaste_nummer: vs.last_number,
})),
behorighetskontroll: {
description: 'Rollbaserad atkomstkontroll med owner/admin/member/viewer',
mfa_stod: true,
rls_aktiv: true,
},
arkivering: {
lagringstid_ar: 7,
format: 'WORM (Write Once, Read Many)',
integritetskontroll: 'SHA-256 hashning vid uppladdning, regelbunden verifiering',
lagringsplats: 'Supabase Storage (krypterad)',
},
integrationer: {
bank: 'Enable Banking (PSD2)',
email: 'Resend',
export_format: 'SIE4',
},
generated_at: new Date().toISOString(),
fiscal_period: {
id: period.id,
start: period.period_start,
end: period.period_end,
},
}
revision.file('systemdokumentation.json', JSON.stringify(systemdokumentation, null, 2))
return zip.generateAsync({ type: 'arraybuffer' })
}