feat(company): ideell förening as a third legal form, behind a flag (#2072 step 1) (#2423)

* 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>
This commit is contained in:
Mattsson
2026-09-08 14:47:50 +02:00
committed by GitHub
co-authored by Claude Fable 5.1
parent 1157ff1b66
commit 26e29f47bc
111 changed files with 1644 additions and 320 deletions
@@ -304,13 +304,14 @@ describe('POST /items/:id/suggest-booking', () => {
)
})
it('falls back to enskild firma when no entity type is stored', async () => {
it('resolves the form from companies when the settings row has none', async () => {
const mock = createQueuedMockSupabase()
mock.enqueue({
data: { id: 'item-1', matched_transaction_id: 'tx-1', created_journal_entry_id: null, created_supplier_invoice_id: null },
})
mock.enqueue({ data: transaction() })
mock.enqueue({ data: null })
mock.enqueue({ data: null }) // company_settings: no row
mock.enqueue({ data: { entity_type: 'enskild_firma' } }) // companies fallback (never a guessed default)
await route.handler(req(), buildCtx(mock.supabase))
expect(evaluateMappingRules).toHaveBeenCalledWith(
expect.anything(), 'company-1', expect.anything(), 'enskild_firma', expect.anything(),
+9 -4
View File
@@ -1,4 +1,5 @@
import type { Extension, ExtensionContext } from '@/lib/extensions/types'
import { resolveCompanyEntityType } from '@/lib/company/entity-type'
import { NextResponse } from 'next/server'
import { createServiceRoleClient } from '@/lib/supabase/service-client'
import { z } from 'zod'
@@ -3339,10 +3340,14 @@ export const invoiceInboxExtension: Extension = {
.select('entity_type')
.eq('company_id', ctx.companyId)
.maybeSingle()
// Same default as categorize-core. Leaving it undefined silently
// proposed enskild-firma accounts to aktiebolag: 2013 instead of
// 2893 for an owner expense, 6991 instead of 7610 for a course.
const entityType: EntityType = (settings?.entity_type as EntityType) || 'enskild_firma'
// Resolved, never defaulted: a guessed form proposes the wrong
// owner account (2013 vs 2893 vs 2890) and the wrong course
// account (6991 vs 7610).
const entityType: EntityType = await resolveCompanyEntityType(
ctx.supabase,
ctx.companyId,
settings?.entity_type,
)
const settlementAccount = await resolveSettlementAccount(
ctx.supabase,
@@ -78,7 +78,7 @@ beforeEach(() => {
} as never)
vi.mocked(assessKontantmetodCutoff).mockResolvedValue({
collection,
lines: buildCutoffLines(collection.receivables, collection.payables),
lines: buildCutoffLines(collection.receivables, collection.payables, 'aktiebolag'),
postings: {
complete: false, hasAny: false, receivableEntryId: null,
receivableReversalId: null, payableEntryId: null, payableReversalId: null,
@@ -140,7 +140,7 @@ describe('gnubok_post_kontantmetod_cutoff', () => {
expect(result.preview.entries.map((entry) => entry.entry_date)).toEqual([
'2026-12-31', '2027-01-01', '2026-12-31', '2027-01-01',
])
expect(result.preview.entries[0]?.lines).toEqual(buildCutoffLines(collection.receivables, []).receivableLines)
expect(result.preview.entries[0]?.lines).toEqual(buildCutoffLines(collection.receivables, [], 'aktiebolag').receivableLines)
expect(supabase.inserts).toHaveLength(1)
expect(supabase.inserts[0]).toMatchObject({
operation_type: 'post_kontantmetod_cutoff',
@@ -168,7 +168,7 @@ describe('gnubok_post_kontantmetod_cutoff', () => {
vi.mocked(assessKontantmetodCutoff).mockResolvedValueOnce({
collection: { ...collection, unknownVatTreatment: ['F-9'] },
lines: buildCutoffLines([], []),
lines: buildCutoffLines([], [], 'aktiebolag'),
postings: { complete: false, hasAny: false, receivableEntryId: null, receivableReversalId: null, payableEntryId: null, payableReversalId: null, missing: [], duplicates: [] },
})
await expect(tool.execute(
@@ -177,7 +177,7 @@ describe('gnubok_post_kontantmetod_cutoff', () => {
vi.mocked(assessKontantmetodCutoff).mockResolvedValueOnce({
collection,
lines: buildCutoffLines(collection.receivables, collection.payables),
lines: buildCutoffLines(collection.receivables, collection.payables, 'aktiebolag'),
postings: { complete: true, hasAny: true, receivableEntryId: 'je-1', receivableReversalId: 'je-2', payableEntryId: 'je-3', payableReversalId: 'je-4', missing: [], duplicates: [] },
})
await expect(tool.execute(
@@ -186,7 +186,7 @@ describe('gnubok_post_kontantmetod_cutoff', () => {
vi.mocked(assessKontantmetodCutoff).mockResolvedValueOnce({
collection: { receivables: [], payables: [], unknownVatTreatment: [], strayVatOnZeroRate: [] },
lines: buildCutoffLines([], []),
lines: buildCutoffLines([], [], 'aktiebolag'),
postings: { complete: true, hasAny: false, receivableEntryId: null, receivableReversalId: null, payableEntryId: null, payableReversalId: null, missing: [], duplicates: [] },
})
await expect(tool.execute(
+22 -14
View File
@@ -1,4 +1,13 @@
import { UUID_RE } from '@/lib/invariants/uuid'
import {
ENTITY_TYPES,
ENTITY_TYPE_LABELS_SV,
creatableEntityTypes,
fiscalYearLockedToCalendar,
isEntityType,
parseEntityType,
resolveCompanyEntityType,
} from '@/lib/company/entity-type'
import { NextResponse, after } from 'next/server'
import {
TASKS_EXTENSION_ID,
@@ -25,7 +34,7 @@ import { CompanySetupSchema, planCompanySetup } from '@/lib/company/onboarding-i
import { lookupCompanyByOrgNumber } from '@/extensions/general/tic/lib/lookup'
import { TICAPIError } from '@/extensions/general/tic/lib/tic-types'
import { normalizeOrgNumber } from '@/lib/company-lookup/normalize-org-number'
import { mapEntityType } from '@/lib/company-lookup/entity-type-map'
import { mapSetupEntityType } from '@/lib/company-lookup/entity-type-map'
import { deriveFirstYearDefaults, parseStartMonthDay } from '@/lib/company/first-year-defaults'
import {
ANONYMOUS_METHODS,
@@ -1444,7 +1453,7 @@ async function categorizeTransactionCore(
.eq('company_id', companyId)
.single()
const entityType: EntityType = (settings?.entity_type as EntityType) || 'enskild_firma'
const entityType: EntityType = await resolveCompanyEntityType(supabase, companyId, settings?.entity_type)
// Build mapping
let mappingResult = buildMappingResultFromCategory(
@@ -2766,9 +2775,7 @@ export async function computeVatCloseCheck(
.eq('company_id', companyId)
.single()
const momsPeriod = (settings?.moms_period as 'monthly' | 'quarterly' | 'yearly' | null) ?? null
const entityType = settings?.entity_type === 'aktiebolag' || settings?.entity_type === 'enskild_firma'
? settings.entity_type
: null
const entityType = isEntityType(settings?.entity_type) ? settings.entity_type : null
// 3) Deadline: based on the *requested* period type, not company setting,
// so the model gets the right deadline even when querying ad-hoc periods.
// Never turn missing settings into a plausible statutory date. Monthly
@@ -2795,10 +2802,11 @@ export async function computeVatCloseCheck(
: null
const reportEndMonth = Number(end.slice(5, 7))
const reportStartMonth = reportEndMonth === 12 ? 1 : reportEndMonth + 1
const fiscalYearMatches = entityType === 'enskild_firma'
const calendarYearOnly = fiscalYearLockedToCalendar(entityType)
const fiscalYearMatches = calendarYearOnly
? reportEndMonth === 12
: configuredStartMonth === reportStartMonth
const filingMethodRequired = entityType === 'aktiebolag' && settings.vat_has_eu_trade === false
const filingMethodRequired = !calendarYearOnly && settings.vat_has_eu_trade === false
const filingProfileComplete = typeof settings.vat_has_eu_trade === 'boolean'
&& (!filingMethodRequired
|| settings.vat_filing_method === 'electronic'
@@ -3698,7 +3706,7 @@ export const tools: McpTool[] = [
const askEverything = [
'name',
'entity_type (enskild firma or aktiebolag)',
'entity_type (enskild_firma, aktiebolag or ideell_forening)',
'f_skatt',
'vat_registered (and moms_period if yes)',
'accounting_method (accrual or cash)',
@@ -3736,7 +3744,7 @@ export const tools: McpTool[] = [
}
}
const entityType = mapEntityType(lookup.legalEntityType)
const entityType = mapSetupEntityType(lookup.legalEntityType)
const warnings: string[] = []
if (lookup.isCeased) {
warnings.push(
@@ -3745,7 +3753,7 @@ export const tools: McpTool[] = [
}
if (!entityType) {
warnings.push(
`Legal form "${lookup.legalEntityType ?? 'unknown'}" is not supported for automatic setup: only enskild firma and aktiebolag can be created here.`
`Legal form "${lookup.legalEntityType ?? 'unknown'}" is not supported for automatic setup: only ${creatableEntityTypes().map((t) => ENTITY_TYPE_LABELS_SV[t]).join(', ')} can be created here.`
)
}
@@ -3757,7 +3765,7 @@ export const tools: McpTool[] = [
// accounting method are ALWAYS the user's answer.
const vatIsFact = lookup.registration.vat === true
const stillToAsk: string[] = []
if (!entityType) stillToAsk.push('entity_type (enskild firma or aktiebolag)')
if (!entityType) stillToAsk.push('entity_type (enskild_firma, aktiebolag or ideell_forening)')
if (entityType === 'enskild_firma') {
stillToAsk.push(
'name: for enskild firma the verksamhetsnamn is freely choosable; suggest the registered name but let the user pick'
@@ -3850,7 +3858,7 @@ export const tools: McpTool[] = [
additionalProperties: false,
properties: {
name: { type: 'string', minLength: 1, maxLength: 200 },
entity_type: { type: 'string', enum: ['enskild_firma', 'aktiebolag'] },
entity_type: { type: 'string', enum: [...ENTITY_TYPES] },
org_number: { type: 'string', description: '10 digits; required when VAT-registered' },
vat_registered: { type: 'boolean' },
moms_period: { type: 'string', enum: ['monthly', 'quarterly', 'yearly'], description: 'Required when vat_registered' },
@@ -17926,7 +17934,7 @@ export const tools: McpTool[] = [
companyId,
period,
nextPeriod.id,
(settings.entity_type ?? 'aktiebolag') as EntityType,
parseEntityType(settings.entity_type),
)
if (assessment.collection.unknownVatTreatment.length > 0) {
throw new Error(
@@ -17956,7 +17964,7 @@ export const tools: McpTool[] = [
}
const reversalDate = nextDay(period.period_end)
const entityType = (settings.entity_type ?? 'aktiebolag') as EntityType
const entityType = parseEntityType(settings.entity_type)
const entries = [
...(assessment.lines.receivableLines.length > 0 &&
!assessment.postings.receivableEntryId &&
+3 -2
View File
@@ -1,6 +1,7 @@
import { sleep } from '@/lib/utils'
import crypto from 'crypto'
import { z } from 'zod'
import { parseEntityType } from '@/lib/company/entity-type'
import type { SupabaseClient } from '@supabase/supabase-js'
import type { Extension, ExtensionContext } from '@/lib/extensions/types'
import { NextResponse, after } from 'next/server'
@@ -923,7 +924,7 @@ export const skatteverketExtension: Extension = {
}
const orgNumber = formatRedovisare(
settings.org_number as string,
settings.entity_type as 'enskild_firma' | 'aktiebolag'
parseEntityType(settings.entity_type)
)
const contestedForVerify = await contestedOrgNumberResponse(orgNumber)
@@ -989,7 +990,7 @@ export const skatteverketExtension: Extension = {
}
const orgNumber = formatRedovisare(
settings.org_number as string,
settings.entity_type as 'enskild_firma' | 'aktiebolag'
parseEntityType(settings.entity_type)
)
const contestedForLink = await contestedOrgNumberResponse(orgNumber)
@@ -1,6 +1,7 @@
import type { SupabaseClient } from '@supabase/supabase-js'
import { createLogger } from '@/lib/logger'
import { formatRedovisare, formatRedovisningsperiod } from '@/lib/skatteverket/format'
import { parseEntityType } from '@/lib/company/entity-type'
import { completeTaxDeadline } from '@/lib/deadlines/complete-tax-deadline'
import { agiGetKvittenser } from './agi-client'
import { resolveReadAuth } from './resolve-auth'
@@ -84,7 +85,7 @@ export async function reconcileAgiDeclaration(
const arbetsgivare = formatRedovisare(
settings.org_number as string,
settings.entity_type as 'enskild_firma' | 'aktiebolag',
parseEntityType(settings.entity_type),
)
const kvittRes = await agiGetKvittenser(resolved.auth, arbetsgivare, period)
@@ -1,4 +1,5 @@
import { type SupabaseClient } from '@supabase/supabase-js'
import { parseEntityType } from '@/lib/company/entity-type'
import { createServiceRoleClient } from '@/lib/supabase/service-client'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import { toRedovisare12 } from '@/lib/invariants/org-number'
@@ -298,7 +299,7 @@ export async function findContestedOrgNumbers(): Promise<Set<string>> {
if (!row.org_number || archivedIds.has(row.company_id)) continue
let redovisare: string
try {
redovisare = toRedovisare12(row.org_number, row.entity_type === 'enskild_firma' ? 'enskild_firma' : 'aktiebolag')
redovisare = toRedovisare12(row.org_number, parseEntityType(row.entity_type))
} catch {
continue
}
@@ -1,4 +1,5 @@
import type { SupabaseClient } from '@supabase/supabase-js'
import { resolveCompanyEntityType } from '@/lib/company/entity-type'
import { commitEntry, createDraftEntry, findFiscalPeriod } from '@/lib/bookkeeping/engine'
import { getEarliestFiscalPeriodStart } from '@/lib/core/bookkeeping/period-service'
import { getBASReference } from '@/lib/bookkeeping/bas-reference'
@@ -297,7 +298,7 @@ export async function loadRuleContext(
let primary: string | null = null
return {
rules,
entityType: (settingsResult.data?.entity_type as EntityType) ?? 'aktiebolag',
entityType: await resolveCompanyEntityType(supabase, companyId, settingsResult.data?.entity_type),
// Same signal as lib/tax/deadline-config.ts: employer_registered is the
// explicit attestation (nullable, 20260717151000; null = never attested)
// and falls back to the onboarding pays_salaries answer. An explicit
@@ -232,12 +232,13 @@ describe('syncStripeConnection', () => {
})
})
it('falls back to accrual/enskild_firma when the company has no settings row', async () => {
it('falls back to accrual and the companies.entity_type row when the company has no settings row', async () => {
stubEvents([makeEvent(makeSession())])
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: [{ id: 'spe-1' }] }) // claim insert
enqueue({ data: payableInvoice() }) // invoice by payment link
enqueue({ data: null }) // company_settings: no row (maybeSingle -> null, no error)
enqueue({ data: { entity_type: 'enskild_firma' } }) // companies: canonical form, never a guessed default
enqueue({ data: null }) // event row finalize
enqueue({ data: null }) // cursor update
+2 -1
View File
@@ -1,4 +1,5 @@
import type Stripe from 'stripe'
import { resolveCompanyEntityType } from '@/lib/company/entity-type'
import type { SupabaseClient } from '@supabase/supabase-js'
import { getStripe } from '@/lib/stripe/client'
import { eventBus } from '@/lib/events/bus'
@@ -393,7 +394,7 @@ async function processCheckoutSessionEvent(
.eq('company_id', connection.company_id)
.maybeSingle()
const accountingMethod = settings?.accounting_method || 'accrual'
const entityType = (settings?.entity_type as EntityType) || 'enskild_firma'
const entityType = await resolveCompanyEntityType(supabase, connection.company_id, settings?.entity_type)
const paymentDate = new Date(event.created * 1000).toISOString().split('T')[0]