Files
accounted/types/skatteverket.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

123 lines
4.1 KiB
TypeScript

/**
* Skatteverket data shapes used by core UI (the /transactions page lives
* in core, but renders skattekonto rows alongside bank tx). The DB table
* `skattekonto_transactions` lives in core migrations even when the
* skatteverket extension is disabled: the extension only owns the API
* that populates it. Keeping these types in core means components can
* render the table's shape without depending on the extension module.
*
* If skatteverket is disabled, the API returns 503 and the UI just sees
* an empty list: the types remain valid descriptors of the schema.
*/
/** Row shape for the `skattekonto_transactions` table (DB → app). */
export interface StoredSkattekontoTransaction {
id: string
company_id: string
transaktionsidentitet: number | null
dedup_key: string
transaktionsdatum: string
forfallodatum: string | null
ranteberakningsdatum: string | null
transaktionstext: string
belopp_skatteverket: number
belopp_kronofogden: number | null
status: 'booked' | 'upcoming'
journal_entry_id: string | null
source: 'api' | 'file_import'
file_import_id: string | null
imported_at: string
updated_at: string
}
/** Row shape for the `skattekonto_file_imports` tracking table (DB → app). */
export interface SkattekontoFileImportRecord {
id: string
company_id: string
/** Importing user; null after that user's account is deleted. */
user_id: string | null
filename: string
file_hash: string
file_variant: 'csv' | 'skv'
row_count: number
imported_count: number
duplicate_count: number
promoted_count: number
date_from: string | null
date_to: string | null
closing_saldo: number | null
status: 'pending' | 'processing' | 'completed' | 'failed'
error_message: string | null
created_at: string
updated_at: string
}
/**
* Single best candidate verifikat for an unmatched SKV row. Attached by
* the `/skattekonto/transaktioner` endpoint when exactly one strong match
* exists, so the UI can offer a one-click "koppla till A12" hint instead
* of forcing the user to open the full Matcha-dialog.
*/
export interface SkattekontoMatchSuggestion {
journal_entry_id: string
voucher_number: number | null
voucher_series: string | null
entry_date: string
description: string
status: 'draft' | 'posted' | 'reversed'
}
/**
* The deterministic counter-account a "Bokför" on this row would use,
* resolved from `skattekonto_rules` server-side. Lets the list show what a
* booking will do ("Bokförs mot 8314 Skattefria ränteintäkter") and drives
* bulk-booking eligibility. `account_name` comes from the BAS reference and
* may be null for custom accounts; `label` is the matched rule's label.
*/
export interface SkattekontoBookingSuggestion {
account: string
account_name?: string | null
label?: string | null
}
/**
* API response variant: stored row plus optional auto-match suggestion.
* `match_suggestion` is optional because kommande/upcoming rows skip the
* enrichment step entirely (no journal entry can match a future event).
* `booking_suggestion` is likewise only computed for unbooked genomförda
* rows: undefined means "not computed", null means "no rule matched".
*/
export interface SkattekontoTransactionWithSuggestion extends StoredSkattekontoTransaction {
match_suggestion?: SkattekontoMatchSuggestion | null
booking_suggestion?: SkattekontoBookingSuggestion | null
}
/**
* Per-row outcome from POST /skattekonto/transaktioner/bokfor-batch.
* `journal_entry_id` is present on success AND on COMMIT_FAILED (the draft
* was created and stays linked; only the commit step failed).
*/
export interface SkattekontoBatchRowResult {
id: string
ok: boolean
journal_entry_id?: string
voucher_number?: number | null
voucher_series?: string | null
error_code?:
| 'NO_COUNTER_ACCOUNT'
| 'NO_FISCAL_PERIOD'
| 'PERIOD_LOCKED'
| 'ALREADY_BOOKED'
| 'NOT_SETTLED'
| 'TRANSACTION_NOT_FOUND'
| 'COMMIT_FAILED'
| 'UNKNOWN'
error_message?: string
}
/** Response envelope body for the bokfor-batch endpoint. */
export interface SkattekontoBatchResult {
results: SkattekontoBatchRowResult[]
summary: { total: number; succeeded: number; failed: number }
}