fix(reports): stop the resultatavslut zeroing declarations, and make the mistake uninventable (#1293)

* fix(settings): explain why account deletion is blocked

The delete-account button was disabled while the user still owned
companies, but the reason only lived behind the "?" on the blocker row,
so the greyed-out button read as broken. Surface it as one visible attn
sentence directly under the button, and point aria-describedby at it
whenever the button is disabled, not only on a load error.

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

* feat(enable-banking): share one PSD2 consent across a user's companies

Connecting the same bank for a second company required a second BankID, and
at SEB that new authorization silently revoked the first one. A user with four
companies at one bank therefore signed four times a quarter and ended up with
three dead feeds, each still rendering as "Aktiv" with a stale last_synced_at
until someone pressed Synka.

Prod says this is not one customer: every SEB customer holding connections in
more than one company has had an earlier company stop syncing at the moment
the next was authorized, most of them while the consent was still formally
valid for weeks. The same measurement over other banks is far quieter, so the
one-active-session-per-PSU limit is real and ASPSP-side.

Enable Banking already supports the shape we want. POST /auth carries no
account restriction, so a session covers every account the user ticked at the
bank, and GET /accounts/{uid}/transactions takes no session id, so a second
company can sync its own accounts from an existing session. bank_connections
has no unique constraint on session_id, so this needs no migration.

Adds lib/session-sharing.ts plus GET /reusable-sessions and POST /attach. When
a live session in another of the user's companies still exposes accounts no
company syncs, the settings panel offers to reuse it: the new row shares
session_id and consent_expires, carries only the unclaimed accounts, and lands
in pending_selection so the existing IBAN-aware account picker does the ledger
mapping. Only the consent is shared; accounts, cash_accounts and transactions
stay strictly per-company.

Sharing a session changes three lifecycle paths, all handled here:

- Disconnect and reconnect now refcount before revoking. A blind revoke would
  take down a sibling company's feed, which is the exact failure this removes.
  The count runs on a service-role client because RLS hides a sibling in a
  company the user has since left, and it fails closed: an uncertain count is
  treated as shared, since a lingering consent lapses on its own in 90 days
  while a wrongly revoked one kills a working feed.
- A renewed consent fans out to every company sharing the old session, and
  re-points their account uids by IBAN. Several ASPSPs reissue uids on
  re-authorization, so carrying the session id alone would have left siblings
  calling retired uids and re-broken them every quarter. This is also why the
  superseded session_id is no longer nulled at /connect: the callback needs it.
- The nightly probe runs once per distinct session and applies the verdict to
  every row holding it, and expiry mails are keyed per (user, session), so one
  dead consent is one probe and one mail rather than four of each.

Only enabled cash_accounts rows count as claiming an IBAN. The callback mirrors
every account in a consent, deselected ones included, so counting any row as a
claim would leave nothing offerable once the first company connects.

An account handed to a company also stops being offered while that company's
picker is still open, closing the window where two companies could book the
same physical account.

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

* fix(ink2): read the resultaträkning from the pre-closing books

INK2R summed journal entries raw, so it included the resultatavslut that
zeroes every P&L account into 2099 at year-end. Nettoomsättning, kostnader,
periodiseringsfond and skatt all came out as 0, which cascaded into INK2S
7650/7651 and the taxable result. INK2 is always filed after bokslut, so
this was every real declaration, and nothing warned: with the P&L at zero
the balance sheet still tied out.

INK2R now reads two views of the same period. The balance sheet comes from
the closed books so 7302 keeps arets resultat via 2099; the income statement
comes from the pre-closing books via excludeFinalClosingEntry, which drops
only fiscal_periods.closing_entry_id so skatt and bokslutsdispositioner stay
on the form (7525, 7528). The equity adjustment is now conditional on a
posted closing entry having moved the result into 2099.

Second, independent bug: accounts were mapped by BAS number with no regard
for the sign of the balance, so konto 1630 with a credit was reported as a
negative fordran instead of a skatteskuld and konto 2641 with a debit was
netted off the liabilities. The three sign-reclassification rules the K2
iXBRL mapper already had are extracted to lib/reports/sign-reclassification
.ts and applied to INK2R too, so both statutory reports present the same
balance sheet. Only the rule table is shared: k2-mapper keeps its sumOre
arithmetic because the iXBRL path is ore-exact while INK2R truncates per
SFL 22:1.

NE-bilaga had the same empty-resultatrakning bug and gets the same fix.

Adds the closed-period coverage that was missing: the old tests only
exercised the mapping table against an open period, the one state in which
the engine happened to work.

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

* fix(reports): make the year-end closing decision explicit at every call site

generateTrialBalance took two optional booleans, so a caller that never
thought about the resultatavslut silently got 'include'. That is the wrong
default for anything summing class 3-8: the closing verifikat posts the
mirror image of every P&L account into 2099 inside the same period, so the
report reads ZERO across the board while the balance sheet still ties out
and nothing warns.

The booleans are replaced by a required
closingEntry: 'include' | 'exclude-final' | 'exclude-all-year-end'
with no default, so the build fails until each call site decides. All 40
were audited individually; every one keeps its current behaviour except
the two that were provably broken:

  - Resultatrapport read zero on every line for a closed year, in JSON,
    PDF and XLSX, and its prior-year comparison column read zero for
    anyone whose previous year was closed.
  - Resultat per projekt (dimension-pnl) had the same defect and must
    stay in lockstep with Resultatrapport to keep reconciling.

Both now pass 'exclude-all-year-end', which keeps them agreeing with the
formal Resultaträkning rather than pre-empting Stage 2 of #1051
(DECISIONS.md:632).

Deliberately unchanged and recorded in DECISIONS.md: the KPI expense
composition, which is blank for a closed year but cannot be fixed without
a migration and a displayed-figure change, and getBookedBolagsskatt, whose
contract is an open period and whose call chain already caused a
too-high-tax customer bug once.

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

* fix(vat): keep the resultatavslut out of the momsdeklaration

The closing verifikat posts the mirror image of every P&L account into
2099 inside the same fiscal period. Revenue accounts drive rutor 05, 39
and 40, so any VAT period containing the fiscal-year end reported NEGATED
turnover once the year was closed. get_vat_declaration_totals already
excluded vat_settlement and opening_balance entries, but not this one.

Reproduced read-only against production: for December of a closed year
the December declaration reported ruta 39 = -794 734 kr. After the fix
that period reports 0 and the January period carrying the real sale is
unchanged at 794 734 kr.

Keyed on fiscal_periods.closing_entry_id, not source_type = 'year_end':
avskrivningar, periodiseringsfond and skatt share that source_type and
must keep whatever VAT effect they carry. A reversed closing entry is
retained together with its storno so the pair still nets to zero, the
same predicate trial-balance.ts uses for closingEntry: 'exclude-final'.

Migration applied to the staging branch only; prod gets it via merge.
The pg test is written but has NOT been executed locally (no DATABASE_URL
configured and no local Postgres), so CI is its first real run.

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

* fix(kpi): keep the resultatavslut off the monthly chart

The monthly income/expense chart summed every posted entry in the fiscal
period. The closing verifikat posts the mirror image of every P&L account,
so once a year was closed the fiscal-year-end month charted the whole
year's revenue as negative income.

Measured read-only on production: 28 companies across 34 month-rows. The
worst case charted December income as -10 347 459,81 kr where the real
figure is +12,88 kr. Other examples: -1 868 731 -> +128 730,
-1 850 501 -> +431 709.

Both paths are fixed together so they keep agreeing: the RPC's monthly
section now joins the tb_ex_ye_entries CTE it already computes for
tb_ex_year_end, and monthly-breakdown.ts (the dimension-filtered fallback
and the MCP path) gains the matching source_type filter plus the
storno/correction chain of REVERSED year-end entries, so an undone bokslut
does not leave half a pair behind.

Migration 20260723180000 had recorded the omission as deliberate, on the
grounds that it mirrored the JS scan. It did, but the JS scan was wrong.

Migration applied to the staging branch (function body identical; three
comment lines differ from the committed file). Prod gets the file via merge.

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

* test(reports): pin every statement generator against a closed fiscal year

The per-generator suites all exercised an OPEN fiscal period, which is the
one state in which a generator that forgets the resultatavslut happens to
work. Declarations are filed AFTER bokslut, so the untested state was the
only state that occurs in production. That is why the same defect could
ship three times.

Two new suites over one shared fixture (closed-year-fixture.ts, a synthetic
closed AB with a resultatavslut, a credit 1630 and a debit 2641):

  closed-year-statements.test.ts enumerates the generators and asserts each
  reports the year's revenue rather than zero, plus its own bottom line. The
  table IS the checklist: a new report either appears in it or nothing stops
  it shipping with this bug. Verified by regressing income-statement back to
  closingEntry 'include', which fails 2 of its assertions.

  cross-surface-agreement.test.ts asserts the surfaces agree with each
  other, which is what every customer complaint actually was. INK2R and the
  K2 årsredovisning must produce the same årets resultat, the same fritt
  eget kapital, the same sign reclassifications and the same balance total.
  The operational family (Resultaträkning, Resultatrapport) must agree
  internally, and the gap BETWEEN the families is asserted explicitly as
  bokslutsdispositioner + skatt, so when Stage 2 of #1051 lands the test
  names the expectation to change instead of failing vaguely.

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

* chore(guards): ratchet against new reports that scan the ledger directly

A statement generator that aggregates journal_entry_lines itself has to
remember, on its own, that the resultatavslut posts the mirror image of
every P&L account into 2099 inside the same fiscal period. Three forgot,
and each read ZERO revenue for a closed year while the balance sheet still
tied out, so nothing warned.

generateTrialBalance now requires an explicit closingEntry mode, which makes
that decision a compile error. This guard is what keeps NEW reports on that
path: any generator under lib/reports or lib/bokslut that reads
journal_entry_lines and is not in the baseline set fails CI. Verified by
adding a throwaway report, which the guard rejects by name.

Voucher and line listings (general-ledger, journal-register, SIE export,
reconciliation, diagnostics) are sanctioned: they show the ledger as posted
and have no closingEntry decision to make.

Four existing lib/bokslut files are grandfathered rather than migrated. One
of them is a genuine open follow-up recorded in DECISIONS.md:
sarskild-loneskatt-calculator sums 7410-7419 with no year-end exclusion, so
its basis reads ~0 if it runs against an already-closed period. Left alone
deliberately: it is a tax figure whose call chain has caused a customer bug
before and deserves its own verified change.

Also ratchets naive-ore-round down 646 -> 641.

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

* test(reports): pin where sign reclassification applies, in both directions

No behaviour change. The sweep asked whether the 1630/2641 sign
reclassification should be extended to the remaining balance-sheet
surfaces; the answer is that there are none left.

Both STATUTORY presentations already have it: the K2 iXBRL årsredovisning
since 2026-07-23 and INK2R since 2026-07-29. The other two balance-sheet
surfaces must NOT have it: /rapporter Balansräkning and Balansrapport are
organised by account number under BAS-prefix headings, and balansrapport
documents an invariant that depends on every row staying debit-positive
where it was booked. Moving konto 1630 into a liability section would break
the add-the-rows-to-verify-the-balance property and hide the account from
anyone looking it up by number.

Asserting both halves is the point. The first half stops the
reclassification silently disappearing from one statutory surface again,
which is how a customer ended up comparing two of our own reports against
each other. The second half stops a future sweep "fixing" the operational
reports into disagreeing with their own documented contract.

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

* feat(reports): detect statement disagreement instead of waiting for a customer

Every year-end problem reported so far was a DISAGREEMENT between two of
our own screens, not a single wrong screen. The årsredovisning said one
figure, INK2 said another, and the customer did the reconciliation for us.
Nothing in the product noticed, because each screen tied out on its own.

Two additions:

  INK2R self-checks. On a closed year it compares the årets resultat it is
  about to declare against the booked konto 2099, and warns in Swedish when
  they disagree. This is the alarm that was missing: when INK2R reported
  0 kr against a booked 469 542 kr, the balance sheet still balanced, so no
  warning fired. Mirrors the equivalent check k2-mapper has had since
  2026-07-23, so both statutory reports now catch the same fault.

  reconcileStatements + GET /api/reports/statement-reconciliation return
  årets resultat from every surface side by side, grouped into families.
  ledger + statutory must agree and a mismatch is named; operational
  legitimately differs by bokslutsdispositioner + skatt until Stage 2 of
  #1051 lands, so that gap is explained rather than flagged.

The visual panel is deliberately not built here: it needs a
/frontend-design pass against the locked concept conventions plus sv/en
strings, and the warning above already puts the alarm where the user looks.

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

* fix(reports): address review findings from PR #1293

pg-real (7 failures, one signature): the new fixture called
insertFiscalPeriod({ isClosed: true }) and then inserted journal entries
into it, so enforce_period_lock (migration 017, legally required) refused
the write. Not worked around: the RPC's predicate keys on
fiscal_periods.closing_entry_id and never reads is_closed, so the fixture
now links the closing entry and leaves the period open, which exercises the
path that actually matters.

CodeRabbit, closed-year-fixture: EX_YEAR_END_ROWS dropped only the P&L legs
of the year_end entries (8811, 8910) and left their balance-sheet legs
(2125, 2512) at pre-closing values, so the 'exclude-all-year-end' view sat
160 000 kr out of balance and misrepresented what generateTrialBalance
returns. Latent, because today's consumers read class 3-8 only, but a shared
fixture that does not balance is a trap for the next consumer. Both legs now
go, and a new test asserts all three views sum to zero.

CodeRabbit, INK2 totals: renamed totals.resultAfterFinancial to
aretsResultat. It holds the result after bokslutsdispositioner AND skatt,
which is årets resultat, not resultat efter finansiella poster, and
build-data.ts uses the old name correctly for the different subtotal. The UI
already labelled the value "Årets resultat", so the name was simply wrong.

CodeRabbit, statement-reconciliation: the statutory branch called a
generator and caught any throw as "wrong entity type", mapping genuine
failures to a null figure that the comparison then skipped, so a real bug in
a declaration generator made the function report isReconciled: true. That is
the opposite of its purpose. It now dispatches on entity_type and surfaces a
generation failure as a named disagreement.

CodeRabbit, enable-banking (Emil's call to include): fetchClaimedIbans
returned an empty Set on a cash_accounts read failure, which is
indistinguishable from "nothing is claimed" and made every IBAN in the
session offerable, including accounts another company already books to. Its
own comment said it failed closed and its log said "offering nothing"; it
failed open. Returns null now, and findReusableSessions offers nothing when
the claimed set is unavailable. The test that pinned the fail-open asserted
toHaveLength(1) under the name "offers nothing"; it now asserts []. Also
removed an em dash per CLAUDE.md.

The remaining enable-banking finding (consent-expiry cooldown stamped only
on the selected connection, so it leaks one duplicate mail per sibling
company) is deliberately left to Emil: it changes email-sending behaviour in
his feature rather than fixing a stated contract.

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

* fix(reports): resolve second-round review findings on PR #1293

pg-real, two NEW signatures (the closed-period one from cycle 1 is gone):

kpi-report-aggregates-rpc.pg.test.ts asserted the exact contract migration
20260730090000 deliberately changes. Its comment read "year_end entries are
NOT excluded from monthly" and expected December expenses 1250. That fixture's
December holds only year-end-chain entries, so with the fix the month drops
out of the chart entirely, which is the correct operational view: a month
whose only activity is bokslut has no operating result. Assertion and file
docstring updated to the new contract rather than the test being removed.

vat-totals-closing-entry.pg.test.ts passed the wrong account arrays. p_net_
accounts is VAT_SETTLEMENT_NET_ACCOUNTS (2650/1650, the momsredovisning
settlement pair), not the output-VAT accounts. Putting 2611 there made the
extra year_end entry match the settlement-SHAPE detector, so an ordinary
sale-with-VAT was classified a momsredovisning and dropped, and the test read
0 instead of 10 000. The RPC was right; the fixture was not.

CodeRabbit, statement-reconciliation: resolveEntityType checked neither
query's error, so a genuine DB failure (RLS, permissions, connectivity)
returned null indistinguishably from "no entity type set", fell into the
unsupported-form branch and reported isReconciled: true. That is the same
silent-false-reconciled bug the cycle-1 refactor closed, one level down. The
companies error now throws; a missing company_settings ROW stays tolerated,
because .single() errors on zero rows and many companies have none. Mirrors
the pattern the INK2 and NE engines already use.

Still open by Emil's explicit choice: the consent-expiry cooldown is stamped
only on the connection it was handed, so it leaks one duplicate mail per
sibling company on the shared session. That changes email-sending behaviour
in his feature rather than fixing a stated contract, so it stays his.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-07-30 09:03:05 +02:00
committed by GitHub
co-authored by Claude Opus 5
parent 954ce873a8
commit 17a7a62ceb
71 changed files with 4908 additions and 335 deletions
+17
View File
@@ -662,6 +662,23 @@ One line per decision: `[YYYY-MM-DD] <decision>: <why>`. Appended by agents and
[2026-07-29] Retired the generic design skills now that emilkowalski/skills is installed globally (animation-vocabulary, apple-design, emil-design-eng, find-animation-opportunities, improve-animations, pick-ui-library, prototype, review-animations in ~/.claude/skills). Deleted .claude/skills/mobile-ux-core (52 lines of universal mobile UX whose file triggers are *.dart/*.swift/*Activity.kt, paths that do not exist in this repo; superseded by design.md's accessibility section plus apple-design) and .claude/skills/scout-design (a design scan that filed Linear tickets via mcp__claude_ai_Linear__save_issue, while this project files GitHub issues and loop-design-scan is the same scan with the right output; loop-design-scan's sibling reference updated). Kept web-design-guidelines: it is a Vercel-plugin symlink, cheap to keep, and may regenerate anyway. Also removed the global ui-ux-pro-max skill, a 67-style/96-palette catalogue that pulls against a locked editorial-monochrome system.
[2026-07-29] Consent-expiry follow-up sent from invoiceservice@arcim.io, not a new sender: matching the address the original batch came from lets the two mails corroborate each other; RESEND_FROM_EMAIL alignment to accounted.se stays a separate ops task.
[2026-07-29] Approval-queue MCP App widget (render_ui on list_pending_operations): high-risk confirmed=true now comes from a human click in-widget instead of agent-asserted; payload ceiling 58K->58.5K per the in-test trim-first convention.
[2026-07-29] PSD2 sessions are now shareable across a user's companies (extensions/general/enable-banking/lib/session-sharing.ts) rather than one authorization per company: SEB (and several other ASPSPs) allow one active AIS session per PSU, so each new company's BankID silently killed the previous company's feed. Prod confirms it: all 7 SEB customers holding connections in more than one company have had an earlier company stop syncing at the moment the next was authorized, 5 of them while consent was still formally valid, versus 2/11 at Lunar and 0/3 at Nordea. Enable Banking supports this shape already (POST /auth carries no account restriction, GET /accounts/{uid}/transactions takes no session id) and bank_connections has no unique constraint on session_id, so no migration. Only session_id and consent_expires are shared; accounts, cash_accounts and transactions stay per-company.
[2026-07-29] Only ENABLED cash_accounts rows count as claiming an IBAN for reuse offers. The connect callback mirrors every account in a consent into cash_accounts, deselected ones included, so counting any row as a claim would mean the first company to connect speaks for the whole bank and no account is ever offerable. Enabled-only also matches the real workflow: sign once, uncheck the other companies' accounts in the picker, and those become what the next company gets.
[2026-07-29] The superseded session_id is kept on a reconnecting row through the bank round-trip instead of being nulled at /connect, because the callback needs it to move sibling companies onto the renewed consent. Renewal also re-points sibling account uids by IBAN: several ASPSPs reissue uids on re-authorization, so carrying the session id alone would have left siblings calling retired uids and re-broken them every quarter.
[2026-07-29] Reuse-offer strings are hardcoded Swedish, not messages/*.json: BankingSettingsPanel.tsx uses no next-intl at all, so adding two t() keys would either strand them or force converting the whole component, a refactor outside this change's scope.
[2026-07-29] INK2R reads two different views of the same period: the balance sheet from the closed books (so 7302 fritt eget kapital carries årets resultat via 2099) and the income statement from the pre-closing books (excludeFinalClosingEntry). The resultatavslut zeroes every P&L account, and INK2 is always filed after bokslut, so a single view cannot serve both sides. Rejected excludeYearEndClosing: tax, avskrivningar and bokslutsdispositioner also carry source_type 'year_end' and belong on the form (7525, 7528).
[2026-07-29] The sign-reclassification rules (1630-1659 credit to skatteskuld, 2500-2599 and 2610-2659 debit to fordran) were extracted to lib/reports/sign-reclassification.ts as a DATA table only. k2-mapper keeps its own sumOre arithmetic rather than calling a shared apply(): the iXBRL path sums in exact öre while INK2R works in kronor and truncates per SFL 22:1, so sharing the arithmetic would have risked öre drift in already-shipped årsredovisningar for no gain.
[2026-07-29] INK2R applies sign reclassification by relocating whole account rows between SRU codes instead of moving a net amount like k2-mapper does, so breakdown[code].accounts always sums to the code total in the UI drill-down. Exact for 'net' rules too: every account in the range moves together, so the moved rows sum to the deviating net by construction.
[2026-07-29] generateTrialBalance now takes a REQUIRED closingEntry: 'include' | 'exclude-final' | 'exclude-all-year-end' instead of two optional booleans, and the options argument is no longer optional. Rationale: picking wrong is silent (a resultatavslut posts the mirror image of every P&L account into 2099 inside the same period, so a caller that forgets reads ZERO across class 3-8 while the balance sheet still ties out and nothing warns). The same defect shipped on the arsredovisning 2026-07-23, on INK2R and NE-bilaga 2026-07-29, and was found sitting unreported on Resultatrapport and dimension-pnl in the same sweep. A required union turns each of those into a compile error at the call site. All 40 call sites were audited individually and every one preserves its current behaviour EXCEPT resultatrapport/dimension-pnl, which were reading zero for any closed year and now pass 'exclude-all-year-end'.
[2026-07-29] Resultatrapport and dimension-pnl use 'exclude-all-year-end', NOT 'exclude-final', so they keep reporting the same profit as the formal Resultaträkning. Moving generateIncomeStatement to 'exclude-final' is Stage 2 of #1051, deliberately deferred per DECISIONS.md:632; picking 'exclude-final' here would have made the operational report disagree with the formal one by the full bokslutsdisposition + skatt, which is the exact class of cross-surface disagreement this work is meant to remove. When Stage 2 lands, these call sites move with it.
[2026-07-29] The KPI route and its xlsx twin keep closingEntry: 'include', which leaves the expense-composition KPI blank for a closed year. Not fixed here: the RPC path reads agg.tb (equally unexcluded), so changing only the fallback would make the two paths disagree, and the RPC exposes tb_ex_year_end already, so the real fix is a migration plus a displayed-figure change for every company that ran bokslut. That is Stage 2 territory per DECISIONS.md:632. Recorded as an open follow-up.
[2026-07-29] get_vat_declaration_totals (migration 20260729110000) excludes the fiscal period's POSTED closing_entry_id, keyed on fiscal_periods.closing_entry_id rather than on source_type = 'year_end'. The resultatavslut debits revenue accounts, which drive rutor 05/39/40, so any VAT period containing the fiscal-year end reported negated turnover once the year was closed: verified read-only on production as ruta 39 = -794 734 kr for December of a closed year, 0 after the fix, with the January period carrying the real sale unchanged. source_type would have been the blunter filter but avskrivningar, periodiseringsfond and skatt share it and must keep whatever VAT effect they carry. A REVERSED closing entry is deliberately retained together with its storno so the pair still nets to zero, mirroring closingEntry: 'exclude-final' in trial-balance.ts; dropping only the reversed original would leave the storno behind and negate turnover a second time.
[2026-07-29] periodisk-sammanstallning.ts needed NO closing-entry fix: it filters source_type with an ALLOWLIST (invoice_created, credit_note), so a year_end entry can never reach it. An earlier sweep flagged it as broken by heuristic (raw ledger read, no year_end filter); reading the query disproved that. Recorded so the next sweep does not re-flag it.
[2026-07-30] The KPI monthly chart now excludes year-end entries, in BOTH paths: migration 20260730090000 points get_kpi_report_aggregates' monthly section at the existing tb_ex_ye_entries CTE instead of period_entries, and lib/reports/monthly-breakdown.ts gains the matching source_type + reversed-chain exclusion. 20260723180000 had documented the omission as deliberate ("year_end entries are NOT excluded here: the JS scan never excluded them either"), which faithfully mirrored the JS but the JS was itself wrong: the resultatavslut posts the mirror image of every P&L account, so the fiscal-year-end month charted the whole year's revenue as NEGATIVE income. Measured read-only on production: 28 companies over 34 month-rows, worst case a single month's income reading -10 347 459,81 kr instead of +12,88 kr. Both paths are changed together so the RPC hot path and the dimension-filtered fallback keep agreeing. This IS a displayed-figure change, but unlike the Stage 2 income-statement question it is not a choice of convention: a negative revenue spike is simply wrong.
[2026-07-30] New check:guards ratchet "ledger-scanning-report": a statement generator under lib/reports or lib/bokslut that aggregates journal_entry_lines itself instead of going through generateTrialBalance. Tracked as a file-set so a NEW generator fails CI even if an old one migrates. Four existing files are grandfathered into the baseline (asset-service, periodiseringsfond-service, bolagsskatt-calculator, sarskild-loneskatt-calculator) rather than migrated now. Voucher and line LISTINGS (general-ledger, journal-register, SIE export, reconciliation, diagnostics) are sanctioned in LEDGER_SCAN_SANCTIONED because they must show the ledger as posted and therefore have no closingEntry decision to get wrong.
[2026-07-30] OPEN FOLLOW-UP found by that guard: sarskild-loneskatt-calculator.ts sums accounts 7410-7419 with status='posted' and no year-end exclusion, so the pensionskostnad basis reads ~0 if the calculator runs against an already-closed period (as happens on an undo-then-redo bokslut). Not changed here for the same reason as getBookedBolagsskatt: it is a tax figure whose call chain DECISIONS.md:632 records as having already caused a too-high-tax customer bug, so it deserves its own change with its own verification rather than riding along in a sweep.
[2026-07-30] Sign reclassification (1630-1659 credit to skatteskuld, 2500-2599 and 2610-2659 debit to fordran) applies to the STATUTORY presentations only: the K2 iXBRL årsredovisning and INK2R. It is deliberately NOT extended to /rapporter Balansräkning (lib/reports/balance-sheet.ts) or Balansrapport (lib/reports/balansrapport.ts). Both are organised BY ACCOUNT NUMBER under BAS-prefix headings, and balansrapport.ts documents an invariant that depends on every row staying debit-positive where it was booked (total_assets_ub + total_equity_liabilities_ub = beraknat_resultat); moving konto 1630 into a liability section would break that add-the-rows-to-verify property and hide the account from anyone looking it up by number. So the answer to "extend it to the remaining balance-sheet surfaces" is that there are none: the two statutory surfaces both have it, and the other two must not. Pinned in BOTH directions by lib/reports/__tests__/sign-reclassification-scope.test.ts so neither a future sweep re-flags the operational reports nor the reclassification silently vanishes from a statutory one again.
[2026-07-30] Reconciliation is delivered in two places rather than as one UI panel. (a) INK2R now self-checks: when the year is closed it compares its own årets resultat against the booked konto 2099 and warns in Swedish if they disagree, mirroring the check k2-mapper has had since 2026-07-23. This is the alarm that was missing when INK2R reported 0 kr against a booked 469 542 kr and nothing warned because the balance sheet still tied out on its own. (b) lib/reports/statement-reconciliation.ts + GET /api/reports/statement-reconciliation return årets resultat from every surface side by side, grouped into families: ledger + statutory MUST agree and a mismatch is reported, while operational legitimately differs by bokslutsdispositioner + skatt until Stage 2 of #1051 lands. The visual panel is deliberately NOT built in this change: it needs a /frontend-design pass against the locked concept conventions plus sv/en strings, and the warning in (a) already puts the alarm where the user actually looks. The endpoint exists so the panel (and the MCP/agent surface) has a data source when it is built.
[2026-07-29] OAuth error popup stays open instead of auto-closing: the postMessage is dropped on any popup/opener origin mismatch, and closing anyway made every such failure invisible (Fortnox silent-connect incident).
[2026-07-29] FORTNOX_REDIRECT_URI on prod deliberately left on app.gnubok.se for now: flipping it to app.accounted.se before that callback URL is registered in the Fortnox Developer Portal would break connect earlier, at the authorize step.