1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
|
# bokf database schema
Status: Draft 0.1 · 2026-09-17 · License: GPL-3.0-or-later
Storage is a single SQLite database (WAL mode) owned exclusively by `bokfd`.
Clients never see it. This document defines the schema, the invariants it
enforces, and the canonical hash encodings that make the ledger tamper-evident.
## 1. Principles
1. **STRICT tables.** Type errors are bugs, not data.
2. **Integer öre.** All amounts are `INTEGER` öre. No floats anywhere.
3. **Append-only ledger.** Vouchers, rows, attachments and audit entries can be
inserted but never updated or deleted. Corrections are new vouchers.
4. **Tenant isolation in the engine.** Every tenant table has
`UNIQUE(org_id, id)` and every reference is a composite foreign key
`(org_id, target_id)`. A row cannot physically reference another org's data,
even if application code is wrong.
5. **One writer.** `bokfd` serializes all writes; SQLite's single-writer model
is therefore never contended between threads.
6. **Hash chains.** Voucher history and audit history are independently
SHA-256 chained and verifiable (`audit.verify`).
## 2. Connection pragmas
Every connection:
```sql
PRAGMA journal_mode = WAL;
PRAGMA foreign_keys = ON;
PRAGMA busy_timeout = 5000;
PRAGMA synchronous = FULL; -- configurable: NORMAL for speed, FULL default
PRAGMA wal_autocheckpoint = 1000;
```
Writes use `BEGIN IMMEDIATE`. This is what makes `DB_BUSY` a transient error
instead of silent corruption.
## 3. Overview
```
orgs ─┬─ memberships ── users ── api_tokens
├─ accounts
├─ fiscal_years ── sequences
├─ vouchers ─┬─ voucher_rows
│ └─ voucher_attachments ── attachments
├─ audit_log (global chain, org_id nullable)
├─ idempotency
├─ report_rules
├─ bank_transactions ── bank_matches
├─ employees ── payroll_run_lines
├─ payroll_runs ── payroll_run_lines
└─ settings
tax_tables / tax_table_meta (national reference data, no org_id)
```
`org_id` is present on every tenant row. `audit_log` is a global chain with a
nullable `org_id`, because user and system events (logins, org creation) are
not org-scoped. `tax_tables` and `tax_table_meta` are the one deliberate
exception: they hold Skatteverket's published tables for the whole country,
identical for every org, so they carry no `org_id` and are shared read-only
reference data. Every command that writes them is owner-only and audited.
## 4. Identity and tenancy
```sql
CREATE TABLE orgs (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
org_nr TEXT, -- "5560123456", leading zeros preserved
vat_nr TEXT, -- "SE556012345601"
address TEXT,
postal_code TEXT,
city TEXT,
country TEXT NOT NULL DEFAULT 'SE',
email TEXT,
phone TEXT,
description TEXT NOT NULL DEFAULT '', -- verksamhetsbeskrivning
shares INTEGER NOT NULL DEFAULT 0,-- antal aktier
fiscal_year_start_month INTEGER NOT NULL DEFAULT 1 CHECK (fiscal_year_start_month BETWEEN 1 AND 12),
moms_period TEXT NOT NULL DEFAULT 'month' CHECK (moms_period IN ('month','quarter','year')),
framework TEXT NOT NULL DEFAULT 'K2' CHECK (framework IN ('K2','K3')),
created_at TEXT NOT NULL,
created_by INTEGER NOT NULL REFERENCES users(id),
archived_at TEXT
) STRICT;
CREATE TABLE users (
id INTEGER PRIMARY KEY,
username TEXT NOT NULL UNIQUE COLLATE NOCASE,
display_name TEXT NOT NULL,
pw_hash TEXT NOT NULL, -- Argon2id PHC string
is_admin INTEGER NOT NULL DEFAULT 0 CHECK (is_admin IN (0,1)),
created_at TEXT NOT NULL,
disabled_at TEXT
) STRICT;
CREATE TABLE board_members ( -- signatures in the årsredovisning
org_id INTEGER NOT NULL REFERENCES orgs(id),
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
title TEXT NOT NULL, -- "Styrelseledamot", "Ordförande", …
created_at TEXT NOT NULL,
UNIQUE (org_id, id)
) STRICT;
CREATE TABLE memberships (
org_id INTEGER NOT NULL REFERENCES orgs(id),
user_id INTEGER NOT NULL REFERENCES users(id),
role TEXT NOT NULL CHECK (role IN ('owner','bookkeeper','viewer')),
created_at TEXT NOT NULL,
PRIMARY KEY (org_id, user_id)
) STRICT;
CREATE TABLE api_tokens (
id INTEGER PRIMARY KEY,
org_id INTEGER NOT NULL REFERENCES orgs(id),
user_id INTEGER NOT NULL REFERENCES users(id),
label TEXT NOT NULL,
token_hash BLOB NOT NULL UNIQUE CHECK (length(token_hash) = 32),
scopes TEXT NOT NULL, -- JSON array of 'read','write','admin'
created_at TEXT NOT NULL,
expires_at TEXT,
last_used_at TEXT,
revoked_at TEXT
) STRICT;
```
Sessions are deliberately absent from the schema: they live in `bokfd` memory
and die with the process.
## 5. Kontoplan
```sql
CREATE TABLE accounts (
org_id INTEGER NOT NULL REFERENCES orgs(id),
id INTEGER PRIMARY KEY,
number TEXT NOT NULL CHECK (number GLOB '[0-9]*' AND length(number) BETWEEN 1 AND 10),
name TEXT NOT NULL, -- kontobeteckning (BFL 3 kap)
type TEXT NOT NULL CHECK (type IN ('asset','liability','equity','revenue','expense')),
sru_code TEXT, -- for SRU/INK2 mapping later
vat_code TEXT, -- default momskod for reporting
active INTEGER NOT NULL DEFAULT 1 CHECK (active IN (0,1)),
created_at TEXT NOT NULL,
updated_at TEXT,
UNIQUE (org_id, id),
UNIQUE (org_id, number)
) STRICT;
CREATE INDEX idx_accounts_type ON accounts(org_id, type);
```
Accounts are seeded from BAS 2026 at org creation (separately attributed seed
data, see `THIRD_PARTY_NOTICES`). They are mutable configuration, not ledger
data: renaming or deactivating an account is allowed and audited; posting to an
inactive account is rejected unless the fiscal year is closed.
## 6. Fiscal years, sequences and locks
```sql
CREATE TABLE fiscal_years (
org_id INTEGER NOT NULL REFERENCES orgs(id),
id INTEGER PRIMARY KEY,
label TEXT NOT NULL, -- "2026", "2025/2026"
start_date TEXT NOT NULL,
end_date TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open','closed')),
locked_until TEXT, -- inclusive last locked date
dividend_ore INTEGER NOT NULL DEFAULT 0, -- board's proposed dividend
events TEXT NOT NULL DEFAULT '', -- väsentliga händelser (årsredovisning)
agm_date TEXT NOT NULL DEFAULT '', -- årsstämmodatum (YYYY-MM-DD)
dividend_date TEXT NOT NULL DEFAULT '', -- utbetalningsdatum (YYYY-MM-DD)
employees TEXT NOT NULL DEFAULT '', -- medelantal anställda
notes TEXT NOT NULL DEFAULT '', -- övriga upplysningar (t.ex. revisor)
created_at TEXT NOT NULL,
closed_at TEXT,
closed_by INTEGER REFERENCES users(id),
UNIQUE (org_id, id),
UNIQUE (org_id, label),
CHECK (start_date < end_date),
CHECK (locked_until IS NULL OR locked_until <= end_date)
) STRICT;
CREATE TABLE sequences (
org_id INTEGER NOT NULL,
fiscal_year_id INTEGER NOT NULL,
series TEXT NOT NULL, -- "A", "B", "IB", ...
next_number INTEGER NOT NULL DEFAULT 1,
PRIMARY KEY (org_id, fiscal_year_id, series),
FOREIGN KEY (org_id, fiscal_year_id) REFERENCES fiscal_years(org_id, id)
) STRICT;
```
`next_number` is incremented in the same transaction as the voucher insert, so
a failed post never consumes a number and a committed post never skips one.
Numbering is per fiscal year and series, matching BFL's requirement of an
unbroken series (obruten nummerserie).
## 7. Vouchers (append-only)
```sql
CREATE TABLE vouchers (
org_id INTEGER NOT NULL REFERENCES orgs(id),
id INTEGER PRIMARY KEY,
fiscal_year_id INTEGER NOT NULL,
series TEXT NOT NULL,
number INTEGER NOT NULL CHECK (number > 0),
date TEXT NOT NULL CHECK (date LIKE '____-__-__'),
description TEXT NOT NULL CHECK (length(description) > 0),
source TEXT NOT NULL DEFAULT 'manual'
CHECK (source IN ('manual','agent','sie_import','system','ib',
'invoice','payroll','payroll_tax')),
client_ref TEXT,
corrects_voucher_id INTEGER,
created_at TEXT NOT NULL,
created_by_user INTEGER NOT NULL REFERENCES users(id),
created_by_token INTEGER REFERENCES api_tokens(id),
hash_prev BLOB NOT NULL CHECK (length(hash_prev) = 32),
hash BLOB NOT NULL CHECK (length(hash) = 32),
UNIQUE (org_id, id),
UNIQUE (org_id, fiscal_year_id, series, number),
UNIQUE (org_id, client_ref),
FOREIGN KEY (org_id, fiscal_year_id) REFERENCES fiscal_years(org_id, id),
FOREIGN KEY (org_id, corrects_voucher_id) REFERENCES vouchers(org_id, id)
) STRICT;
CREATE TABLE voucher_rows (
org_id INTEGER NOT NULL,
id INTEGER PRIMARY KEY,
voucher_id INTEGER NOT NULL,
line_no INTEGER NOT NULL,
account_id INTEGER NOT NULL,
debit_ore INTEGER NOT NULL DEFAULT 0 CHECK (debit_ore >= 0),
credit_ore INTEGER NOT NULL DEFAULT 0 CHECK (credit_ore >= 0),
description TEXT,
CHECK ((debit_ore = 0) <> (credit_ore = 0)), -- exactly one side non-zero
CHECK (debit_ore > 0 OR credit_ore > 0),
UNIQUE (org_id, id),
UNIQUE (org_id, voucher_id, line_no),
FOREIGN KEY (org_id, voucher_id) REFERENCES vouchers(org_id, id),
FOREIGN KEY (org_id, account_id) REFERENCES accounts(org_id, id)
) STRICT;
CREATE INDEX idx_vouchers_date ON vouchers(org_id, date);
CREATE INDEX idx_vouchers_fy ON vouchers(org_id, fiscal_year_id, series, number);
CREATE INDEX idx_rows_voucher ON voucher_rows(org_id, voucher_id, line_no);
CREATE INDEX idx_rows_account ON voucher_rows(org_id, account_id);
```
Immutability is enforced by triggers, not convention:
```sql
CREATE TRIGGER vouchers_no_update BEFORE UPDATE ON vouchers
BEGIN SELECT RAISE(ABORT, 'vouchers are append-only'); END;
CREATE TRIGGER vouchers_no_delete BEFORE DELETE ON vouchers
BEGIN SELECT RAISE(ABORT, 'vouchers are append-only'); END;
CREATE TRIGGER voucher_rows_no_update BEFORE UPDATE ON voucher_rows
BEGIN SELECT RAISE(ABORT, 'voucher rows are append-only'); END;
CREATE TRIGGER voucher_rows_no_delete BEFORE DELETE ON voucher_rows
BEGIN SELECT RAISE(ABORT, 'voucher rows are append-only'); END;
```
Consequences worth stating explicitly:
- There is no `updated_at` on a voucher. There is no way to change one,
including through `sqlite3` as root, without dropping the trigger first.
- `corrects_voucher_id` points old → new is the reverse of the wording: the
**new** voucher carries `corrects_voucher_id = <original>`. The original stays
untouched, and reports show both.
- Balance is enforced by the posting algorithm inside a transaction; `audit.verify`
additionally scans for any unbalanced voucher as a integrity backstop.
### 7.1 Voucher hash (canonical bytes)
```
SHA256( "bokf-v1-voucher\0"
prev_hash[32]
org_id u64be
fiscal_year label u16len + utf8 bytes
series u16len + utf8 bytes
number u64be
date "YYYY-MM-DD" (10 bytes)
description u32len + utf8 bytes
row_count u32be
for each row, line_no order:
account number u16len + utf8 bytes
debit_ore u64be
credit_ore u64be
row description u32len + utf8 bytes )
```
`prev_hash` is the `hash` of the previous voucher **by `id`** (insertion
order = posting order) in the same org, or 32 zero bytes for the first voucher
of the org. The chain therefore spans fiscal years, and any retroactive edit,
insertion or deletion breaks it at a detectable point.
## 8. Attachments (underlag)
```sql
CREATE TABLE attachments (
org_id INTEGER NOT NULL REFERENCES orgs(id),
id INTEGER PRIMARY KEY,
sha256 BLOB NOT NULL CHECK (length(sha256) = 32),
filename TEXT NOT NULL,
mime TEXT NOT NULL,
size_bytes INTEGER NOT NULL CHECK (size_bytes >= 0),
content BLOB NOT NULL, -- stored in-DB; backups stay trivial
created_at TEXT NOT NULL,
created_by INTEGER NOT NULL REFERENCES users(id),
UNIQUE (org_id, id),
UNIQUE (org_id, sha256, filename)
) STRICT;
CREATE TRIGGER attachments_no_update BEFORE UPDATE ON attachments
BEGIN SELECT RAISE(ABORT, 'attachments are append-only'); END;
CREATE TRIGGER attachments_no_delete BEFORE DELETE ON attachments
BEGIN SELECT RAISE(ABORT, 'attachments are append-only'); END;
CREATE TABLE voucher_attachments (
org_id INTEGER NOT NULL,
voucher_id INTEGER NOT NULL,
attachment_id INTEGER NOT NULL,
created_at TEXT NOT NULL,
PRIMARY KEY (org_id, voucher_id, attachment_id),
FOREIGN KEY (org_id, voucher_id) REFERENCES vouchers(org_id, id),
FOREIGN KEY (org_id, attachment_id) REFERENCES attachments(org_id, id)
) STRICT;
```
Attachments are content-addressed and immutable — the triggers abort updates
and deletes even for a root `sqlite3` session, and `audit.verify full:true`
re-hashes the content; linking is an insert into
`voucher_attachments` and is itself audited (the link table stays mutable so
underlag can be unlinked). Unlinked attachments form the
inbox the TUI shows. The 7-year archive rule means content must never be
garbage-collected; deduplication by hash keeps repeated receipts cheap.
### 8.1 Bank transactions and matches (schema v8)
Phase 1 of bank reconciliation: imported statement rows are evidence, never
ledger data, and matching only links them to already-booked vouchers. No path
in the server books, edits or deletes a voucher from here.
```sql
CREATE TABLE bank_transactions (
org_id INTEGER NOT NULL REFERENCES orgs(id),
id INTEGER PRIMARY KEY,
account TEXT NOT NULL, -- bank account number, e.g. "1930"
booked_at TEXT NOT NULL, -- YYYY-MM-DD
value_date TEXT NOT NULL, -- YYYY-MM-DD
text TEXT NOT NULL,
type TEXT NOT NULL,
amount_ore INTEGER NOT NULL, -- signed: deposit positive, withdrawal negative
balance_ore INTEGER, -- nullable
source TEXT NOT NULL, -- "seb-csv"
source_hash BLOB NOT NULL CHECK (length(source_hash) = 32),
imported_at TEXT NOT NULL,
imported_by INTEGER NOT NULL REFERENCES users(id),
UNIQUE (org_id, id),
UNIQUE (org_id, source_hash)
) STRICT;
CREATE INDEX idx_bank_tx_date ON bank_transactions(org_id, booked_at);
CREATE TABLE bank_matches (
org_id INTEGER NOT NULL,
transaction_id INTEGER NOT NULL,
voucher_id INTEGER NOT NULL,
matched_at TEXT NOT NULL,
matched_by INTEGER NOT NULL REFERENCES users(id),
kind TEXT NOT NULL DEFAULT 'manual' CHECK (kind IN ('manual','auto')),
PRIMARY KEY (org_id, transaction_id, voucher_id),
FOREIGN KEY (org_id, transaction_id) REFERENCES bank_transactions(org_id, id),
FOREIGN KEY (org_id, voucher_id) REFERENCES vouchers(org_id, id)
) STRICT;
```
Imported rows are immutable in practice: the daemon exposes no update or
delete handler for `bank_transactions`, and re-importing the same export is a
no-op thanks to `UNIQUE (org_id, source_hash)`. `kind:'auto'` is reserved for
a later matching phase; phase 1 writes `'manual'` only. `bank_matches` stays
mutable so a wrong link can be removed (`bank.unmatch`); every link and unlink
is audited. A transaction may have several matches (partial payments), and one
voucher may reconcile several transactions.
The `source_hash` is SHA-256 over a canonical encoding of the row including
the account: `"bokf-v1-bank-tx\0"`, then each of `account`, `booked_at`,
`value_date` as `u16len + UTF-8`, `text` and `type` as `u32len + UTF-8`,
`amount_ore` as `i64be`, and a `u8` flag followed by `i64be balance_ore` when
the balance is present. The SEB parser and this encoding live in
`src/commands.c`.
The `settings` key `bank_account` (digits only, up to 10 characters, default
`1930`) selects the account `bank.import` uses when the request omits
`account`. See `PROTOCOL.md` §7.9.
## 9. Audit log and idempotency
```sql
CREATE TABLE audit_log (
seq INTEGER PRIMARY KEY,
org_id INTEGER REFERENCES orgs(id),
at TEXT NOT NULL, -- RFC 3339 UTC
actor_user_id INTEGER REFERENCES users(id),
actor_token_id INTEGER REFERENCES api_tokens(id),
action TEXT NOT NULL, -- "voucher.post", "auth.fail", ...
request_json TEXT NOT NULL DEFAULT '{}', -- redacted, exact bytes are hashed
result_code TEXT NOT NULL, -- "OK", "UNBALANCED", ...
hash_prev BLOB NOT NULL CHECK (length(hash_prev) = 32),
hash BLOB NOT NULL CHECK (length(hash) = 32)
) STRICT;
CREATE TRIGGER audit_no_update BEFORE UPDATE ON audit_log
BEGIN SELECT RAISE(ABORT, 'audit log is append-only'); END;
CREATE TRIGGER audit_no_delete BEFORE DELETE ON audit_log
BEGIN SELECT RAISE(ABORT, 'audit log is append-only'); END;
CREATE TABLE idempotency (
org_id INTEGER NOT NULL,
client_ref TEXT NOT NULL,
cmd TEXT NOT NULL,
response_json TEXT NOT NULL,
created_at TEXT NOT NULL,
PRIMARY KEY (org_id, client_ref),
FOREIGN KEY (org_id) REFERENCES orgs(id)
) STRICT;
```
### 9.1 Audit hash (canonical bytes)
```
SHA256( "bokf-v1-audit\0"
prev_hash[32]
seq u64be
at u16len + utf8
actor_user_id u64be -- 0 = none
actor_token_id u64be -- 0 = none
org_id u64be -- 0 = none
action u16len + utf8
request_json u32len + exact stored bytes
result_code u16len + utf8 )
```
Hashing the stored bytes verbatim avoids canonicalization disputes. Secrets are
redacted **before** the bytes are stored and hashed: `session.open` records
`{"method":"password","username":"anders"}` and the outcome, never the
password or token.
Actions written to the log include: `auth.open`, `auth.fail`, `session.close`,
`org.create`, `org.update`, `member.add`, `member.set_role`, `member.remove`,
`user.create`, `token.create`, `token.revoke`, `account.create`,
`account.update`, `fiscal_year.open`, `fiscal_year.close`, `period.lock`,
`period.unlock`, `voucher.post`, `voucher.correct`, `attachment.put`,
`attachment.link`, `sie.import`, `sie.export`, `backup.snapshot`,
`bank.import`, `bank.match`, `bank.unmatch`, `settings.update`,
`customer.create`, `invoice.issue`, `invoice.send`, `employee.create`,
`employee.update`, `employee.archive`, `payroll.tax_tables_fetch`,
`payroll.tax_tables_import`, `payroll.run_post`, `payroll.pay_tax`,
`payroll.settings_set`. Reads are logged only when `audit_reads = true`.
## 10. Reporting rules and settings
```sql
CREATE TABLE report_rules (
org_id INTEGER NOT NULL REFERENCES orgs(id),
id INTEGER PRIMARY KEY,
report TEXT NOT NULL, -- "vat", "income_statement", ...
box TEXT NOT NULL, -- "05", "10", ...
match_type TEXT NOT NULL CHECK (match_type IN ('account','range','type')),
pattern TEXT NOT NULL, -- "2610" | "2610-2619" | "revenue"
sign INTEGER NOT NULL DEFAULT 1 CHECK (sign IN (1,-1)),
sort_order INTEGER NOT NULL DEFAULT 0,
UNIQUE (org_id, id)
) STRICT;
CREATE TABLE settings (
org_id INTEGER NOT NULL REFERENCES orgs(id),
key TEXT NOT NULL,
value TEXT NOT NULL,
PRIMARY KEY (org_id, key)
) STRICT;
```
`report_rules` is seeded per org with a moms mapping over BAS account ranges and
is editable by owners when Skatteverket changes the blankett. The seed rules
are data, not code: the system ships a reviewed default set per fiscal year and
keeps older sets for older years.
Several rules may target the same `box`; `report.vat` sums them into one entry
per box. Ruta 49 is the sum of the payable boxes only (`10`,`11`,`12`,`30`,
`31`,`32`,`48`,`60`,`61`,`62`); the other boxes are underlag and never change
what is payable.
### 10.1 Voucher templates (schema v2)
Konteringsmallar: named sets of rows with a formula over the variable `x`.
Configuration data, mutable and audited, never part of the ledger.
```sql
CREATE TABLE voucher_templates (
org_id INTEGER NOT NULL REFERENCES orgs(id),
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
series TEXT NOT NULL DEFAULT 'A',
description TEXT NOT NULL DEFAULT '',
active INTEGER NOT NULL DEFAULT 1 CHECK (active IN (0,1)),
created_at TEXT NOT NULL,
updated_at TEXT,
UNIQUE (org_id, id),
UNIQUE (org_id, name)
) STRICT;
CREATE TABLE voucher_template_rows (
org_id INTEGER NOT NULL,
id INTEGER PRIMARY KEY,
template_id INTEGER NOT NULL,
line_no INTEGER NOT NULL,
account_id INTEGER NOT NULL,
formula TEXT NOT NULL CHECK (length(formula) > 0),
description TEXT,
UNIQUE (org_id, id),
UNIQUE (org_id, template_id, line_no),
FOREIGN KEY (org_id, template_id)
REFERENCES voucher_templates(org_id, id),
FOREIGN KEY (org_id, account_id) REFERENCES accounts(org_id, id)
) STRICT;
```
Formulas are evaluated in kronor, rounded per row to whole öre, and the
rounding remainder is assigned to the largest row before posting, so the
resulting voucher always balances. See `PROTOCOL.md` §7.4.1.
## 11. The posting algorithm
Every write path (`voucher.post`, `voucher.correct`, `sie.import`) runs the same
steps inside one `BEGIN IMMEDIATE` transaction:
1. Authenticate, resolve org, check role/scope.
2. Validate arguments; resolve accounts by number; reject inactive.
3. Resolve fiscal year by date; reject `FISCAL_YEAR_CLOSED`,
`DATE_OUT_OF_RANGE`, `PERIOD_LOCKED`.
4. Rows: ≥ 2, exactly one non-zero side per row, `sum(debit) == sum(credit)`,
else `UNBALANCED` with `difference_ore`.
5. Reserve and increment `sequences.next_number`; the assigned number is the
only number the voucher can have (`SEQUENCE_GAP` on mismatch).
6. Read `hash_prev` = last voucher hash by id for the org; compute `hash`.
7. Insert voucher, rows, and `voucher_attachments` links.
8. Insert `audit_log` entry with its own chain hash.
9. Insert `idempotency` row if `client_ref` was given.
10. Commit. On any failure, roll back everything — no number is consumed.
`dry_run` runs steps 1–5 and 7's validation, computes the hash with the
*candidate* number and a temporary `id`, and returns the preview without
writing. The preview hash is not the final hash (the number could change if
another voucher is posted in between) — clients must not persist it.
## 12. Migrations and versioning
- `meta(key TEXT PRIMARY KEY, value TEXT)` holds `schema_version` (integer)
and `created_at`. Current version: **10** (v10 adds the payroll tables and
the `payroll`/`payroll_tax` voucher sources, v9 adds the invoicing tables
and `invoice`, v8 the two bank reconciliation tables, v7 makes attachments
append-only, v3 replaces the seeded moms rules with the corrected mapping;
v2 adds the two template tables).
- Migrations are forward-only, applied automatically at daemon start, each in
one transaction. Before the first migration statement a consistent
`VACUUM INTO` snapshot is written to
`<backup_dir>/pre-migration-v<old>-<UTC timestamp>.db` (a numeric suffix is
added when the name is taken); if the snapshot cannot be taken the upgrade
is aborted and the database is left at its old version.
- `audit.verify` must pass before and after any migration; migrations never
rewrite ledger rows.
## 13. Integrity and operations
- Daily sanity checks by the daemon: `PRAGMA quick_check`, `audit.verify`,
unbalanced-voucher scan. Failures are logged loudly and surfaced in `meta`.
- `backup.snapshot` uses `VACUUM INTO` to a timestamped file: consistent, no
downtime, and safe for restic to pick up. The live `*.db`/`-wal`/`-shm` files
must never be handed to a file-copy backup tool.
- Restore procedure: stop `bokfd`, replace the database with a snapshot, start,
run `audit.verify` and a report smoke test. Restores are tested on a
schedule; the same procedure is the 7-year archive retrieval path.
- Size: SQLite with `page_size` default and WAL suits the load easily
(thousands of vouchers per year are trivial). Attachments dominate growth;
they live in the same file so a snapshot remains a single artifact.
## 14. Invoicing (schema v9)
`customers`, `invoice_sequence`, `invoices` and `invoice_rows` hold the
customer register, the per-org global invoice number series and issued
invoices with their rows. They are business documents, not ledger data:
invoices are written once at issue and only their status and send fields
change afterwards. The DDL and field semantics are in `docs/INVOICING.md`
§6. `vouchers.source` gained `'invoice'`; widening that CHECK required
rebuilding the table in the v9 migration (foreign keys are disabled for the
migration and `PRAGMA foreign_key_check` runs before they are re-enabled).
## 15. Payroll (schema v10)
The employee register and the monthly runs. `personal_no_enc` holds the
AES-256-GCM envelope (`enc:v1:<nonce>:<ciphertext>`, `src/secret.c`) under
`BOKFD_SECRET_KEY`; the plain number never touches the database. The run
tables are mutable configuration/business documents, not ledger data: the
money is in the immutable voucher of each run. `vouchers.source` gained
`'payroll'` (the monthly run) and `'payroll_tax'` (the payment to the tax
account); widening that CHECK required rebuilding the table in the v10
migration, exactly like v9 (foreign keys are disabled for the migration and
`PRAGMA foreign_key_check` runs before they are re-enabled).
```sql
CREATE TABLE employees (
org_id INTEGER NOT NULL REFERENCES orgs(id),
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
personal_no_enc TEXT NOT NULL, -- enc:v1:... (AES-256-GCM)
address TEXT NOT NULL DEFAULT '',
postal_code TEXT NOT NULL DEFAULT '',
city TEXT NOT NULL DEFAULT '',
bank_account TEXT NOT NULL DEFAULT '',
salary_account TEXT NOT NULL DEFAULT '7210',
monthly_salary_ore INTEGER NOT NULL DEFAULT 0 CHECK (monthly_salary_ore >= 0),
tax_table INTEGER NOT NULL DEFAULT 30 CHECK (tax_table BETWEEN 29 AND 42),
tax_column INTEGER NOT NULL DEFAULT 1 CHECK (tax_column BETWEEN 1 AND 6),
active INTEGER NOT NULL DEFAULT 1 CHECK (active IN (0,1)),
created_at TEXT NOT NULL,
updated_at TEXT,
UNIQUE (org_id, id)
) STRICT;
CREATE TABLE payroll_runs (
org_id INTEGER NOT NULL REFERENCES orgs(id),
id INTEGER PRIMARY KEY,
fiscal_year_id INTEGER NOT NULL,
period TEXT NOT NULL, -- YYYY-MM
pay_date TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'posted'
CHECK (status IN ('posted','paid')),
gross_ore INTEGER NOT NULL,
tax_ore INTEGER NOT NULL,
avgifter_ore INTEGER NOT NULL,
net_ore INTEGER NOT NULL,
voucher_id INTEGER,
payment_voucher_id INTEGER,
created_at TEXT NOT NULL,
created_by INTEGER NOT NULL REFERENCES users(id),
UNIQUE (org_id, id),
UNIQUE (org_id, period, pay_date),
FOREIGN KEY (org_id, fiscal_year_id) REFERENCES fiscal_years(org_id, id),
FOREIGN KEY (org_id, voucher_id) REFERENCES vouchers(org_id, id),
FOREIGN KEY (org_id, payment_voucher_id) REFERENCES vouchers(org_id, id)
) STRICT;
CREATE TABLE payroll_run_lines (
org_id INTEGER NOT NULL,
id INTEGER PRIMARY KEY,
run_id INTEGER NOT NULL,
employee_id INTEGER NOT NULL,
gross_ore INTEGER NOT NULL,
tax_ore INTEGER NOT NULL,
avgifter_ore INTEGER NOT NULL,
net_ore INTEGER NOT NULL,
tax_table INTEGER NOT NULL,
tax_column INTEGER NOT NULL,
UNIQUE (org_id, id),
UNIQUE (org_id, run_id, employee_id),
FOREIGN KEY (org_id, run_id) REFERENCES payroll_runs(org_id, id),
FOREIGN KEY (org_id, employee_id) REFERENCES employees(org_id, id)
) STRICT;
```
`payroll_runs` stores the posted totals and links both vouchers; the
one-run-per-period rule is enforced by `payroll.run_post` on top of the
`(org_id, period, pay_date)` key, and `status` flips to `paid` when
`payroll.pay_tax` links the payment voucher.
Skatteverket's allmänna monthly tables are national reference data and the
only tables without `org_id` (an explicit exception to principle 4):
```sql
CREATE TABLE tax_tables (
in_year INTEGER NOT NULL,
table_no INTEGER NOT NULL, -- 29..42
column_no INTEGER NOT NULL, -- 1..6
income_from_ore INTEGER NOT NULL,
income_to_ore INTEGER, -- NULL = open-ended top range
tax_ore INTEGER NOT NULL, -- whole kronor x100 for B rows
pct INTEGER, -- % rows: percent x100, else NULL
PRIMARY KEY (in_year, table_no, column_no, income_from_ore)
) STRICT;
CREATE TABLE tax_table_meta (
in_year INTEGER PRIMARY KEY,
source_url TEXT NOT NULL,
sha256 BLOB NOT NULL CHECK (length(sha256) = 32),
fetched_at TEXT NOT NULL
) STRICT;
```
B rows (`pct IS NULL`) hold the withholding in öre; % rows above the
tabulated 80,000 kr/month range hold the percentage ×100 in `pct` with
`tax_ore = 0` and may have `income_to_ore IS NULL` for the open-ended top
range. Wave 1 looks up only B ranges (see `PROTOCOL.md` §7.12).
## 16. Seeds
| Data | Source | Notes |
|---|---|---|
| BAS 2026 kontoplan | `data/bas2026.csv` | separately attributed (FAR); loaded at org creation |
| Moms report rules | `data/vat_rules_<year>.json` | account → ruta mapping, reviewed per year |
| Standard series | code | `A` (normal), `IB` (opening balances), `SIE` (import) |
| SRU codes | `data/sru_map.csv` | for later INK2/SRU export |
|