Files
accounted/lib/agent/composer/fallback.ts
T
Mattsson 26e29f47bc 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>
2026-09-08 14:47:50 +02:00

137 lines
5.2 KiB
TypeScript

import type { ComposerInputs } from './inputs'
import type { AtomSelection } from './schemas'
import { ENTITY_TYPE_LABELS_SV, isEntityType } from '@/lib/company/entity-type'
// Deterministic atom selection used when the Opus call times out or fails.
//
// Per plan §7 Phase A: "Fall back to a default vertical from SNI prefix and
// a generic horizontal set (vat, invoice, year-end)". The result is good
// enough that the user can proceed; they can refine atom selection in Phase B
// or rebuild later.
//
// We pick deliberately conservatively: better to load a few extra horizontals
// than to miss one. The agent loop pays for cache, not for content; an extra
// 8k tokens of swedish-financial-reporting on a sole-trader profile is cheap
// noise, while missing swedish-vat on any Swedish company is a correctness bug.
export function fallbackAtomSelection(inputs: ComposerInputs): AtomSelection {
const knownIds = new Set(inputs.atomIndex.map((a) => a.id))
const has = (id: string) => knownIds.has(id)
const isAB = inputs.entityType === 'aktiebolag'
const isEF = inputs.entityType === 'enskild_firma'
const tic = inputs.ticSnapshot as
| {
registration?: { payroll?: boolean }
sniCodes?: { code: string; name: string }[]
employeeRange?: string | null
}
| null
const isEmployer = Boolean(tic?.registration?.payroll)
const horizontal: string[] = []
// These three apply to every Swedish business.
pushIfKnown(horizontal, 'horizontal/swedish-vat', has)
pushIfKnown(horizontal, 'horizontal/swedish-invoice-compliance', has)
pushIfKnown(horizontal, 'horizontal/swedish-year-end-closing', has)
pushIfKnown(horizontal, 'horizontal/swedish-accounting-compliance', has)
// SIE and assets are common needs across both entity types.
pushIfKnown(horizontal, 'horizontal/swedish-sie-import-export', has)
pushIfKnown(horizontal, 'horizontal/swedish-asset-accounting', has)
if (isAB) {
pushIfKnown(horizontal, 'horizontal/swedish-financial-reporting', has)
pushIfKnown(horizontal, 'horizontal/swedish-sru-filing', has)
pushIfKnown(horizontal, 'horizontal/swedish-tax-planning', has)
}
if (isEmployer) {
pushIfKnown(horizontal, 'horizontal/swedish-payroll', has)
}
// Vertical fallback: best-effort SNI-prefix match. Empty list is acceptable:
// vertical atoms are not yet authored (Phase 3).
const verticals: string[] = []
const sniCodes = tic?.sniCodes ?? []
if (sniCodes.length > 0) {
for (const atom of inputs.atomIndex) {
if (atom.tier !== 'vertical') continue
const matches = sniCodes.some((sni) =>
atom.sni_prefixes.some((prefix) => sni.code.startsWith(prefix)),
)
if (matches) verticals.push(atom.id)
}
}
// Modifier fallback: pick what we can derive from entity_type + employer flag.
const modifiers: string[] = []
if (isAB) {
pushIfKnown(modifiers, 'modifier/single-shareholder-ab-fmb', has)
}
if (isEF) {
pushIfKnown(modifiers, 'modifier/enskild-firma', has)
}
if (isEmployer) {
pushIfKnown(modifiers, 'modifier/small-employer', has)
}
return {
horizontal_atoms: horizontal,
vertical_atoms: verticals,
modifier_atoms: modifiers,
is_multi_vertical: verticals.length > 1,
verification_questions: buildFallbackQuestions(inputs),
uncertainty_notes: ['Selection produced by deterministic fallback: Opus call failed or was skipped.'],
}
}
function pushIfKnown(arr: string[], id: string, has: (id: string) => boolean) {
if (has(id)) arr.push(id)
}
function buildFallbackQuestions(inputs: ComposerInputs): string[] {
const qs: string[] = []
if (!inputs.ticSnapshot) {
qs.push('Vad är din huvudsakliga verksamhet? (några ord räcker)')
}
if (inputs.entityType === 'aktiebolag') {
qs.push('Är du ensamägare till bolaget?')
qs.push('Har bolaget anställda förutom dig?')
}
qs.push('Vilken momsperiod använder ni: månad, kvartal eller år?')
return qs
}
// Build a minimal Swedish narrative for the fallback path so Phase B has
// something to render even when the Sonnet call also failed. Mirrors the
// Sonnet prompt's voice-branching: second-person only when the user is a
// confirmed director, neutral otherwise.
export function fallbackNarrative(inputs: ComposerInputs): string {
const parts: string[] = []
const name = inputs.companyName || 'företaget'
const form = isEntityType(inputs.entityType) ? ENTITY_TYPE_LABELS_SV[inputs.entityType].toLowerCase() : null
if (inputs.userIsConfirmedDirector) {
if (form) {
parts.push(`Du driver ${name} som ${form}.`)
} else {
parts.push(`Du driver ${name}.`)
}
} else {
if (form) {
parts.push(`${name} är ${form === 'enskild firma' ? 'en enskild firma' : 'ett aktiebolag'}.`)
} else {
parts.push(`${name} är ett företag i gnubok.`)
}
}
parts.push(
'Jag har laddat de svenska reglerna som gäller bredast: moms, fakturering, bokslut och årsavslutning.',
)
parts.push(
inputs.userIsConfirmedDirector
? 'Berätta gärna lite mer om din verksamhet i nästa steg så kan jag skräddarsy stöden mer.'
: 'Berätta gärna lite mer om verksamheten i nästa steg så kan jag skräddarsy stöden mer.',
)
return parts.join(' ')
}