* feat(company): ideell förening as a third legal form, behind a flag (#2072 step 1) Why the problem occurred: the legal form was modelled as a binary flag in ~300 files. `EntityType` was a two-member union, but nothing dispatched on it exhaustively: 28 sites defaulted `?? 'enskild_firma'` (invoice, categorize, match, stripe, invoice-inbox) or `?? 'aktiebolag'` (year-end, bokslut, MCP), and every form-dependent choice was an `=== 'aktiebolag' ? A : B` ternary. Widening the union compiled everywhere and changed nothing, so a förening would have booked as an enskild firma in the app and as an aktiebolag in bokslut and MCP, with no error anywhere. The lookup refused föreningar at the door (mapEntityType returned null), which is what the tester hit. What was removed or simplified: the silent defaults. One module, lib/company/entity-type.ts, now holds the list (ENTITY_TYPES), the parser (never defaults), the resolver (settings hint, then companies.entity_type, then throw) and `byEntityType`, whose Record arms make the compiler refuse the next widening until each site has an answer. The form-dependent facts (closing account, owner settlement account, calendar-year lock, default method, K1/K2 label, personnummer vs 16-prefix) live there once instead of in the ternaries. On the SQL side supported_entity_types() replaces four copies of the literal list in the create RPCs. Why this shape and not the proposed one: the tracker asked for the enum widening plus a chart; that alone was the dangerous version (compiles, books wrong). Bundling stiftelse was considered and dropped: identical plumbing but no chart block. Creation sits behind NEXT_PUBLIC_IDEELL_FORENING_ENABLED so the CHECK, RPCs and seed can ship now and the first partner is switched on without a migration; the flag goes when Phase 2 (packs, INK3, årsbokslut, Swish) lands on the tracker. Domain choices (DECISIONS.md 2026-09-08, verify with an accountant before Phase 2): result closes to 2069 with 2068 as prior-year carry; no owner accounts, member settlement on 2890; accrual default; brutet räkenskapsår allowed; K1 label for the 5 000 kr accrual threshold (BFNAR 2010:1); org number gets the 16 prefix. Migration 20260908110835 widens the three CHECK constraints, adds supported_entity_types(), re-creates the three create RPCs with the widened guard and adds the förening block to seed_chart_of_accounts. Applied to staging and covered by ideell-forening-entity-type.pg.test.ts. Part of #2072 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PdGafpUA7jVV1oYjkwfQCh * fix(company): close the förening paths the skeptic refuted (#2072) Five refutations from the /skeptic pass on 7a05c54d2, each fixed at the shared definition rather than the reported site: 1. Privately paid supplier invoices and the utlägg dialog resolved the owner account in lib/expenses/payer.ts with its own AB/EF ternary, so a förening member's invoice was built on 2893 and then refused by the expense-claim service (which already said 2890), burning an ankomstnummer. The helper now uses ownerSettlementAccount. 2. Booking templates substitute their `_ab` accounts only for an aktiebolag; the `private_expense` template kept its base 2013 for a förening. Template accounts now resolve through templateAccountForForm: EF base, AB override, förening base with owner accounts translated to 2890 (booking-templates.ts and proposal-lines.ts share it). 3. A VAT-registered förening with helårsmoms got no momsdeklaration deadline: the annual VAT rule bailed on anything but AB/EF. A förening is a juridisk person and follows the räkenskapsår schedule (SFL 26 kap 33 §), so the rule now keys on fiscalYearLockedToCalendar instead of the two literals; same in the MCP VAT report. 4. 2069 would have accumulated across years: the year-open omföring was AB-only with 2099/2098 hard-coded. planResultAppropriation now takes the pair from resultClosingAccounts (AB 2099 -> 2098, förening 2069 -> 2068) and skips forms with no carry (EF). 5. With the flag off, a registry lookup that returned "Ideell förening" was prefilled into the onboarding journey, the form picker was skipped and the create step answered "Ogiltig företagsform" with no way back. The journey, the BankID picker, the onboarding page and the MCP lookup now use mapSetupEntityType, which maps only creatable forms, so a flagged-off form falls through to the picker as before. Also: form picker keeps its AB-first order; tests for each fix. Part of #2072 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PdGafpUA7jVV1oYjkwfQCh * chore(migrations): move ideell förening migration after main's latest version (20260908143051) Two migrations landed on main after the branch forked; a lower version would be skipped by the merge-time apply. Staging history row renamed to match. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PdGafpUA7jVV1oYjkwfQCh * chore(skills): regenerate accounted-api reference for the widened entity_type enum Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PdGafpUA7jVV1oYjkwfQCh --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
211 lines
8.5 KiB
TypeScript
211 lines
8.5 KiB
TypeScript
import type { SupabaseClient } from '@supabase/supabase-js'
|
||
import { resolveCompanyEntityType, resultClosingAccounts } from '@/lib/company/entity-type'
|
||
import { createJournalEntry } from '@/lib/bookkeeping/engine'
|
||
import { getOpeningBalances } from '@/lib/reports/opening-balances'
|
||
import { roundOre, ORE_TOLERANCE } from '@/lib/bokslut/rounding'
|
||
import { createLogger } from '@/lib/logger'
|
||
import type { JournalEntry, CreateJournalEntryLineInput } from '@/types'
|
||
|
||
const log = createLogger('result-appropriation-service')
|
||
|
||
/** Årets resultat (current-year result, aktiebolag). */
|
||
export const RESULT_ACCOUNT = '2099'
|
||
/** Vinst eller förlust från föregående år. */
|
||
export const PRIOR_RESULT_ACCOUNT = '2098'
|
||
|
||
export interface ResultAppropriationPlan {
|
||
periodId: string
|
||
periodName: string
|
||
/** entry_date for the omföring: the new period's first day. */
|
||
periodStart: string
|
||
/** The form's "årets resultat" account (AB 2099, ideell förening 2069). */
|
||
resultAccount: string
|
||
/** Where last year's result is carried (AB 2098, ideell förening 2068). */
|
||
priorResultAccount: string
|
||
/** Net result-account IB balance, credit-positive (a profit is > 0, a loss is < 0). */
|
||
net: number
|
||
/** Absolute, öre-rounded amount that moves between the two accounts. */
|
||
amount: number
|
||
direction: 'profit' | 'loss'
|
||
/** Balanced lines for the omföring verifikat. */
|
||
lines: CreateJournalEntryLineInput[]
|
||
}
|
||
|
||
/**
|
||
* Read-only computation of the year-open omföring (no writes). Returns the plan
|
||
* to move 2099 "Årets resultat" onto 2098 "Vinst eller förlust från föregående
|
||
* år", or null when there is nothing to do.
|
||
*
|
||
* Returns null when:
|
||
* - the company is not an aktiebolag (enskild firma books to 2010, no 2099),
|
||
* - the period already has a POSTED result_appropriation entry (idempotency;
|
||
* a reversed one has been stornoed, no longer moves any balance, and must
|
||
* not block re-planning: the year-end undo flow reverses the omföring and
|
||
* the subsequent re-run has to be able to post a fresh one), or
|
||
* - 2099 carries no balance (within ORE_TOLERANCE).
|
||
*
|
||
* Shared by generateResultAppropriation (which posts the plan) and the
|
||
* retroactive catch-up script (which previews it in dry-run) so the preview
|
||
* and the committed entry can never diverge.
|
||
*/
|
||
export async function planResultAppropriation(
|
||
supabase: SupabaseClient,
|
||
companyId: string,
|
||
periodId: string,
|
||
): Promise<ResultAppropriationPlan | null> {
|
||
// Aktiebolag only. Same resolution as previewYearEndClosing's closing-account
|
||
// decision, so the omföring runs exactly when the result was posted to 2099.
|
||
const { data: settings } = await supabase
|
||
.from('company_settings')
|
||
.select('entity_type')
|
||
.eq('company_id', companyId)
|
||
.maybeSingle()
|
||
const entityType = await resolveCompanyEntityType(supabase, companyId, settings?.entity_type)
|
||
// Only forms that close into a dedicated "årets resultat" account carry it
|
||
// forward: AB 2099 -> 2098, ideell förening 2069 -> 2068. An enskild firma
|
||
// closes straight into 2010 and has nothing to reclassify.
|
||
const accounts = resultClosingAccounts(entityType)
|
||
if (!accounts.priorYearCarry) return null
|
||
const resultAccount = accounts.closing
|
||
const priorResultAccount = accounts.priorYearCarry
|
||
|
||
// Idempotency: never plan a second omföring for a period that already has a
|
||
// LIVE one. Deliberately posted-only: a reversed omföring is storno-cancelled
|
||
// (net zero effect on 2099), so it must not block the re-run after an
|
||
// administrative year-end undo (scripts/undo-year-end-closing.ts).
|
||
const { data: existing } = await supabase
|
||
.from('journal_entries')
|
||
.select('id')
|
||
.eq('company_id', companyId)
|
||
.eq('fiscal_period_id', periodId)
|
||
.eq('source_type', 'result_appropriation')
|
||
.eq('status', 'posted')
|
||
.limit(1)
|
||
.maybeSingle()
|
||
if (existing) return null
|
||
|
||
const { data: period } = await supabase
|
||
.from('fiscal_periods')
|
||
.select('period_start, name, opening_balance_entry_id')
|
||
.eq('id', periodId)
|
||
.eq('company_id', companyId)
|
||
.single()
|
||
if (!period) throw new Error('Fiscal period not found')
|
||
|
||
// Read 2099 from the period's INGÅENDE BALANS only: the carried-forward
|
||
// prior result that the IB entry mirrored from last year's UB: NOT the full
|
||
// trial balance. The omföring must reclassify exactly that carried amount;
|
||
// scoping to IB makes it correct even when the period already has current-year
|
||
// 2099 activity (e.g. the retroactive catch-up script running mid-year, where
|
||
// closing = IB + activity would over/under-reclassify). getOpeningBalances
|
||
// reads the committed opening_balance entry, falling back to a server-side
|
||
// aggregate of prior posted lines when none is set. credit − debit is positive
|
||
// for a profit (2099 is credit-normal).
|
||
const { balances } = await getOpeningBalances(supabase, companyId, period)
|
||
const ibResult = balances.get(resultAccount)
|
||
const net = ibResult ? roundOre(ibResult.credit - ibResult.debit) : 0
|
||
if (Math.abs(net) < ORE_TOLERANCE) return null
|
||
|
||
const amount = roundOre(Math.abs(net))
|
||
const lines: CreateJournalEntryLineInput[] =
|
||
net > 0
|
||
? [
|
||
// Profit: move the credit balance off the result account onto the carry.
|
||
{
|
||
account_number: resultAccount,
|
||
debit_amount: amount,
|
||
credit_amount: 0,
|
||
line_description: 'Omföring av föregående års resultat',
|
||
},
|
||
{
|
||
account_number: priorResultAccount,
|
||
debit_amount: 0,
|
||
credit_amount: amount,
|
||
line_description: 'Föregående års resultat',
|
||
},
|
||
]
|
||
: [
|
||
// Loss: move the debit balance off the result account onto the carry.
|
||
{
|
||
account_number: priorResultAccount,
|
||
debit_amount: amount,
|
||
credit_amount: 0,
|
||
line_description: 'Föregående års resultat',
|
||
},
|
||
{
|
||
account_number: resultAccount,
|
||
debit_amount: 0,
|
||
credit_amount: amount,
|
||
line_description: 'Omföring av föregående års resultat',
|
||
},
|
||
]
|
||
|
||
return {
|
||
periodId,
|
||
periodName: period.name,
|
||
periodStart: period.period_start,
|
||
resultAccount,
|
||
priorResultAccount,
|
||
net,
|
||
amount,
|
||
direction: net > 0 ? 'profit' : 'loss',
|
||
lines,
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Omföring av föregående års resultat: reclassify 2099 at new-year open.
|
||
*
|
||
* After a new fiscal year's opening balances are generated, account 2099
|
||
* "Årets resultat" carries the prior year's result forward (the IB entry is a
|
||
* faithful mirror of the prior period's UB). Per BAS practice the prior result
|
||
* must not remain on 2099: each year must start with 2099 = 0 so it only ever
|
||
* holds the *current* year's result. This posts the year-open reclassification
|
||
* as a SEPARATE verifikat in the new period:
|
||
*
|
||
* profit (2099 has a credit balance): Dr 2099 / Cr 2098
|
||
* loss (2099 has a debit balance): Dr 2098 / Cr 2099
|
||
*
|
||
* It is deliberately NOT folded into the opening-balance entry. The IB entry
|
||
* must stay a faithful mirror of the prior UB, or validateBalanceContinuity():
|
||
* which reads IB solely from the period's opening_balance entry, would flag
|
||
* 2099 and 2098 as discrepancies and executeYearEndClosing would self-reverse.
|
||
* A standalone entry is invisible to that check.
|
||
*
|
||
* The further disposition 2098 → 2091 (balanserat resultat) / 2898 (utdelning)
|
||
* is the bolagsstämma's decision and is intentionally left to a separate step.
|
||
*
|
||
* Idempotent / AB-only: see planResultAppropriation for the no-op conditions.
|
||
* Powers both executeYearEndClosing (steady state) and the retroactive
|
||
* catch-up script (clears any accumulated 2099 in a company's open period).
|
||
*/
|
||
export async function generateResultAppropriation(
|
||
supabase: SupabaseClient,
|
||
companyId: string,
|
||
userId: string,
|
||
periodId: string,
|
||
): Promise<JournalEntry | null> {
|
||
const plan = await planResultAppropriation(supabase, companyId, periodId)
|
||
if (!plan) return null
|
||
|
||
const entry = await createJournalEntry(supabase, companyId, userId, {
|
||
fiscal_period_id: periodId,
|
||
entry_date: plan.periodStart,
|
||
description: `Omföring av föregående års resultat (${plan.resultAccount} → ${plan.priorResultAccount})`,
|
||
source_type: 'result_appropriation',
|
||
voucher_series: 'A',
|
||
lines: plan.lines,
|
||
})
|
||
|
||
log.info('Posted result appropriation omföring', {
|
||
operation: 'result_appropriation.post',
|
||
companyId,
|
||
entityType: 'journal_entry',
|
||
entityId: entry.id,
|
||
amount: plan.amount,
|
||
direction: plan.direction,
|
||
})
|
||
|
||
return entry
|
||
}
|