# RAMA AG — SMGV Database Architecture (Phase 04)

Status: **IMPLEMENTED (develop/v1) — tested on `rama_workforce_laravel_test`; deployed at the final rebuild.**

Migration: `database/migrations/2026_11_27_100000_create_smgv_accounting_tables.php`. It is forward-only and additive: no existing table, column, constraint or trigger is changed. Its `down()` deliberately refuses; recovery means restoring a verified backup.

## Principles

- **Raw evidence stays where it is.** `attendance_sessions`, `attendance_events` and `attendance_locations` are untouched and keep their 26 original integrity triggers. SMGV never copies attendance facts; it recomputes them from the events using the existing `DurationEngine`.
- **Integer accounting.** Every duration is stored as integer **minutes**, signed where a balance can go negative. Percentages are stored as **basis points** (10000 = 100.00 %). No floating point is used for any stored balance.
- **Effective dating.** Pensum history (`smgv_employment_periods`) is insert-or-close only. A change closes the previous row with `valid_to` and inserts a new row; historical conditions are never overwritten.
- **Immutability.**
  - `smgv_corrections` is an append-only ledger.
  - `smgv_month_closings` holds immutable snapshots.
  - `smgv_month_reopenings` is append-only.
  - All three are guarded twice: by the application (`Immutable` trait) and by 6 new MariaDB `BEFORE UPDATE/DELETE` triggers. The total is now 32 triggers: the 26 original plus 6 new.
- **Draft rules.** `smgv_rule_sets` is versioned with `valid_from` and `valid_to`, and every rule carries its own `verified` flag. The seeded version `2026.1-draft` is `unverified`, so every computed report is labelled a draft.

## Tables

| Table | Purpose | Key constraints |
| --- | --- | --- |
| `smgv_employee_profiles` | Basisblatt address, AHV number (encrypted with APP_KEY), birth date | unique `user_id`; FK users RESTRICT |
| `smgv_contracts` | Entry/exit, daily target at 100 %, automatic vacation calculation | unique (`user_id`, `entry_date`); CHECK exit ≥ entry; target 1–1440 |
| `smgv_employment_periods` | Pensum per weekday (MO–SO, basis points) with effective dates | unique (`user_id`, `valid_from`); CHECK each value ≤ 10000 |
| `smgv_holiday_calendars`, `smgv_holidays` | Feiertagskalender; holidays are marked like the PDF grid | unique (`calendar_id`, `date`) |
| `smgv_absence_types` | The 15 client codes, labels verbatim (DE) plus SQ, GAV article | unique `code`; CHECK kind |
| `smgv_absences` | Unproductive hours per day and code | unique (`user_id`, `date`, `type`); CHECK minutes 1–1440 and source |
| `smgv_opening_balances` | Vorjahr Stundensaldo and Ferien (signed minutes) | unique (`user_id`, `year`) |
| `smgv_rule_sets` | Versioned accounting rules (JSON), status unverified / verified / retired | unique `version` |
| `smgv_corrections` | Correction ledger: employee, date, category, original value, corrected value, reason, administrator, timestamp | CHECK category list; reason ≥ 3 characters; **no update or delete** (triggers) |
| `smgv_month_states` | Lifecycle draft / review / ready / closed / reopened, revision, Bemerkungen | unique (`user_id`, `year`, `month`) |
| `smgv_month_closings` | Snapshot: canonical JSON payload, SHA-256 checksum, rule set, rules_verified, closing administrator and time | unique (`user`, `year`, `month`, `revision`); **immutable** (triggers) |
| `smgv_month_reopenings` | Reopen audit: previous revision, mandatory reason, administrator, time | reason ≥ 10 characters; **immutable** |
| `smgv_exports` | Export and download history (private path, SHA-256, pages, bytes) | CHECK status |
| `smgv_import_batches` | Historical PDF uploads (private path, unique SHA-256, extracted JSON, confirmed mapping) | unique `sha256` (duplicate detection) |

Daily and monthly accounting results are **computed, not stored**, until a month is closed. Closing stores the complete daily and monthly result, the rule version and the source references (session IDs and record counts) in the snapshot. This avoids duplicating attendance facts while guaranteeing that a closed month never changes silently.

## Reference data seeded by the migration

- 15 absence types: `f, kv, kj, a, k, u, s, e, m, bs, ku, ka, ba, fu, fe`, with German labels taken verbatim from the client PDF and Albanian translations.
- One empty default holiday calendar, "Standard". No holidays are invented; the canton is an open question for the owner.
- Rule set `2026.1-draft` (`unverified`), with the per-rule sources documented in `App\Domain\Smgv\RuleSet::defaults()`.

These are configuration records, not business records.

## Tests

`tests/Feature/SmgvAccountingTest.php` (MariaDB test DB) covers:
- schema and seeding;
- trigger count;
- month calculation from real event sequences;
- Pensum history;
- close / reopen / revision, and the database refusing a snapshot update;
- incomplete attendance blocking a close;
- the append-only ledger;
- Employees being refused;
- AHV encryption, with nothing written to the audit log.

`tests/Unit/SmgvTimeEngineTest.php` covers the engine vectors.
