17a7a62ceb
* 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>
1106 lines
35 KiB
TypeScript
1106 lines
35 KiB
TypeScript
import type { SupabaseClient } from '@supabase/supabase-js'
|
|
import { loadTaxAdjustmentSnapshot } from '@/lib/bokslut/tax-provision/tax-adjustment-service'
|
|
import { generateTrialBalance } from '@/lib/reports/trial-balance'
|
|
import {
|
|
SIGN_RECLASSIFICATION_RULES,
|
|
selectReclassifiedAccounts,
|
|
type SignReclassificationId,
|
|
} from '@/lib/reports/sign-reclassification'
|
|
import type { FiscalPeriod, TrialBalanceRow } from '@/types'
|
|
import type {
|
|
INK2Declaration,
|
|
INK2RRutor,
|
|
INK2Rutor,
|
|
INK2SRutor,
|
|
INK2AccountMapping,
|
|
INK2RSRUCode,
|
|
} from './types'
|
|
import {
|
|
INK2R_ASSET_CODES,
|
|
INK2R_EQUITY_LIABILITY_CODES,
|
|
} from './types'
|
|
|
|
/**
|
|
* INK2 Declaration Engine
|
|
*
|
|
* Generates INK2 (huvudblankett), INK2R (räkenskapsschema), and INK2S
|
|
* (skattemässiga justeringar) for aktiebolag tax reporting.
|
|
*
|
|
* Account mappings follow the official BAS-to-SRU mapping from
|
|
* bas.se/kontoplaner/sru/ and Skatteverket field code spec.
|
|
*
|
|
* INK2R contains the full balance sheet + income statement.
|
|
* INK2S auto-derives basic fields (result + tax → taxable result), as well as
|
|
* periodiseringsfond and överavskrivningar when those have been posted via the
|
|
* bokslut-dispositions calculators in lib/bokslut/.
|
|
*
|
|
* Balances come from generateTrialBalance, never from a raw journal scan, and
|
|
* the two sides of INK2R read DIFFERENT views of the same period:
|
|
*
|
|
* - Balance sheet: the closed books. After year-end the resultatavslut has
|
|
* moved årets resultat into 2099, so fritt eget kapital (7302) is only
|
|
* right when the closing verifikat is included.
|
|
* - Income statement: the pre-closing books (excludeFinalClosingEntry). The
|
|
* resultatavslut zeroes every P&L account against 2099, so including it
|
|
* collapses the whole resultaträkning to zero, which then cascades into
|
|
* INK2S 7650/7651 and the taxable result. INK2 is always filed after
|
|
* bokslut, so that is the normal state, not an edge case.
|
|
*
|
|
* excludeFinalClosingEntry drops only fiscal_periods.closing_entry_id: tax,
|
|
* depreciation and bokslutsdispositioner also carry source_type 'year_end' and
|
|
* must stay on the form (7525, 7528).
|
|
*/
|
|
|
|
/**
|
|
* BAS-to-SRU account mappings for INK2R
|
|
* Source: bas.se/kontoplaner/sru/ (stable since 2017)
|
|
*/
|
|
export const INK2R_ACCOUNT_MAPPINGS: INK2AccountMapping[] = [
|
|
// ---- Balance sheet: Assets ----
|
|
{
|
|
sruCode: '7201',
|
|
description: 'Koncessioner, patent, licenser, varumärken, goodwill',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [
|
|
{ start: '1010', end: '1079' },
|
|
{ start: '1090', end: '1099' },
|
|
],
|
|
},
|
|
{
|
|
sruCode: '7202',
|
|
description: 'Förskott immateriella anläggningstillgångar',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '1080', end: '1089' }],
|
|
},
|
|
{
|
|
sruCode: '7214',
|
|
description: 'Byggnader och mark',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [
|
|
{ start: '1100', end: '1119' },
|
|
{ start: '1130', end: '1179' },
|
|
{ start: '1190', end: '1199' },
|
|
],
|
|
},
|
|
{
|
|
sruCode: '7215',
|
|
description: 'Maskiner, inventarier, övriga materiella',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '1200', end: '1299' }],
|
|
},
|
|
{
|
|
sruCode: '7216',
|
|
description: 'Förbättringsutgifter på annans fastighet',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '1120', end: '1129' }],
|
|
},
|
|
{
|
|
sruCode: '7217',
|
|
description: 'Pågående nyanläggningar, förskott materiella',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '1180', end: '1189' }],
|
|
},
|
|
{
|
|
sruCode: '7230',
|
|
description: 'Andelar i koncernföretag',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '1311', end: '1316' }],
|
|
},
|
|
{
|
|
sruCode: '7231',
|
|
description: 'Andelar i intresseföretag',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '1330', end: '1338' }],
|
|
},
|
|
{
|
|
sruCode: '7233',
|
|
description: 'Ägarintressen övriga företag + långfristiga värdepapper',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [
|
|
{ start: '1350', end: '1359' },
|
|
{ start: '1380', end: '1389' },
|
|
],
|
|
},
|
|
{
|
|
sruCode: '7232',
|
|
description: 'Fordringar koncern/intresse',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [
|
|
{ start: '1320', end: '1329' },
|
|
{ start: '1340', end: '1349' },
|
|
],
|
|
},
|
|
{
|
|
sruCode: '7234',
|
|
description: 'Lån till delägare eller närstående',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '1360', end: '1369' }],
|
|
},
|
|
{
|
|
sruCode: '7235',
|
|
description: 'Övriga långfristiga fordringar',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [
|
|
{ start: '1370', end: '1379' },
|
|
{ start: '1390', end: '1399' },
|
|
],
|
|
},
|
|
{
|
|
sruCode: '7241',
|
|
description: 'Råvaror och förnödenheter',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '1410', end: '1419' }],
|
|
},
|
|
{
|
|
sruCode: '7242',
|
|
description: 'Varor under tillverkning',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '1440', end: '1449' }],
|
|
},
|
|
{
|
|
sruCode: '7243',
|
|
description: 'Färdiga varor och handelsvaror',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '1450', end: '1469' }],
|
|
},
|
|
{
|
|
sruCode: '7244',
|
|
description: 'Övriga lagertillgångar',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '1470', end: '1489' }],
|
|
},
|
|
{
|
|
sruCode: '7245',
|
|
description: 'Pågående arbeten för annans räkning',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '1490', end: '1499' }],
|
|
},
|
|
{
|
|
sruCode: '7246',
|
|
description: 'Förskott till leverantörer',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '1400', end: '1409' }],
|
|
},
|
|
{
|
|
sruCode: '7251',
|
|
description: 'Kundfordringar',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '1500', end: '1519' }],
|
|
},
|
|
{
|
|
sruCode: '7252',
|
|
description: 'Fordringar koncern/intresse (kortfristiga)',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '1560', end: '1579' }],
|
|
},
|
|
{
|
|
sruCode: '7261',
|
|
description: 'Övriga fordringar',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [
|
|
{ start: '1520', end: '1559' },
|
|
{ start: '1580', end: '1599' },
|
|
{ start: '1600', end: '1619' },
|
|
{ start: '1621', end: '1699' },
|
|
],
|
|
},
|
|
{
|
|
sruCode: '7262',
|
|
description: 'Upparbetad men ej fakturerad intäkt',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '1620', end: '1620' }],
|
|
},
|
|
{
|
|
sruCode: '7263',
|
|
description: 'Förutbetalda kostnader och upplupna intäkter',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '1700', end: '1799' }],
|
|
},
|
|
{
|
|
sruCode: '7270',
|
|
description: 'Andelar i koncernföretag (kortfristiga)',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '1860', end: '1869' }],
|
|
},
|
|
{
|
|
sruCode: '7271',
|
|
description: 'Övriga kortfristiga placeringar',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [
|
|
{ start: '1800', end: '1859' },
|
|
{ start: '1870', end: '1899' },
|
|
],
|
|
},
|
|
{
|
|
sruCode: '7281',
|
|
description: 'Kassa, bank och redovisningsmedel',
|
|
section: 'assets',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '1900', end: '1999' }],
|
|
},
|
|
|
|
// ---- Balance sheet: Equity & Liabilities ----
|
|
{
|
|
sruCode: '7301',
|
|
description: 'Bundet eget kapital',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '2010', end: '2089' }],
|
|
},
|
|
{
|
|
sruCode: '7302',
|
|
description: 'Fritt eget kapital',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '2090', end: '2099' }],
|
|
},
|
|
{
|
|
sruCode: '7321',
|
|
description: 'Periodiseringsfonder',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [
|
|
{ start: '2100', end: '2109' },
|
|
{ start: '2110', end: '2129' },
|
|
],
|
|
},
|
|
{
|
|
sruCode: '7322',
|
|
description: 'Ackumulerade överavskrivningar',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '2150', end: '2159' }],
|
|
},
|
|
{
|
|
sruCode: '7323',
|
|
description: 'Övriga obeskattade reserver',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [
|
|
{ start: '2130', end: '2149' },
|
|
{ start: '2160', end: '2199' },
|
|
],
|
|
},
|
|
{
|
|
sruCode: '7331',
|
|
description: 'Pensionsavsättningar tryggandelagen',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '2210', end: '2219' }],
|
|
},
|
|
{
|
|
sruCode: '7332',
|
|
description: 'Övriga pensionsavsättningar',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '2220', end: '2229' }],
|
|
},
|
|
{
|
|
sruCode: '7333',
|
|
description: 'Övriga avsättningar',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '2230', end: '2299' }],
|
|
},
|
|
{
|
|
sruCode: '7350',
|
|
description: 'Obligationslån',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [
|
|
{ start: '2300', end: '2319' },
|
|
{ start: '2320', end: '2329' },
|
|
],
|
|
},
|
|
{
|
|
sruCode: '7351',
|
|
description: 'Checkräkningskredit (långfristig)',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '2330', end: '2339' }],
|
|
},
|
|
{
|
|
sruCode: '7352',
|
|
description: 'Övriga skulder kreditinstitut (långfristiga)',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '2340', end: '2359' }],
|
|
},
|
|
{
|
|
sruCode: '7353',
|
|
description: 'Skulder koncern/intresse (långfristiga)',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '2360', end: '2379' }],
|
|
},
|
|
{
|
|
sruCode: '7354',
|
|
description: 'Övriga skulder (långfristiga)',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '2380', end: '2399' }],
|
|
},
|
|
{
|
|
sruCode: '7360',
|
|
description: 'Checkräkningskredit (kortfristig)',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '2410', end: '2419' }],
|
|
},
|
|
{
|
|
sruCode: '7361',
|
|
description: 'Övriga skulder kreditinstitut (kortfristiga)',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '2420', end: '2439' }],
|
|
},
|
|
{
|
|
sruCode: '7362',
|
|
description: 'Förskott från kunder',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '2400', end: '2409' }],
|
|
},
|
|
{
|
|
sruCode: '7363',
|
|
description: 'Pågående arbeten (skuldsida)',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '2450', end: '2459' }],
|
|
},
|
|
{
|
|
sruCode: '7364',
|
|
description: 'Fakturerad men ej upparbetad intäkt',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '2460', end: '2469' }],
|
|
},
|
|
{
|
|
sruCode: '7365',
|
|
description: 'Leverantörsskulder',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '2440', end: '2449' }],
|
|
},
|
|
{
|
|
sruCode: '7366',
|
|
description: 'Växelskulder',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '2490', end: '2490' }],
|
|
},
|
|
{
|
|
sruCode: '7367',
|
|
description: 'Skulder koncern/intresse (kortfristiga)',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '2470', end: '2479' }],
|
|
},
|
|
{
|
|
sruCode: '7369',
|
|
description: 'Övriga skulder (kortfristiga)',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [
|
|
{ start: '2480', end: '2489' },
|
|
{ start: '2491', end: '2499' },
|
|
{ start: '2600', end: '2799' },
|
|
{ start: '2800', end: '2899' },
|
|
],
|
|
},
|
|
{
|
|
sruCode: '7368',
|
|
description: 'Skatteskulder',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '2500', end: '2599' }],
|
|
},
|
|
{
|
|
sruCode: '7370',
|
|
description: 'Upplupna kostnader och förutbetalda intäkter',
|
|
section: 'equity_liabilities',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '2900', end: '2999' }],
|
|
},
|
|
|
|
// ---- Income statement ----
|
|
{
|
|
sruCode: '7410',
|
|
description: 'Nettoomsättning',
|
|
section: 'income_statement',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '3000', end: '3799' }],
|
|
},
|
|
{
|
|
sruCode: '7412',
|
|
description: 'Aktiverat arbete för egen räkning',
|
|
section: 'income_statement',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '3800', end: '3899' }],
|
|
},
|
|
{
|
|
sruCode: '7413',
|
|
description: 'Övriga rörelseintäkter',
|
|
section: 'income_statement',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '3900', end: '3999' }],
|
|
},
|
|
{
|
|
sruCode: '7411',
|
|
description: 'Förändring av lager',
|
|
section: 'income_statement',
|
|
normalBalance: 'net',
|
|
accountRanges: [{ start: '4900', end: '4999' }],
|
|
},
|
|
{
|
|
sruCode: '7511',
|
|
description: 'Råvaror och förnödenheter',
|
|
section: 'income_statement',
|
|
normalBalance: 'debit',
|
|
accountRanges: [
|
|
{ start: '4000', end: '4499' },
|
|
{ start: '4500', end: '4599' },
|
|
{ start: '4700', end: '4899' },
|
|
],
|
|
},
|
|
{
|
|
sruCode: '7512',
|
|
description: 'Handelsvaror',
|
|
section: 'income_statement',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '4600', end: '4699' }],
|
|
},
|
|
// CRITICAL: BAS 5000-6999 ALL map to SRU 7513
|
|
{
|
|
sruCode: '7513',
|
|
description: 'Övriga externa kostnader',
|
|
section: 'income_statement',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '5000', end: '6999' }],
|
|
},
|
|
{
|
|
sruCode: '7514',
|
|
description: 'Personalkostnader',
|
|
section: 'income_statement',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '7000', end: '7699' }],
|
|
},
|
|
{
|
|
sruCode: '7515',
|
|
description: 'Av- och nedskrivningar materiella/immateriella',
|
|
section: 'income_statement',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '7800', end: '7899' }],
|
|
},
|
|
{
|
|
sruCode: '7516',
|
|
description: 'Nedskrivningar omsättningstillgångar',
|
|
section: 'income_statement',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '7700', end: '7799' }],
|
|
},
|
|
{
|
|
sruCode: '7517',
|
|
description: 'Övriga rörelsekostnader',
|
|
section: 'income_statement',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '7900', end: '7999' }],
|
|
},
|
|
{
|
|
sruCode: '7414',
|
|
description: 'Resultat från andelar i koncernföretag',
|
|
section: 'income_statement',
|
|
normalBalance: 'net',
|
|
accountRanges: [{ start: '8000', end: '8099' }],
|
|
},
|
|
{
|
|
sruCode: '7415',
|
|
description: 'Resultat från andelar i intresseföretag',
|
|
section: 'income_statement',
|
|
normalBalance: 'net',
|
|
accountRanges: [{ start: '8100', end: '8199' }],
|
|
},
|
|
{
|
|
sruCode: '7423',
|
|
description: 'Resultat från övriga företag med ägarintresse',
|
|
section: 'income_statement',
|
|
normalBalance: 'net',
|
|
accountRanges: [{ start: '8200', end: '8269' }],
|
|
},
|
|
{
|
|
sruCode: '7416',
|
|
description: 'Resultat från övriga finansiella anläggningstillgångar',
|
|
section: 'income_statement',
|
|
normalBalance: 'net',
|
|
accountRanges: [{ start: '8270', end: '8299' }],
|
|
},
|
|
{
|
|
sruCode: '7417',
|
|
description: 'Övriga ränteintäkter och liknande',
|
|
section: 'income_statement',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '8300', end: '8399' }],
|
|
},
|
|
{
|
|
sruCode: '7522',
|
|
description: 'Räntekostnader och liknande',
|
|
section: 'income_statement',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '8400', end: '8499' }],
|
|
},
|
|
{
|
|
sruCode: '7521',
|
|
description: 'Nedskrivningar finansiella anläggningstillgångar',
|
|
section: 'income_statement',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '8500', end: '8599' }],
|
|
},
|
|
// Bokslutsdispositioner: account numbers per BAS 2020 (verified against
|
|
// lib/bookkeeping/bas-data/class-8-financial.ts).
|
|
{
|
|
sruCode: '7525',
|
|
description: 'Avsättning till periodiseringsfond',
|
|
section: 'income_statement',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '8811', end: '8811' }],
|
|
},
|
|
{
|
|
sruCode: '7420',
|
|
description: 'Återföring av periodiseringsfond',
|
|
section: 'income_statement',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '8819', end: '8819' }],
|
|
},
|
|
{
|
|
sruCode: '7419',
|
|
description: 'Mottagna koncernbidrag',
|
|
section: 'income_statement',
|
|
normalBalance: 'credit',
|
|
accountRanges: [{ start: '8820', end: '8820' }],
|
|
},
|
|
{
|
|
sruCode: '7524',
|
|
description: 'Lämnade koncernbidrag',
|
|
section: 'income_statement',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '8830', end: '8830' }],
|
|
},
|
|
{
|
|
sruCode: '7421',
|
|
description: 'Förändring av överavskrivningar',
|
|
section: 'income_statement',
|
|
normalBalance: 'net',
|
|
// 8850 = grupp, 8851-8853 = per kategori (immateriella, byggnader, M&I)
|
|
accountRanges: [{ start: '8850', end: '8859' }],
|
|
},
|
|
{
|
|
sruCode: '7422',
|
|
description: 'Övriga bokslutsdispositioner',
|
|
section: 'income_statement',
|
|
normalBalance: 'net',
|
|
// 8840 = Lämnade gottgörelser, 8860-8899 = övriga
|
|
accountRanges: [
|
|
{ start: '8840', end: '8840' },
|
|
{ start: '8860', end: '8899' },
|
|
],
|
|
},
|
|
{
|
|
sruCode: '7528',
|
|
description: 'Skatt på årets resultat',
|
|
section: 'income_statement',
|
|
normalBalance: 'debit',
|
|
accountRanges: [{ start: '8900', end: '8989' }],
|
|
},
|
|
// 7450/7550 (årets resultat vinst/förlust) are calculated, not mapped from accounts
|
|
]
|
|
|
|
/** One mapping per SRU code: pinned by a test in __tests__/ink2-engine.test.ts. */
|
|
const MAPPING_BY_CODE = new Map<INK2RSRUCode, INK2AccountMapping>(
|
|
INK2R_ACCOUNT_MAPPINGS.map((mapping) => [mapping.sruCode, mapping]),
|
|
)
|
|
|
|
/**
|
|
* INK2R posts each shared sign-reclassification rule moves between. The rules
|
|
* live in lib/reports/sign-reclassification.ts and are shared with the K2
|
|
* iXBRL årsredovisning so both statutory reports present the same balance
|
|
* sheet. A test pins that every rule's account range really does map to the
|
|
* `from` code below.
|
|
*/
|
|
const SIGN_RECLASSIFICATION_ROUTES: Record<
|
|
SignReclassificationId,
|
|
{ from: INK2RSRUCode; to: INK2RSRUCode }
|
|
> = {
|
|
tax_account_credit_to_liability: { from: '7261', to: '7368' },
|
|
tax_liability_debit_to_receivable: { from: '7368', to: '7261' },
|
|
vat_liability_debit_to_receivable: { from: '7369', to: '7261' },
|
|
}
|
|
|
|
/**
|
|
* Check if an account number falls within a mapping's ranges
|
|
*/
|
|
export function isAccountInMapping(accountNumber: string, mapping: INK2AccountMapping): boolean {
|
|
for (const range of mapping.accountRanges) {
|
|
if (accountNumber >= range.start && accountNumber <= range.end) {
|
|
if (range.exclude && range.exclude.includes(accountNumber)) {
|
|
continue
|
|
}
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
/**
|
|
* Truncate to nearest krona (drop öre) per SFL 22 kap. 1 §
|
|
*/
|
|
function truncateToKrona(value: number): number {
|
|
return value >= 0 ? Math.floor(value) : Math.ceil(value)
|
|
}
|
|
|
|
/**
|
|
* Slack allowed before a difference counts as a real disagreement. Every INK2
|
|
* field is truncated to whole kronor per SFL 22 kap. 1 §, so a few öre of
|
|
* truncation residual can accumulate across the form legitimately.
|
|
*/
|
|
const ROUNDING_TOLERANCE_KR = 2
|
|
|
|
/**
|
|
* Check if the balance sheet totals differ beyond the expected rounding tolerance.
|
|
*/
|
|
export function checkBalanceWarning(totalAssets: number, totalEquityLiabilities: number): string | null {
|
|
const balanceDiff = Math.abs(totalAssets - totalEquityLiabilities)
|
|
if (balanceDiff > ROUNDING_TOLERANCE_KR && (totalAssets > 0 || totalEquityLiabilities > 0)) {
|
|
return `Balansräkningen är inte i balans. Tillgångar: ${totalAssets} kr, Eget kapital och skulder: ${totalEquityLiabilities} kr (differens: ${balanceDiff} kr).`
|
|
}
|
|
return null
|
|
}
|
|
|
|
/** Create zero-initialized INK2R rutor */
|
|
function createEmptyINK2RRutor(): INK2RRutor {
|
|
return {
|
|
'7201': 0, '7202': 0, '7214': 0, '7215': 0, '7216': 0, '7217': 0,
|
|
'7230': 0, '7231': 0, '7233': 0, '7232': 0, '7234': 0, '7235': 0,
|
|
'7241': 0, '7242': 0, '7243': 0, '7244': 0, '7245': 0, '7246': 0,
|
|
'7251': 0, '7252': 0, '7261': 0, '7262': 0, '7263': 0,
|
|
'7270': 0, '7271': 0, '7281': 0,
|
|
'7301': 0, '7302': 0,
|
|
'7321': 0, '7322': 0, '7323': 0,
|
|
'7331': 0, '7332': 0, '7333': 0,
|
|
'7350': 0, '7351': 0, '7352': 0, '7353': 0, '7354': 0,
|
|
'7360': 0, '7361': 0, '7362': 0, '7363': 0, '7364': 0,
|
|
'7365': 0, '7366': 0, '7367': 0, '7369': 0, '7368': 0, '7370': 0,
|
|
'7410': 0, '7411': 0, '7412': 0, '7413': 0,
|
|
'7511': 0, '7512': 0, '7513': 0, '7514': 0, '7515': 0, '7516': 0, '7517': 0,
|
|
'7414': 0, '7415': 0, '7423': 0, '7416': 0, '7417': 0,
|
|
'7521': 0, '7522': 0,
|
|
'7524': 0, '7419': 0, '7420': 0, '7525': 0, '7421': 0, '7422': 0,
|
|
'7528': 0,
|
|
'7450': 0, '7550': 0,
|
|
}
|
|
}
|
|
|
|
// Reuse canonical code arrays from types.ts (single source of truth)
|
|
const ASSET_CODES = INK2R_ASSET_CODES
|
|
const EQUITY_LIABILITY_CODES = INK2R_EQUITY_LIABILITY_CODES
|
|
|
|
/** One account's contribution to an SRU code, before orientation and truncation. */
|
|
interface AccountContribution {
|
|
accountNumber: string
|
|
accountName: string
|
|
/** Raw ledger balance, debit-positive. */
|
|
balance: number
|
|
}
|
|
|
|
/** UB per account from a trial balance, debit-positive. */
|
|
function toSignedBalances(rows: TrialBalanceRow[]): Map<string, number> {
|
|
const balances = new Map<string, number>()
|
|
for (const row of rows) {
|
|
balances.set(
|
|
row.account_number,
|
|
(Number(row.closing_debit) || 0) - (Number(row.closing_credit) || 0),
|
|
)
|
|
}
|
|
return balances
|
|
}
|
|
|
|
function findMappingForAccount(accountNumber: string): INK2AccountMapping | null {
|
|
for (const mapping of INK2R_ACCOUNT_MAPPINGS) {
|
|
if (isAccountInMapping(accountNumber, mapping)) return mapping
|
|
}
|
|
return null
|
|
}
|
|
|
|
/**
|
|
* Orient a raw ledger balance to the amount Skatteverket expects in the field.
|
|
* Every INK2R amount is reported positive when the post carries its normal
|
|
* balance; costs are positive on the income statement side.
|
|
*/
|
|
function orientedAmount(balance: number, mapping: INK2AccountMapping): number {
|
|
if (mapping.normalBalance === 'debit') return balance
|
|
// Credit-normal posts, and 'net' posts where positive means income.
|
|
return -balance
|
|
}
|
|
|
|
/**
|
|
* Relocate balance sheet accounts whose balance deviates from their post's
|
|
* normal side (1630 with a credit is a skatteskuld, 2641 with a debit is a
|
|
* fordran). Whole account rows move, so the per-account breakdown stays
|
|
* consistent with the post totals; for `net` rules the moved rows sum to the
|
|
* deviating net by construction because every account in range moves together.
|
|
*/
|
|
function applySignReclassifications(
|
|
contributions: Map<INK2RSRUCode, AccountContribution[]>,
|
|
balanceSheetBalances: ReadonlyMap<string, number>,
|
|
warnings: string[],
|
|
): void {
|
|
for (const rule of SIGN_RECLASSIFICATION_RULES) {
|
|
const route = SIGN_RECLASSIFICATION_ROUTES[rule.id]
|
|
const moving = new Set(selectReclassifiedAccounts(rule, balanceSheetBalances))
|
|
if (moving.size === 0) continue
|
|
|
|
const source = contributions.get(route.from) ?? []
|
|
const moved = source.filter((c) => moving.has(c.accountNumber))
|
|
if (moved.length === 0) continue
|
|
|
|
contributions.set(
|
|
route.from,
|
|
source.filter((c) => !moving.has(c.accountNumber)),
|
|
)
|
|
contributions.set(route.to, [...(contributions.get(route.to) ?? []), ...moved])
|
|
warnings.push(rule.warning)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Whether the resultatavslut has already moved årets resultat into 2099.
|
|
*
|
|
* Mirrors the predicate generateTrialBalance uses to drop the closing entry: a
|
|
* reversed closing entry nets to zero against its storno and has therefore not
|
|
* moved anything.
|
|
*/
|
|
async function isResultClosedIntoEquity(
|
|
supabase: SupabaseClient,
|
|
companyId: string,
|
|
closingEntryId: string | null | undefined,
|
|
): Promise<boolean> {
|
|
if (!closingEntryId) return false
|
|
const { data } = await supabase
|
|
.from('journal_entries')
|
|
.select('status')
|
|
.eq('id', closingEntryId)
|
|
.eq('company_id', companyId)
|
|
.maybeSingle()
|
|
return (data as { status?: string } | null)?.status === 'posted'
|
|
}
|
|
|
|
/**
|
|
* Generate INK2 declaration for a fiscal period
|
|
*/
|
|
export async function generateINK2Declaration(
|
|
supabase: SupabaseClient,
|
|
companyId: string,
|
|
fiscalPeriodId: string
|
|
): Promise<INK2Declaration> {
|
|
|
|
// Fetch fiscal period
|
|
const { data: period, error: periodError } = await supabase
|
|
.from('fiscal_periods')
|
|
.select('*')
|
|
.eq('id', fiscalPeriodId)
|
|
.eq('company_id', companyId)
|
|
.single()
|
|
|
|
if (periodError || !period) {
|
|
throw new Error('Fiscal period not found')
|
|
}
|
|
|
|
// Fetch company settings
|
|
const { data: settings } = await supabase
|
|
.from('company_settings')
|
|
.select('company_name, org_number, entity_type, address_line1, postal_code, city, email')
|
|
.eq('company_id', companyId)
|
|
.single()
|
|
|
|
// Resolve entity_type: prefer company_settings, fall back to companies table (NOT NULL, always reliable)
|
|
let entityType = settings?.entity_type
|
|
if (!entityType) {
|
|
const { data: company, error: companyError } = await supabase
|
|
.from('companies')
|
|
.select('entity_type')
|
|
.eq('id', companyId)
|
|
.single()
|
|
if (companyError) throw new Error(`Failed to resolve entity type: ${companyError.message}`)
|
|
entityType = company?.entity_type
|
|
}
|
|
|
|
if (entityType !== 'aktiebolag') {
|
|
throw new Error('INK2 declaration is only for aktiebolag (limited company)')
|
|
}
|
|
|
|
// The balance sheet reads the closed books, the income statement the
|
|
// pre-closing books. See the module docblock for why the two differ.
|
|
const [taxAdjustments, closedTrialBalance, preClosingTrialBalance, resultClosedIntoEquity] =
|
|
await Promise.all([
|
|
loadTaxAdjustmentSnapshot(supabase, companyId, fiscalPeriodId),
|
|
generateTrialBalance(supabase, companyId, fiscalPeriodId, { closingEntry: 'include' }),
|
|
generateTrialBalance(supabase, companyId, fiscalPeriodId, {
|
|
closingEntry: 'exclude-final',
|
|
}),
|
|
isResultClosedIntoEquity(supabase, companyId, period.closing_entry_id as string | null),
|
|
])
|
|
|
|
const balanceSheetBalances = toSignedBalances(closedTrialBalance.rows)
|
|
const incomeBalances = toSignedBalances(preClosingTrialBalance.rows)
|
|
|
|
const accountNameMap = new Map<string, string>()
|
|
for (const row of [...closedTrialBalance.rows, ...preClosingTrialBalance.rows]) {
|
|
accountNameMap.set(row.account_number, row.account_name)
|
|
}
|
|
|
|
const warnings: string[] = []
|
|
|
|
// Collect each account's contribution to its SRU code, keeping the raw
|
|
// balance so a reclassified account can be re-oriented under its new code.
|
|
const contributions = new Map<INK2RSRUCode, AccountContribution[]>()
|
|
const allAccountNumbers = new Set([
|
|
...balanceSheetBalances.keys(),
|
|
...incomeBalances.keys(),
|
|
])
|
|
|
|
for (const accountNumber of allAccountNumbers) {
|
|
// Skip account 8999: årets resultat is calculated
|
|
if (accountNumber === '8999') continue
|
|
|
|
const mapping = findMappingForAccount(accountNumber)
|
|
|
|
if (!mapping) {
|
|
// BAS accounts 4500-4599, 4700-4899, and 1300-1310 have no standard SRU
|
|
// mapping. These are unusual and may indicate custom accounts.
|
|
const hasBalance =
|
|
Math.abs(balanceSheetBalances.get(accountNumber) ?? 0) >= 0.01
|
|
|| Math.abs(incomeBalances.get(accountNumber) ?? 0) >= 0.01
|
|
const classChar = accountNumber.charAt(0)
|
|
if (hasBalance && classChar >= '1' && classChar <= '8') {
|
|
// Only warn for standard BAS range accounts that weren't mapped
|
|
warnings.push(`Konto ${accountNumber} (${accountNameMap.get(accountNumber) || 'okänt'}) kunde inte mappas till ett SRU-fält.`)
|
|
}
|
|
continue
|
|
}
|
|
|
|
const balance =
|
|
mapping.section === 'income_statement'
|
|
? incomeBalances.get(accountNumber) ?? 0
|
|
: balanceSheetBalances.get(accountNumber) ?? 0
|
|
if (Math.abs(balance) < 0.01) continue
|
|
|
|
const list = contributions.get(mapping.sruCode)
|
|
const contribution: AccountContribution = {
|
|
accountNumber,
|
|
accountName: accountNameMap.get(accountNumber) || `Konto ${accountNumber}`,
|
|
balance,
|
|
}
|
|
if (list) {
|
|
list.push(contribution)
|
|
} else {
|
|
contributions.set(mapping.sruCode, [contribution])
|
|
}
|
|
}
|
|
|
|
applySignReclassifications(contributions, balanceSheetBalances, warnings)
|
|
|
|
// Initialize INK2R rutor and breakdown
|
|
const ink2r = createEmptyINK2RRutor()
|
|
const allCodes = Object.keys(ink2r) as INK2RSRUCode[]
|
|
const breakdown = {} as INK2Declaration['breakdown']
|
|
for (const code of allCodes) {
|
|
breakdown[code] = { accounts: [], total: 0 }
|
|
}
|
|
|
|
for (const [code, list] of contributions) {
|
|
const mapping = MAPPING_BY_CODE.get(code)
|
|
if (!mapping) continue
|
|
for (const contribution of list) {
|
|
const amount = orientedAmount(contribution.balance, mapping)
|
|
ink2r[code] += amount
|
|
breakdown[code].accounts.push({
|
|
accountNumber: contribution.accountNumber,
|
|
accountName: contribution.accountName,
|
|
amount: truncateToKrona(amount),
|
|
})
|
|
}
|
|
}
|
|
|
|
// Truncate all INK2R rutor to whole kronor
|
|
for (const code of allCodes) {
|
|
ink2r[code] = truncateToKrona(ink2r[code])
|
|
breakdown[code].total = ink2r[code]
|
|
}
|
|
|
|
// Calculate totals
|
|
const totalAssets = ASSET_CODES.reduce((sum, code) => sum + ink2r[code], 0)
|
|
const totalEquityLiabilities = EQUITY_LIABILITY_CODES.reduce((sum, code) => sum + ink2r[code], 0)
|
|
|
|
// Operating result: revenue minus costs (costs are positive per Skatteverket convention)
|
|
const operatingResult =
|
|
ink2r['7410'] + ink2r['7411'] + ink2r['7412'] + ink2r['7413']
|
|
- ink2r['7511'] - ink2r['7512'] - ink2r['7513'] - ink2r['7514']
|
|
- ink2r['7515'] - ink2r['7516'] - ink2r['7517']
|
|
|
|
// Financial items: income minus costs
|
|
const financialItems =
|
|
ink2r['7414'] + ink2r['7415'] + ink2r['7423'] + ink2r['7416'] + ink2r['7417']
|
|
- ink2r['7521'] - ink2r['7522']
|
|
|
|
// Bokslutsdispositioner: subtract debit-normal, add credit-normal and net
|
|
const bokslutsdispositioner =
|
|
- ink2r['7524'] + ink2r['7419'] + ink2r['7420'] - ink2r['7525']
|
|
+ ink2r['7421'] + ink2r['7422']
|
|
|
|
// Result before tax
|
|
const resultBeforeTax = operatingResult + financialItems + bokslutsdispositioner
|
|
|
|
// Result after tax (7528 is positive, subtract it)
|
|
const aretsResultat = resultBeforeTax - ink2r['7528']
|
|
|
|
// Set årets resultat: vinst (7450) or förlust (7550)
|
|
if (aretsResultat >= 0) {
|
|
ink2r['7450'] = aretsResultat
|
|
ink2r['7550'] = 0
|
|
} else {
|
|
ink2r['7450'] = 0
|
|
ink2r['7550'] = Math.abs(aretsResultat)
|
|
}
|
|
|
|
// During an open fiscal year 2099 has no balance yet: the result exists only
|
|
// as the net of the income statement accounts, so add it to make the balance
|
|
// sheet tie out. Once the resultatavslut is posted, 7302 already carries it
|
|
// via 2099 and adding it again would double-count årets resultat.
|
|
const adjustedEquityLiabilities = resultClosedIntoEquity
|
|
? totalEquityLiabilities
|
|
: totalEquityLiabilities + aretsResultat
|
|
|
|
// Fiscal year dates as YYYYMMDD
|
|
const fyStart = (period.period_start as string).replace(/-/g, '')
|
|
const fyEnd = (period.period_end as string).replace(/-/g, '')
|
|
|
|
// Build INK2 (huvudblankett)
|
|
// Auto-derive from INK2S result and the saved tax-only adjustments.
|
|
// 7528 is already positive per Skatteverket convention
|
|
const taxAmount = ink2r['7528']
|
|
// INK2/SRU amounts are declared in whole kronor with ören omitted. Use the
|
|
// same whole-krona values in both the adjustment fields and the tax result
|
|
// so the worksheet remains internally consistent.
|
|
const nonDeductibleExpenses = Math.trunc(taxAdjustments.nonDeductibleExpenses)
|
|
const nonTaxableIncome = Math.trunc(taxAdjustments.nonTaxableIncome)
|
|
const taxableResult =
|
|
aretsResultat + taxAmount
|
|
+ nonDeductibleExpenses - nonTaxableIncome
|
|
|
|
const ink2: INK2Rutor = {
|
|
'7011': fyStart,
|
|
'7012': fyEnd,
|
|
'7113': taxableResult >= 0 ? taxableResult : 0,
|
|
'7114': taxableResult < 0 ? Math.abs(taxableResult) : 0,
|
|
}
|
|
|
|
// Build INK2S (skattemässiga justeringar, auto-derived basics only)
|
|
const ink2s: INK2SRutor = {
|
|
'7011': fyStart,
|
|
'7012': fyEnd,
|
|
'7650': aretsResultat >= 0 ? aretsResultat : 0,
|
|
'7750': aretsResultat < 0 ? Math.abs(aretsResultat) : 0,
|
|
'7651': taxAmount, // Skatt (ej avdragsgill)
|
|
'7653': nonDeductibleExpenses,
|
|
'7754': nonTaxableIncome,
|
|
'8020': taxableResult >= 0 ? taxableResult : 0,
|
|
'8021': taxableResult < 0 ? Math.abs(taxableResult) : 0,
|
|
}
|
|
|
|
// Add warnings
|
|
if (!(period as FiscalPeriod).is_closed) {
|
|
warnings.push('Räkenskapsåret är inte stängt; deklarationen kan genereras, men siffrorna kan ändras om fler bokföringar görs.')
|
|
}
|
|
|
|
if (totalAssets === 0 && totalEquityLiabilities === 0 && ink2r['7410'] === 0) {
|
|
warnings.push('Inga bokförda transaktioner hittades för perioden.')
|
|
}
|
|
|
|
const balanceWarning = checkBalanceWarning(totalAssets, adjustedEquityLiabilities)
|
|
if (balanceWarning) {
|
|
warnings.push(balanceWarning)
|
|
}
|
|
|
|
// Cross-surface self-check. When the year is closed, the resultaträkning the
|
|
// form reports must equal the årets resultat the books actually carry on 2099,
|
|
// which is also the figure the fastställda årsredovisningen shows. Mirrors the
|
|
// equivalent check in lib/bokslut/ixbrl/k2-mapper.ts so both statutory reports
|
|
// catch the same disagreement.
|
|
//
|
|
// This is the alarm that was missing: when INK2R reported 0 kr against a
|
|
// booked result of 469 542 kr, nothing warned, because the balance sheet
|
|
// still tied out on its own. A customer found it instead.
|
|
if (resultClosedIntoEquity) {
|
|
const bookedResult = truncateToKrona(-(balanceSheetBalances.get('2099') ?? 0))
|
|
const declaredResult = aretsResultat
|
|
if (Math.abs(bookedResult - declaredResult) > ROUNDING_TOLERANCE_KR) {
|
|
warnings.push(
|
|
`Årets resultat enligt resultaträkningen (${declaredResult} kr) stämmer inte med det bokförda resultatet på konto 2099 (${bookedResult} kr). Deklarationen stämmer då inte med det fastställda bokslutet.`,
|
|
)
|
|
}
|
|
}
|
|
|
|
return {
|
|
fiscalYear: {
|
|
id: period.id,
|
|
name: period.name,
|
|
start: period.period_start,
|
|
end: period.period_end,
|
|
isClosed: period.is_closed,
|
|
},
|
|
ink2,
|
|
ink2r,
|
|
ink2s,
|
|
breakdown,
|
|
totals: {
|
|
totalAssets,
|
|
totalEquityLiabilities: adjustedEquityLiabilities,
|
|
operatingResult,
|
|
aretsResultat,
|
|
},
|
|
companyInfo: {
|
|
companyName: settings?.company_name || 'Okänt företag',
|
|
orgNumber: settings?.org_number || null,
|
|
addressLine1: settings?.address_line1 || null,
|
|
postalCode: settings?.postal_code || null,
|
|
city: settings?.city || null,
|
|
email: settings?.email || null,
|
|
},
|
|
warnings,
|
|
}
|
|
}
|