Bug/invalid imports (#1146)
* feat: add Accounted MCP namespace * fix(bookkeeping): stop flagging verifikat whose underlag lives on a referenced supplier invoice The missing-underlag surfaces only accepted a document directly linked to the entry, so payment verifikat for supplier invoices (doc on the registration entry per design) and entries whose doc was pinned to the bank transaction before matching were falsely flagged; opening the entry showed the referenced doc and cleared the warning client-side, and it came back on reload. - verifikat_without_documents + transactions_without_documents now treat an entry as covered when a supplier invoice referencing it (registration or payment FK, or a supplier_invoice_payments row) carries a document anchored to a journal entry (BFL 5 kap 7 paragraf hänvisning till underlag; anchoring required because the WORM deletion guards key on document_attachments.journal_entry_id) - match-supplier-invoice routes (dashboard + v1) propagate the transaction's pinned document onto the payment verifikat, mirroring the categorize route; migration backfills rows already written (open unlocked periods, company-guarded, never steals a linked doc) - /api/documents/counts, the transactions-page badges, the bulk "Inget underlag krävs" count and the push-notification scheduler share the same reference-aware predicate, so every surface agrees with the RPC - counts route validates journal_entry_ids as UUIDs (they are interpolated into a PostgREST or-filter) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(transactions): align table columns flush with page edges Collapse the checkbox gutter column to zero width and hang the hover-revealed checkbox/expand chevron in the page margins, drop the outer padding so DATUM sits flush left and STATUS flush right, and tuck the overflow-menu dots under the middle of the STATUS header. Applied to both the inbox and history tables so they stay identical. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(arsredovisning): tie anlaggningstillgangar note to booked depreciation The ARL 5:8 roll-forward note recomputed depreciation from its own day-based linear formula (365.25/12 month length, non-inclusive day count, linear only), drifting ~20 kr per year per asset from the ledger-driven resultat- and balansrakning and misstating non-linear methods entirely. Note figures now come from posted depreciation_schedules rows (the same source disposeAsset reverses), falling back to the engine's computeAnnualDepreciation when nothing is posted; pre-onboarding opening balances iterate prior years through the engine. Adds a note-vs-trial-balance tie-out warning (accounts 1000-1299, over 1 kr) surfaced before download. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * refactor(stripe): move connect and sync surface from settings to import page Stripe's transaction feed is a continuous import source in the same category as the PSD2 bank connection, so its connect/sync surface now lives on the import page as a source card (mode=stripe), gated "kommer snart" on hosted like before; self-hosted keeps the full panel. - Import page: Stripe card after Koppla bank, renders the existing StripeSettingsPanel via the settings-panel registry - OAuth callback and panel cleanup return to /import?mode=stripe - Settings > Betalningar retired: nav item removed, route redirects, PaymentsSettingsContent deleted, legacy ?tab=payments mapped - New import.stripe_* strings in sv+en; dead settings_nav.payments removed Crons and sync logic unchanged; payment-link settings stay in the invoicing section. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(underlag): paginate missing-underlag cron and harden doc-surface queries Resolve PR review findings on bug/invalid-imports: - notification-scheduler: fetchAllRows on all 5 global reads; past 1000 rows the capped reads produced false "saknade underlag" notifications - bulk-missing: LOOKUP_CHUNK 300->150 so the twice-embedded .or() id list stays under the PostgREST URL limit - bulk-missing + transactions page: UUID-guard the .or()-interpolated id lists, matching documents/counts - match-supplier-invoice (dashboard + v1): log documentId/journalEntryId on the non-fatal doc-link warning - well-known/oauth-protected-resource: document the tool_namespace allow-list - messages/en: reword stripe_description - DECISIONS.md: record the asset ibAck tie-out and Tailwind !important calls Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(tic): convert registrationDate from Unix seconds to millisecond epoch in lookup and profile tests --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
51ca574ca4
commit
53e343ee92
@@ -1,12 +1,31 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
buildAnlaggningstillgangarNote,
|
||||
computeRollforwardTotals,
|
||||
_buildRollforwardForTests,
|
||||
type AnlaggningAsset,
|
||||
} from '../anlaggningstillgangar-note'
|
||||
|
||||
const PERIOD_START = '2025-01-01'
|
||||
const PERIOD_END = '2025-12-31'
|
||||
|
||||
// Depreciation figures are resolved upstream (asset-note-figures.ts) from
|
||||
// posted schedules; this suite supplies them and pins the aggregation and
|
||||
// formatting only. The exact-amount assertions replace the old approximate
|
||||
// bands: the builder must pass figures through verbatim.
|
||||
function makeAsset(overrides: Partial<AnlaggningAsset> = {}): AnlaggningAsset {
|
||||
return {
|
||||
category: 'equipment',
|
||||
acquisition_date: '2024-01-01',
|
||||
acquisition_cost: 60_000,
|
||||
salvage_value: 0,
|
||||
useful_life_months: 60,
|
||||
disposed_at: null,
|
||||
figures: { ibAck: 0, aretsAvskrivning: 0, avgaendeAck: 0 },
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('buildAnlaggningstillgangarNote: roll-forward', () => {
|
||||
it('returns null when no assets fall in the period', () => {
|
||||
expect(
|
||||
@@ -22,14 +41,12 @@ describe('buildAnlaggningstillgangarNote: roll-forward', () => {
|
||||
it('skips assets disposed before the period', () => {
|
||||
const rows = _buildRollforwardForTests(
|
||||
[
|
||||
{
|
||||
category: 'equipment',
|
||||
makeAsset({
|
||||
acquisition_date: '2020-01-01',
|
||||
acquisition_cost: 100_000,
|
||||
salvage_value: 0,
|
||||
useful_life_months: 60,
|
||||
disposed_at: '2024-12-31',
|
||||
},
|
||||
figures: { ibAck: 100_000, aretsAvskrivning: 0, avgaendeAck: 0 },
|
||||
}),
|
||||
],
|
||||
PERIOD_START,
|
||||
PERIOD_END,
|
||||
@@ -37,17 +54,12 @@ describe('buildAnlaggningstillgangarNote: roll-forward', () => {
|
||||
expect(rows).toEqual([])
|
||||
})
|
||||
|
||||
it('records IB anskaffningsvärde for assets acquired before the period', () => {
|
||||
it('records IB anskaffningsvärde and booked depreciation for assets acquired before the period', () => {
|
||||
const rows = _buildRollforwardForTests(
|
||||
[
|
||||
{
|
||||
category: 'equipment',
|
||||
acquisition_date: '2024-01-01',
|
||||
acquisition_cost: 60_000,
|
||||
salvage_value: 0,
|
||||
useful_life_months: 60,
|
||||
disposed_at: null,
|
||||
},
|
||||
makeAsset({
|
||||
figures: { ibAck: 12_000, aretsAvskrivning: 12_000, avgaendeAck: 0 },
|
||||
}),
|
||||
],
|
||||
PERIOD_START,
|
||||
PERIOD_END,
|
||||
@@ -57,25 +69,19 @@ describe('buildAnlaggningstillgangarNote: roll-forward', () => {
|
||||
expect(r.ibAnskaffning).toBe(60_000)
|
||||
expect(r.tillkommande).toBe(0)
|
||||
expect(r.ubAnskaffning).toBe(60_000)
|
||||
// 1 year of depreciation on the books at IB (Jan 1 2024 → Dec 31 2024)
|
||||
expect(r.ibAck).toBeGreaterThan(11_500)
|
||||
expect(r.ibAck).toBeLessThan(12_500)
|
||||
// Year's depreciation ≈ 12,000 (60,000 / 5)
|
||||
expect(r.aretsAvskrivning).toBeGreaterThan(11_500)
|
||||
expect(r.aretsAvskrivning).toBeLessThan(12_500)
|
||||
expect(r.ibAck).toBe(12_000)
|
||||
expect(r.aretsAvskrivning).toBe(12_000)
|
||||
expect(r.ubAck).toBe(24_000)
|
||||
expect(r.ubRedovisat).toBe(36_000)
|
||||
})
|
||||
|
||||
it('records tillkommande for assets acquired during the period', () => {
|
||||
it('records tillkommande for assets acquired during the period without any IB ack', () => {
|
||||
const rows = _buildRollforwardForTests(
|
||||
[
|
||||
{
|
||||
category: 'equipment',
|
||||
makeAsset({
|
||||
acquisition_date: '2025-07-01',
|
||||
acquisition_cost: 60_000,
|
||||
salvage_value: 0,
|
||||
useful_life_months: 60,
|
||||
disposed_at: null,
|
||||
},
|
||||
figures: { ibAck: 999, aretsAvskrivning: 6_049, avgaendeAck: 0 },
|
||||
}),
|
||||
],
|
||||
PERIOD_START,
|
||||
PERIOD_END,
|
||||
@@ -84,23 +90,20 @@ describe('buildAnlaggningstillgangarNote: roll-forward', () => {
|
||||
const r = rows[0]
|
||||
expect(r.ibAnskaffning).toBe(0)
|
||||
expect(r.tillkommande).toBe(60_000)
|
||||
// ibAck only accrues for assets acquired before the period, even if the
|
||||
// upstream figure carried a nonzero value.
|
||||
expect(r.ibAck).toBe(0)
|
||||
// ~6 months depreciation ≈ 6,000
|
||||
expect(r.aretsAvskrivning).toBeGreaterThan(5_500)
|
||||
expect(r.aretsAvskrivning).toBeLessThan(6_500)
|
||||
expect(r.aretsAvskrivning).toBe(6_049)
|
||||
})
|
||||
|
||||
it('records avgående for assets disposed during the period', () => {
|
||||
it('records avgående and the reversed accumulated depreciation for in-period disposals', () => {
|
||||
const rows = _buildRollforwardForTests(
|
||||
[
|
||||
{
|
||||
category: 'equipment',
|
||||
makeAsset({
|
||||
acquisition_date: '2023-01-01',
|
||||
acquisition_cost: 60_000,
|
||||
salvage_value: 0,
|
||||
useful_life_months: 60,
|
||||
disposed_at: '2025-06-30',
|
||||
},
|
||||
figures: { ibAck: 24_000, aretsAvskrivning: 5_951, avgaendeAck: 29_951 },
|
||||
}),
|
||||
],
|
||||
PERIOD_START,
|
||||
PERIOD_END,
|
||||
@@ -110,31 +113,22 @@ describe('buildAnlaggningstillgangarNote: roll-forward', () => {
|
||||
expect(r.ibAnskaffning).toBe(60_000)
|
||||
expect(r.avgaende).toBe(60_000)
|
||||
expect(r.ubAnskaffning).toBe(0)
|
||||
// Disposed asset: at IB it had 2 years of depreciation ≈ 24,000;
|
||||
// at disposal it had ~2.5 years ≈ 30,000.
|
||||
expect(r.avgaendeAck).toBeGreaterThan(29_000)
|
||||
expect(r.avgaendeAck).toBeLessThan(31_000)
|
||||
expect(r.avgaendeAck).toBe(29_951)
|
||||
expect(r.ubAck).toBe(0)
|
||||
expect(r.ubRedovisat).toBe(0)
|
||||
})
|
||||
|
||||
it('groups multiple assets in the same category', () => {
|
||||
const rows = _buildRollforwardForTests(
|
||||
[
|
||||
{
|
||||
category: 'equipment',
|
||||
acquisition_date: '2024-01-01',
|
||||
acquisition_cost: 60_000,
|
||||
salvage_value: 0,
|
||||
useful_life_months: 60,
|
||||
disposed_at: null,
|
||||
},
|
||||
{
|
||||
category: 'equipment',
|
||||
makeAsset({
|
||||
figures: { ibAck: 12_000, aretsAvskrivning: 12_000, avgaendeAck: 0 },
|
||||
}),
|
||||
makeAsset({
|
||||
acquisition_date: '2025-01-01',
|
||||
acquisition_cost: 40_000,
|
||||
salvage_value: 0,
|
||||
useful_life_months: 60,
|
||||
disposed_at: null,
|
||||
},
|
||||
figures: { ibAck: 0, aretsAvskrivning: 8_000, avgaendeAck: 0 },
|
||||
}),
|
||||
],
|
||||
PERIOD_START,
|
||||
PERIOD_END,
|
||||
@@ -144,27 +138,22 @@ describe('buildAnlaggningstillgangarNote: roll-forward', () => {
|
||||
expect(r.ibAnskaffning).toBe(60_000)
|
||||
expect(r.tillkommande).toBe(40_000)
|
||||
expect(r.ubAnskaffning).toBe(100_000)
|
||||
expect(r.aretsAvskrivning).toBe(20_000)
|
||||
expect(r.ubAck).toBe(32_000)
|
||||
})
|
||||
|
||||
it('separates categories', () => {
|
||||
const rows = _buildRollforwardForTests(
|
||||
[
|
||||
{
|
||||
category: 'equipment',
|
||||
acquisition_date: '2024-01-01',
|
||||
acquisition_cost: 60_000,
|
||||
salvage_value: 0,
|
||||
useful_life_months: 60,
|
||||
disposed_at: null,
|
||||
},
|
||||
{
|
||||
makeAsset({
|
||||
figures: { ibAck: 12_000, aretsAvskrivning: 12_000, avgaendeAck: 0 },
|
||||
}),
|
||||
makeAsset({
|
||||
category: 'computer',
|
||||
acquisition_date: '2024-01-01',
|
||||
acquisition_cost: 20_000,
|
||||
salvage_value: 0,
|
||||
useful_life_months: 36,
|
||||
disposed_at: null,
|
||||
},
|
||||
figures: { ibAck: 6_667, aretsAvskrivning: 6_667, avgaendeAck: 0 },
|
||||
}),
|
||||
],
|
||||
PERIOD_START,
|
||||
PERIOD_END,
|
||||
@@ -178,14 +167,9 @@ describe('buildAnlaggningstillgangarNote: roll-forward', () => {
|
||||
const note = buildAnlaggningstillgangarNote({
|
||||
noteNumber: 5,
|
||||
assets: [
|
||||
{
|
||||
category: 'equipment',
|
||||
acquisition_date: '2024-01-01',
|
||||
acquisition_cost: 60_000,
|
||||
salvage_value: 0,
|
||||
useful_life_months: 60,
|
||||
disposed_at: null,
|
||||
},
|
||||
makeAsset({
|
||||
figures: { ibAck: 12_000, aretsAvskrivning: 12_000, avgaendeAck: 0 },
|
||||
}),
|
||||
],
|
||||
periodStart: PERIOD_START,
|
||||
periodEnd: PERIOD_END,
|
||||
@@ -197,40 +181,37 @@ describe('buildAnlaggningstillgangarNote: roll-forward', () => {
|
||||
expect(note!.body).toContain('Ingående anskaffningsvärde')
|
||||
expect(note!.body).toContain('Utgående anskaffningsvärde')
|
||||
expect(note!.body).toContain('Ingående ackumulerade avskrivningar')
|
||||
expect(note!.body).toContain('Utgående redovisat värde')
|
||||
// sv-SE formatting uses a non-breaking thousands separator: build the
|
||||
// expected strings with the same formatter instead of literal spaces.
|
||||
const sv = (n: number) => n.toLocaleString('sv-SE')
|
||||
expect(note!.body).toContain(`Årets avskrivningar: -${sv(12_000)} kr`)
|
||||
expect(note!.body).toContain(`Utgående redovisat värde: ${sv(36_000)} kr`)
|
||||
})
|
||||
|
||||
it('respects salvage_value when computing depreciation', () => {
|
||||
it('passes upstream figures through verbatim without recomputing', () => {
|
||||
// Deliberately "impossible" figures for the asset's schedule: the
|
||||
// builder must not derive anything from cost/life/dates on its own.
|
||||
const rows = _buildRollforwardForTests(
|
||||
[
|
||||
{
|
||||
category: 'equipment',
|
||||
acquisition_date: '2024-01-01',
|
||||
acquisition_cost: 60_000,
|
||||
salvage_value: 10_000,
|
||||
useful_life_months: 60,
|
||||
disposed_at: null,
|
||||
},
|
||||
makeAsset({
|
||||
figures: { ibAck: 1_234.56, aretsAvskrivning: 7_890.12, avgaendeAck: 0 },
|
||||
}),
|
||||
],
|
||||
PERIOD_START,
|
||||
PERIOD_END,
|
||||
)
|
||||
// Depreciable base 50,000 over 5 years → 10,000/yr (not 12,000)
|
||||
expect(rows[0].aretsAvskrivning).toBeGreaterThan(9_500)
|
||||
expect(rows[0].aretsAvskrivning).toBeLessThan(10_500)
|
||||
expect(rows[0].ibAck).toBe(1_234.56)
|
||||
expect(rows[0].aretsAvskrivning).toBe(7_890.12)
|
||||
expect(rows[0].ubAck).toBe(9_124.68)
|
||||
})
|
||||
|
||||
it('caps accumulated depreciation at depreciable base after useful life', () => {
|
||||
it('caps at the depreciable base only via upstream figures (fully depreciated asset)', () => {
|
||||
const rows = _buildRollforwardForTests(
|
||||
[
|
||||
{
|
||||
category: 'equipment',
|
||||
makeAsset({
|
||||
acquisition_date: '2010-01-01',
|
||||
acquisition_cost: 60_000,
|
||||
salvage_value: 0,
|
||||
useful_life_months: 60,
|
||||
disposed_at: null,
|
||||
},
|
||||
figures: { ibAck: 60_000, aretsAvskrivning: 0, avgaendeAck: 0 },
|
||||
}),
|
||||
],
|
||||
PERIOD_START,
|
||||
PERIOD_END,
|
||||
@@ -241,3 +222,25 @@ describe('buildAnlaggningstillgangarNote: roll-forward', () => {
|
||||
expect(rows[0].ubRedovisat).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('computeRollforwardTotals', () => {
|
||||
it('sums closing book value and accumulated depreciation across categories', () => {
|
||||
const totals = computeRollforwardTotals(
|
||||
[
|
||||
makeAsset({
|
||||
figures: { ibAck: 12_000, aretsAvskrivning: 12_000, avgaendeAck: 0 },
|
||||
}),
|
||||
makeAsset({
|
||||
category: 'computer',
|
||||
acquisition_cost: 20_000,
|
||||
figures: { ibAck: 6_667, aretsAvskrivning: 6_667, avgaendeAck: 0 },
|
||||
}),
|
||||
],
|
||||
PERIOD_START,
|
||||
PERIOD_END,
|
||||
)
|
||||
// equipment: 60,000 - 24,000 = 36,000; computer: 20,000 - 13,334 = 6,666
|
||||
expect(totals.ubAck).toBe(37_334)
|
||||
expect(totals.ubRedovisat).toBe(42_666)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -380,6 +380,17 @@ describe('buildArsredovisningData: K3', () => {
|
||||
expect(data.warnings.find((w) => w.startsWith('Aktiekapitalnoten saknas'))).toBeDefined()
|
||||
})
|
||||
|
||||
it('never queries depreciation_schedules when the asset register is empty', async () => {
|
||||
// buildRollforwardAssets skips the posted-schedules fetch entirely for
|
||||
// an empty register: pinning this keeps the makeSupabase mock (which has
|
||||
// no depreciation_schedules branch) honest.
|
||||
const supabase = makeSupabase({ accountingFramework: 'k3' })
|
||||
// @ts-expect-error: chainable mock isn't fully typed as SupabaseClient
|
||||
await buildArsredovisningData(supabase, 'co1', 'fp1')
|
||||
const tables = supabase.from.mock.calls.map((call) => call[0])
|
||||
expect(tables).not.toContain('depreciation_schedules')
|
||||
})
|
||||
|
||||
it('DROPS the old "K3 noter need manual augmentation" warning text', async () => {
|
||||
const supabase = makeSupabase({ accountingFramework: 'k3' })
|
||||
// @ts-expect-error: chainable mock isn't fully typed as SupabaseClient
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
computeAssetNoteFigures,
|
||||
type PostedScheduleRow,
|
||||
type PeriodLike,
|
||||
} from '../asset-note-figures'
|
||||
import type { Asset } from '@/types'
|
||||
|
||||
const FP2023: PeriodLike = { id: 'fp2023', period_start: '2023-01-01', period_end: '2023-12-31' }
|
||||
const FP2024: PeriodLike = { id: 'fp2024', period_start: '2024-01-01', period_end: '2024-12-31' }
|
||||
const FP2025: PeriodLike = { id: 'fp2025', period_start: '2025-01-01', period_end: '2025-12-31' }
|
||||
const ALL_PERIODS = [FP2023, FP2024, FP2025]
|
||||
|
||||
function makeAsset(overrides: Partial<Asset> = {}): Asset {
|
||||
return {
|
||||
id: 'asset-1',
|
||||
user_id: 'user-1',
|
||||
company_id: 'company-1',
|
||||
name: 'Testinventarie',
|
||||
category: 'equipment',
|
||||
acquisition_date: '2024-01-01',
|
||||
acquisition_cost: 146_000,
|
||||
salvage_value: 0,
|
||||
useful_life_months: 60,
|
||||
depreciation_method: 'linear',
|
||||
bas_asset_account: '1220',
|
||||
bas_accumulated_account: '1229',
|
||||
bas_expense_account: '7832',
|
||||
restvarde_target: null,
|
||||
disposed_at: null,
|
||||
disposed_proceeds: null,
|
||||
disposed_proceeds_vat: 0,
|
||||
disposed_vat_treatment: null,
|
||||
jamkning_amount: 0,
|
||||
jamkning_remaining_months: null,
|
||||
jamkning_total_months: null,
|
||||
jamkning_original_input_vat: null,
|
||||
k3_components: null,
|
||||
notes: null,
|
||||
created_at: '2024-01-01T00:00:00Z',
|
||||
updated_at: '2024-01-01T00:00:00Z',
|
||||
...overrides,
|
||||
} as Asset
|
||||
}
|
||||
|
||||
function posted(
|
||||
assetId: string,
|
||||
periodId: string,
|
||||
amount: number | string,
|
||||
): PostedScheduleRow {
|
||||
return {
|
||||
asset_id: assetId,
|
||||
fiscal_period_id: periodId,
|
||||
planned_depreciation: amount,
|
||||
journal_entry_id: `je-${assetId}-${periodId}`,
|
||||
}
|
||||
}
|
||||
|
||||
function figuresFor(
|
||||
asset: Asset,
|
||||
schedules: PostedScheduleRow[],
|
||||
periods: PeriodLike[] = ALL_PERIODS,
|
||||
currentPeriodId = 'fp2025',
|
||||
) {
|
||||
const map = computeAssetNoteFigures({
|
||||
assets: [asset],
|
||||
postedSchedules: schedules,
|
||||
fiscalPeriods: periods,
|
||||
currentPeriodId,
|
||||
})
|
||||
return map.get(asset.id)
|
||||
}
|
||||
|
||||
describe('computeAssetNoteFigures', () => {
|
||||
it('uses posted schedule amounts verbatim (regression: 20 kr note drift)', () => {
|
||||
// 146,000 kr over 60 months books round(146000 * 12/60) = 29,200/year.
|
||||
// The old theoretical formula (base * 365 / (60 * 30.4375)) gave 29,180:
|
||||
// the exact 20 kr inconsistency reported against the ledger-driven RR/BR.
|
||||
const asset = makeAsset()
|
||||
const f = figuresFor(asset, [
|
||||
posted('asset-1', 'fp2024', 29_200),
|
||||
posted('asset-1', 'fp2025', 29_200),
|
||||
])
|
||||
expect(f).toEqual({ ibAck: 29_200, aretsAvskrivning: 29_200, avgaendeAck: 0 })
|
||||
})
|
||||
|
||||
it('falls back to the booking engine for the current year when nothing is posted', () => {
|
||||
const asset = makeAsset()
|
||||
const f = figuresFor(asset, [posted('asset-1', 'fp2024', 29_200)])
|
||||
// Engine full-year linear: round(146000 * 12/60) = 29,200, not 29,180.
|
||||
expect(f).toEqual({ ibAck: 29_200, aretsAvskrivning: 29_200, avgaendeAck: 0 })
|
||||
})
|
||||
|
||||
it('iterates synthetic prior years through the engine for pre-onboarding assets', () => {
|
||||
// Acquired 2023-01-01 but only the current fiscal period exists in the
|
||||
// DB and nothing was ever posted: two synthetic 12-month windows.
|
||||
const asset = makeAsset({ acquisition_date: '2023-01-01' })
|
||||
const f = figuresFor(asset, [], [FP2025])
|
||||
expect(f).toEqual({ ibAck: 58_400, aretsAvskrivning: 29_200, avgaendeAck: 0 })
|
||||
})
|
||||
|
||||
it('caps the engine-iterated fallback at the depreciable base after useful life', () => {
|
||||
const asset = makeAsset({ acquisition_date: '2010-01-01' })
|
||||
const f = figuresFor(asset, [], [FP2025])
|
||||
expect(f).toEqual({ ibAck: 146_000, aretsAvskrivning: 0, avgaendeAck: 0 })
|
||||
})
|
||||
|
||||
it('applies declining_balance_30 on the posted book value', () => {
|
||||
const asset = makeAsset({
|
||||
acquisition_date: '2024-01-01',
|
||||
acquisition_cost: 100_000,
|
||||
depreciation_method: 'declining_balance_30',
|
||||
})
|
||||
const f = figuresFor(asset, [posted('asset-1', 'fp2024', 30_000)])
|
||||
// Book value 70,000 * 30% = 21,000
|
||||
expect(f).toEqual({ ibAck: 30_000, aretsAvskrivning: 21_000, avgaendeAck: 0 })
|
||||
})
|
||||
|
||||
it('floors restvardesavskrivning_25 at the restvarde target', () => {
|
||||
const asset = makeAsset({
|
||||
acquisition_date: '2024-01-01',
|
||||
acquisition_cost: 100_000,
|
||||
depreciation_method: 'restvardesavskrivning_25',
|
||||
restvarde_target: 50_000,
|
||||
})
|
||||
const f = figuresFor(asset, [posted('asset-1', 'fp2024', 50_000)])
|
||||
expect(f).toEqual({ ibAck: 50_000, aretsAvskrivning: 0, avgaendeAck: 0 })
|
||||
})
|
||||
|
||||
it('sums K3 component depreciation via the engine fallback', () => {
|
||||
const asset = makeAsset({
|
||||
acquisition_date: '2025-01-01',
|
||||
acquisition_cost: 100_000,
|
||||
k3_components: [
|
||||
{ name: 'Stomme', cost: 80_000, useful_life_months: 120 },
|
||||
{ name: 'Tak', cost: 20_000, useful_life_months: 60, salvage_value: 0 },
|
||||
],
|
||||
})
|
||||
const f = figuresFor(asset, [])
|
||||
// round(80000 * 12/120) + round(20000 * 12/60) = 8,000 + 4,000
|
||||
expect(f).toEqual({ ibAck: 0, aretsAvskrivning: 12_000, avgaendeAck: 0 })
|
||||
})
|
||||
|
||||
it('ignores draft schedules (journal_entry_id null) everywhere', () => {
|
||||
const asset = makeAsset()
|
||||
const drafts: PostedScheduleRow[] = [
|
||||
{ asset_id: 'asset-1', fiscal_period_id: 'fp2024', planned_depreciation: 999, journal_entry_id: null },
|
||||
{ asset_id: 'asset-1', fiscal_period_id: 'fp2025', planned_depreciation: 999, journal_entry_id: null },
|
||||
]
|
||||
const f = figuresFor(asset, drafts)
|
||||
// Both fall back to the engine: 2024 via prior-year iteration, 2025 live.
|
||||
expect(f).toEqual({ ibAck: 29_200, aretsAvskrivning: 29_200, avgaendeAck: 0 })
|
||||
})
|
||||
|
||||
it('mirrors disposeAsset for in-period disposals: all posted rows reversed, nothing new charged', () => {
|
||||
const asset = makeAsset({
|
||||
acquisition_date: '2023-01-01',
|
||||
disposed_at: '2025-06-30',
|
||||
disposed_proceeds: 10_000,
|
||||
})
|
||||
const f = figuresFor(asset, [
|
||||
posted('asset-1', 'fp2023', 29_200),
|
||||
posted('asset-1', 'fp2024', 29_200),
|
||||
])
|
||||
// disposeAsset reversed sumPostedDepreciation() = 58,400; no current-year
|
||||
// charge was ever booked, so the note must not invent one.
|
||||
expect(f).toEqual({ ibAck: 58_400, aretsAvskrivning: 0, avgaendeAck: 58_400 })
|
||||
})
|
||||
|
||||
it('includes a posted current-year row in the disposal reversal so the asset nets to zero', () => {
|
||||
const asset = makeAsset({
|
||||
acquisition_date: '2023-01-01',
|
||||
disposed_at: '2025-06-30',
|
||||
disposed_proceeds: 10_000,
|
||||
})
|
||||
const f = figuresFor(asset, [
|
||||
posted('asset-1', 'fp2023', 29_200),
|
||||
posted('asset-1', 'fp2024', 29_200),
|
||||
posted('asset-1', 'fp2025', 29_200),
|
||||
])
|
||||
expect(f).toEqual({ ibAck: 58_400, aretsAvskrivning: 29_200, avgaendeAck: 87_600 })
|
||||
expect(f!.ibAck + f!.aretsAvskrivning - f!.avgaendeAck).toBe(0)
|
||||
})
|
||||
|
||||
it('previews engine amounts for disposals with no posted schedules at all', () => {
|
||||
const asset = makeAsset({
|
||||
acquisition_date: '2023-01-01',
|
||||
disposed_at: '2025-06-30',
|
||||
disposed_proceeds: 10_000,
|
||||
})
|
||||
const f = figuresFor(asset, [])
|
||||
// Fallback ibAck = 2 full engine years = 58,400. Current year clamps at
|
||||
// the disposal date: round(29200 * 181/365) = 14,480. The reversal takes
|
||||
// the asset's accumulated depreciation back to zero.
|
||||
expect(f).toEqual({ ibAck: 58_400, aretsAvskrivning: 14_480, avgaendeAck: 72_880 })
|
||||
})
|
||||
|
||||
it('coerces NUMERIC string amounts from PostgREST', () => {
|
||||
const asset = makeAsset()
|
||||
const f = figuresFor(asset, [
|
||||
posted('asset-1', 'fp2024', '29200.00'),
|
||||
posted('asset-1', 'fp2025', '29200.00'),
|
||||
])
|
||||
expect(f).toEqual({ ibAck: 29_200, aretsAvskrivning: 29_200, avgaendeAck: 0 })
|
||||
})
|
||||
|
||||
it('omits assets disposed before the period', () => {
|
||||
const asset = makeAsset({
|
||||
acquisition_date: '2023-01-01',
|
||||
disposed_at: '2024-12-31',
|
||||
disposed_proceeds: 0,
|
||||
})
|
||||
const map = computeAssetNoteFigures({
|
||||
assets: [asset],
|
||||
postedSchedules: [],
|
||||
fiscalPeriods: ALL_PERIODS,
|
||||
currentPeriodId: 'fp2025',
|
||||
})
|
||||
expect(map.has('asset-1')).toBe(false)
|
||||
})
|
||||
|
||||
it('throws when the current period is missing from the period list', () => {
|
||||
expect(() =>
|
||||
computeAssetNoteFigures({
|
||||
assets: [makeAsset()],
|
||||
postedSchedules: [],
|
||||
fiscalPeriods: [FP2024],
|
||||
currentPeriodId: 'fp2025',
|
||||
}),
|
||||
).toThrow('Current fiscal period not found')
|
||||
})
|
||||
})
|
||||
@@ -14,14 +14,16 @@
|
||||
*
|
||||
* Utgående redovisat värde = utgående anskaffningsvärde − utgående ack. avskrivningar
|
||||
*
|
||||
* Driven entirely off the assets table. Accumulated depreciation is
|
||||
* computed from the linear schedule (acquisition_date, useful_life_months,
|
||||
* salvage_value) at the relevant as-of date: we do not depend on
|
||||
* journal-derived avskrivningskonton because not all companies post
|
||||
* monthly avskrivningar.
|
||||
* Anskaffningsvärden come from the asset register. Depreciation figures are
|
||||
* resolved UPSTREAM (asset-note-figures.ts) from posted depreciation
|
||||
* schedules, with the booking engine as fallback, so the note ties to the
|
||||
* balansräkning and resultaträkning instead of re-deriving a theoretical
|
||||
* schedule that can drift from what was actually booked. This module only
|
||||
* aggregates per category and formats.
|
||||
*/
|
||||
|
||||
import type { NoteEntry } from './types'
|
||||
import type { AssetDepreciationFigures } from './asset-note-figures'
|
||||
|
||||
export interface AnlaggningAsset {
|
||||
category: string
|
||||
@@ -30,6 +32,7 @@ export interface AnlaggningAsset {
|
||||
salvage_value: number
|
||||
useful_life_months: number
|
||||
disposed_at: string | null
|
||||
figures: AssetDepreciationFigures
|
||||
}
|
||||
|
||||
interface CategoryRollforward {
|
||||
@@ -56,44 +59,11 @@ const CATEGORY_LABELS: Record<string, string> = {
|
||||
other_tangible: 'Övriga materiella anläggningstillgångar',
|
||||
}
|
||||
|
||||
function daysBetween(startIso: string, endIso: string): number {
|
||||
const start = new Date(`${startIso}T00:00:00Z`)
|
||||
const end = new Date(`${endIso}T00:00:00Z`)
|
||||
if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) return 0
|
||||
if (end < start) return 0
|
||||
return Math.floor((end.getTime() - start.getTime()) / 86400000)
|
||||
}
|
||||
|
||||
/**
|
||||
* Linear depreciation accumulated between acquisition_date and asOfIso.
|
||||
* Caps at (cost − salvage) once useful life elapses. Day-based pro-rata
|
||||
* matching how computeLinearDepreciation pro-rates the first/last year.
|
||||
*/
|
||||
function accumulatedDepreciation(
|
||||
asset: AnlaggningAsset,
|
||||
asOfIso: string,
|
||||
): number {
|
||||
if (asOfIso < asset.acquisition_date) return 0
|
||||
const lifeDays = asset.useful_life_months * (365.25 / 12)
|
||||
const elapsedDays = Math.min(lifeDays, daysBetween(asset.acquisition_date, asOfIso))
|
||||
if (lifeDays === 0) return 0
|
||||
const depreciable = asset.acquisition_cost - asset.salvage_value
|
||||
return Math.round((depreciable * elapsedDays) / lifeDays * 100) / 100
|
||||
}
|
||||
|
||||
/** ISO date one day before a given ISO date. Used for "day before period start". */
|
||||
function isoMinusOneDay(iso: string): string {
|
||||
const d = new Date(`${iso}T00:00:00Z`)
|
||||
d.setUTCDate(d.getUTCDate() - 1)
|
||||
return d.toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
function buildRollforward(
|
||||
assets: AnlaggningAsset[],
|
||||
periodStart: string,
|
||||
periodEnd: string,
|
||||
): CategoryRollforward[] {
|
||||
const dayBeforeStart = isoMinusOneDay(periodStart)
|
||||
const byCategory = new Map<string, CategoryRollforward>()
|
||||
|
||||
const getRow = (category: string): CategoryRollforward => {
|
||||
@@ -136,30 +106,17 @@ function buildRollforward(
|
||||
if (acquiredBeforePeriod) {
|
||||
// Was on the books at the start of the period
|
||||
row.ibAnskaffning += asset.acquisition_cost
|
||||
row.ibAck += accumulatedDepreciation(asset, dayBeforeStart)
|
||||
row.ibAck += asset.figures.ibAck
|
||||
}
|
||||
if (acquiredDuringPeriod) {
|
||||
row.tillkommande += asset.acquisition_cost
|
||||
}
|
||||
if (disposedDuringPeriod) {
|
||||
row.avgaende += asset.acquisition_cost
|
||||
row.avgaendeAck += accumulatedDepreciation(asset, asset.disposed_at!)
|
||||
row.avgaendeAck += asset.figures.avgaendeAck
|
||||
}
|
||||
|
||||
// Year's depreciation: from max(acquisition_date, period_start)
|
||||
// to min(disposed_at ?? period_end, period_end). Computed as the
|
||||
// delta in accumulated depreciation between those two dates.
|
||||
const yearStart =
|
||||
asset.acquisition_date > periodStart ? asset.acquisition_date : periodStart
|
||||
const yearEnd =
|
||||
asset.disposed_at != null && asset.disposed_at < periodEnd
|
||||
? asset.disposed_at
|
||||
: periodEnd
|
||||
if (yearStart <= yearEnd) {
|
||||
const startAck = accumulatedDepreciation(asset, isoMinusOneDay(yearStart))
|
||||
const endAck = accumulatedDepreciation(asset, yearEnd)
|
||||
row.aretsAvskrivning += Math.max(0, endAck - startAck)
|
||||
}
|
||||
row.aretsAvskrivning += asset.figures.aretsAvskrivning
|
||||
}
|
||||
|
||||
// Close out totals + ordering
|
||||
@@ -187,6 +144,23 @@ function buildRollforward(
|
||||
return rows
|
||||
}
|
||||
|
||||
/**
|
||||
* Document-level totals for the roll-forward: used by build-data to
|
||||
* cross-check the note's closing book value against the balansräkning.
|
||||
*/
|
||||
export function computeRollforwardTotals(
|
||||
assets: AnlaggningAsset[],
|
||||
periodStart: string,
|
||||
periodEnd: string,
|
||||
): { ubRedovisat: number; ubAck: number } {
|
||||
const rows = buildRollforward(assets, periodStart, periodEnd)
|
||||
return {
|
||||
ubRedovisat:
|
||||
Math.round(rows.reduce((sum, r) => sum + r.ubRedovisat, 0) * 100) / 100,
|
||||
ubAck: Math.round(rows.reduce((sum, r) => sum + r.ubAck, 0) * 100) / 100,
|
||||
}
|
||||
}
|
||||
|
||||
const fmt = (n: number) => Math.round(n).toLocaleString('sv-SE')
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
/**
|
||||
* Per-asset depreciation figures for the anläggningstillgångar roll-forward
|
||||
* note (ÅRL 5:8 §), anchored to what was actually BOOKED.
|
||||
*
|
||||
* The note must reconcile with the balansräkning, which is ledger-driven.
|
||||
* Posted `depreciation_schedules` rows are the source of truth: they carry
|
||||
* the exact amounts the engine committed to the journal, and they are also
|
||||
* exactly what `disposeAsset()` reverses via `sumPostedDepreciation()`.
|
||||
*
|
||||
* Fallbacks (only when nothing is posted for the relevant span) reuse the
|
||||
* booking engine's `computeAnnualDepreciation` so the note previews the
|
||||
* same amount that WOULD be booked: never a parallel formula. For years
|
||||
* before the company's fiscal periods exist in the DB (pre-onboarding
|
||||
* assets), synthetic 12-month windows are stepped back from the earliest
|
||||
* known period start; irregular pre-onboarding years are approximated,
|
||||
* which the balansräkning tie-out warning in build-data surfaces.
|
||||
*/
|
||||
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { computeAnnualDepreciation } from '@/lib/bokslut/assets/depreciation-engine'
|
||||
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
||||
import type { Asset } from '@/types'
|
||||
|
||||
export interface AssetDepreciationFigures {
|
||||
/** Accumulated depreciation on the books at period start. */
|
||||
ibAck: number
|
||||
/** Depreciation charged during the period (posted schedule, else engine). */
|
||||
aretsAvskrivning: number
|
||||
/** Accumulated depreciation reversed on in-period disposal. */
|
||||
avgaendeAck: number
|
||||
}
|
||||
|
||||
export interface PostedScheduleRow {
|
||||
asset_id: string
|
||||
fiscal_period_id: string
|
||||
/** NUMERIC arrives as string from PostgREST. */
|
||||
planned_depreciation: number | string
|
||||
journal_entry_id: string | null
|
||||
}
|
||||
|
||||
export interface PeriodLike {
|
||||
id: string
|
||||
period_start: string
|
||||
period_end: string
|
||||
}
|
||||
|
||||
const round2 = (n: number) => Math.round(n * 100) / 100
|
||||
|
||||
/** Posted (journal-linked) schedule rows for the whole company, paginated. */
|
||||
export async function loadPostedSchedules(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
): Promise<PostedScheduleRow[]> {
|
||||
return fetchAllRows<PostedScheduleRow>(({ from, to }) =>
|
||||
supabase
|
||||
.from('depreciation_schedules')
|
||||
.select('asset_id, fiscal_period_id, planned_depreciation, journal_entry_id')
|
||||
.eq('company_id', companyId)
|
||||
.not('journal_entry_id', 'is', null)
|
||||
.order('id')
|
||||
.range(from, to),
|
||||
)
|
||||
}
|
||||
|
||||
function isoAddDays(iso: string, days: number): string {
|
||||
const d = new Date(`${iso}T00:00:00Z`)
|
||||
d.setUTCDate(d.getUTCDate() + days)
|
||||
return d.toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
/** Shift an ISO date by whole years, clamping Feb 29 to Feb 28. */
|
||||
function isoShiftYears(iso: string, deltaYears: number): string {
|
||||
const d = new Date(`${iso}T00:00:00Z`)
|
||||
const year = d.getUTCFullYear() + deltaYears
|
||||
const month = d.getUTCMonth()
|
||||
const lastDay = new Date(Date.UTC(year, month + 1, 0)).getUTCDate()
|
||||
return new Date(Date.UTC(year, month, Math.min(d.getUTCDate(), lastDay)))
|
||||
.toISOString()
|
||||
.slice(0, 10)
|
||||
}
|
||||
|
||||
/**
|
||||
* Accumulated depreciation at period start for an asset with NO posted
|
||||
* prior schedules. Iterates prior years chronologically through the
|
||||
* engine (declining methods compound, so order matters): real DB fiscal
|
||||
* periods where they exist, synthetic 12-month windows stepped back from
|
||||
* the earliest known period start for the pre-onboarding years before.
|
||||
*/
|
||||
function fallbackAccumulatedBefore(
|
||||
asset: Asset,
|
||||
currentPeriodStart: string,
|
||||
fiscalPeriods: PeriodLike[],
|
||||
): number {
|
||||
const priorPeriods = fiscalPeriods
|
||||
.filter((p) => p.period_start < currentPeriodStart)
|
||||
.sort((a, b) => a.period_start.localeCompare(b.period_start))
|
||||
|
||||
const anchorStart =
|
||||
priorPeriods.length > 0 ? priorPeriods[0].period_start : currentPeriodStart
|
||||
const synthetic: { period_start: string; period_end: string }[] = []
|
||||
let windowEnd = isoAddDays(anchorStart, -1)
|
||||
let windowStart = isoShiftYears(anchorStart, -1)
|
||||
while (windowEnd >= asset.acquisition_date) {
|
||||
synthetic.unshift({ period_start: windowStart, period_end: windowEnd })
|
||||
windowEnd = isoAddDays(windowStart, -1)
|
||||
windowStart = isoShiftYears(windowStart, -1)
|
||||
}
|
||||
|
||||
let accumulated = 0
|
||||
for (const window of [...synthetic, ...priorPeriods]) {
|
||||
if (window.period_end < asset.acquisition_date) continue
|
||||
const { amount } = computeAnnualDepreciation(asset, window, accumulated)
|
||||
accumulated = round2(accumulated + amount)
|
||||
}
|
||||
return accumulated
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve booked-anchored figures for every asset alive in the period.
|
||||
* Assets disposed before the period are omitted (the note skips them).
|
||||
*/
|
||||
export function computeAssetNoteFigures(params: {
|
||||
assets: Asset[]
|
||||
postedSchedules: PostedScheduleRow[]
|
||||
fiscalPeriods: PeriodLike[]
|
||||
currentPeriodId: string
|
||||
}): Map<string, AssetDepreciationFigures> {
|
||||
const { assets, postedSchedules, fiscalPeriods, currentPeriodId } = params
|
||||
const currentPeriod = fiscalPeriods.find((p) => p.id === currentPeriodId)
|
||||
if (!currentPeriod) {
|
||||
throw new Error('Current fiscal period not found in fiscal period list')
|
||||
}
|
||||
|
||||
const periodStartById = new Map(fiscalPeriods.map((p) => [p.id, p.period_start]))
|
||||
const byAsset = new Map<string, PostedScheduleRow[]>()
|
||||
for (const row of postedSchedules) {
|
||||
if (row.journal_entry_id == null) continue
|
||||
const list = byAsset.get(row.asset_id)
|
||||
if (list) list.push(row)
|
||||
else byAsset.set(row.asset_id, [row])
|
||||
}
|
||||
|
||||
const figures = new Map<string, AssetDepreciationFigures>()
|
||||
for (const asset of assets) {
|
||||
if (asset.disposed_at && asset.disposed_at < currentPeriod.period_start) continue
|
||||
|
||||
const rows = byAsset.get(asset.id) ?? []
|
||||
const currentPosted = rows.find((r) => r.fiscal_period_id === currentPeriodId)
|
||||
const priorPosted = rows.filter((r) => {
|
||||
const start = periodStartById.get(r.fiscal_period_id)
|
||||
return start != null && start < currentPeriod.period_start
|
||||
})
|
||||
|
||||
let ibAck: number
|
||||
if (priorPosted.length > 0) {
|
||||
ibAck = round2(
|
||||
priorPosted.reduce((sum, r) => sum + (Number(r.planned_depreciation) || 0), 0),
|
||||
)
|
||||
} else if (asset.acquisition_date >= currentPeriod.period_start) {
|
||||
ibAck = 0
|
||||
} else {
|
||||
ibAck = fallbackAccumulatedBefore(asset, currentPeriod.period_start, fiscalPeriods)
|
||||
}
|
||||
|
||||
const disposedDuringPeriod =
|
||||
asset.disposed_at != null &&
|
||||
asset.disposed_at >= currentPeriod.period_start &&
|
||||
asset.disposed_at <= currentPeriod.period_end
|
||||
|
||||
let aretsAvskrivning: number
|
||||
let avgaendeAck = 0
|
||||
if (disposedDuringPeriod) {
|
||||
const hasAnyPosted = rows.length > 0
|
||||
if (hasAnyPosted) {
|
||||
// Mirror sumPostedDepreciation()/disposeAsset(): the ledger reversed
|
||||
// exactly the sum of all posted rows, and the current year's charge
|
||||
// is whatever was posted for this period (often nothing).
|
||||
aretsAvskrivning = currentPosted
|
||||
? Number(currentPosted.planned_depreciation) || 0
|
||||
: 0
|
||||
avgaendeAck = round2(
|
||||
rows.reduce((sum, r) => sum + (Number(r.planned_depreciation) || 0), 0),
|
||||
)
|
||||
} else {
|
||||
// Nothing ever posted: preview what the engine would have booked so
|
||||
// the disposed asset still nets out of the roll-forward.
|
||||
aretsAvskrivning = computeAnnualDepreciation(asset, currentPeriod, ibAck).amount
|
||||
avgaendeAck = round2(ibAck + aretsAvskrivning)
|
||||
}
|
||||
} else if (currentPosted) {
|
||||
aretsAvskrivning = Number(currentPosted.planned_depreciation) || 0
|
||||
} else {
|
||||
aretsAvskrivning = computeAnnualDepreciation(asset, currentPeriod, ibAck).amount
|
||||
}
|
||||
|
||||
figures.set(asset.id, {
|
||||
ibAck,
|
||||
aretsAvskrivning: round2(aretsAvskrivning),
|
||||
avgaendeAck,
|
||||
})
|
||||
}
|
||||
return figures
|
||||
}
|
||||
@@ -19,7 +19,12 @@ import {
|
||||
buildMateriellaAnlaggningsNot,
|
||||
buildUppskjutenSkattNot,
|
||||
} from './k3-noter-builder'
|
||||
import { buildAnlaggningstillgangarNote } from './anlaggningstillgangar-note'
|
||||
import {
|
||||
buildAnlaggningstillgangarNote,
|
||||
computeRollforwardTotals,
|
||||
type AnlaggningAsset,
|
||||
} from './anlaggningstillgangar-note'
|
||||
import { computeAssetNoteFigures, loadPostedSchedules } from './asset-note-figures'
|
||||
import { computeMedelantalAnstallda } from '@/lib/salary/medelantal'
|
||||
import type {
|
||||
ArsredovisningData,
|
||||
@@ -250,6 +255,8 @@ export async function buildArsredovisningData(
|
||||
period.period_end,
|
||||
narrative,
|
||||
tbFull.rows,
|
||||
fiscalPeriodId,
|
||||
(periodList ?? []) as PeriodRow[],
|
||||
),
|
||||
generateKassaflodesanalys(supabase, companyId, fiscalPeriodId).then(
|
||||
(cashFlow) => ({ ok: true as const, cashFlow }),
|
||||
@@ -292,6 +299,9 @@ export async function buildArsredovisningData(
|
||||
period.period_start,
|
||||
period.period_end,
|
||||
narrative,
|
||||
tbFull.rows,
|
||||
fiscalPeriodId,
|
||||
(periodList ?? []) as PeriodRow[],
|
||||
)
|
||||
noter = k2Noter.notes
|
||||
noterWarnings = k2Noter.warnings
|
||||
@@ -519,6 +529,60 @@ function buildEquityChanges(mapping: K2MappingResult): EgenKapitalRow[] {
|
||||
return rows
|
||||
}
|
||||
|
||||
/**
|
||||
* Map register assets to the roll-forward note input, resolving per-asset
|
||||
* depreciation figures from posted schedules (engine fallback) so the note
|
||||
* ties to the ledger. Shared by the K2 and K3 note builders. Skips the
|
||||
* schedules query entirely when the register is empty.
|
||||
*/
|
||||
async function buildRollforwardAssets(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
assets: Asset[],
|
||||
allPeriods: PeriodRow[],
|
||||
fiscalPeriodId: string,
|
||||
): Promise<AnlaggningAsset[]> {
|
||||
if (assets.length === 0) return []
|
||||
const schedules = await loadPostedSchedules(supabase, companyId)
|
||||
const figures = computeAssetNoteFigures({
|
||||
assets,
|
||||
postedSchedules: schedules,
|
||||
fiscalPeriods: allPeriods,
|
||||
currentPeriodId: fiscalPeriodId,
|
||||
})
|
||||
return assets.map((a) => ({
|
||||
category: a.category,
|
||||
acquisition_date: a.acquisition_date,
|
||||
acquisition_cost: a.acquisition_cost,
|
||||
salvage_value: a.salvage_value,
|
||||
useful_life_months: a.useful_life_months,
|
||||
disposed_at: a.disposed_at,
|
||||
figures: figures.get(a.id) ?? { ibAck: 0, aretsAvskrivning: 0, avgaendeAck: 0 },
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* Cross-check the roll-forward note's closing book value against the
|
||||
* balansräkning (full TB net of accounts 1000-1299: immateriella +
|
||||
* materiella anläggningstillgångar; 13xx financial assets are outside the
|
||||
* note). Returns a user-facing warning when they diverge by more than 1 kr,
|
||||
* which is the exact inconsistency ÅRL 5:8 § forbids in a filed document.
|
||||
*/
|
||||
function rollforwardTieOutWarning(
|
||||
rollforwardAssets: AnlaggningAsset[],
|
||||
tbFullRows: TrialBalanceRow[],
|
||||
periodStart: string,
|
||||
periodEnd: string,
|
||||
): string | null {
|
||||
const totals = computeRollforwardTotals(rollforwardAssets, periodStart, periodEnd)
|
||||
const tbNet = tbFullRows
|
||||
.filter((r) => r.account_number >= '1000' && r.account_number < '1300')
|
||||
.reduce((sum, r) => sum + (r.closing_debit || 0) - (r.closing_credit || 0), 0)
|
||||
if (Math.abs(totals.ubRedovisat - tbNet) <= 1) return null
|
||||
const fmtKr = (n: number) => Math.round(n).toLocaleString('sv-SE')
|
||||
return `Anläggningsnotens utgående redovisade värde (${fmtKr(totals.ubRedovisat)} kr) stämmer inte med balansräkningens bokförda värde för konto 1000-1299 (${fmtKr(tbNet)} kr). Kontrollera att anläggningsregistret är komplett och att årets avskrivningar är bokförda.`
|
||||
}
|
||||
|
||||
async function buildK2Noter(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
@@ -526,6 +590,9 @@ async function buildK2Noter(
|
||||
periodStart: string,
|
||||
periodEnd: string,
|
||||
narrative: NarrativeRow | null,
|
||||
tbFullRows: TrialBalanceRow[],
|
||||
fiscalPeriodId: string,
|
||||
allPeriods: PeriodRow[],
|
||||
): Promise<{ notes: NoteEntry[]; warnings: string[] }> {
|
||||
const notes: NoteEntry[] = []
|
||||
const warnings: string[] = []
|
||||
@@ -639,21 +706,31 @@ async function buildK2Noter(
|
||||
// Anläggningstillgångar roll-forward (ÅRL 5:8 §). Per-category IB →
|
||||
// tillkommande → avgående → UB anskaffningsvärde, same for ackumulerade
|
||||
// avskrivningar, ending in utgående redovisat värde. Hard ÅR requirement
|
||||
// for any company with assets on the books.
|
||||
// for any company with assets on the books. Depreciation figures come
|
||||
// from posted schedules so the note ties to the balansräkning.
|
||||
const rollforwardAssets = await buildRollforwardAssets(
|
||||
supabase,
|
||||
companyId,
|
||||
assets,
|
||||
allPeriods,
|
||||
fiscalPeriodId,
|
||||
)
|
||||
const rollforwardNote = buildAnlaggningstillgangarNote({
|
||||
noteNumber: notes.length + 1,
|
||||
assets: assets.map((a) => ({
|
||||
category: a.category,
|
||||
acquisition_date: a.acquisition_date,
|
||||
acquisition_cost: a.acquisition_cost,
|
||||
salvage_value: a.salvage_value,
|
||||
useful_life_months: a.useful_life_months,
|
||||
disposed_at: a.disposed_at,
|
||||
})),
|
||||
assets: rollforwardAssets,
|
||||
periodStart,
|
||||
periodEnd,
|
||||
})
|
||||
if (rollforwardNote) notes.push(rollforwardNote)
|
||||
if (rollforwardNote) {
|
||||
notes.push(rollforwardNote)
|
||||
const tieOut = rollforwardTieOutWarning(
|
||||
rollforwardAssets,
|
||||
tbFullRows,
|
||||
periodStart,
|
||||
periodEnd,
|
||||
)
|
||||
if (tieOut) warnings.push(tieOut)
|
||||
}
|
||||
|
||||
// Medelantal anställda: FTE-weighted average per ÅRL 5:20 §. We fetch the
|
||||
// full employment-window data because the column 'is_active' doesn't exist
|
||||
@@ -758,6 +835,8 @@ async function buildK3Noter(
|
||||
periodEndIso: string,
|
||||
narrative: NarrativeRow | null,
|
||||
tbFullRows: TrialBalanceRow[],
|
||||
fiscalPeriodId: string,
|
||||
allPeriods: PeriodRow[],
|
||||
): Promise<{ notes: NoteEntry[]; warnings: string[] }> {
|
||||
const notes: NoteEntry[] = []
|
||||
const warnings: string[] = []
|
||||
@@ -886,21 +965,31 @@ async function buildK3Noter(
|
||||
// 3b. Anläggningstillgångar roll-forward (ÅRL 5:8 §). Required even under
|
||||
// K3: K3 ch.17 layers component depreciation on top, but the basic
|
||||
// per-category roll-forward of anskaffningsvärde + ackumulerade
|
||||
// avskrivningar is the statutory baseline.
|
||||
// avskrivningar is the statutory baseline. Depreciation figures come
|
||||
// from posted schedules so the note ties to the balansräkning.
|
||||
const rollforwardAssets = await buildRollforwardAssets(
|
||||
supabase,
|
||||
companyId,
|
||||
assets,
|
||||
allPeriods,
|
||||
fiscalPeriodId,
|
||||
)
|
||||
const rollforwardNote = buildAnlaggningstillgangarNote({
|
||||
noteNumber: notes.length + 1,
|
||||
assets: assets.map((a) => ({
|
||||
category: a.category,
|
||||
acquisition_date: a.acquisition_date,
|
||||
acquisition_cost: a.acquisition_cost,
|
||||
salvage_value: a.salvage_value,
|
||||
useful_life_months: a.useful_life_months,
|
||||
disposed_at: a.disposed_at,
|
||||
})),
|
||||
assets: rollforwardAssets,
|
||||
periodStart: periodStartIso,
|
||||
periodEnd: periodEndIso,
|
||||
})
|
||||
if (rollforwardNote) notes.push(rollforwardNote)
|
||||
if (rollforwardNote) {
|
||||
notes.push(rollforwardNote)
|
||||
const tieOut = rollforwardTieOutWarning(
|
||||
rollforwardAssets,
|
||||
tbFullRows,
|
||||
periodStartIso,
|
||||
periodEndIso,
|
||||
)
|
||||
if (tieOut) warnings.push(tieOut)
|
||||
}
|
||||
|
||||
// 4. Uppskjutna skatter. K3 ch.29 requires disclosure of opening,
|
||||
// movement, and closing balance of uppskjuten skatteskuld. We derive
|
||||
|
||||
Reference in New Issue
Block a user