Files
accounted/lib/import/sie-parser.ts
T
Mattsson f3eacb436d Fix/articles (#1216)
* fix(security): gate replace_sie_import behind owner/admin membership

The RPC was SECURITY DEFINER with EXECUTE granted to PUBLIC and anon, no
company_members lookup, no auth.uid() reference and no unauthorized raise,
while setting gnubok.allow_delete to disarm the BFL immutability and
retention triggers. Any caller holding a company_id and an import id could
hard delete another tenant's verifikationer. Confirmed live in production.

Applies the same fail closed owner/admin guard that undo_sie_import already
carries (migration 20260624120000), resolving the actor from
COALESCE(p_user_id, auth.uid()) so it denies when the role is NULL, then
revokes EXECUTE from PUBLIC and anon. search_path and the raised
statement_timeout are restated, since CREATE OR REPLACE drops settings that
are not repeated.

userId is a required parameter on replaceSIEImport: the service client has a
NULL auth.uid(), so a caller without an explicit actor now fails to compile
rather than hitting the closed gate at runtime.

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

* fix(security): validate arcim OAuth callback state server side

The callback route is skipAuth and decoded the state parameter as plain
base64url JSON, trusting consentId and provider from it. A one time code was
minted at flow start and never read. An unauthenticated attacker who learned
a consent id could run an OAuth flow on their own provider account and post
the callback with a forged state, landing their tokens on another tenant's
consent, so the victim's next migration imported the attacker's ledger.

State is now an opaque randomBytes(32) pointer to a provider_otc row,
consumed by a single atomic UPDATE guarded on used_at IS NULL and
expires_at, so a replay loses the row lock race and updates nothing.
provider is read from provider_consents rather than trusted from the client.
provider_otc already existed for exactly this purpose and was never wired up.

Also scopes getConsent to an owning company, closing a cross tenant status
oracle where the preview and migrate paths echoed a consent's status before
the scoped check ran.

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

* fix(security): scope documents storage to company_id (phase A)

The documents bucket policies matched on auth.uid(), and upload keys were
documents/{userId}/..., so company membership was never consulted. Removing a
member revoked nothing: their session still authenticated and they kept
direct Storage read access to every receipt, supplier invoice and bank
statement they had uploaded. The same bug was fixed for sie-files in
20260416120000; this bucket was left behind.

Phase A is additive. Company scoped policies are added alongside the
uploader scoped ones, uploads move to documents/{companyId}/{userId}/..., and
reads accept either layout so nothing breaks mid migration. Phase C, which
drops the old policies, is gated on the backfill reporting zero remaining
legacy prefix objects.

The policy compares the company segment as text rather than casting to uuid
the way sie-files does: this bucket holds keys whose second segment is not a
uuid (MCP audit packages), and Postgres does not guarantee the bucket prefix
qual runs before the cast, so a planner reordering would raise 22P02 and fail
the whole query instead of filtering the row out.

deleteDocument now removes both candidate keys. Removing only the stored
pointer would leave a readable orphan copy of a document the user asked to
erase.

The backfill script is included but has never been run. It defaults to dry
run, refuses .env.local by name, and verifies each copy is readable and
SHA-256 identical before repointing the row.

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

* fix(security): enforce events:read scope and membership on /api/events

This was the only one of the three validateApiKey call sites with no
downstream guard: v1 and the MCP server both check scope and re-verify
company membership, this route did neither. An events:read scope existed and
was documented as gating the endpoint but was never called, so a legacy key
falling back to DEFAULT_SCOPES read the full log. The bound company id went
straight from the api_keys row into a service role query, so a key whose user
had been removed from the company kept reading.

Adds the scope check before any database access, re-verifies company_members
with archived_at IS NULL, honours test mode by stamping X-Gnubok-Mode instead
of ignoring it, applies minimisePayload so the pull surface can never return
a wider payload than the push surface, and replaces the three flat error
strings with the canonical envelope.

Test key reads are served rather than blocked: TEST_KEY_WRITE_BLOCKED is
gated on mutations in with-api-v1, so a read gets the same treatment as every
other v1 read endpoint.

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

* perf(bookkeeping): sweep remaining journal_entries!inner embeds

A previous refactor removed this pattern from lib/reports and introduced
fetchEntryLines, but the class was never swept. Seventeen sites remained and
had become the top application consumer of production database time:
measured across the resulting query shapes, 32,694 calls and 25,848 seconds
of execution, mean 790ms, with shapes averaging 2.6s and 3.0s and maxing at
7,962ms against the 8s statement_timeout, which surfaced to users as 500s on
the booking path.

PostgREST compiles an embed with filters on the embedded side into a
correlated INNER JOIN LATERAL with a parameterized LIMIT, which stops
Postgres reordering the join, so each query walked the whole
journal_entry_lines table across all tenants. Driving from the entries side
instead turns that into two indexed round trips.

Converted sites keep their existing shape: the helper reattaches the parent
entry under the same key the embed produced. Several conversions also remove
a latent silent truncation where an unpaginated query was capped at
PostgREST's 1000 row ceiling.

Two deliberate exceptions. The free text ilike legs of the MCP display query
stay on the embed, because each is capped at legLimit and that cap drives the
truncation contract the tool reports, while the helper is unbounded. The
accounts route moves to the existing get_account_usage_counts RPC instead,
since its embed was a head count and the helper returns rows.

commitEntry's write path is untouched: the change there is confined to the
read query of the pre-commit dimension rule check.

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

* fix(api): anchor v1 list cursors on created_at

Page two returned page one, forever, while still advertising a fresh
next_cursor. The three routes sorted by and encoded a Postgres date column,
which serializes as YYYY-MM-DD, but decodeDefaultCursor validates the cursor
timestamp as full ISO-8601 and returned null, so the keyset filter was never
applied and has_more never went false. An integrator syncing verifikat looped
on the newest rows indefinitely.

The transactions route already solved this and its comment names the trap;
the fix was never ported. All three now order and encode on created_at with
an id tie break, matching the transactions keyset predicate exactly.
ISO_TIMESTAMP is deliberately left alone: relaxing it would silently change
sort semantics on the route that currently works.

Default ordering therefore moves from business date to insert order. Every
business date is still on the row, and the invoices list gains date_from and
date_to filters so a date range is still reachable; the other two already had
them.

The tests use an in-memory PostgREST that actually evaluates the filters,
because the repo's pass-through mock cannot catch this class of bug: the bug
is that the filter is never sent. They walk to exhaustion with a hard
iteration cap, so an unterminated walk fails instead of hanging.

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

* fix(api): separate dry run from commit in the idempotency hash

The request hash was built from url.pathname, which excludes the query
string, so a dry run and its commit hashed identically. Following the flow
documented in dry-run.ts, re-issuing the request with the same
Idempotency-Key returned the cached preview with Idempotent-Replayed set and
wrote nothing, while reporting 200. An agent or integrator saw success for a
write that never happened.

dry_run is folded into the hash only when true, not as an unconditional
boolean. Including it as false would change the hash of every ordinary write,
and with a 24h idempotency TTL any key in flight across the deploy would fail
the request_hash comparison and 409 on a legitimate retry. Both hash call
sites now go through one shared helper so they cannot drift into a permanent
cache miss, and dry run responses are no longer stored at all.

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

* ci: install the Bedrock SDK out of tree in the compliance review

The Swedish accounting compliance gate had failed ten consecutive runs and so
was posting nothing. With --no-package-lock npm discarded the lockfile and
re-resolved the whole tree from package.json, floating @hookform/resolvers to
5.4.3, whose valibot ^1 peer conflicts with the pinned valibot 0.39.0.

Installing into the parent of the checkout resolves only that one package, so
an unrelated peer conflict can never take the gate down again. Node still
finds it because ESM bare specifiers walk up parent node_modules; NODE_PATH
would not have worked, as it is CommonJS only. --legacy-peer-deps was
rejected because it masks future genuine peer conflicts and still reifies the
full tree.

The same step's SDK version is aligned from 0.31.0 back to the 0.29.1 that
package.json and check:guards enforce after the streaming outage. That drift
went unnoticed because the pin guard only inspects package.json and the
lockfile, never workflow files.

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

* build(docker): generate crontabs from vercel.json

vercel.json defines 16 cron jobs; both Docker crontabs carried 9, and were
byte identical to each other. Self hosted deployments therefore never sent
recurring invoices, never dispatched webhooks and never cleaned up
idempotency keys. tax-deadlines also ran once a year on 2 January instead of
daily, and documents/verify weekly instead of daily.

Extension crons are included rather than excluded. The Dockerfile copies the
whole tree before building, so every extension cron route is compiled into
the image regardless of the enabled preset, and each returns 200 when its
extension is unconfigured, so curl -sf logs no failure. Two such entries were
already present in the crontab for extensions absent from the preset, which
settles the intent.

documents/verify is treated as drift rather than a self hosted concession:
the weekly cadence was present in the hosted crontab too, and the run is
capped at 200 documents walking a nulls-first queue, so weekly drains the
integrity queue seven times slower on a check that exists for BFL retention.

webhooks/dispatch keeps its per minute cadence, adding 1,440 requests a day
on self hosted. A gentler tick would silently stretch the first retry, since
the retry ladder opens at 60 seconds. SCHEDULE_OVERRIDES is the one line
place to change that.

A parity test asserts the path sets match minus a documented exclusion list,
and ratchets three cron routes that are currently scheduled nowhere so they
are named rather than silently rotting.

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

* chore(observability): add a provider agnostic error sink

There is no error tracking in this codebase: logs go to console and Vercel
retention and nowhere else, nothing alerts on the 16 cron jobs, and seven
code comments across lib, app, components and extensions asserted that Sentry
captures errors when Sentry is not a dependency. The two most recent bug
fixes on this repo were both discovered by customer email.

This adds the sink, not a vendor. No dependency is taken: the interface has a
no-op default and a registration point, so behaviour is unchanged until an
adapter is registered. Releases are tagged from the build id already inlined
by next.config.ts.

Redaction moved out of lib/logger.ts into a leaf module that both the logger
and the sink import, so there is one denylist and no path from application
data to a third party can skip the personnummer regex, including direct sink
calls that bypass the logger. That matters here because these logs carry
personnummer and financial data.

verifyCronSecret now reports its own 401s, which covers all 16 jobs without
touching a route file and catches the case where CRON_SECRET is rotated
without updating the scheduler and every job silently 401s forever. The
threshold is one failure rather than the backup alert's three: suppressing
the first occurrence is precisely how an outage stays invisible.

The seven misleading comments are corrected to describe what the code
actually does, including the two cases that still are not covered: the client
side one, since the sink is server side, and a warn level call that is not
forwarded.

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

* fix: remediate the 2026-07-26 similar-sweep findings across all surfaces

Resolves the ~150-finding sweep (dev_docs/similar-sweep-2026-07-26.md) with
one agent per finding; every behavioural fix carries a regression test proven
to fail at HEAD. Full status, corrections to the sweep, refusals and open
decisions in dev_docs/similar-sweep-2026-07-26-remediation-status.md.

Structural roots closed:
- resolveSekAmountOrNull(): honest SEK resolution refuses instead of booking
  1:1; four duplicated toSek closures now refuse via INVOICE_FX_RATE_MISSING
- ledger-line-amount.ts: journal_entry_lines.currency labels the document,
  not the amount; SQL pre-filter decoy proven and fixed
- sparse-patch.ts: .partial() does not strip .default() in Zod 4.4.3; the
  exploitable salary payslip-line PATCH and KPI preferences sinks fixed
- tests/schema: migration-replay phantom-column guard (13k+ refs, closed
  CHECK sets, onConflict targets); found 28 real defects, all fixed, all
  four baselines now empty
- three new ratchet guards: sek-labelled-amount, cross-extension-import,
  ungated-extension-route

Highlights: lawful VAT-rate set on all seven invoice surfaces (ML 6 kap),
RC input VAT mismatch wired on web + both MCP callers, missing-underlag
resource delegates to the shared RPC predicate, push-notifications consent
polarity fail-closed, deadlines undo honours requested state, silent-failure
and read-side-fabrication classes fixed across settings/KPI/inbox/Stripe/
Arcim/kassaflodesanalys, error-envelope stringification fixed at 10+ sites
with isSwedishUserMessage extended.

Also includes the parallel session's MCP invoice tools (update_invoice,
recurring schedules, invoice deliveries) which share files with the sweep
work and are verified green together.

13 new migrations are NOT applied anywhere; they apply via branch merge.
20260726120000 backfills 1247 supplier-invoice rows. pg tests for new
DDL are written but unrun (no local Postgres).

Verified: 11088 tests / 881 files green, tsc 0 non-test errors, lint 0
errors, check:guards passing, MCP payload 57475/57500.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(migrations): rename replace_sie_import migration off main's 20260726090000 version

origin/main shipped 20260726090000_agent_quota_rpc_caller_guard.sql; keeping
our replace_sie_import migration on the same version would abort the Supabase
apply with a schema_migrations_pkey duplicate at merge time.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(review): remediate pre-publish deep-review findings across all slices

A 13-agent review of the full branch diff surfaced 1 critical, 5 high and
~45 further findings; this commit resolves them in one pass:

- replace_sie_import / undo_sie_import: p_user_id honored only for
  service_role callers; any other caller is pinned to auth.uid()
  (impersonation gate bypass), authz raise errcode 42501 mapped to a
  Swedish 403 in the route, new caller-guard migration for undo
- bulk_book_transactions refuses homogeneous non-SEK batches instead of
  writing foreign magnitudes into SEK ledger columns
- credit-note cap trigger: company-match on credited_invoice_id, no
  cross-tenant figures in exception text
- link_voucher RPCs resolve NULL invoice currency as SEK end to end
- personal-number ciphertext CHECK split into NOT VALID + VALIDATE
- same-currency foreign settlements clear 1510 at booking rate and book
  realized diff to 3960/7960; rate-less foreign write paths refuse
- receivables revaluation covers partially_paid and outstanding amounts
- period lock guard paginates candidates past the PostgREST 1000 cap
- documents: service-client storage removals after authz, dual-layout
  reads in integrity cron and archive export, backfill delete-source
  sweep actually deletes with hash verification and shared-key grouping
- invoice matching normalizes NULL/lowercase currencies (regression),
  duplicate candidates stop claiming amount matches they never ran
- match-invoice aborts on any booking failure (no paid-without-verifikat)
- refresh-exchange-rate reverts on concurrent booking (TOCTOU window)
- KPI preferences upsert arbiter aligned to the company-scoped constraint
- personnummer_last4 stripped from all salary responses incl. MCP tools
- worked-hours batch restores destroyed rows on conflict and error paths
- MCP: shared duplicate-claim builder (no more 'null kr'), short-circuit
  on tag_journal_lines overflow, auto_send schedules stage as high risk
- observability sink redacts emails/IBANs/API keys and keeps redacted
  stacks in prod; assorted small guards (safe-return-to /@, dry_run=True,
  cursor helper off-by-one, OAuth state TTL 10 min, arcim saveMappings
  call removed)

Full dispositions, deferred items and hand-verified accounting numbers
are documented in the PR body and DECISIONS.md.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(personnummer): implement masking and encryption for personal numbers with tests

* fix(review): address CI and compliance-bot findings for PR #1215

pg-real: the CI image's auth shim reads the legacy request.jwt.claim.role
GUC, so both service-role simulations (runAsServiceRole and the
invoice-delivery test's local helper) never satisfied auth.role() =
'service_role' and every legitimate p_user_id path failed closed; the
shared helper now sets both GUC shapes plus SET LOCAL ROLE with a
fail-loud sanity check, and the delivery test reuses it. The link-voucher
migration had recreated both RPCs from pre-rewrite file text,
reintroducing the NULL-unsafe membership pattern the
null-safe-tenant-guards ratchet bans; both guards now use
public.caller_is_company_member() with all currency changes preserved.

Compliance bots: the customers export now emits the standard masked form
instead of raw AES-256-GCM ciphertext in the Org-/personnummer column,
and maskCustomerRow returns a non-round-trippable placeholder on decrypt
failure instead of 500ing the list. MCP parity: gnubok_lock_period's
staging pre-check now runs the exact countUnbookedInPeriod the commit
path enforces (exported from period-service; local mirror deleted), and
gnubok_agi_status resolves AGI state run-scoped so a correction run no
longer renders as already filed.

Declined with evidence: PR-Agent's opening-balances null-zeroing concern
(all mergeable columns are NOT NULL with defaults per 20260713101000).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(review): address codex review findings on PR #1215

- restore 20260726140000 to its preview-recorded content and restate the
  NULL-safe tenant guard under 20260727130000: a recorded migration version
  never re-runs, so the in-place edit could not reach the preview branch
- replace toFixed() with sv-SE two-decimal formatting in the ROT/RUT cap
  warning texts and update the pinned test expectations
- drop the em dash in the fiscal-periods route comment
- strip trailing whitespace in import-existing.test.ts

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test(reports): raise timeout on real PDF render tests

renderToBuffer does real @react-pdf layout work and exceeds the 5s
default when the full suite saturates the CPU; tests pass in isolation.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(review): remediate the 2026-07-27 compliance and security review findings

- ROT/RUT deduction base is arbetskostnaden INKLUSIVE moms (HUSFL 2009:194
  6-9 par.): computeDeduction takes the line vat_rate, all five call sites
  pass it, and tests pin Skatteverkets worked example (18 000 kr excl =
  22 500 incl, ROT 6 750).
- Momsdeklaration: new SALES_OUTPUT_VAT_SHORTFALL warning catches output VAT
  short of the reported sales base (one-directional, never filing-blocking).
- SIE import: #RAR records validated for every year index (dates, ordering,
  18-month BFL cap as warn-and-keep).
- build-invoice-write: SEK invoices populate the *_sek twin columns (rate 1)
  so both creation paths produce the same row shape.
- CI: daily Trivy SCA scan of the npm lockfile (replaces removed Dependabot);
  compliance review fails loudly on empty review.md.
- arcim migration FX logging routed through the redacting structured logger.
- docs/security/: authorization policy for the SIE bulk-delete RPC pair and
  the observability redaction contract.
- Rewrote the swedish-payroll ob-overtime reference (was a byte-identical
  copy of sick-pay.md); skills:generate emitted the atom-body seed migration.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 03:54:42 +02:00

1198 lines
39 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* SIE File Parser
*
* Parses SIE (Standard Import Export) files, the Swedish standard format
* for accounting data exchange. Supports SIE1-SIE4 formats.
*
* SIE4 is the most complete format with full transaction history.
* SIE1 contains only year-end balances.
*
* Reference: https://sie.se/format/
*/
import { monthsBetween } from '@/lib/bookkeeping/validate-period-duration'
import type {
SIEType,
SIEEncoding,
SIEHeader,
SIEAccount,
SIEBalance,
SIEVoucher,
SIETransactionLine,
SIEDimension,
SIEDimensionValue,
ParsedSIEFile,
ParseIssue,
ParseIssueSeverity,
ValidationResult,
} from './types'
// CP437 to UTF-8 mapping: full 0x80-0x9F range
// CP437 was the standard encoding for DOS/early Windows (used by SIE #FORMAT PC8)
const CP437_MAP: Record<number, string> = {
// 0x80-0x8F
0x80: 'Ç', // Ç
0x81: 'ü', // ü
0x82: 'é', // é
0x83: 'â', // â
0x84: 'ä', // ä
0x85: 'à', // à
0x86: 'å', // å
0x87: 'ç', // ç
0x88: 'ê', // ê
0x89: 'ë', // ë
0x8a: 'è', // è
0x8b: 'ï', // ï
0x8c: 'î', // î
0x8d: 'ì', // ì
0x8e: 'Ä', // Ä
0x8f: 'Å', // Å
// 0x90-0x9F
0x90: 'É', // É
0x91: 'æ', // æ
0x92: 'Æ', // Æ
0x93: 'ô', // ô
0x94: 'ö', // ö
0x95: 'ò', // ò
0x96: 'û', // û
0x97: 'ù', // ù
0x98: 'ÿ', // ÿ
0x99: 'Ö', // Ö
0x9a: 'Ü', // Ü
0x9b: 'ø', // ø (Norwegian)
0x9c: '£', // £
0x9d: 'Ø', // Ø (Norwegian)
0x9e: '×', // ×
0x9f: 'ƒ', // ƒ
}
// Windows-1252 bytes for Swedish characters (superset of ISO-8859-1)
// These bytes are NOT in the CP437 map, so they need separate detection.
const WIN1252_SWEDISH_BYTES = new Set([
0xe5, // å
0xe4, // ä
0xf6, // ö
0xc5, // Å
0xc4, // Ä
0xd6, // Ö
])
/**
* Detect the encoding of a SIE file by looking for Swedish characters.
*
* Strategy:
* 1. UTF-8 BOM → utf8
* 2. `#FORMAT PC8` in raw bytes → cp437 (SIE standard header for CP437)
* 3. Range-based discrimination: CP437 Swedish chars live in 0x80-0x9F,
* Windows-1252 Swedish chars live in 0xC0-0xFF. These ranges don't overlap,
* so presence in one range rules out the other.
* 4. UTF-8 multi-byte sequences (0xC3 + continuation) are detected with proper
* skipping of continuation bytes to avoid false CP437 counts.
*
* Scans the entire buffer (not a sample): SIE files are capped at 50 MB and
* Swedish characters often only appear deep in voucher descriptions, well past
* any small header sample.
*/
export function detectEncoding(buffer: ArrayBuffer): SIEEncoding {
const bytes = new Uint8Array(buffer)
// Check for UTF-8 BOM
if (bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) {
return 'utf8'
}
// NOTE: #FORMAT PC8 is NOT used for encoding detection.
// Almost all SIE files declare #FORMAT PC8 regardless of actual encoding
// (Fortnox, Bokio, Dooer etc. export UTF-8 with #FORMAT PC8).
// Instead, we detect encoding from actual byte patterns.
let cp437Count = 0 // Swedish chars in 0x80-0x9F (CP437 range)
let utf8Count = 0 // Valid UTF-8 multi-byte Swedish sequences
let win1252Count = 0 // Swedish chars in 0xC0-0xFF (Win-1252 range)
for (let i = 0; i < bytes.length; i++) {
const byte = bytes[i]
// Check for UTF-8 multi-byte sequences for Swedish chars FIRST
// to avoid false CP437/Win-1252 counts from continuation bytes.
// Ä = C3 84, Å = C3 85, Ö = C3 96, ä = C3 A4, å = C3 A5, ö = C3 B6, é = C3 A9
if (byte === 0xc3 && i + 1 < bytes.length) {
const nextByte = bytes[i + 1]
if ([0x84, 0x85, 0x96, 0xa4, 0xa5, 0xb6, 0xa9].includes(nextByte)) {
utf8Count++
i++ // Skip continuation byte to avoid false CP437 count (e.g. 0x84 = ä in CP437)
continue
}
}
// Check for CP437 Swedish characters (0x80-0x9F range)
if (CP437_MAP[byte]) {
cp437Count++
}
// Check for Windows-1252 Swedish characters (0xC0-0xFF range)
if (WIN1252_SWEDISH_BYTES.has(byte)) {
win1252Count++
}
}
if (utf8Count > cp437Count && utf8Count > win1252Count) return 'utf8'
if (cp437Count > win1252Count) return 'cp437'
if (win1252Count > 0) return 'windows1252'
// Pure ASCII (no high bytes): UTF-8 is a superset of ASCII
return 'utf8'
}
/**
* Decode a buffer to string using the specified encoding.
*
* After decoding, validates the result for U+FFFD replacement characters
* (which signal that the chosen encoding was wrong). When found, retries
* with each alternate encoding and returns the first result without U+FFFD.
* This guards against `detectEncoding` heuristic misses on files where
* Swedish characters are rare or absent in the bytes the detector looked at.
*/
export function decodeBuffer(buffer: ArrayBuffer, encoding: SIEEncoding): string {
const primary = decodeBufferRaw(buffer, encoding)
if (!primary.includes('\uFFFD')) return primary
const alternates: SIEEncoding[] = (['utf8', 'windows1252', 'cp437'] as const).filter(
(e) => e !== encoding
)
for (const alt of alternates) {
const candidate = decodeBufferRaw(buffer, alt)
if (!candidate.includes('\uFFFD')) return candidate
}
return primary
}
function decodeBufferRaw(buffer: ArrayBuffer, encoding: SIEEncoding): string {
if (encoding === 'utf8') {
const decoder = new TextDecoder('utf-8')
return decoder.decode(buffer)
}
if (encoding === 'windows1252') {
const decoder = new TextDecoder('windows-1252')
return decoder.decode(buffer)
}
// CP437 decoding
const bytes = new Uint8Array(buffer)
let result = ''
for (let i = 0; i < bytes.length; i++) {
const byte = bytes[i]
if (CP437_MAP[byte]) {
result += CP437_MAP[byte]
} else if (byte < 128) {
result += String.fromCharCode(byte)
} else {
// For other high bytes, try to preserve as-is
result += String.fromCharCode(byte)
}
}
return result
}
/**
* Parse a date from SIE format (YYYYMMDD) into a Date object.
* Used for voucher dates where Date arithmetic is needed.
*/
function parseSIEDate(dateStr: string): Date | null {
if (!dateStr || dateStr.length !== 8) {
return null
}
const year = parseInt(dateStr.substring(0, 4), 10)
const month = parseInt(dateStr.substring(4, 6), 10) - 1
const day = parseInt(dateStr.substring(6, 8), 10)
if (isNaN(year) || isNaN(month) || isNaN(day)) {
return null
}
const date = new Date(year, month, day)
// Reject invalid dates that auto-roll (e.g. Feb 30 → Mar 2)
if (date.getFullYear() !== year || date.getMonth() !== month || date.getDate() !== day) {
return null
}
return date
}
/**
* Parse a date from SIE format (YYYYMMDD) into an ISO date string "YYYY-MM-DD".
* Used for fiscal year dates and generated dates to avoid timezone issues
* during JSON serialization (Date objects shift when crossing UTC boundaries).
*/
function parseSIEDateString(dateStr: string): string | null {
if (!dateStr || dateStr.length !== 8) {
return null
}
const year = dateStr.substring(0, 4)
const month = dateStr.substring(4, 6)
const day = dateStr.substring(6, 8)
const y = parseInt(year, 10)
const m = parseInt(month, 10)
const d = parseInt(day, 10)
if (isNaN(y) || isNaN(m) || isNaN(d)) {
return null
}
// Validate by round-tripping through Date (rejects Feb 30, etc.)
const date = new Date(y, m - 1, d)
if (date.getFullYear() !== y || date.getMonth() !== m - 1 || date.getDate() !== d) {
return null
}
return `${year}-${month}-${day}`
}
/**
* Parse a quoted string field from SIE
* Handles: "value" or value
*/
function parseStringField(field: string): string {
if (!field) return ''
// Remove surrounding quotes if present
if (field.startsWith('"') && field.endsWith('"')) {
return field.slice(1, -1).replace(/\\"/g, '"')
}
return field
}
/**
* Parse a numeric field from SIE
*/
function parseNumberField(field: string): number {
if (!field) return 0
// Strip quotes and use dot as decimal separator
const cleaned = parseStringField(field)
return parseFloat(cleaned.replace(',', '.')) || 0
}
/**
* Split a SIE line into fields, respecting quoted strings and braced object lists
*/
function splitSIELine(line: string): string[] {
const fields: string[] = []
let current = ''
let inQuotes = false
let braceDepth = 0
let escaped = false
for (let i = 0; i < line.length; i++) {
const char = line[i]
if (escaped) {
current += char
escaped = false
continue
}
if (char === '\\') {
escaped = true
current += char
continue
}
if (char === '"' && braceDepth === 0) {
inQuotes = !inQuotes
current += char
continue
}
// Track brace depth for object lists like {1 "ProjectA"}
if (char === '{' && !inQuotes) {
braceDepth++
current += char
continue
}
if (char === '}' && !inQuotes) {
braceDepth = Math.max(0, braceDepth - 1)
current += char
continue
}
// SIE 4 spec allows either space or tab as field separator (programs like
// Bollbok export tab-separated lines). Quoted strings and brace-bounded
// dimension lists preserve any interior whitespace via the guards above.
if ((char === ' ' || char === '\t') && !inQuotes && braceDepth === 0) {
if (current) {
fields.push(current)
current = ''
}
continue
}
current += char
}
if (current) {
fields.push(current)
}
return fields
}
/**
* Parse a #TRANS object list (`{1 "KS01" 6 "P001"}`) into an SIE dim
* number → object code map. The list arrives as ONE field thanks to the
* brace-aware splitter; the inner content is itself space-separated with
* SIE quoting, so it re-runs through splitSIELine. Returns undefined for an
* empty list ({}), malformed pairs are skipped with a warning issue.
*/
function parseObjectList(
raw: string,
issues: ParseIssue[],
lineNum: number
): Record<string, string> | undefined {
const inner = raw.replace(/^\{/, '').replace(/\}$/, '').trim()
if (!inner) return undefined
const parts = splitSIELine(inner)
if (parts.length % 2 !== 0) {
addIssue(issues, 'warning', lineNum, `Objektlista med udda antal fält ignoreras delvis: ${raw}`, 'TRANS')
}
const dims: Record<string, string> = {}
for (let i = 0; i + 1 < parts.length; i += 2) {
const dimNoRaw = parseStringField(parts[i])
const code = parseStringField(parts[i + 1]).trim()
const dimNo = parseInt(dimNoRaw, 10)
if (isNaN(dimNo) || dimNo < 1 || !code) {
addIssue(issues, 'warning', lineNum, `Ogiltigt objektpar i objektlista: ${dimNoRaw} ${code}`, 'TRANS')
continue
}
// Canonical numeric key ('01' → '1'): matches normalizeLineDimensions.
dims[String(dimNo)] = code
}
return Object.keys(dims).length > 0 ? dims : undefined
}
/**
* Add an issue to the issues list
*/
function addIssue(
issues: ParseIssue[],
severity: ParseIssueSeverity,
line: number,
message: string,
tag?: string
): void {
issues.push({ severity, line, message, tag })
}
/**
* Parse a SIE file content string
*/
export function parseSIEFile(content: string): ParsedSIEFile {
const lines = content.split(/\r?\n/)
const issues: ParseIssue[] = []
// Initialize header with defaults
// Per SIE spec: if #SIETYP is absent, assume type 1 (closing balances only)
const header: SIEHeader = {
sieType: 1,
flagga: null,
program: null,
programVersion: null,
generatedDate: null,
format: null,
companyName: null,
orgNumber: null,
address: null,
fiscalYears: [],
currency: 'SEK',
kontoPlanType: null,
}
const accounts: SIEAccount[] = []
const openingBalances: SIEBalance[] = []
const closingBalances: SIEBalance[] = []
const resultBalances: SIEBalance[] = []
const vouchers: SIEVoucher[] = []
const dimensions: SIEDimension[] = []
const dimensionValues: SIEDimensionValue[] = []
let objectBalanceCount = 0
// Track current voucher being parsed (inside #VER { ... })
let currentVoucher: SIEVoucher | null = null
for (let i = 0; i < lines.length; i++) {
const lineNum = i + 1
const line = lines[i].trim()
// Skip empty lines
if (!line) continue
// Handle voucher block end
if (line === '}') {
if (currentVoucher) {
// Validate voucher balance
const total = currentVoucher.lines.reduce((sum, l) => sum + l.amount, 0)
if (Math.abs(total) > 0.01) {
addIssue(
issues,
'error',
lineNum,
`Verifikation ${currentVoucher.series}${currentVoucher.number} balanserar inte (differens: ${total.toFixed(2)} kr)`,
'VER'
)
}
vouchers.push(currentVoucher)
currentVoucher = null
}
continue
}
// Handle voucher block start
if (line === '{') {
continue
}
// Skip lines that don't start with #
if (!line.startsWith('#')) {
continue
}
// Parse the tag and fields
const fields = splitSIELine(line)
const tag = fields[0].substring(1).toUpperCase()
try {
switch (tag) {
case 'FLAGGA':
header.flagga = parseInt(fields[1], 10) || 0
break
case 'FORMAT':
header.format = parseStringField(fields[1])
break
case 'SIETYP':
header.sieType = parseInt(fields[1], 10) as SIEType
if (![1, 2, 3, 4].includes(header.sieType)) {
addIssue(issues, 'warning', lineNum, `Okänd SIE-typ: ${fields[1]}. Filen tolkas som SIE4.`, tag)
header.sieType = 4
}
break
case 'PROGRAM':
header.program = parseStringField(fields[1])
header.programVersion = parseStringField(fields[2])
break
case 'GEN':
if (fields[1]) {
header.generatedDate = parseSIEDateString(fields[1])
}
break
case 'ORGNR':
header.orgNumber = parseStringField(fields[1])
break
case 'FNAMN':
header.companyName = parseStringField(fields[1])
break
case 'ADRESS':
header.address = [fields[1], fields[2], fields[3], fields[4]]
.filter(Boolean)
.map(parseStringField)
.join(', ')
break
case 'VALUTA':
header.currency = parseStringField(fields[1]) || 'SEK'
break
case 'KPTYP':
header.kontoPlanType = parseStringField(fields[1])
break
case 'RAR': {
// #RAR yearIndex start end
//
// Validated for EVERY year index, not just 0: prior-year records
// (#RAR -1, -2, ...) land in header.fiscalYears too, and a bogus
// entry there used to pass through silently. Malformed records are
// reported and skipped so fiscalYears never carries an entry the
// rest of the pipeline cannot trust. The one exception is the
// 18-month BFL 3 kap. cap: an over-long span is reported as a
// warning but the entry is KEPT, because executeSIEImport refuses
// the current year (#RAR 0) with a precise Swedish error that needs
// the real dates, and dropping the record here would degrade that
// message to "no fiscal year defined".
const yearIndex = parseInt(fields[1], 10)
const start = parseSIEDateString(fields[2])
const end = parseSIEDateString(fields[3])
if (!Number.isInteger(yearIndex)) {
addIssue(issues, 'warning', lineNum, `Ogiltigt årsindex i #RAR: "${fields[1] ?? ''}"`, tag)
break
}
if (!start || !end) {
addIssue(issues, 'warning', lineNum, 'Invalid fiscal year dates', tag)
break
}
if (end < start) {
addIssue(
issues,
'warning',
lineNum,
`Räkenskapsårets slutdatum (${end}) ligger före startdatumet (${start}) i #RAR ${yearIndex}`,
tag
)
break
}
const rarMonths = monthsBetween(start, end)
if (rarMonths > 18) {
addIssue(
issues,
'warning',
lineNum,
`Räkenskapsåret i #RAR ${yearIndex} (${start} till ${end}) omfattar ${rarMonths} månader: ett räkenskapsår får vara högst 18 månader (BFL 3 kap.)`,
tag
)
}
header.fiscalYears.push({ yearIndex, start, end })
break
}
case 'KONTO': {
// #KONTO number "name"
const number = fields[1]
const name = parseStringField(fields[2])
if (number && name) {
accounts.push({ number, name })
} else {
addIssue(issues, 'warning', lineNum, 'Invalid account definition', tag)
}
break
}
case 'SRU': {
// #SRU accountNumber sruCode
const accountNum = fields[1]
const sruCode = fields[2]
const account = accounts.find((a) => a.number === accountNum)
if (account) {
account.sruCode = sruCode
}
break
}
case 'KTYP': {
// #KTYP accountNumber type
// Bollbok 2025 writes the type unquoted (T), Bollbok 2026 writes it
// quoted ("T"). parseStringField strips the quotes in both cases.
const accountNum = fields[1]
const accountType = parseStringField(fields[2])
const account = accounts.find((a) => a.number === accountNum)
if (account) {
account.accountType = accountType
}
break
}
case 'IB': {
// #IB yearIndex accountNumber amount [quantity]
const yearIndex = parseInt(fields[1], 10)
const account = fields[2]
const amountStr = fields[3]
if (!amountStr || amountStr.trim() === '') {
addIssue(issues, 'warning', lineNum, 'Belopp saknas i #IB: raden hoppas över', tag)
break
}
const amount = parseNumberField(amountStr)
const quantity = fields[4] ? parseNumberField(fields[4]) : undefined
if (account) {
openingBalances.push({ yearIndex, account, amount, quantity })
}
break
}
case 'UB': {
// #UB yearIndex accountNumber amount [quantity]
const yearIndex = parseInt(fields[1], 10)
const account = fields[2]
const amountStr = fields[3]
if (!amountStr || amountStr.trim() === '') {
addIssue(issues, 'warning', lineNum, 'Belopp saknas i #UB: raden hoppas över', tag)
break
}
const amount = parseNumberField(amountStr)
const quantity = fields[4] ? parseNumberField(fields[4]) : undefined
if (account) {
closingBalances.push({ yearIndex, account, amount, quantity })
}
break
}
case 'RES': {
// #RES yearIndex accountNumber amount [quantity]
const yearIndex = parseInt(fields[1], 10)
const account = fields[2]
const amountStr = fields[3]
if (!amountStr || amountStr.trim() === '') {
addIssue(issues, 'warning', lineNum, 'Belopp saknas i #RES: raden hoppas över', tag)
break
}
const amount = parseNumberField(amountStr)
const quantity = fields[4] ? parseNumberField(fields[4]) : undefined
if (account) {
resultBalances.push({ yearIndex, account, amount, quantity })
}
break
}
case 'VER': {
// #VER series number date "description" [regdate] [signature]
// Some programs quote all fields, so strip quotes from number/date too
const series = parseStringField(fields[1])
const number = parseInt(parseStringField(fields[2]), 10)
const date = parseSIEDate(parseStringField(fields[3]))
const description = parseStringField(fields[4])
if (!isNaN(number) && date) {
currentVoucher = {
series,
number,
date,
description: description || '',
lines: [],
}
// Optional registration date and signature
if (fields[5]) {
currentVoucher.registrationDate = parseSIEDate(parseStringField(fields[5])) || undefined
}
if (fields[6]) {
currentVoucher.signature = parseStringField(fields[6])
}
} else {
addIssue(issues, 'error', lineNum, 'Ogiltig verifikationsdefinition: nummer eller datum kunde inte tolkas', tag)
}
break
}
case 'TRANS':
case 'RTRANS':
case 'BTRANS': {
// #TRANS = final transaction lines (the current state of the voucher)
// #RTRANS = supplementary/corrected transaction (must be followed by identical #TRANS for backward compat)
// #BTRANS = removed/cancelled transaction (programs not understanding BTRANS simply ignore it)
//
// When a voucher has been corrected, Fortnox/Visma emit all three types.
// Only #TRANS represents the final voucher state; #RTRANS and #BTRANS are
// supplementary history. We skip RTRANS/BTRANS to avoid double-counting
// which would make balanced vouchers appear unbalanced.
if (!currentVoucher) {
addIssue(issues, 'error', lineNum, `#${tag} utanför verifikationsblock (#VER): filen kan vara skadad`, tag)
break
}
// Skip RTRANS/BTRANS: they are correction audit trail, not final state
if (tag === 'RTRANS' || tag === 'BTRANS') {
break
}
// Parse account and capture the object list (in braces)
let fieldIndex = 1
const account = parseStringField(fields[fieldIndex++])
// Object list (single field thanks to brace-aware splitting):
// dimension tags like {1 "KS01" 6 "P001"}. Parsed onto the line so
// import is lossless (dimensions plan PR5).
let objectListRaw: string | null = null
if (fields[fieldIndex]?.startsWith('{')) {
objectListRaw = fields[fieldIndex]
fieldIndex++
}
const transAmountStr = fields[fieldIndex]
if (!transAmountStr || transAmountStr.trim() === '') {
addIssue(issues, 'warning', lineNum, `Belopp saknas i #${tag}: raden hoppas över`, tag)
break
}
const amount = parseNumberField(fields[fieldIndex++])
const transLine: SIETransactionLine = {
account,
amount,
}
if (objectListRaw) {
const dims = parseObjectList(objectListRaw, issues, lineNum)
if (dims) {
transLine.dimensions = dims
}
}
// Optional fields
if (fields[fieldIndex]) {
transLine.date = parseSIEDate(parseStringField(fields[fieldIndex++])) || undefined
}
if (fields[fieldIndex]) {
transLine.description = parseStringField(fields[fieldIndex++])
}
if (fields[fieldIndex]) {
transLine.quantity = parseNumberField(fields[fieldIndex++])
}
if (fields[fieldIndex]) {
transLine.signature = parseStringField(fields[fieldIndex++])
}
currentVoucher.lines.push(transLine)
break
}
case 'DIM': {
// #DIM dimNo "name"
const dimNo = parseInt(parseStringField(fields[1]), 10)
const name = parseStringField(fields[2])
if (!isNaN(dimNo) && dimNo >= 1) {
dimensions.push({ sieDimNo: dimNo, name: name || '' })
} else {
addIssue(issues, 'warning', lineNum, 'Ogiltig dimensionsdefinition: numret kunde inte tolkas', tag)
}
break
}
case 'UNDERDIM': {
// #UNDERDIM dimNo "name" parentDimNo
const dimNo = parseInt(parseStringField(fields[1]), 10)
const name = parseStringField(fields[2])
const parent = parseInt(parseStringField(fields[3]), 10)
if (!isNaN(dimNo) && dimNo >= 1 && !isNaN(parent) && parent >= 1) {
dimensions.push({ sieDimNo: dimNo, name: name || '', parentSieDimNo: parent })
} else {
addIssue(issues, 'warning', lineNum, 'Ogiltig underdimension: nummer eller överdimension kunde inte tolkas', tag)
}
break
}
case 'OBJEKT': {
// #OBJEKT dimNo "code" "name"
const dimNo = parseInt(parseStringField(fields[1]), 10)
const code = parseStringField(fields[2]).trim()
const name = parseStringField(fields[3])
if (!isNaN(dimNo) && dimNo >= 1 && code) {
dimensionValues.push({ sieDimNo: dimNo, code, name: name || code })
} else {
addIssue(issues, 'warning', lineNum, 'Ogiltigt objekt: dimension eller kod kunde inte tolkas', tag)
}
break
}
default:
// Unknown tag - add info issue for notable ones. OIB/OUB (per-object
// opening/closing balances) are counted and surfaced as ONE info
// issue below: dimension reporting is P&L-only in v1, so
// object-level balance records have no consumer yet, but dropping
// them must never be silent (#866 review).
if (tag === 'OIB' || tag === 'OUB') {
objectBalanceCount++
} else if (!['KSUMMA', 'BKOD', 'TAXAR', 'OMFATTN', 'PBUDGET', 'PSALDO'].includes(tag)) {
addIssue(issues, 'info', lineNum, `Okänd tagg: #${tag}, ignoreras`, tag)
}
}
} catch (error) {
addIssue(
issues,
'error',
lineNum,
`Fel vid tolkning av #${tag}: ${error instanceof Error ? error.message : 'Okänt fel'}`,
tag
)
}
}
// Collect accounts referenced in balances and vouchers but missing from #KONTO
const definedAccountNumbers = new Set(accounts.map((a) => a.number))
const referencedAccounts = new Set<string>()
for (const balance of [...openingBalances, ...closingBalances, ...resultBalances]) {
if (balance.account && !definedAccountNumbers.has(balance.account)) {
referencedAccounts.add(balance.account)
}
}
for (const voucher of vouchers) {
for (const line of voucher.lines) {
if (line.account && !definedAccountNumbers.has(line.account)) {
referencedAccounts.add(line.account)
}
}
}
for (const accountNumber of referencedAccounts) {
accounts.push({ number: accountNumber, name: '' })
addIssue(issues, 'info', 0, `Account ${accountNumber} added from transaction data (not in #KONTO)`)
}
// Silent-failure diagnostic: if the raw input declares #IB / #VER records
// but parsing produced none, surface a warning instead of letting the file
// look empty. Historically a tab-separator or encoding mismatch could swallow
// all balance/voucher records without any visible signal.
//
// Suppressed when per-record 'error' issues already exist for the same tag:
// in that case the parser already pinpointed the root cause (e.g. malformed
// verification definition), so the generic "check separator/encoding" hint
// would be misleading.
const rawIBCount = lines.filter((l) => /^\s*#IB\b/.test(l)).length
const rawVERCount = lines.filter((l) => /^\s*#VER\b/.test(l)).length
const hasIBError = issues.some((i) => i.severity === 'error' && i.tag === 'IB')
const hasVERError = issues.some((i) => i.severity === 'error' && i.tag === 'VER')
if (rawIBCount > 0 && openingBalances.length === 0 && !hasIBError) {
addIssue(
issues,
'warning',
0,
`${rawIBCount} #IB-rader hittades men inga ingående saldon kunde tolkas: kontrollera fältavskiljare och teckenkodning`,
'IB'
)
}
if (rawVERCount > 0 && vouchers.length === 0 && !hasVERError) {
addIssue(
issues,
'warning',
0,
`${rawVERCount} #VER-rader hittades men inga verifikationer kunde tolkas: kontrollera fältavskiljare och teckenkodning`,
'VER'
)
}
// Dimension visibility: the preview step renders parse issues, so these
// make dimension handling explicit BEFORE the user executes the import.
if (objectBalanceCount > 0) {
addIssue(
issues,
'info',
0,
`${objectBalanceCount} objektbalansrader (#OIB/#OUB) hoppades över: balanser per objekt stöds inte ännu`,
'OIB'
)
}
const taggedLineCount = vouchers.reduce(
(sum, v) => sum + v.lines.filter((l) => l.dimensions).length,
0
)
if (dimensions.length > 0 || dimensionValues.length > 0 || taggedLineCount > 0) {
addIssue(
issues,
'info',
0,
`Filen innehåller dimensionsdata (kostnadsställen/projekt): ${taggedLineCount} taggade rader, dimensionerna följer med importen`,
'DIM'
)
}
// Calculate statistics
const currentFiscalYear = header.fiscalYears.find((fy) => fy.yearIndex === 0)
const totalTransactionLines = vouchers.reduce((sum, v) => sum + v.lines.length, 0)
return {
header,
accounts,
openingBalances,
closingBalances,
resultBalances,
vouchers,
dimensions,
dimensionValues,
issues,
stats: {
totalAccounts: accounts.length,
totalVouchers: vouchers.length,
totalTransactionLines,
fiscalYearStart: currentFiscalYear?.start || null,
fiscalYearEnd: currentFiscalYear?.end || null,
},
}
}
/**
* Wording that identifies a voucher as the year's opening balance
* (ingående balans). Shared between the parser's OB-voucher candidate
* detection below and the importer's isLikelyOpeningBalance tagging
* (lib/import/sie-import.ts) so the two checks can never drift apart.
*/
export const OPENING_BALANCE_DESCRIPTION_RE = /ing[åa]ende balans|ing[åa]ende saldo|opening balance/i
/**
* Vouchers mentioning share capital are never treated as opening balances:
* a share-capital deposit dated on the FY start is a real bank movement.
*/
export const SHARE_CAPITAL_DESCRIPTION_RE = /aktiekapital/i
/**
* Determine if an account is balance sheet (class 1-2) or P&L (class 3-8)
*/
export function isBalanceSheetAccount(accountNumber: string): boolean {
const firstDigit = parseInt(accountNumber.charAt(0), 10)
return firstDigit >= 1 && firstDigit <= 2
}
/**
* Format a Date to "YYYY-MM-DD" using LOCAL components.
* parseSIEDate() builds local-time Dates, so toISOString() would shift the
* day across the UTC boundary in non-UTC timezones: never use it here.
*/
function formatLocalDate(date: Date): string {
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
}
/**
* True when the file contains a voucher that looks like the year's opening
* balance: dated on the fiscal-year start, only balance-sheet accounts,
* IB wording in the description and no share-capital mention.
*
* Raw-file mirror of the importer's isLikelyOpeningBalance check
* (lib/import/sie-import.ts), but deliberately MORE eager: it runs on
* source account numbers with no knowledge of account mappings, so a
* candidate containing an unmapped line still counts here even though the
* importer would later skip that voucher as unmapped. In that residual case
* no IB is created at all: the user falls back to the manual
* "Märk som ingående balans" action in Bankavstämning.
*/
export function hasOpeningBalanceVoucherCandidate(parsed: ParsedSIEFile): boolean {
const fyStart = parsed.stats.fiscalYearStart
if (!fyStart) return false
return parsed.vouchers.some(
(v) =>
v.lines.length > 0 &&
formatLocalDate(v.date) === fyStart.slice(0, 10) &&
v.lines.every((l) => isBalanceSheetAccount(l.account)) &&
OPENING_BALANCE_DESCRIPTION_RE.test(v.description || '') &&
!SHARE_CAPITAL_DESCRIPTION_RE.test(v.description || '')
)
}
/**
* Resolve the opening balances the import should actually book (issue #675).
*
* Some systems export no #IB 0 records at all: the current year's IB exists
* only implicitly via the SIE continuity invariant IB(year 0) = UB(year -1).
* Every IB consumer goes through this helper so the precedence below is the
* single source of truth:
*
* 1. Explicit #IB 0 records: trusted as-is, never merged with #UB -1.
* 2. An opening-balance #VER candidate: the voucher itself serves as IB
* during voucher import (tagged source_type 'opening_balance');
* deriving from #UB -1 as well would double-count every
* balance-sheet account.
* 3. #UB -1 records, re-labeled to yearIndex 0 and filtered to
* balance-sheet accounts (result accounts must always open at zero).
* 4. Nothing: the file genuinely carries no opening balances.
*/
export function getEffectiveOpeningBalances(parsed: ParsedSIEFile): {
balances: SIEBalance[]
derivedFromPriorYearUB: boolean
} {
const explicit = parsed.openingBalances.filter((b) => b.yearIndex === 0)
if (explicit.length > 0) {
return { balances: explicit, derivedFromPriorYearUB: false }
}
if (hasOpeningBalanceVoucherCandidate(parsed)) {
return { balances: [], derivedFromPriorYearUB: false }
}
const derived = parsed.closingBalances
.filter((b) => b.yearIndex === -1 && isBalanceSheetAccount(b.account))
.map((b) => ({ ...b, yearIndex: 0 }))
return { balances: derived, derivedFromPriorYearUB: derived.length > 0 }
}
/**
* Validate a parsed SIE file
*/
export function validateSIEFile(parsed: ParsedSIEFile): ValidationResult {
const errors: string[] = []
const warnings: string[] = []
// Check #FLAGGA for already-imported files
if (parsed.header.flagga === 1) {
warnings.push('Filen är markerad som redan importerad (#FLAGGA 1). Kontrollera att den inte redan har importerats i ett annat system.')
}
// Check for SIE type
if (!parsed.header.sieType) {
errors.push('SIE-typ saknas (#SIETYP). Filen kanske inte är en giltig SIE-fil: kontrollera att du exporterat i rätt format.')
}
// Check for company info
if (!parsed.header.companyName) {
warnings.push('Företagsnamn saknas (#FNAMN): vanligtvis ofarligt men bör kontrolleras')
}
// Check for fiscal year
if (parsed.header.fiscalYears.length === 0) {
errors.push('Inget räkenskapsår definierat (#RAR). Filen saknar information om vilken period bokföringen gäller: kontrollera att exporten inkluderar räkenskapsårsdata.')
}
// Check for accounts
if (parsed.accounts.length === 0) {
warnings.push('Inga konton hittades (#KONTO). Om filen bara innehåller saldon (SIE1) är detta normalt.')
}
// Warn if non-BAS kontoplan declared: mapping logic assumes BAS number ranges
if (parsed.header.kontoPlanType) {
const planType = parsed.header.kontoPlanType.toUpperCase()
const isBAS = planType.startsWith('BAS') || planType === 'EUBAS' || planType === 'EU-BAS'
if (!isBAS) {
warnings.push(
`Kontoplanstyp "${parsed.header.kontoPlanType}" är inte BAS-baserad. Automatisk kontomappning kan bli felaktig: granska alla mappningar manuellt i nästa steg.`
)
}
}
// Check for unbalanced vouchers
const unbalancedVouchers: string[] = []
for (const voucher of parsed.vouchers) {
const total = voucher.lines.reduce((sum, l) => sum + l.amount, 0)
if (Math.abs(total) > 0.01) {
unbalancedVouchers.push(
`${voucher.series}${voucher.number} (${voucher.date.toISOString().split('T')[0]}, diff: ${total.toFixed(2)} kr)`
)
}
}
if (unbalancedVouchers.length > 0) {
const shown = unbalancedVouchers.slice(0, 5)
const remaining = unbalancedVouchers.length - shown.length
errors.push(
`${unbalancedVouchers.length} verifikation(er) balanserar inte (debet ≠ kredit): ${shown.join(', ')}${remaining > 0 ? ` och ${remaining} till` : ''}. Kontrollera att exporten från källsystemet är komplett.`
)
}
// Check for accounts referenced but not defined
const definedAccounts = new Set(parsed.accounts.map((a) => a.number))
const referencedAccounts = new Set<string>()
for (const balance of [...parsed.openingBalances, ...parsed.closingBalances, ...parsed.resultBalances]) {
referencedAccounts.add(balance.account)
}
for (const voucher of parsed.vouchers) {
for (const line of voucher.lines) {
referencedAccounts.add(line.account)
}
}
const undefinedAccounts: string[] = []
for (const account of referencedAccounts) {
if (!definedAccounts.has(account)) {
undefinedAccounts.push(account)
}
}
if (undefinedAccounts.length > 0) {
const shown = undefinedAccounts.slice(0, 10)
const remaining = undefinedAccounts.length - shown.length
warnings.push(
`${undefinedAccounts.length} konto(n) används i verifikationer men definieras inte i #KONTO: ${shown.join(', ')}${remaining > 0 ? ` och ${remaining} till` : ''}. Kontona skapas automatiskt vid import.`
)
}
// Check opening balance is balanced (for balance sheet accounts).
// Uses the effective set so files without #IB 0 (where IB is derived from
// #UB -1, issue #675) still get the 2099-adjustment heads-up.
const effectiveIB = getEffectiveOpeningBalances(parsed)
if (effectiveIB.derivedFromPriorYearUB) {
warnings.push(
'Filen saknar ingående balanser (#IB) för aktuellt räkenskapsår: de härleds från föregående års utgående balans (#UB -1) vid import.'
)
}
const ibTotal = effectiveIB.balances.reduce((sum, b) => sum + b.amount, 0)
if (Math.abs(ibTotal) > 0.01) {
warnings.push(`Ingående balanser balanserar inte (differens: ${ibTotal.toFixed(2)} kr). En automatisk justeringspost mot konto 2099 skapas vid import.`)
}
// Completed fiscal year whose vouchers leave a residual on P&L accounts:
// the year's result was never transferred to equity (omföring saknas).
// Later years derive their opening balance from balance-sheet accounts
// only, so the residual becomes a permanent balansräkning differens for
// every subsequent year. SIE amounts are debit-positive, so the class 3-8
// sum is the un-transferred result with flipped sign.
const currentFiscalYear = parsed.header.fiscalYears.find((fy) => fy.yearIndex === 0)
if (currentFiscalYear?.end && currentFiscalYear.end < formatLocalDate(new Date())) {
const plResidual = parsed.vouchers.reduce(
(sum, voucher) =>
sum +
voucher.lines.reduce(
(lineSum, line) =>
lineSum + (isBalanceSheetAccount(line.account) ? 0 : line.amount),
0
),
0
)
if (Math.abs(plResidual) > 0.01) {
warnings.push(
`Räkenskapsåret är avslutat men filen saknar omföring av årets resultat (${Math.abs(plResidual).toFixed(2)} kr ligger kvar på resultatkonton). ` +
`Om senare räkenskapsår importeras kommer balansräkningen att visa en differens på ${Math.abs(plResidual).toFixed(2)} kr tills omföringen bokförs.`
)
}
}
// Add parse issues as errors/warnings
for (const issue of parsed.issues) {
if (issue.severity === 'error') {
errors.push(`Line ${issue.line}: ${issue.message}`)
} else if (issue.severity === 'warning') {
warnings.push(`Line ${issue.line}: ${issue.message}`)
}
}
return {
valid: errors.length === 0,
errors,
warnings,
}
}
/**
* Calculate a hash of the file content for duplicate detection
*/
export async function calculateFileHash(content: string): Promise<string> {
const encoder = new TextEncoder()
const data = encoder.encode(content)
const hashBuffer = await crypto.subtle.digest('SHA-256', data)
const hashArray = Array.from(new Uint8Array(hashBuffer))
return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('')
}