Files
accounted/lib/skatteverket/skattekonto-dedup.ts
T
4921d1da5e feat(import): import skattekontoutdrag files into the skattekonto pipeline (#1637)
* feat(import): import skattekontoutdrag files into the skattekonto pipeline

Users can now upload the kontohändelse export from Skatteverket's
skattekonto e-service (current CSV layout, verified against a real
2026-08 export, plus legacy .skv files) instead of needing the paid API
connection. Parsed rows land in skattekonto_transactions as booked
file_import rows and inherit the existing 1630 rules engine, bulk
booking, match-to-verifikat and both UIs unchanged.

- Core parser lib/import/skattekonto-file/ with strict detection
  (orgnr header + saldo markers, or two distinct SKV vocabulary terms
  plus row shape), sum-integrity check (opening + rows must equal
  closing) and a wrong-company guard against company_settings.
- computeDedupKey moves to core (lib/skatteverket/skattekonto-dedup);
  the extension re-imports it. File rows hash-key; content-signature
  partitioning skips rows already booked (either key form) and promotes
  matching upcoming rows in place.
- syncSkattekonto gains a takeover step: an id-keyed API row adopts a
  matching hash-keyed imported row in place, so journal links survive
  connecting the API after a file import. Upcoming rows can no longer
  clobber a booked row on hash collision.
- New skattekonto_file_imports table (company-scoped file-hash dedup)
  plus source/file_import_id provenance columns on
  skattekonto_transactions.
- /import gains a Skattekontoutdrag wizard (upload/preview/result,
  deep link ?mode=skattekonto); the bank-file flow detects skattekonto
  files and redirects instead of importing them as bank rows.
- /skattekonto renders imported rows for unconnected companies (attn
  line + import CTA) instead of discarding them behind the StartCard.
- Free for everyone: the local-data booking/match routes were already
  ungated; only API sync/saldo stay capability-gated.

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

* fix(skattekonto): align the EF F-skatt rule with the 2012 -> 2013 decision

20260810120000 established that 2012 is not standard BAS and moved the
booking templates to 2013 (owner taxes in an enskild firma are an eget
uttag), but the skattekonto_rules seed still booked EF preliminarskatt
against 2012. The file importer makes this rule fire for every EF
F-skatt row, so bring it onto 2013 too.

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

* fix(import): apply review findings on the skattekonto file import

- Fix the takeover candidate comparator: the single-argument sort was an
  inconsistent relation and could adopt a stale upcoming row ahead of the
  booked file row in a 3+ candidate queue (regression test added), and
  page the candidate scan with fetchAllRows so a multi-year window is not
  silently capped at 1000 rows.
- Fail parsing when a statement HAS saldo markers but not both readable
  balances: a file cut off before "Utgående saldo" previously skipped the
  sum check entirely. sum_valid stays null only for marker-less legacy
  files.
- Count a promotion only when the UPDATE matched a row, so a concurrent
  sync cannot inflate promoted_count; log a failed finalize of the import
  record instead of discarding the error.
- Migration (unshipped, edited in place): user_id is nullable with
  ON DELETE SET NULL so import records and their file-hash dedup survive
  user deletion, and the INSERT policy binds user_id to auth.uid() so a
  member cannot attribute an import to a colleague. pg tests cover both.
- Make the upload drop zone keyboard-reachable (role, tabIndex, Enter/
  Space) and give the six count-bearing strings ICU plural forms in both
  locales.

Skipped with reasons on the PR: binding execute rows to file bytes and
re-checking orgnr in execute (same client-trust model as the shipped
bank-file execute; Zod + RLS scope writes to the caller's own company),
a 404 test (the route has no not-found path), event-bus clearing in the
route test (the route touches no events), and FK NOT VALID (new column
referencing a brand-new empty table).

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

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-17 13:18:32 +02:00

168 lines
6.4 KiB
TypeScript

import crypto from 'crypto'
/**
* Dedup identity for skattekonto_transactions rows.
*
* Lives in core (not the skatteverket extension) because two producers write
* the table: the extension's API sync and the core skattekontoutdrag file
* importer. Both must compute byte-identical keys or every row would double
* on the next sync. Same pattern as SKATTEKONTO_ACCOUNT in
* manual-verifikat-prefill.ts: core owns the constant, the extension imports
* it back.
*
* Key forms:
* - `id:<transaktionsidentitet>` when Skatteverket's stable id is present
* (always on tidigare from the API, sometimes on kommande).
* - `h:sha256(transaktionsdatum|beloppSkatteverket|transaktionstext)` when
* it is not: kommande rows, and every file-imported row (statement exports
* carry no transaktionsidentitet).
*
* The amount is interpolated with JS number formatting. Both producers hold
* the amount as a number, so `500` stringifies as "500" on both sides; a
* parser must never feed a pre-formatted string in here.
*/
/**
* Compute the dedup key for a transaction.
*
* The point of this function is reproducibility: the same logical
* transaction must always produce the same dedup_key. The material format
* is a stored contract (every existing hash row in prod was written with
* it): never change it.
*/
export function computeDedupKey(tx: {
transaktionsidentitet?: number | null
transaktionsdatum: string
beloppSkatteverket: number
transaktionstext: string
}): string {
if (tx.transaktionsidentitet != null) {
return `id:${tx.transaktionsidentitet}`
}
return `h:${hashMaterial(contentSignature(tx.transaktionsdatum, tx.beloppSkatteverket, tx.transaktionstext))}`
}
/**
* The content identity of a row independent of which producer wrote it and
* which key form it got. Exactly the hash material of the `h:` key form, so
* `computeDedupKey` for an id-less row is `h:sha256(contentSignature(...))`.
* Used to pair file rows against `id:`-keyed API rows (import-time duplicate
* detection) and API rows against `h:`-keyed imported rows (sync-time
* takeover).
*/
export function contentSignature(
transaktionsdatum: string,
beloppSkatteverket: number,
transaktionstext: string,
): string {
return `${transaktionsdatum}|${beloppSkatteverket}|${transaktionstext}`
}
function hashMaterial(material: string): string {
return crypto.createHash('sha256').update(material).digest('hex')
}
/** The subset of a parsed statement row that dedup identity is built from. */
export interface SkattekontoFileRowIdentity {
transaktionsdatum: string
transaktionstext: string
/** SKV sign convention: positive = credit on the tax account. */
belopp: number
}
/**
* Assign dedup keys to parsed file rows.
*
* Identical rows within one file are legal (two equal payments on the same
* day). The first occurrence gets the plain content hash; later occurrences
* suffix the material with `|2`, `|3`, ... by occurrence order. This is
* deterministic per file content, so re-importing the same or an overlapping
* file resolves onto the same keys instead of inserting twice.
*/
export function assignFileDedupKeys(
rows: SkattekontoFileRowIdentity[],
): { row: SkattekontoFileRowIdentity; index: number; dedupKey: string }[] {
const seen = new Map<string, number>()
return rows.map((row, index) => {
const sig = contentSignature(row.transaktionsdatum, row.belopp, row.transaktionstext)
const occurrence = (seen.get(sig) ?? 0) + 1
seen.set(sig, occurrence)
const material = occurrence === 1 ? sig : `${sig}|${occurrence}`
return { row, index, dedupKey: `h:${hashMaterial(material)}` }
})
}
/** Existing table rows needed to partition an incoming file. */
export interface ExistingSkattekontoRow {
id: string
dedup_key: string
status: 'booked' | 'upcoming'
transaktionsdatum: string
transaktionstext: string
belopp_skatteverket: number
}
export interface SkattekontoFilePartition {
/** New rows to insert as booked file_import rows. */
toInsert: { row: SkattekontoFileRowIdentity; index: number; dedupKey: string }[]
/**
* Existing upcoming rows the statement proves have settled: flip their
* status to booked in place (keeps id, journal_entry_id, forfallodatum).
*/
promotions: { row: SkattekontoFileRowIdentity; index: number; existingId: string }[]
/** File rows already present as booked rows (either key form): skip. */
duplicates: { row: SkattekontoFileRowIdentity; index: number; existingId: string }[]
}
/**
* Partition parsed file rows against the rows already in the table.
*
* Matching is by content signature, not by dedup key, because the API writes
* `id:` keys for the same logical transactions a file hash-keys. Multiset
* semantics: each existing row is consumed at most once, so two identical
* file rows against one existing row yield one duplicate and one insert.
* Booked matches win over upcoming matches (a booked row IS this
* transaction; an upcoming row merely predicts it).
*/
export function partitionFileRows(
keyed: { row: SkattekontoFileRowIdentity; index: number; dedupKey: string }[],
existing: ExistingSkattekontoRow[],
): SkattekontoFilePartition {
const bookedBySig = new Map<string, ExistingSkattekontoRow[]>()
const upcomingBySig = new Map<string, ExistingSkattekontoRow[]>()
for (const row of existing) {
const sig = contentSignature(
row.transaktionsdatum,
row.belopp_skatteverket,
row.transaktionstext,
)
const bucket = row.status === 'booked' ? bookedBySig : upcomingBySig
const queue = bucket.get(sig)
if (queue) queue.push(row)
else bucket.set(sig, [row])
}
const result: SkattekontoFilePartition = { toInsert: [], promotions: [], duplicates: [] }
for (const entry of keyed) {
const sig = contentSignature(
entry.row.transaktionsdatum,
entry.row.belopp,
entry.row.transaktionstext,
)
const booked = bookedBySig.get(sig)
if (booked && booked.length > 0) {
const match = booked.shift() as ExistingSkattekontoRow
result.duplicates.push({ row: entry.row, index: entry.index, existingId: match.id })
continue
}
const upcoming = upcomingBySig.get(sig)
if (upcoming && upcoming.length > 0) {
const match = upcoming.shift() as ExistingSkattekontoRow
result.promotions.push({ row: entry.row, index: entry.index, existingId: match.id })
continue
}
result.toInsert.push(entry)
}
return result
}