* fix(copy): make K3, leasing and year-end claims match what the code does
Follow-up to the batch that removed the uppskjuten-skatt posting on
obeskattade reserver (K3 29.37 gross in juridisk person) and added the K2
asset-account gate. Six user-facing strings still described the old
behaviour or made claims the code cannot support.
1. Arsredovisning page: the K3 explainer promised an uppskjuten skatt-not
and a materiella anlaggningstillgangar-not in every K3 document. Both
are conditional (a 2240/8940 balance, assets in the register) and the
first is now absent in the normal case. The kassaflodesanalys is
dropped with a warning when it cannot be generated, so it is named
only when the document actually carries one.
2. Regelverk settings: kassaflodesanalys was presented as following from
K3. It follows from being ett storre foretag
(swedish-year-end-closing/references/reporting-and-filing.md:10,
legal-framework.md:42); the copy now says the product includes one and
states the storre-foretag rule separately. Komponentavskrivning was
presented as optional under K3; it is mandatory where component useful
lives differ materially (k2-vs-k3.md:5, asset-accounting
references/depreciation.md:33).
3. Note 1 and the Uppskjutna skatter-not no longer claim the 2240 balance
is hanforlig till obeskattade reserver. deriveLatentTaxMovement reads
the 2240/8940 balances only, and under K3 that account carries deferred
tax on all temporary differences (k2-vs-k3.md:11-13).
4. The deferredTax 'unknown' branch emitted the gross-reserve statement,
which is the denial phrased positively: the same affirmative claim
about books that could not be read. It now emits no deferred-tax
paragraph at all; build-data already warns on that path.
5. Capitalized-lease detection looked at 1260/1269 only. On the shipped
BAS 2026 chart 1260 is a free inventarier account and 1269 is ack.
avskrivningar pa datorer, so owned computers were reported as leased,
while 1217/1227 (finansiellt leasade) were missed. Detection now reads
the company's own account names in kontogrupp 12, which is where BAS
keeps capitalized leases (leasing-and-disposal.md:28) and which owned
inventarier on 1220 never matches. 1720 forutbetalda leasingavgifter
stays out: that is the operational treatment.
6a. gnubok_year_end_readiness listed FX revaluation as a blocker (it is a
warning) and omitted UNBOOKED_TRANSACTIONS, the common one. The
description now names every actionable blocker kind, within the
280-char budget, and a test pins it against YEAR_END_BLOCKER_KIND.
6b. companies.accounting_framework defaults to 'k2', so every enskild
firma hit the K2 asset gate and was handed a BFNAR 2016:10 punkt 10.4
citation plus a K3 remedy it cannot take: a sole trader prepares ett
forenklat arsbokslut, not an arsredovisning (legal-framework.md:29,
:48). entity_type now rides along on the companies read the routes
already do, and non-AB entities get wording with no citation and no
K3, keeping the 1090 remedy. The K1 counterpart of punkt 10.4 is not
sourced in the repo skills, so nothing was invented in its place.
* fix(copy): close the review findings on the copy-truth sweep
Three follow-ups from the source and code reviews. (1) The K2/K3 help text had upgraded a vague sentence into a definite boundary claim ('gransen gar vid <trosklar>'), which excludes the other routes into mandatory K3 that are live right now for this control's audience: noterade vardepapper, and from fiscal years starting after 2025-12-31 also utlandsk filial, kryptotillgangar, aktierelaterade ersattningar and fastighetsbolag. An AB in one of those categories would have read the sentence and stayed on a regelverk it may no longer use. (2) hasCapitalizedLeaseAsset compared per-side cumulative totals, so a lease acquired earlier and disposed this year still claimed the balance sheet carries a leased asset; it now compares the net balance. (3) The K3 warning enumerated a kassaflodesanalys the document may not contain, contradicting the newly conditional page copy on the same screen.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
217 lines
8.7 KiB
TypeScript
217 lines
8.7 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import { z } from 'zod'
|
|
import { withRouteContext } from '@/lib/api/with-route-context'
|
|
import { errorResponse } from '@/lib/errors/get-structured-error'
|
|
import { validateBody } from '@/lib/api/validate'
|
|
import { K3ComponentSchema } from '@/lib/api/schemas'
|
|
import {
|
|
getAsset,
|
|
updateAsset,
|
|
defaultAccountsForCategory,
|
|
} from '@/lib/bokslut/assets/asset-service'
|
|
import { validateComponents } from '@/lib/bokslut/assets/k3-components'
|
|
import {
|
|
findK2ExcludedAccount,
|
|
k2ExcludedAccountMessages,
|
|
} from '@/lib/bokslut/assets/k2-account-guard'
|
|
import type { AssetCategory, WritableDepreciationMethod } from '@/types'
|
|
|
|
const ASSET_CATEGORIES: readonly AssetCategory[] = [
|
|
'immaterial',
|
|
'building',
|
|
'land_improvement',
|
|
'machinery',
|
|
'equipment',
|
|
'vehicle',
|
|
'computer',
|
|
'other_tangible',
|
|
] as const
|
|
|
|
const DEPRECIATION_METHODS: readonly WritableDepreciationMethod[] = [
|
|
'linear',
|
|
] as const
|
|
|
|
const UpdateAssetSchema = z
|
|
.object({
|
|
name: z.string().min(1).optional(),
|
|
notes: z.string().nullable().optional(),
|
|
// Acquisition-basis corrections. The service (updateAsset) only permits
|
|
// these while the asset is neither disposed nor depreciated, returning
|
|
// ASSET_CORRECTION_BLOCKED (409) otherwise: they redefine the
|
|
// depreciation basis, so a post-posting change must go through storno.
|
|
category: z
|
|
.enum(ASSET_CATEGORIES as unknown as [AssetCategory, ...AssetCategory[]])
|
|
.optional(),
|
|
acquisition_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
|
|
acquisition_cost: z.number().positive().optional(),
|
|
salvage_value: z.number().nonnegative().optional(),
|
|
useful_life_months: z.number().int().positive().optional(),
|
|
depreciation_method: z
|
|
.enum(DEPRECIATION_METHODS as unknown as [
|
|
WritableDepreciationMethod,
|
|
...WritableDepreciationMethod[],
|
|
])
|
|
.optional(),
|
|
restvarde_target: z.null().optional(),
|
|
bas_asset_account: z.string().regex(/^\d{4}$/).optional(),
|
|
bas_accumulated_account: z.string().regex(/^\d{4}$/).optional(),
|
|
bas_expense_account: z.string().regex(/^\d{4}$/).optional(),
|
|
// K3 component depreciation. Accepting `null` lets the caller clear an
|
|
// existing breakdown (the engine then falls back to depreciation_method).
|
|
// Per-component validation runs whenever the field is set to a non-null
|
|
// value; the cross-sum check needs the asset's acquisition_cost so it runs
|
|
// in the PATCH handler below, which can read the existing row.
|
|
k3_components: z.array(K3ComponentSchema).nullable().optional(),
|
|
})
|
|
|
|
export const GET = withRouteContext(
|
|
'assets.get',
|
|
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
|
|
const { id } = await params
|
|
const { supabase, companyId, log, requestId } = ctx
|
|
try {
|
|
const asset = await getAsset(supabase, companyId, id)
|
|
if (!asset) {
|
|
return NextResponse.json({ error: { code: 'ASSET_NOT_FOUND' } }, { status: 404 })
|
|
}
|
|
return NextResponse.json({ data: asset })
|
|
} catch (err) {
|
|
return errorResponse(err, log, { requestId })
|
|
}
|
|
},
|
|
)
|
|
|
|
export const PATCH = withRouteContext(
|
|
'assets.update',
|
|
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
|
|
const { id } = await params
|
|
const { supabase, companyId, log, requestId } = ctx
|
|
const validation = await validateBody(request, UpdateAssetSchema)
|
|
if (!validation.success) return validation.response
|
|
|
|
// K3 component depreciation gating + cross-sum check.
|
|
// The Zod refinement cannot see the existing asset's acquisition_cost,
|
|
// so we do both the framework check and the sum validation here at
|
|
// route level before delegating to updateAsset().
|
|
if (validation.data.k3_components !== undefined && validation.data.k3_components !== null) {
|
|
const [{ data: company }, existing] = await Promise.all([
|
|
supabase
|
|
.from('companies')
|
|
.select('accounting_framework')
|
|
.eq('id', companyId)
|
|
.single(),
|
|
getAsset(supabase, companyId, id),
|
|
])
|
|
if (!company || company.accounting_framework !== 'k3') {
|
|
return NextResponse.json(
|
|
{
|
|
error: {
|
|
code: 'K3_REQUIRED_FOR_COMPONENTS',
|
|
message: 'Komponentuppdelning (k3_components) kräver att företaget tillämpar K3 (BFNAR 2012:1).',
|
|
},
|
|
},
|
|
{ status: 422 },
|
|
)
|
|
}
|
|
if (!existing) {
|
|
return NextResponse.json({ error: { code: 'ASSET_NOT_FOUND' } }, { status: 404 })
|
|
}
|
|
// Validate against the cost that will be in effect after this PATCH —
|
|
// a body that changes acquisition_cost and k3_components together must
|
|
// sum to the NEW cost, not the stored one.
|
|
const { errors } = validateComponents({
|
|
acquisition_cost: validation.data.acquisition_cost ?? Number(existing.acquisition_cost),
|
|
k3_components: validation.data.k3_components,
|
|
})
|
|
if (errors.length > 0) {
|
|
return NextResponse.json(
|
|
{
|
|
error: {
|
|
code: 'INVALID_K3_COMPONENTS',
|
|
message: errors.join(' '),
|
|
},
|
|
},
|
|
{ status: 400 },
|
|
)
|
|
}
|
|
}
|
|
|
|
// K2_EXCLUDED_ACCOUNT gate: when the patch touches the category or the
|
|
// asset/accumulated accounts, the asset must not END UP on an account the
|
|
// BAS reference flags as k2_excluded ("Ej K2") unless the company applies
|
|
// K3. The guard supplies the message, citing BFNAR 2016:10 punkt 10.4
|
|
// only for the egenupparbetade-immateriella group and staying generic for
|
|
// the other Ej K2 accounts (uppskjuten skatt, verkligt värde, ...), which
|
|
// this route can reach: UpdateAssetSchema has no BAS range refinement, so
|
|
// an explicit override outside the category range lands here first.
|
|
// The final accounts mirror updateAsset()'s resolution: a category
|
|
// change without explicit accounts realigns the triple to the new
|
|
// category's framework-aware defaults, so recategorizing to "Immateriell
|
|
// tillgång" lands a K2 company on the acquired pair 1090/1099 and passes.
|
|
// Only a deliberate override onto an Ej K2 account trips the gate.
|
|
// Patches that leave category and accounts alone skip the gate entirely,
|
|
// so legacy assets already sitting on an excluded account stay editable
|
|
// (name, notes, useful life, ...).
|
|
const touchesAccounts =
|
|
validation.data.category !== undefined ||
|
|
validation.data.bas_asset_account !== undefined ||
|
|
validation.data.bas_accumulated_account !== undefined
|
|
if (touchesAccounts) {
|
|
const [{ data: company }, existing] = await Promise.all([
|
|
supabase
|
|
.from('companies')
|
|
// entity_type rides along on the same fetch: the rejection wording
|
|
// must not cite BFNAR 2016:10 at an enskild firma, which prepares no
|
|
// årsredovisning under K2. See lib/bokslut/assets/k2-account-guard.ts.
|
|
.select('accounting_framework, entity_type')
|
|
.eq('id', companyId)
|
|
.single(),
|
|
getAsset(supabase, companyId, id),
|
|
])
|
|
if (!company || company.accounting_framework !== 'k3') {
|
|
if (!existing) {
|
|
return NextResponse.json({ error: { code: 'ASSET_NOT_FOUND' } }, { status: 404 })
|
|
}
|
|
const finalCategory = validation.data.category ?? existing.category
|
|
const categoryDefaultsApply =
|
|
validation.data.category !== undefined &&
|
|
validation.data.category !== existing.category &&
|
|
validation.data.bas_asset_account === undefined &&
|
|
validation.data.bas_accumulated_account === undefined &&
|
|
validation.data.bas_expense_account === undefined
|
|
const defaults = defaultAccountsForCategory(
|
|
finalCategory,
|
|
company?.accounting_framework,
|
|
)
|
|
const excluded = findK2ExcludedAccount([
|
|
validation.data.bas_asset_account ??
|
|
(categoryDefaultsApply ? defaults.asset : existing.bas_asset_account),
|
|
validation.data.bas_accumulated_account ??
|
|
(categoryDefaultsApply ? defaults.accumulated : existing.bas_accumulated_account),
|
|
])
|
|
if (excluded) {
|
|
const messages = k2ExcludedAccountMessages(excluded, company?.entity_type)
|
|
return NextResponse.json(
|
|
{
|
|
error: {
|
|
code: 'K2_EXCLUDED_ACCOUNT',
|
|
message: messages.message_sv,
|
|
message_en: messages.message_en,
|
|
},
|
|
},
|
|
{ status: 422 },
|
|
)
|
|
}
|
|
}
|
|
}
|
|
|
|
try {
|
|
const asset = await updateAsset(supabase, companyId, id, validation.data)
|
|
return NextResponse.json({ data: asset })
|
|
} catch (err) {
|
|
return errorResponse(err, log, { requestId })
|
|
}
|
|
},
|
|
{ requireWrite: true },
|
|
)
|