Commit Graph

5 Commits

Author SHA1 Message Date
Jakob Wennberg d11d0a2e90 feat(reconciliation): match one bank event to several verifikationer (1:N) (#1553) (#2029)
One bank row can now settle several vouchers: journal_entry_id stays NULL and one transaction_voucher_links row per voucher carries a signed allocated_amount slice (sum must equal the row within the link tolerance, each slice bounded by the voucher's net line on the account). linkTransactionToVouchers does the locked transaction UPDATE first and rolls back on a failed junction insert; unlink and the re-booking guards understand junction-only rows; a storno of one of the N vouchers releases the row when the remaining slices no longer sum to its amount. The worksheet's right pane becomes multi-select when exactly one bank row is picked (Koppla only at difference 0); the v1/dashboard pair schemas accept allocations; the MCP reconcile resolver and executor carry 1:N pairs; skattekonto keeps single-pointer semantics. Closes #1553
2026-08-30 11:56:15 +02:00
Jakob Wennberg 1a27b5bd4a fix(auth): route document integrity, transaction delete/list and agent categorize through withRouteContext (#1926)
Two handlers hand-rolled supabase.auth.getUser() and therefore skipped the
MFA (AAL2) gate on hosted: DELETE /api/transactions/[id] and
GET /api/transactions. Both sat next to a sibling handler that was already
wrapped, and the raw-route-auth ratchet exempted a file as soon as any
withRouteContext call appeared in it, so they were never flagged.

GET /api/documents/[id]/integrity and POST /api/agent/categorize called
requireAuth() directly (MFA enforced, but no request id, no completion log,
no canonical error envelope). All four are now withRouteContext handlers
with identical company scoping and responses; the transaction delete keeps
its viewer rejection via requireWrite.

The guard now judges each top-level export segment of a route file on its
own, so a wrapped handler no longer exempts a hand-rolled sibling. Baseline
is unchanged (mcp-oauth/authorize remains the one grandfathered file).

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-26 13:34:31 +02:00
Mattsson e11f70b347 Bug/gh issues fiz (#1103)
* refactor: optimize page loading and data fetching

* fix: resolve recurring production runtime errors

* feat: add MCP company and customer updates

* fix: handle year-end tax adjustments

* feat: harden annual report compliance

* fix: expand invoice logo and font support

* fix: sanitize API route error responses

* fix: sanitize user-facing error messages

* feat: persist onboarding and tax assessment notices

* fix: reduce cloud backup audit churn

* feat: refine invoice editor layout

* fix: show saved tax adjustments in INK2

* fix: complete annual report API mappings

* docs: record operational safeguards and decisions

* fix: harden annual report review findings

* fix: adjust column span for description based on VAT registration

* New css class name
2026-07-21 23:00:15 +02:00
Jakob Wennberg ec27228a8e style: remove em/en dashes repo-wide, add CLAUDE.md rule against them (#890)
Em dashes (—) and en dashes (–) had spread across comments, docs, tests,
and a few UI strings, reading as AI-generated boilerplate rather than
house style. Replaced each with punctuation matching its context: colon
for explanatory clauses, comma for asides, plain hyphen for numeric/legal
ranges (e.g. "21-23§"), "to"/"till" for date ranges, parentheses for
paired-dash asides. messages/en.json and messages/sv.json were fixed by
hand together to keep sv/en in sync.

Left untouched where the dash is the functional subject rather than
decorative punctuation: date-range-parser.ts's separator regex,
charset-repair.ts's CP1252 byte-mapping table (and its test), the SIE
encoding mojibake docs, generic-csv.ts's minus-sign normalizer, the
agent system-prompt files that already instruct against em dashes, and
a golden iXBRL test fixture compared byte-for-byte.

Also fixes two bugs surfaced along the way: an off-by-one in
ApiKeysPanel's scope-label split (a leftover from an earlier partial
pass), and a charset-repair test that had lost the literal en-dash it
exists to verify.

Regenerated the agent atom seed migration (skills:generate) since 27
SKILL.md files changed. Added a CLAUDE.md rule against em/en dashes,
with an explicit carve-out for the functional-dash cases above.

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-04 15:58:06 +02:00
Jakob Wennberg 2c03dac981 fix(reports): convert FX to SEK in supplier/AR ledger reconciliation (#396)
* fix(reports): convert FX to SEK in supplier/AR ledger reconciliation

The supplier and AR ledger reports were summing remaining_amount
directly without converting foreign-currency invoices, so a
EUR/USD invoice would land in the aging total at face value while
the corresponding 2440 / 1510 GL line was already posted in SEK.
This produced false reconciliation discrepancies (e.g. 496,25 kr
ledger vs 952,50 kr GL with four EUR/USD invoices).

Apply resolveSekAmount(remaining, null, currency, exchange_rate)
in supplier-ledger, supplier-reconciliation, ar-ledger, and
ar-reconciliation. Per-invoice detail rows on the AR ledger keep
the original currency for display; only aging buckets and totals
become SEK. Adds mixed-currency test cases to all four files.

Also bundles unrelated WIP from the working tree:
- bank-reconciliation: log the swallowed catch error and drop the
  fallback path for the deleted get_unlinked_bank_lines RPC, using
  get_unlinked_1930_lines directly.
- new GET /api/transactions list endpoint with unmatched/reconciled/
  currency/date filters and full route tests.

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

* fix(reports): address PR #396 review findings

Compliance and Greptile review identified four issues; all four are
addressed here.

- Reconciliation: surface unconverted_fx_count on ReconciliationResult
  and ARReconciliationResult. When > 0 the difference field may be a
  data gap (FX invoice with no exchange_rate) rather than a true
  reconciliation break. UI now renders a Swedish caveat below the
  Avstämd / Ej avstämd badge so users understand the cause. New tests
  assert the count is set on legacy FX rows.

- Reconciliation: document the invoice-date-rate assumption explicitly
  in the JSDoc of both reconciliation generators. Per ML 8 kap 21–23 §,
  the report uses each invoice's stored exchange_rate; partial payments
  settled at a different rate produce a delta correctly booked to
  3960/7960 as valutakursvinst/-förlust, but the GL will diverge from
  the report by that amount until a subledger-derived total is wired up
  (deferred follow-up).

- fetchUnlinkedGLLines: drop the misleading bankAccount parameter.
  It was advertised as configurable but the function silently returned
  [] for any value other than '1930'. Now the signature is honest:
  1930-only until proper multi-account support is built.

- /api/transactions: query MAX_ROWS+1 rows so the response can include
  has_more and limit fields. Callers can now detect truncation, which
  matters once a company crosses 500 unmatched transactions in the
  selected range. New test asserts has_more=true when 501 rows are
  returned by the DB and the response is sliced to MAX_ROWS.

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

* fix(reports): address PR #396 round-2 compliance review

Compliance bot v2 review surfaced four findings on the previous commit;
three are addressed here. The fourth (an fx_rate_diff_amount indicator
distinguishing real reconciliation breaks from correctly-booked
valutakursvinst/-förlust) requires a subledger-derived total against
3960/7960 — already documented as a deferred follow-up in the JSDoc.

Changes:

- Exclude unconvertible FX rows from SEK sums. resolveSekAmount's
  null-rate fallback returned the raw foreign amount, so a 100 EUR
  invoice with no rate was being added to a SEK total as if it were
  100 SEK. All four generators (supplier-ledger,
  supplier-reconciliation, ar-ledger, ar-reconciliation) now skip
  rows where currency != SEK and exchange_rate is missing/zero, and
  count them in unconverted_fx_count.

- Surface unconverted_fx_count on SupplierLedgerReport /
  ARLedgerReport (not just the reconciliation result). UI shows a
  Swedish caption beneath the "Totalt utestående" card whenever the
  count is positive, so users see the warning even if they don't
  enable the reconciliation panel.

- Add outstanding_sek: number | null to ARInvoiceDetail. The
  per-invoice detail row keeps `outstanding` in invoice currency for
  display, but now also exposes the converted SEK value (or null when
  unconvertible). Defensive against future callers that sum across
  customers — they should use outstanding_sek to avoid mixing
  currencies (a real momsdeklaration foot-gun otherwise).

- Add a 1930-only notice to BankReconciliationView. The reconciliation
  is scoped to account 1930; users with Plusgiro 1920, kreditkort 1940,
  or valutakonton now see a Swedish caption explaining those are
  reconciled separately.

Tests:

- supplier-ledger: previous "falls back to original amount" case
  flipped to assert the row is excluded and counted; assertion that
  the legacy supplier disappears from the list when their only row is
  unconvertible.
- supplier-reconciliation: previous "1 100 ledger vs 1 000 GL" case
  flipped to assert ledger=1 000 and is_reconciled=true with
  unconverted_fx_count=1.
- ar-reconciliation: same pattern.
- ar-ledger: existing FX-mix test extended to assert outstanding_sek
  on each detail row; new test covering the null-rate exclusion path
  asserts the detail row is still pushed (with outstanding_sek=null)
  but excluded from buckets and the grand total.

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

* fix(reports): address PR #396 round-3 compliance review

Compliance bot v3 surfaced four findings on the previous commit; two
are addressed here, two are deliberately skipped (rationale in JSDoc /
this message).

Addressed:

- is_reconciled now returns false whenever unconverted_fx_count > 0,
  even if the numeric difference is zero. Per BFL 5 kap, the
  reconciliation must cover all affärshändelser; if a row was
  excluded for a missing exchange rate, the calculation is
  incomplete by construction and the period cannot honestly be
  stamped Avstämd. The fix is for the user to fill in the missing
  rate, not for the system to claim balance on partial data.

- AR reconciliation now sums account 1510 + 1513 in the GL balance
  comparison. Forward-looking defense for ROT/RUT fakturamodellen
  invoices that split AR receivables across the customer portion
  (1510) and the Skatteverket claim (1513). Today no production code
  posts to 1513 so the value is unchanged in practice; once
  fakturamodellen invoicing is added, the reconciliation will
  continue to balance without requiring another fix. UI label
  updated to "Kundfordringar (1510 + 1513) saldo" so the inclusion
  is visible. Field name and shape are unchanged for back-compat
  with the supplier-side parallel.

Skipped:

- "Block is_reconciled=true when any FX invoice exists in an open
  period" — overly aggressive; would block reconciliation for any
  FX-using company even when their books are correctly matched. The
  proper solution is the deferred subledger-derived total against
  3960/7960 (already documented in JSDoc on both reconciliation
  generators), which can compute the *expected* FX rate difference
  and either subtract it from `difference` or expose it as
  `fx_rate_difference`. Not in scope for this PR.

- Plusgiro 1920 wording in BankReconciliationView — bot itself
  marked this "not a hard finding". The 1920 reference is accurate
  per BAS 2026.

Tests:

- supplier-reconciliation: existing v3 exclusion test updated —
  asserts is_reconciled=false despite numbers matching, with
  comment explaining BFL rationale.
- ar-reconciliation: same update + new test covering the 1510 + 1513
  sum (1 200 on 1510, 300 on 1513, ledger total 1 500 → reconciled).

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 22:30:40 +02:00