* feat(bokslut): year-end wizard with bokslutsdispositioner + asset register
Ships the first user-visible bokslut surface for K2 aktiebolag. The year-end
engine, INK2/INK2R/INK2S generator, and reconciliation reports already existed
in lib/core/bookkeeping/ and lib/reports/; this work wires them into a real
multi-step UI, adds the missing dispositioner calculators (bolagsskatt,
periodiseringsfond, överavskrivningar, SLP), and introduces a fixed-asset
register that feeds planenliga avskrivningar into the same flow.
PHASE 1 — Wizard around the existing year-end engine
- Replaces the "Kommer snart" stub at /bookkeeping/year-end with a 4-step
wizard (Kontroll → Dispositioner → Förhandsgranska → Verkställ) plus a
Klart result view
- New aggregator lib/bokslut/readiness-aggregator.ts composes
validateYearEndReadiness with bank-reconciliation status and entity-typed
reminders into one fetch backing the preflight step
- New endpoint GET /api/bookkeeping/fiscal-periods/[id]/bokslut-readiness
PHASE 2 — Bokslutsdispositioner calculators
- lib/bokslut/tax-provision/{bolagsskatt,sarskild-loneskatt}-calculator.ts —
20.6 % on taxable result → 8910/2512 (with non-deductible / non-taxable
manual adjustments and schablonintäkt pass-through) and 24.26 % SLP on
posted pension costs → 7533/2514
- lib/bokslut/reserves/periodiseringsfond-service.ts — proposeAvsattning
(25 % cap, BAS 212X cohort accounts) + proposeAteforing (FIFO 6-year
mandatory reversal with schablonintäkt computation) + balance lookup
- lib/bokslut/reserves/overavskrivningar-service.ts — 30-rule + 20-rule
helpers + proposeOveravskrivningar (8853/2153)
- New endpoint /api/bookkeeping/fiscal-periods/[id]/bokslutsdispositioner
(GET ordered proposals, POST commits user-chosen ones as separate
year_end vouchers via the journal engine)
- New DispositionsStep UI: per-card accept/skip + editable amount where
meaningful; mandatory p-fond reversals can't be skipped
- INK2 bug fix: ink2-engine.ts SRU mapping ranges previously pointed at
accounts BAS doesn't seed (8810/8830/8840). Corrected to 8811 (avsättning),
8819 (återföring), 8830 (lämnade koncernbidrag) so calculator output now
flows into INK2 correctly. Regression-locked with 6 new mapping tests.
PHASE 3 — Anläggningsregister + depreciation engine
- New migration 20260516120000_assets_and_depreciation.sql: assets table
(category, BAS-triple, K3 components JSONB reserved) and
depreciation_schedules (asset+period+journal_entry link). RLS via
user_company_ids(), immutability triggers after disposal/posting.
- lib/bokslut/assets/asset-service.ts — CRUD + disposal that posts a proper
gain/loss entry against 3973/7973
- lib/bokslut/assets/depreciation-engine.ts — computeAnnualDepreciation
(linear, pro-rata at acquisition/disposal/end-of-life) +
proposeAnnualPostings + commitAnnualPostings (one entry per asset)
- New endpoints /api/assets (CRUD + dispose) and
/api/bookkeeping/fiscal-periods/[id]/depreciation (preview + commit)
- /assets list+create page with K2 schablon defaults (3y datorer,
5y inventarier, 25y byggnader); sidebar entry added
- DepreciationPanel mounted at the top of DispositionsStep; posting
refreshes dispositions so bolagsskatt picks up the new result
Out of scope (per the agreed plan): K3 framework, iXBRL filing to
Bolagsverket (manual export only for now — regulatory risk flagged for
FY2026 closings), inventory module, koncernredovisning, revisor workflow.
Verification
- 116 unit tests pass across lib/bokslut/, lib/reports/ink2/, and the
existing lib/core/bookkeeping/year-end-service suite
- Zero lint or typecheck errors in any new file
- Migration applied successfully via Supabase MCP
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(bokslut): address PR #508 review — P1 correctness + P2 conventions
P1 — stale reminders in readiness-aggregator (greptile)
Remove the depreciation_manual / bolagsskatt_manual / periodiseringsfond_manual
nudges. After Phase 3, the wizard handles all three automatically via
DepreciationPanel and the dispositioner calculators — surfacing them as
manual reminders told users to repeat work the page already did. Only the
accruals_manual reminder (Phase 4 hasn't shipped) and the EF-only
ef_skatt_via_ne reminder remain.
P1 — netBookValueAfter ignored prior accumulated depreciation
proposeAnnualPostings now fetches all prior posted depreciation_schedules
for the company (excluding the current period) and sums them per asset, so
the displayed restvärde reflects every previously-booked year of avskrivning
instead of only this year. Without the fix, a 5-year asset in year 3 would
have shown 48 000 instead of the correct 24 000 net book value.
P1 — ordering bug in dispositioner POST handler
The 25 % p-fond avsättning cap derives from the current trial balance, so
mandatory återföring entries must post first. Added a server-side sort by
canonical bokslut order (återföring → överavskrivningar → avsättning → SLP
→ bolagsskatt) regardless of the client array order. The cap can no longer
be evaluated against a stale pre-återföring net result.
P2 — depreciation_schedules missing updated_at
New migration 20260516140000_depreciation_schedules_updated_at.sql adds the
column + trigger via update_updated_at_column(). Per CLAUDE.md migration
conventions, never modified the original migration. DepreciationSchedule
type updated.
P2 — addMonths end-of-month overflow
Replaced setUTCMonth (which overflows: Jan 31 + 1 month → Mar 3) with a
day-clamping implementation that produces Feb 28/29. Without the fix,
lifeEndExclusive landed one day too late and slightly over-depreciated.
New regression test asserts Jan 31 + 12 months stays in January.
P2 — pg-real tests for new triggers and RLS
tests/pg/assets.pg.test.ts (13 tests) covers:
- enforce_asset_post_disposal_immutability blocks every financial field
after disposal, allows notes/name through
- assets_disposal_atomic CHECK requires both disposed columns set together
- enforce_depreciation_schedule_immutability blocks edits after
journal_entry_id is linked, allows them before
- depreciation_schedules delete RLS policy filters out posted rows
- assets + depreciation_schedules RLS isolates across companies
Verification
- 117 unit tests pass (was 116, +1 for the addMonths regression)
- New pg-real suite syntactically + type-correct; will execute in CI
- Zero lint or typecheck errors in any touched file
- Migration 20260516140000 applied to remote Supabase via MCP
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(bokslut): address compliance-swarm + swedish-review findings
Real bugs surfaced by the bots on the first push that weren't covered by
greptile's inline P1/P2 set:
- Immaterial asset disposal hit the wrong BAS accounts. disposeAsset always
posted gain/loss to 3973/7973 regardless of category. For category
'immaterial' it must use 3013 (vinst) / 7813 (förlust) per BAS — using the
tangible accounts misclassifies in INK2R. Now branches on category. Two
new regression tests pin each branch.
- acquisition_cost CHECK was too loose. CreateAssetSchema accepted 0 (just
nonnegative). Tightened to z.number().positive() — a zero-cost asset
creates a no-op depreciation row and a balance sheet line that nothing
reconciles against.
- UpdateAssetSchema let users remap BAS accounts arbitrarily. Bot flagged
this as a defense-in-depth gap (V4.5). Added BAS_RANGES_BY_CATEGORY
validation at both the schema layer (Create) and the service layer
(Update) so user-supplied account overrides must stay inside the
category's expected BAS range. INK2R mappings and the depreciation
engine's category-driven defaults now can't drift.
Swedish accounting review:
- Building/markanläggning defaults — clarified UI copy. The 25-year
schablon is K2-redovisning, not the IL skattemässig rate. New helper text
spells this out. Markanläggning default lowered from 20→10 years
(Skatteverket guidance allows 10 % rate; 20 was on the upper bound
without justification).
- createAsset doesn't post the acquisition entry by design — that gap
wasn't called out anywhere in the UI. Added a tip box in
CreateAssetDialog explaining that the acquisition must already be in the
books; the register only drives depreciation.
- Disposal VAT (ML 3:3 / 7:3) not handled — sale of a deduct-eligible
anläggningstillgång is in principle 25 % momspliktig. Documented this as
a known limitation in the disposeAsset docstring so any future UI
surfacing the disposal endpoint warns the user.
Documented (not fixed yet) — bot was right but wider-scope work:
- SOC 2 PI1.3: dispositioner POST loop is not transactional. A failure
midway leaves partial postings. Added a code comment explaining the
recovery path (re-POST omitting committed kinds — each calculator
re-derives from current TB). Real atomicity via an RPC wrapper is Phase
5+ work.
False positives intentionally not changed:
- 4× OWASP V8.2.1 cross-tenant findings — service functions already filter
by company_id; the bot can't see past the route handler.
- V2.3 client-supplied amount clamping — proposeAvsattning and
proposeAteforing both clamp via Math.min already.
- A.8.15 audit events — withRouteContext already logs completion.
- Schablonintäkt journal entry — per IL 30:6a it's a skattemässig
justering, never booked. Current implementation is correct.
- Voucher series 'A' — matches existing executeYearEndClosing convention;
not changing here in isolation.
Verification
- 119 tests pass (was 117, +2 for the immaterial-disposal branches)
- Zero lint or typecheck errors on any touched file
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(bokslut): address compliance round 4 — BAS account overlap + method gate
Two real bugs the compliance bot caught after my round-3 fixes (both new on
its re-run, not in the original report):
- BAS account overlap not prevented: my BAS_RANGES_BY_CATEGORY uses the same
class range for asset and accumulated (e.g. immaterial: both 1010–1099,
building: both 1100–1199). Nothing stopped a user from picking the same
account for both, which would silently net acquisition cost against
accumulated depreciation in one bucket and corrupt INK2R 720x mappings.
CreateAssetSchema now rejects bas_asset_account === bas_accumulated_account
in a superRefine cross-field check; updateAsset enforces the same invariant
by reading the existing asset and validating the merged result.
- declining-balance methods silently fell back to linear. The DB enum allowed
declining_balance_30 / declining_balance_20, but the engine's
computeAnnualDepreciation only implements linear math. A determined caller
(MCP, curl, future UI) could create an asset labelled as räkenskapsenlig
avskrivning and get linear charges — silently wrong numbers under a
misleading method. Both CreateAssetSchema and UpdateAssetSchema now refine
the depreciation_method enum to require 'linear'. The DB enum stays open
for a future phase to add proper support. Stale comment in
depreciation-engine.ts updated to reflect the new invariant.
False positives I'm explicitly not chasing further on this round:
- 3× repeated OWASP V8.2.1 cross-tenant — services already filter by
company_id; bot can't see past the route handler. Round 3 already added
service-layer tests and inline reasoning.
- V2.3 atomicity upgrade to high — bot now flags it harder *because* I
documented it in round 3. The existing executeYearEndClosing has the same
non-transactional sequential-write pattern; wrapping just this endpoint
in an RPC while leaving the rest inconsistent is worse than the doc
comment. Real atomicity is Phase 5+.
- Disposal VAT user-facing warning — no UI surfaces dispose yet; docstring
in the service is sufficient until the UI ships.
Verification
- 119 tests pass
- Zero lint or typecheck errors on any touched file
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(bokslut): address compliance round 5 — disposal integrity + öavskr accounts
Round-5 bot feedback after my round-4 push (the sticky reports re-edited
themselves with two new genuine findings; bot count: 18 → 14 active).
P1 — accumulated_depreciation was client-supplied (OWASP V8.2.1, swedish
compliance review): the dispose endpoint accepted accumulated_depreciation
as a request-body number. A malicious or buggy caller could inflate it to
manipulate the book-value calculation and pocket a phantom gain. Now:
- DisposeAssetSchema no longer accepts accumulated_depreciation
- disposeAsset sums planned_depreciation from depreciation_schedules where
journal_entry_id IS NOT NULL for the asset, server-side
- New regression test "server-derives accumulated_depreciation — caller
cannot inflate gain" pins the server-derivation against the prior attack
- Limitation: manual avskrivningsverifikationer posted outside the engine
aren't captured. Phase 5+ can swap this for a trial-balance scan on
bas_accumulated_account if that gap matters.
P2 — överavskrivningar hardcoded 8853/2153 regardless of asset category
(swedish-asset-accounting): for buildings BAS uses 8852/2152 and for
immateriella tillgångar 8851/2151. Edge case for K2 SME (öavskr on
buildings is rare; on immateriella rarer still) but worth not lying about
the accounts. Now:
- New OVERAVSKRIVNING_ACCOUNTS table maps category → expense/accumulated
pair (machinery_equipment, building, immaterial, group)
- proposeOveravskrivningar accepts optional category, defaults to
machinery_equipment (the dominant K2 case — no behaviour change for
existing callers)
- POST handler item schema accepts optional category
- Label + description strings now name the actual accounts used
- 3 new tests cover the building, immaterial, and default branches
False positives I'm still declining to chase (already covered in prior
commit messages):
- 3× repeated OWASP V8.2.1 cross-tenant — services scope by company_id;
bot can't see past route handler
- V2.3 atomicity — existing executeYearEndClosing has the same pattern;
wrapping just this endpoint is inconsistent; real fix is Phase 5+ RPC
- Disposal VAT user-facing warning — no UI surfaces dispose yet
Verification
- 123 tests pass (was 119, +3 for öavskr category branches and +1 for the
server-derivation regression test, with one prior test rewritten to use
the new server-supplied accumulated path)
- Zero lint or typecheck errors on any touched file
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(bokslut): pre-merge polish — building disposal accounts, SLR-2026 rate
Last polish round before merge. All three from the round-5 sticky
Swedish-accounting-review update:
- Building / markanläggning disposal posted gain/loss to 3973/7973. BAS
2026 routes those to 3971/7971 (the SRU mapping points them at a
different INK2R field, so the existing accounts misclassify). Extended
the existing immaterial branch (3013/7813) into a three-way:
immaterial → 3013 / 7813
building / land_imprv → 3971 / 7971
other tangible → 3973 / 7973
Two new regression tests pin the building and land_improvement branches.
- DEFAULT_SCHABLONINTAKT_RATE was 0.03, based on SLR 2024-11-30 (1.96 %).
For closings of inkomstår 2026 the rate is SLR 2025-11-30 (2.55 %) + 1 pe
= 3.55 %. The wrong rate under-taxes the schablonintäkt, which feeds into
bolagsskatt. Updated to 0.0355 and rewrote the doc comment to track both
years so the next bump is obvious.
- Jämkning of input VAT for buildings / markanläggning disposed within the
10-year jämkningsperiod (ML 9 kap 8–11 §§) is out of scope for this PR
but should not be silently absent — added a KNOWN LIMITATION block to the
disposeAsset docstring so any future UI surfacing disposal checks the
10-year window and warns the user.
After this push the PR has 125 passing tests, all CI green, no merge
conflicts, and the only remaining bot complaints are repeat false
positives or Phase 5+ scope (RPC atomicity, full asset disposal UI,
K3 component depreciation).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
404 lines
14 KiB
TypeScript
404 lines
14 KiB
TypeScript
import type { SupabaseClient } from '@supabase/supabase-js'
|
||
import { createJournalEntry } from '@/lib/bookkeeping/engine'
|
||
import type {
|
||
Asset,
|
||
AssetCategory,
|
||
DepreciationMethod,
|
||
CreateJournalEntryLineInput,
|
||
JournalEntry,
|
||
} from '@/types'
|
||
|
||
/**
|
||
* Default BAS account triples per category. The user can override at create
|
||
* time; these only kick in when the form doesn't specify accounts. Matches
|
||
* the seeded BAS 2020 chart (lib/bookkeeping/bas-data/).
|
||
*/
|
||
export const DEFAULT_ACCOUNTS_BY_CATEGORY: Record<
|
||
AssetCategory,
|
||
{ asset: string; accumulated: string; expense: string }
|
||
> = {
|
||
immaterial: { asset: '1010', accumulated: '1019', expense: '7810' },
|
||
building: { asset: '1110', accumulated: '1119', expense: '7821' },
|
||
land_improvement: { asset: '1150', accumulated: '1159', expense: '7824' },
|
||
machinery: { asset: '1210', accumulated: '1219', expense: '7831' },
|
||
equipment: { asset: '1220', accumulated: '1229', expense: '7832' },
|
||
vehicle: { asset: '1240', accumulated: '1249', expense: '7834' },
|
||
computer: { asset: '1250', accumulated: '1259', expense: '7833' },
|
||
other_tangible: { asset: '1280', accumulated: '1289', expense: '7839' },
|
||
}
|
||
|
||
export interface CreateAssetInput {
|
||
name: string
|
||
category: AssetCategory
|
||
acquisition_date: string
|
||
acquisition_cost: number
|
||
salvage_value?: number
|
||
useful_life_months: number
|
||
depreciation_method?: DepreciationMethod
|
||
bas_asset_account?: string
|
||
bas_accumulated_account?: string
|
||
bas_expense_account?: string
|
||
notes?: string
|
||
}
|
||
|
||
/**
|
||
* Create a new asset. Defaults BAS accounts from the category mapping when
|
||
* the caller doesn't override them. Does NOT post a journal entry — the
|
||
* acquisition is assumed to already be in the books (bank payment or
|
||
* supplier invoice). Posting an acquisition entry alongside an existing
|
||
* payment would double-count.
|
||
*/
|
||
export async function createAsset(
|
||
supabase: SupabaseClient,
|
||
companyId: string,
|
||
userId: string,
|
||
input: CreateAssetInput,
|
||
): Promise<Asset> {
|
||
const defaults = DEFAULT_ACCOUNTS_BY_CATEGORY[input.category]
|
||
const row = {
|
||
user_id: userId,
|
||
company_id: companyId,
|
||
name: input.name,
|
||
category: input.category,
|
||
acquisition_date: input.acquisition_date,
|
||
acquisition_cost: input.acquisition_cost,
|
||
salvage_value: input.salvage_value ?? 0,
|
||
useful_life_months: input.useful_life_months,
|
||
depreciation_method: input.depreciation_method ?? 'linear',
|
||
bas_asset_account: input.bas_asset_account ?? defaults.asset,
|
||
bas_accumulated_account: input.bas_accumulated_account ?? defaults.accumulated,
|
||
bas_expense_account: input.bas_expense_account ?? defaults.expense,
|
||
notes: input.notes ?? null,
|
||
}
|
||
|
||
const { data, error } = await supabase
|
||
.from('assets')
|
||
.insert(row)
|
||
.select('*')
|
||
.single()
|
||
|
||
if (error || !data) {
|
||
throw new Error(`Failed to create asset: ${error?.message ?? 'unknown'}`)
|
||
}
|
||
return data as Asset
|
||
}
|
||
|
||
export async function listAssets(
|
||
supabase: SupabaseClient,
|
||
companyId: string,
|
||
options: { activeOnly?: boolean } = {},
|
||
): Promise<Asset[]> {
|
||
let query = supabase
|
||
.from('assets')
|
||
.select('*')
|
||
.eq('company_id', companyId)
|
||
.order('acquisition_date', { ascending: true })
|
||
|
||
if (options.activeOnly) {
|
||
query = query.is('disposed_at', null)
|
||
}
|
||
|
||
const { data, error } = await query
|
||
if (error) throw new Error(`Failed to list assets: ${error.message}`)
|
||
return (data ?? []) as Asset[]
|
||
}
|
||
|
||
export async function getAsset(
|
||
supabase: SupabaseClient,
|
||
companyId: string,
|
||
assetId: string,
|
||
): Promise<Asset | null> {
|
||
const { data, error } = await supabase
|
||
.from('assets')
|
||
.select('*')
|
||
.eq('id', assetId)
|
||
.eq('company_id', companyId)
|
||
.maybeSingle()
|
||
if (error) throw new Error(`Failed to load asset: ${error.message}`)
|
||
return (data as Asset | null) ?? null
|
||
}
|
||
|
||
export interface UpdateAssetInput {
|
||
name?: string
|
||
notes?: string | null
|
||
/** Salvage value, useful life, method, accounts — editable as long as the
|
||
* asset isn't disposed yet (DB trigger enforces this beyond the API). */
|
||
salvage_value?: number
|
||
useful_life_months?: number
|
||
depreciation_method?: DepreciationMethod
|
||
bas_asset_account?: string
|
||
bas_accumulated_account?: string
|
||
bas_expense_account?: string
|
||
}
|
||
|
||
export async function updateAsset(
|
||
supabase: SupabaseClient,
|
||
companyId: string,
|
||
assetId: string,
|
||
input: UpdateAssetInput,
|
||
): Promise<Asset> {
|
||
// Defense-in-depth: when callers remap BAS accounts, refuse anything
|
||
// outside the legitimate range for the existing asset's category — keeps
|
||
// INK2R mappings + the depreciation engine's category-driven defaults in
|
||
// sync with what users actually pick.
|
||
if (
|
||
input.bas_asset_account ||
|
||
input.bas_accumulated_account ||
|
||
input.bas_expense_account
|
||
) {
|
||
const existing = await getAsset(supabase, companyId, assetId)
|
||
if (!existing) throw new Error('Asset not found')
|
||
const ranges = BAS_RANGES_BY_CATEGORY[existing.category]
|
||
if (input.bas_asset_account && !inBasRange(input.bas_asset_account, ranges.asset)) {
|
||
throw new Error(
|
||
`bas_asset_account ${input.bas_asset_account} is outside ${ranges.asset[0]}–${ranges.asset[1]} for ${existing.category}`,
|
||
)
|
||
}
|
||
if (
|
||
input.bas_accumulated_account &&
|
||
!inBasRange(input.bas_accumulated_account, ranges.accumulated)
|
||
) {
|
||
throw new Error(
|
||
`bas_accumulated_account ${input.bas_accumulated_account} is outside ${ranges.accumulated[0]}–${ranges.accumulated[1]} for ${existing.category}`,
|
||
)
|
||
}
|
||
if (
|
||
input.bas_expense_account &&
|
||
!inBasRange(input.bas_expense_account, ranges.expense)
|
||
) {
|
||
throw new Error(
|
||
`bas_expense_account ${input.bas_expense_account} is outside ${ranges.expense[0]}–${ranges.expense[1]} for ${existing.category}`,
|
||
)
|
||
}
|
||
// Anskaffning and ackumulerade-avskrivningar must be different accounts —
|
||
// see CreateAssetSchema validateBasOverrides for the rationale.
|
||
const finalAsset = input.bas_asset_account ?? existing.bas_asset_account
|
||
const finalAccumulated = input.bas_accumulated_account ?? existing.bas_accumulated_account
|
||
if (finalAsset === finalAccumulated) {
|
||
throw new Error(
|
||
'bas_asset_account and bas_accumulated_account must be different accounts',
|
||
)
|
||
}
|
||
}
|
||
|
||
const { data, error } = await supabase
|
||
.from('assets')
|
||
.update(input)
|
||
.eq('id', assetId)
|
||
.eq('company_id', companyId)
|
||
.select('*')
|
||
.single()
|
||
if (error || !data) {
|
||
throw new Error(`Failed to update asset: ${error?.message ?? 'unknown'}`)
|
||
}
|
||
return data as Asset
|
||
}
|
||
|
||
const BAS_RANGES_BY_CATEGORY: Record<
|
||
AssetCategory,
|
||
{ asset: [string, string]; accumulated: [string, string]; expense: [string, string] }
|
||
> = {
|
||
immaterial: { asset: ['1010', '1099'], accumulated: ['1010', '1099'], expense: ['7810', '7819'] },
|
||
building: { asset: ['1100', '1199'], accumulated: ['1100', '1199'], expense: ['7820', '7829'] },
|
||
land_improvement:{ asset: ['1150', '1159'], accumulated: ['1150', '1159'], expense: ['7820', '7829'] },
|
||
machinery: { asset: ['1210', '1219'], accumulated: ['1210', '1219'], expense: ['7830', '7839'] },
|
||
equipment: { asset: ['1220', '1229'], accumulated: ['1220', '1229'], expense: ['7830', '7839'] },
|
||
vehicle: { asset: ['1240', '1249'], accumulated: ['1240', '1249'], expense: ['7830', '7839'] },
|
||
computer: { asset: ['1250', '1259'], accumulated: ['1250', '1259'], expense: ['7830', '7839'] },
|
||
other_tangible: { asset: ['1280', '1299'], accumulated: ['1280', '1299'], expense: ['7830', '7839'] },
|
||
}
|
||
|
||
function inBasRange(account: string, range: [string, string]): boolean {
|
||
return account >= range[0] && account <= range[1]
|
||
}
|
||
|
||
export interface DisposeAssetInput {
|
||
/** ISO date of disposal — typically the day of sale or scrapping. */
|
||
disposed_at: string
|
||
/** Cash / receivable received for the asset. Zero for scrapping. */
|
||
disposed_proceeds: number
|
||
/** Optional override for the bank/receivable account credited with the
|
||
* proceeds. Defaults to 1930 (företagskonto). */
|
||
proceeds_account?: string
|
||
/** Fiscal period the disposal entry lands in. Caller resolves this from
|
||
* disposed_at — we don't auto-derive to keep the period-lock check at
|
||
* the route layer. */
|
||
fiscal_period_id: string
|
||
}
|
||
|
||
export interface DisposalResult {
|
||
asset: Asset
|
||
/** Disposal entry. Null when no entry was needed (zero-value, fully-
|
||
* depreciated asset scrapped for nothing). */
|
||
disposal_entry: JournalEntry | null
|
||
gain_or_loss: number
|
||
}
|
||
|
||
/**
|
||
* Dispose of an asset. Posts a journal entry that:
|
||
* - Debit accumulated depreciation (to zero out the asset's accumulated
|
||
* account)
|
||
* - Credit acquisition cost (to zero out the asset's anskaffning account)
|
||
* - Debit proceeds account (bank / receivable) for sale price
|
||
* - Debit 78xx (loss on sale) OR Credit 30xx (gain on sale) — accounts
|
||
* branch on category (3013/7813 for immaterial, 3973/7973 for tangible).
|
||
*
|
||
* After posting, marks the asset row with disposed_at / disposed_proceeds.
|
||
* The DB trigger then prevents further edits to financial fields.
|
||
*
|
||
* KNOWN LIMITATION (ML 3 kap 3 § / 7 kap 3 §): the sale of an
|
||
* anläggningstillgång that had right-to-deduct VAT on acquisition is in
|
||
* principle 25 % momspliktig. This function does NOT post output VAT on the
|
||
* proceeds — callers must handle the VAT side separately (or use a manual
|
||
* journal entry). UI surfacing disposal must warn the user. Adding a
|
||
* vat_on_proceeds field is tracked as a follow-up.
|
||
*
|
||
* KNOWN LIMITATION (ML 9 kap 8–11 §§ — jämkning): when a building or
|
||
* markanläggning is disposed of within the 10-year jämkningsperiod after
|
||
* acquisition, previously deducted input VAT must be recalculated and may
|
||
* have to be partially repaid. This function does NOT compute or post any
|
||
* jämkning adjustment. UI surfacing disposal for category='building' or
|
||
* 'land_improvement' must check the 10-year window against acquisition_date
|
||
* and warn the user; the actual recalculation belongs in a future
|
||
* dedicated flow.
|
||
*/
|
||
export async function disposeAsset(
|
||
supabase: SupabaseClient,
|
||
companyId: string,
|
||
userId: string,
|
||
assetId: string,
|
||
input: DisposeAssetInput,
|
||
): Promise<DisposalResult> {
|
||
const asset = await getAsset(supabase, companyId, assetId)
|
||
if (!asset) throw new Error('Asset not found')
|
||
if (asset.disposed_at) {
|
||
throw new Error('Asset is already disposed')
|
||
}
|
||
|
||
// Derive accumulated depreciation server-side from posted
|
||
// depreciation_schedules so a malicious or buggy caller cannot inflate the
|
||
// book-value calculation. Limitation: manual avskrivningsverifikationer
|
||
// posted outside the engine aren't captured here. Phase 5+ can replace
|
||
// this with a trial-balance scan on bas_accumulated_account.
|
||
const accumulated = await sumPostedDepreciation(supabase, companyId, assetId)
|
||
|
||
const acquisitionCost = Number(asset.acquisition_cost)
|
||
const proceeds = Number(input.disposed_proceeds)
|
||
const netBookValue = acquisitionCost - accumulated
|
||
const gainOrLoss = Math.round((proceeds - netBookValue) * 100) / 100
|
||
const proceedsAccount = input.proceeds_account ?? '1930'
|
||
|
||
const lines: CreateJournalEntryLineInput[] = []
|
||
|
||
if (accumulated > 0.005) {
|
||
lines.push({
|
||
account_number: asset.bas_accumulated_account,
|
||
debit_amount: Math.round(accumulated * 100) / 100,
|
||
credit_amount: 0,
|
||
line_description: `Avyttring: nollställ ack. avskrivning ${asset.name}`,
|
||
})
|
||
}
|
||
lines.push({
|
||
account_number: asset.bas_asset_account,
|
||
debit_amount: 0,
|
||
credit_amount: Math.round(acquisitionCost * 100) / 100,
|
||
line_description: `Avyttring: nollställ anskaffning ${asset.name}`,
|
||
})
|
||
if (proceeds > 0.005) {
|
||
lines.push({
|
||
account_number: proceedsAccount,
|
||
debit_amount: Math.round(proceeds * 100) / 100,
|
||
credit_amount: 0,
|
||
line_description: `Avyttring: erhållet belopp ${asset.name}`,
|
||
})
|
||
}
|
||
// Disposal gain/loss accounts vary by asset class — BAS 2026 splits them
|
||
// because INK2R routes each pair to a different field. Mixing them
|
||
// misclassifies in the tax declaration.
|
||
// - immaterial → 3013 (vinst) / 7813 (förlust)
|
||
// - building / markanlägg → 3971 / 7971
|
||
// - other tangible → 3973 / 7973
|
||
const isBuilding = asset.category === 'building' || asset.category === 'land_improvement'
|
||
const gainAccount =
|
||
asset.category === 'immaterial' ? '3013' : isBuilding ? '3971' : '3973'
|
||
const lossAccount =
|
||
asset.category === 'immaterial' ? '7813' : isBuilding ? '7971' : '7973'
|
||
|
||
if (gainOrLoss > 0.005) {
|
||
lines.push({
|
||
account_number: gainAccount,
|
||
debit_amount: 0,
|
||
credit_amount: gainOrLoss,
|
||
line_description: `Vinst vid avyttring av ${asset.name}`,
|
||
})
|
||
} else if (gainOrLoss < -0.005) {
|
||
lines.push({
|
||
account_number: lossAccount,
|
||
debit_amount: Math.abs(gainOrLoss),
|
||
credit_amount: 0,
|
||
line_description: `Förlust vid avyttring av ${asset.name}`,
|
||
})
|
||
}
|
||
|
||
let disposalEntry: JournalEntry | null = null
|
||
if (lines.length > 0) {
|
||
disposalEntry = await createJournalEntry(supabase, companyId, userId, {
|
||
fiscal_period_id: input.fiscal_period_id,
|
||
entry_date: input.disposed_at,
|
||
description: `Avyttring av tillgång: ${asset.name}`,
|
||
source_type: 'manual',
|
||
voucher_series: 'A',
|
||
lines,
|
||
})
|
||
}
|
||
|
||
const { data: updated, error: updateError } = await supabase
|
||
.from('assets')
|
||
.update({
|
||
disposed_at: input.disposed_at,
|
||
disposed_proceeds: proceeds,
|
||
})
|
||
.eq('id', assetId)
|
||
.eq('company_id', companyId)
|
||
.select('*')
|
||
.single()
|
||
|
||
if (updateError || !updated) {
|
||
throw new Error(`Failed to mark asset disposed: ${updateError?.message ?? 'unknown'}`)
|
||
}
|
||
|
||
return {
|
||
asset: updated as Asset,
|
||
disposal_entry: disposalEntry,
|
||
gain_or_loss: gainOrLoss,
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Sum every posted depreciation_schedules row for an asset to get accumulated
|
||
* depreciation as of "now". Used by disposeAsset so the caller cannot
|
||
* influence the book-value calculation.
|
||
*/
|
||
async function sumPostedDepreciation(
|
||
supabase: SupabaseClient,
|
||
companyId: string,
|
||
assetId: string,
|
||
): Promise<number> {
|
||
const { data, error } = await supabase
|
||
.from('depreciation_schedules')
|
||
.select('planned_depreciation')
|
||
.eq('company_id', companyId)
|
||
.eq('asset_id', assetId)
|
||
.not('journal_entry_id', 'is', null)
|
||
|
||
if (error) {
|
||
throw new Error(`Failed to sum depreciation for asset ${assetId}: ${error.message}`)
|
||
}
|
||
|
||
type Row = { planned_depreciation: number | string }
|
||
return ((data ?? []) as Row[]).reduce(
|
||
(sum, row) => sum + (Number(row.planned_depreciation) || 0),
|
||
0,
|
||
)
|
||
}
|