* feat(assets): allow editing fixed asset fields before depreciation The fixed asset register only offered a "Dispose" action, so correcting a mis-entered acquisition date/cost/category meant running the disposal flow — which posts a real divestment voucher plus a Ch. 8a VAT adjustment. Disproportionate and wrong for a data-entry fix. Add an Edit action that allows correcting those fields directly, gated for correctness: - service: extend updateAsset() with category/acquisition_date/ acquisition_cost; block the change once the asset is disposed or has posted depreciation (AssetCorrectionBlockedError) where it would desync posted vouchers from the register; realign the BAS triple on category change. Name, useful life, and method stay editable. - api: extend the PATCH schema; annotate GET /api/assets with has_posted_depreciation so the UI can lock basis fields proactively. - ui: EditAssetDialog + pencil action; disables date/cost/category when depreciation has been booked, with an inline explanation. - errors: register ASSET_CORRECTION_BLOCKED (409). - tests: unit tests for the guard; pg test for pre-disposal editability. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(assets): also block basis edits when depreciation was hand-posted The correction guard only consulted depreciation_schedules, so an avskrivning booked as a manual journal entry (no schedule row) slipped through and a basis correction was wrongly allowed. Add a ledger scan: any posted credit to the asset's ackumulerade- avskrivningar account (12x9) counts as depreciation. Entries that depreciation_schedules attributes to a *different* asset are excluded, so a sibling's engine avskrivning on a shared 12x9 account doesn't produce a false block. What remains is depreciation tied to this asset (engine or manual); a basis correction is blocked there and must go through storno. Adds two unit tests: blocks on a hand-posted credit, allows when the only 12x9 credit belongs to a sibling's engine entry. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(invoices): allow negative unit prices for discount lines The invoice creation form rejected negative unit prices via a frontend superRefine check, blocking valid discount lines (e.g. "Rabatt -100"). The unit_price error was never rendered inline, so submission failed silently. The backend schema already allows negative unit prices (see CreateInvoiceItemSchema test), so the form was simply out of sync. Remove the non-negative constraint; empty/NaN prices are still rejected by the base z.number() type. Drop the now-unused validation_price_positive translation key from both locale files. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(invoices): allow editing draft invoices Drafts could be saved but not edited — the only way to change a draft's lines, customer, dates or amounts was to delete and recreate it. Add a "Redigera" action on draft invoices that opens the invoice editor pre-filled with the draft and saves changes in place. A verifikat is only created when an invoice is sent (or paid, under kontantmetoden), so every status=draft invoice is uncommitted and safe to edit; sent/paid invoices stay immutable and still require a credit note. - Extract buildInvoiceWriteData() with the shared validation + computation (VAT rules, ROT/RUT, accruals, totals, currency, item rows); POST now uses it too, behaviour unchanged. - Add UpdateInvoiceSchema and PATCH /api/invoices/[id], guarded to drafts (status=draft, no journal entry, not self-billed); number and status are preserved and no invoice.created is emitted. - Extract the invoice creator into a shared InvoiceEditor with create / edit modes; /invoices/new is now a thin wrapper and /invoices/[id]/edit is the new edit page. - Add a "Redigera" button on draft invoice detail pages + sv/en strings. - Tests for the builder, UpdateInvoiceSchema and the PATCH route. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(reports): make Huvudbok findable via account/saldo search terms Searching the command palette for natural phrases like 'saldo per konto', 'kontoutdrag', 'kontoanalys' or 'transaktioner per konto' returned nothing, so users couldn't find the general ledger. Enrich the Huvudbok entry's keywords with those synonyms, and let Saldobalans and Balansrapport match 'saldo per konto' too since they are genuinely per-account balance views. Companion change — the clearer Huvudbok report description ('Saldo och alla transaktioner per konto') — already landed in d5f474cb. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(settings): let users edit their personal name Add an editable Namn field to /settings/account that updates profiles.full_name and best-effort syncs auth user_metadata. Previously the personal name was only ever set from BankID's legal name at signup with no way to correct it, so users whose tilltalsnamn isn't their first given name were greeted by the wrong name (and email/password users had no name at all). New POST /api/user/profile route (requireAuth, RLS-scoped update) mirrors /api/user/locale. sv/en strings added. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * feat(invoices): per-invoice öresavrundning override Add a display-only öresavrundning flag per invoice that wins over the company-wide setting. Resolution order in getDisplayTotal: per-invoice override -> company setting -> default-on. The stored total and the booked verifikat keep the exact öre; only the rendered total changes. Supplier invoices gain the same flag but resolve a null to off (they never had rounding historically), exposed via a toggle on the new-invoice form and a rounding row on the detail page. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * feat(transactions): warn on possible duplicate before booking Before committing a transaction (via book or categorize), detect an already-booked sibling with the same date and amount and return a 409 TRANSACTION_BOOK_POSSIBLE_DUPLICATE instead of silently double-booking. The user can override with force=true, which must be bound to the reviewed sibling via expected_duplicate_transaction_id; the candidate is re-detected server-side, so a stale or guessed id is rejected with TRANSACTION_BOOK_FORCE_CANDIDATE_MISMATCH. Detection is fail-open on the non-force path and fail-closed under force. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * feat(transactions): shadow-mode scope-drift dedup counter in bank ingest Count rows that an enforcing same-feed scope-drift rule WOULD treat as re-imports (the IBAN-drift re-imports the external_id check misses) and surface it as IngestResult.shadow_scope_drift_candidates. Nothing is blocked yet -- the counter only measures how often the rule would fire so it can be validated against real data before enforcement. Also gitignore scripts/delete-duplicate-transactions.ts: a destructive, hand-run cleanup tool kept out of the repo so it can't run in CI/cron or be mistaken for a supported feature. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(bokslut): base bolagsskatt on post-disposition result Bokslutsdispositioner are booked as source_type='year_end', which the income statement excludes, so net_result alone overstates resultat före skatt and the booked tax ignored the periodiseringsfond avsättning (too-high tax, ÅR/INK2 mismatch). calculateBolagsskatt now accepts resultBeforeTaxOverride. The preview builder mirrors each proposal's P&L effect (+återföring, -avsättning, -SLP) onto the pre-disposition result; the commit path sums the already-posted dispositions via the new sumPostedYearEndDispositions (class 88 + 7533) since bolagsskatt is committed last. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * feat(settings): fiscal years manager Add a FiscalYearsManager to the bookkeeping settings that lists fiscal periods with their status (closed > locked > open) and creates the next year via CreatePeriodDialog, seeded to chain forward from the latest period end. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(api): return 400 when locking a period with unbooked transactions lockPeriod() refuses to lock a period that still has uncategorized business transactions. Detect that message in the lock route and surface it as a clear PERIOD_HAS_UNBOOKED_TRANSACTIONS (400) instead of a generic 500. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * feat(invoices): implement isEditableInvoiceDraft utility and apply it across invoice edit routes feat(transactions): log duplicate dismissal events in behandlingshistorik test(invoices): add tests for isEditableInvoiceDraft function test(transactions): enhance tests to verify behandlingshistorik logging refactor(bokslut): update tax calculation test descriptions for clarity --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
226 lines
8.8 KiB
TypeScript
226 lines
8.8 KiB
TypeScript
import type { SupabaseClient } from '@supabase/supabase-js'
|
||
import { generateIncomeStatement } from '@/lib/reports/income-statement'
|
||
import { generateTrialBalance } from '@/lib/reports/trial-balance'
|
||
import { calculateBolagsskatt } from './tax-provision/bolagsskatt-calculator'
|
||
import { calculateSarskildLoneskatt } from './tax-provision/sarskild-loneskatt-calculator'
|
||
import {
|
||
computeLatentTax,
|
||
LATENT_TAX_EXPENSE_ACCOUNT,
|
||
LATENT_TAX_LIABILITY_ACCOUNT,
|
||
proposeLatentTaxChange,
|
||
} from './tax-provision/latent-tax-calculator'
|
||
import {
|
||
listExistingPeriodiseringsfonder,
|
||
proposeAvsattning,
|
||
proposeAteforing,
|
||
} from './reserves/periodiseringsfond-service'
|
||
import type { DispositionsProposal, ProposedDisposition } from './types'
|
||
import type { AccountingFramework } from '@/types'
|
||
|
||
const DEFAULT_SCHABLONINTAKT_RATE = 0.0355
|
||
|
||
/**
|
||
* Shared core of the GET /bokslutsdispositioner endpoint, lifted out so the
|
||
* MCP tool can call the same builder without duplicating the proposal logic.
|
||
* The API route and the MCP tool both hand its output to the caller, who
|
||
* picks which proposals to commit via the POST endpoint.
|
||
*/
|
||
export async function buildDispositionsProposal(
|
||
supabase: SupabaseClient,
|
||
companyId: string,
|
||
fiscalPeriodId: string,
|
||
): Promise<DispositionsProposal> {
|
||
const { data: period, error: periodError } = await supabase
|
||
.from('fiscal_periods')
|
||
.select('id, name, period_start, period_end')
|
||
.eq('id', fiscalPeriodId)
|
||
.eq('company_id', companyId)
|
||
.single()
|
||
if (periodError || !period) {
|
||
throw new Error('Fiscal period not found')
|
||
}
|
||
|
||
const { data: settings } = await supabase
|
||
.from('company_settings')
|
||
.select('entity_type')
|
||
.eq('company_id', companyId)
|
||
.maybeSingle()
|
||
const entityType = (settings?.entity_type ?? 'aktiebolag') as DispositionsProposal['entityType']
|
||
|
||
if (entityType !== 'aktiebolag') {
|
||
// Non-AB entities (enskild firma, handelsbolag, etc.) do not produce
|
||
// bookable bokslutsdispositioner — bolagsskatt, periodiseringsfond and
|
||
// SLP are AB-only mechanisms. EF tax mechanisms (egenavgifter,
|
||
// räntefördelning, periodiseringsfond-EF, expansionsfond) are
|
||
// declaration-only and surface through the dedicated
|
||
// /api/bookkeeping/fiscal-periods/[id]/ef-declaration endpoint and the
|
||
// EfDeclarationSection in the wizard — they never produce journal
|
||
// entries, so they have no place in this list.
|
||
const incomeStatement = await generateIncomeStatement(supabase, companyId, fiscalPeriodId)
|
||
return {
|
||
entityType,
|
||
fiscalPeriod: period,
|
||
netResultBefore: incomeStatement.net_result,
|
||
proposals: [],
|
||
}
|
||
}
|
||
|
||
// Look up the accounting framework — K3 (BFNAR 2012:1) triggers the
|
||
// uppskjuten-skatt provision step; K2 skips it.
|
||
const { data: companyRow } = await supabase
|
||
.from('companies')
|
||
.select('accounting_framework')
|
||
.eq('id', companyId)
|
||
.maybeSingle()
|
||
const accountingFramework: AccountingFramework =
|
||
(companyRow as { accounting_framework?: AccountingFramework } | null)?.accounting_framework
|
||
=== 'k3'
|
||
? 'k3'
|
||
: 'k2'
|
||
|
||
const fiscalYear = parseInt(period.period_end.slice(0, 4), 10)
|
||
const incomeStatement = await generateIncomeStatement(supabase, companyId, fiscalPeriodId)
|
||
const resultBeforeTax = incomeStatement.net_result
|
||
|
||
const proposals: ProposedDisposition[] = []
|
||
|
||
const existingFonder = await listExistingPeriodiseringsfonder(supabase, companyId, period.period_end)
|
||
const ateforing = proposeAteforing(existingFonder, {
|
||
schablonintaktRate: DEFAULT_SCHABLONINTAKT_RATE,
|
||
})
|
||
proposals.push(...ateforing.proposals)
|
||
|
||
const taxableBeforeAvsattning =
|
||
resultBeforeTax +
|
||
ateforing.proposals.reduce((sum, p) => sum + p.amount, 0) +
|
||
ateforing.schablonintaktAmount
|
||
const avsattning = proposeAvsattning({
|
||
skattemassigtResultatBeforeAvsattning: taxableBeforeAvsattning,
|
||
fiscalYear,
|
||
})
|
||
if (avsattning) proposals.push(avsattning)
|
||
|
||
const slp = await calculateSarskildLoneskatt(supabase, companyId, fiscalPeriodId)
|
||
if (slp) proposals.push(slp)
|
||
|
||
// Bolagsskatt must be computed on the result AFTER the dispositions above.
|
||
// In preview mode nothing is posted yet, so the income statement still shows
|
||
// the pre-disposition result — we mirror each proposal's effect on resultat
|
||
// före skatt and hand the post-disposition base to the calculator:
|
||
// + återföring (8819, intäkt)
|
||
// − avsättning (8811, kostnad)
|
||
// − SLP (7533, kostnad)
|
||
// Without this, the previewed tax ignores the avsättning (tax too high) and
|
||
// diverges from what the sequential commit books and from ÅR/INK2.
|
||
const ateforingTotal = ateforing.proposals.reduce((sum, p) => sum + p.amount, 0)
|
||
const resultAfterDispositions =
|
||
resultBeforeTax + ateforingTotal - (avsattning?.amount ?? 0) - (slp?.amount ?? 0)
|
||
|
||
const bolagsskatt = await calculateBolagsskatt(supabase, companyId, fiscalPeriodId, {
|
||
resultBeforeTaxOverride: resultAfterDispositions,
|
||
manualAdjustments: {
|
||
schablonintaktPeriodiseringsfond: ateforing.schablonintaktAmount,
|
||
},
|
||
})
|
||
if (bolagsskatt) proposals.push(bolagsskatt)
|
||
|
||
// K3 only: split obeskattade reserver into the 79.4 % equity portion and
|
||
// the 20.6 % uppskjuten skatteskuld. We sum the projected 21xx balance
|
||
// AFTER the dispositions above have been applied so the latent-tax
|
||
// amount reflects the closing position — anything else would diverge
|
||
// from the BR the user sees in the preview.
|
||
if (accountingFramework === 'k3') {
|
||
const latentTax = await buildLatentTaxProposal({
|
||
supabase,
|
||
companyId,
|
||
fiscalPeriodId,
|
||
proposalsBeforeLatentTax: proposals,
|
||
})
|
||
if (latentTax) proposals.push(latentTax)
|
||
}
|
||
|
||
return {
|
||
entityType,
|
||
fiscalPeriod: period,
|
||
netResultBefore: resultBeforeTax,
|
||
proposals,
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Compose the K3 uppskjuten-skatt proposal.
|
||
*
|
||
* The latent tax provision must reflect the *closing* obeskattade-reserver
|
||
* balance, so we pull the current 21xx balance from the trial balance and
|
||
* adjust it for any 21xx-touching dispositions that haven't yet posted
|
||
* (avsättning ↑, återföring ↓). 2240's current balance is the existing
|
||
* provision; the delta becomes the new verifikat.
|
||
*/
|
||
export async function buildLatentTaxProposal(params: {
|
||
supabase: SupabaseClient
|
||
companyId: string
|
||
fiscalPeriodId: string
|
||
/** Optional — additional 21xx-touching dispositions that have NOT yet been
|
||
* posted but will be in the same batch. The TB already reflects everything
|
||
* posted, so leave this empty if the latent-tax run is sequenced after the
|
||
* 21xx postings (the API route's case). */
|
||
proposalsBeforeLatentTax?: ProposedDisposition[]
|
||
}): Promise<ProposedDisposition | null> {
|
||
const { supabase, companyId, fiscalPeriodId, proposalsBeforeLatentTax = [] } = params
|
||
|
||
const tb = await generateTrialBalance(supabase, companyId, fiscalPeriodId)
|
||
|
||
// 21xx — obeskattade reserver (credit-normal, so we measure credit − debit).
|
||
let untaxedReserves = tb.rows
|
||
.filter((r) => r.account_number.startsWith('21'))
|
||
.reduce((s, r) => s + (r.closing_credit - r.closing_debit), 0)
|
||
|
||
// Pending 21xx postings from the proposals that will commit alongside
|
||
// latent tax. Avsättning adds to the reserves (credit 21xx), återföring
|
||
// removes (debit 21xx).
|
||
for (const p of proposalsBeforeLatentTax) {
|
||
if (
|
||
p.kind !== 'periodiseringsfond_avsattning'
|
||
&& p.kind !== 'periodiseringsfond_ateforing'
|
||
) continue
|
||
for (const line of p.lines) {
|
||
if (!line.account_number.startsWith('21')) continue
|
||
untaxedReserves += (line.credit_amount ?? 0) - (line.debit_amount ?? 0)
|
||
}
|
||
}
|
||
|
||
// Current 2240 balance — credit-normal. Equal to existing latent tax.
|
||
const current2240 = tb.rows
|
||
.filter((r) => r.account_number === LATENT_TAX_LIABILITY_ACCOUNT)
|
||
.reduce((s, r) => s + (r.closing_credit - r.closing_debit), 0)
|
||
|
||
const split = computeLatentTax({ untaxedReserves })
|
||
const lines = proposeLatentTaxChange(current2240, split.liabilityPortion)
|
||
if (!lines) return null
|
||
|
||
const delta = Math.round((split.liabilityPortion - current2240) * 100) / 100
|
||
const amount = Math.abs(delta)
|
||
const direction = delta > 0 ? 'avsättning' : 'återföring'
|
||
|
||
return {
|
||
kind: 'uppskjuten_skatt',
|
||
label: 'Uppskjuten skatt (K3)',
|
||
description:
|
||
delta > 0
|
||
? `Avsättning till uppskjuten skatteskuld 20,6 % av obeskattade reserver. Debet ${LATENT_TAX_EXPENSE_ACCOUNT}, kredit ${LATENT_TAX_LIABILITY_ACCOUNT}.`
|
||
: `Återföring av uppskjuten skatteskuld när obeskattade reserver minskar. Debet ${LATENT_TAX_LIABILITY_ACCOUNT}, kredit ${LATENT_TAX_EXPENSE_ACCOUNT}.`,
|
||
amount,
|
||
lines,
|
||
warnings: [],
|
||
computation: {
|
||
untaxedReserves,
|
||
taxRate: 0.206,
|
||
target2240: split.liabilityPortion,
|
||
current2240,
|
||
delta,
|
||
direction,
|
||
equityPortion: split.equityPortion,
|
||
},
|
||
}
|
||
}
|