* 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:
co-authored by
Claude Fable 5.1
parent
1157ff1b66
commit
26e29f47bc
@@ -75,7 +75,7 @@ describe('distributeOre', () => {
|
||||
|
||||
describe('buildCutoffLines: fordringar', () => {
|
||||
it('books the receivable against revenue and VILANDE output moms', () => {
|
||||
const { receivableLines } = buildCutoffLines([receivable()], [])
|
||||
const { receivableLines } = buildCutoffLines([receivable()], [], 'aktiebolag')
|
||||
|
||||
const debit = receivableLines.find((l) => l.debit_amount > 0)
|
||||
expect(debit?.account_number).toBe('1510')
|
||||
@@ -98,6 +98,7 @@ describe('buildCutoffLines: fordringar', () => {
|
||||
receivable({ id: 'c', outstanding: 106, vat: 6, vatTreatment: 'reduced_6' }),
|
||||
],
|
||||
[],
|
||||
'aktiebolag',
|
||||
)
|
||||
const totals = sum(receivableLines)
|
||||
expect(totals.debit).toBe(totals.credit)
|
||||
@@ -110,6 +111,7 @@ describe('buildCutoffLines: fordringar', () => {
|
||||
const { receivableLines } = buildCutoffLines(
|
||||
[receivable({ outstanding: 1000.01, vat: 200.003 })],
|
||||
[],
|
||||
'aktiebolag',
|
||||
)
|
||||
const totals = sum(receivableLines)
|
||||
expect(totals.debit).toBe(totals.credit)
|
||||
@@ -122,6 +124,7 @@ describe('buildCutoffLines: fordringar', () => {
|
||||
receivable({ id: 'b', outstanding: 1120, vat: 120, vatTreatment: 'reduced_12' }),
|
||||
],
|
||||
[],
|
||||
'aktiebolag',
|
||||
)
|
||||
expect(receivableLines.find((l) => l.account_number === VILANDE_OUTPUT_VAT_ACCOUNTS.standard_25)).toBeDefined()
|
||||
expect(receivableLines.find((l) => l.account_number === VILANDE_OUTPUT_VAT_ACCOUNTS.reduced_12)).toBeDefined()
|
||||
@@ -133,6 +136,7 @@ describe('buildCutoffLines: fordringar', () => {
|
||||
const { receivableLines } = buildCutoffLines(
|
||||
[receivable({ vatTreatment: 'export', outstanding: 5000, vat: 0 })],
|
||||
[],
|
||||
'aktiebolag',
|
||||
)
|
||||
expect(receivableLines.some((l) => l.account_number.startsWith('26'))).toBe(false)
|
||||
expect(receivableLines.find((l) => l.account_number === '3305')?.credit_amount).toBe(5000)
|
||||
@@ -147,6 +151,7 @@ describe('buildCutoffLines: fordringar', () => {
|
||||
const { receivableLines } = buildCutoffLines(
|
||||
[receivable({ vatTreatment: 'export', outstanding: 5000, vat: 100 })],
|
||||
[],
|
||||
'aktiebolag',
|
||||
)
|
||||
const totals = sum(receivableLines)
|
||||
expect(totals.debit).toBe(totals.credit)
|
||||
@@ -154,14 +159,14 @@ describe('buildCutoffLines: fordringar', () => {
|
||||
})
|
||||
|
||||
it('emits nothing when there is nothing outstanding', () => {
|
||||
expect(buildCutoffLines([], []).receivableLines).toEqual([])
|
||||
expect(buildCutoffLines([receivable({ outstanding: 0, vat: 0 })], []).receivableLines).toEqual([])
|
||||
expect(buildCutoffLines([], [], 'aktiebolag').receivableLines).toEqual([])
|
||||
expect(buildCutoffLines([receivable({ outstanding: 0, vat: 0 })], [], 'aktiebolag').receivableLines).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildCutoffLines: skulder', () => {
|
||||
it('books the payable against expense and VILANDE input moms', () => {
|
||||
const { payableLines } = buildCutoffLines([], [payable()])
|
||||
const { payableLines } = buildCutoffLines([], [payable()], 'aktiebolag')
|
||||
|
||||
const credit = payableLines.find((l) => l.credit_amount > 0)
|
||||
expect(credit?.account_number).toBe('2440')
|
||||
@@ -188,6 +193,7 @@ describe('buildCutoffLines: skulder', () => {
|
||||
],
|
||||
}),
|
||||
],
|
||||
'aktiebolag',
|
||||
)
|
||||
const totals = sum(payableLines)
|
||||
expect(totals.debit).toBe(totals.credit)
|
||||
@@ -209,6 +215,7 @@ describe('buildCutoffLines: skulder', () => {
|
||||
],
|
||||
}),
|
||||
],
|
||||
'aktiebolag',
|
||||
)
|
||||
const totals = sum(payableLines)
|
||||
expect(totals.debit).toBe(totals.credit)
|
||||
@@ -216,7 +223,7 @@ describe('buildCutoffLines: skulder', () => {
|
||||
})
|
||||
|
||||
it('falls back to a generic expense account when item detail is missing', () => {
|
||||
const { payableLines } = buildCutoffLines([], [payable({ netByAccount: [] })])
|
||||
const { payableLines } = buildCutoffLines([], [payable({ netByAccount: [] })], 'aktiebolag')
|
||||
expect(payableLines.find((l) => l.account_number === '6990')?.debit_amount).toBe(1000)
|
||||
const totals = sum(payableLines)
|
||||
expect(totals.debit).toBe(totals.credit)
|
||||
@@ -226,6 +233,7 @@ describe('buildCutoffLines: skulder', () => {
|
||||
const lines = buildCutoffLines(
|
||||
[receivable({ outstanding: -1250, vat: -250 })],
|
||||
[payable({ outstanding: -1250, vat: -250 })],
|
||||
'aktiebolag',
|
||||
)
|
||||
expect(lines.receivableLines.find((line) => line.account_number === '1510')).toMatchObject({
|
||||
debit_amount: 0,
|
||||
@@ -250,7 +258,7 @@ describe('buildCutoffLines: skulder', () => {
|
||||
|
||||
describe('reverseLines', () => {
|
||||
it('swaps every debit and credit so the vändning nets to zero', () => {
|
||||
const { receivableLines } = buildCutoffLines([receivable()], [])
|
||||
const { receivableLines } = buildCutoffLines([receivable()], [], 'aktiebolag')
|
||||
const reversed = reverseLines(receivableLines)
|
||||
|
||||
const original = sum(receivableLines)
|
||||
@@ -374,7 +382,7 @@ describe('cut-off snapshot and posting inspection', () => {
|
||||
})
|
||||
|
||||
it('requires exact cut-off lines and exact next-period reversals', async () => {
|
||||
const lines = buildCutoffLines([receivable()], [payable()])
|
||||
const lines = buildCutoffLines([receivable()], [payable()], 'aktiebolag')
|
||||
const rows = [
|
||||
{
|
||||
id: 'ar', fiscal_period_id: 'fp-1',
|
||||
@@ -413,7 +421,7 @@ describe('cut-off snapshot and posting inspection', () => {
|
||||
})
|
||||
|
||||
it('treats a single stale immutable marker as a conflict', async () => {
|
||||
const lines = buildCutoffLines([receivable()], [])
|
||||
const lines = buildCutoffLines([receivable()], [], 'aktiebolag')
|
||||
const stale = lines.receivableLines.map((line) =>
|
||||
line.account_number === '1510' ? { ...line, debit_amount: 999 } : line,
|
||||
)
|
||||
@@ -439,7 +447,7 @@ describe('cut-off snapshot and posting inspection', () => {
|
||||
})
|
||||
|
||||
it('treats an otherwise exact marker on the wrong date as a conflict', async () => {
|
||||
const lines = buildCutoffLines([receivable()], [])
|
||||
const lines = buildCutoffLines([receivable()], [], 'aktiebolag')
|
||||
const status = await inspectKontantmetodCutoffPostings(
|
||||
makeJournalSupabase([{
|
||||
id: 'ar',
|
||||
@@ -456,7 +464,7 @@ describe('cut-off snapshot and posting inspection', () => {
|
||||
})
|
||||
|
||||
it('treats multiple exact markers as a duplicate conflict', async () => {
|
||||
const lines = buildCutoffLines([receivable()], [])
|
||||
const lines = buildCutoffLines([receivable()], [], 'aktiebolag')
|
||||
const rows = [
|
||||
{
|
||||
id: 'ar', fiscal_period_id: 'fp-1',
|
||||
@@ -487,7 +495,7 @@ describe('cut-off snapshot and posting inspection', () => {
|
||||
await expect(
|
||||
inspectKontantmetodCutoffPostings(
|
||||
makeJournalSupabase([], { message: 'connection lost' }),
|
||||
'co-1', 'fp-1', 'fp-2', '2026-12-31', buildCutoffLines([], []),
|
||||
'co-1', 'fp-1', 'fp-2', '2026-12-31', buildCutoffLines([], [], 'aktiebolag'),
|
||||
),
|
||||
).rejects.toThrow(/kunde inte kontrolleras/i)
|
||||
})
|
||||
@@ -626,7 +634,7 @@ describe('collectKontantmetodCutoff', () => {
|
||||
invoice_payments: paymentOf(17500),
|
||||
}) as never, 'co-1', '2026-01-01', '2026-12-31')
|
||||
expect(result.receivables).toEqual([])
|
||||
expect(buildCutoffLines(result.receivables, []).receivableLines).toEqual([])
|
||||
expect(buildCutoffLines(result.receivables, [], 'aktiebolag').receivableLines).toEqual([])
|
||||
})
|
||||
|
||||
it('carries only the customer residual on a part-paid ROT invoice, moms scaled by the customer share', async () => {
|
||||
@@ -639,7 +647,7 @@ describe('collectKontantmetodCutoff', () => {
|
||||
expect(result.receivables).toEqual([
|
||||
expect.objectContaining({ id: 'inv-rot', outstanding: 7500, vat: 2142.86 }),
|
||||
])
|
||||
const { receivableLines } = buildCutoffLines(result.receivables, [])
|
||||
const { receivableLines } = buildCutoffLines(result.receivables, [], 'aktiebolag')
|
||||
expect(receivableLines.find((l) => l.account_number === '1510')?.debit_amount).toBe(7500)
|
||||
expect(receivableLines.find((l) => l.account_number === '2618')?.credit_amount).toBe(2142.86)
|
||||
expect(receivableLines.find((l) => l.account_number === '3001')?.credit_amount).toBe(5357.14)
|
||||
@@ -684,7 +692,7 @@ describe('collectKontantmetodCutoff', () => {
|
||||
}) as never, 'co-1', '2026-01-01', '2026-12-31')
|
||||
expect(result.receivables.map((r) => r.outstanding)).toEqual([17500, -17500])
|
||||
expect(result.receivables.map((r) => r.vat)).toEqual([5000, -5000])
|
||||
expect(buildCutoffLines(result.receivables, []).receivableLines).toEqual([])
|
||||
expect(buildCutoffLines(result.receivables, [], 'aktiebolag').receivableLines).toEqual([])
|
||||
})
|
||||
|
||||
it('leaves a plain invoice with the same figures exactly as before', async () => {
|
||||
@@ -701,7 +709,7 @@ describe('collectKontantmetodCutoff', () => {
|
||||
expect(result.receivables).toEqual([
|
||||
expect.objectContaining({ id: 'inv-rot', outstanding: 7500, vat: 1500 }),
|
||||
])
|
||||
const { receivableLines } = buildCutoffLines(result.receivables, [])
|
||||
const { receivableLines } = buildCutoffLines(result.receivables, [], 'aktiebolag')
|
||||
expect(receivableLines.find((l) => l.account_number === '1510')?.debit_amount).toBe(7500)
|
||||
expect(receivableLines.find((l) => l.account_number === '3001')?.credit_amount).toBe(6000)
|
||||
expect(receivableLines.find((l) => l.account_number === '2618')?.credit_amount).toBe(1500)
|
||||
@@ -737,7 +745,7 @@ describe('collectKontantmetodCutoff', () => {
|
||||
supplierType: 'eu_business',
|
||||
}],
|
||||
})
|
||||
const lines = buildCutoffLines([], result.payables).payableLines
|
||||
const lines = buildCutoffLines([], result.payables, 'aktiebolag').payableLines
|
||||
expect(lines.find((line) => line.account_number === '2624')?.credit_amount).toBe(1104)
|
||||
expect(lines.find((line) => line.account_number === '2645')?.debit_amount).toBe(1104)
|
||||
expect(lines.find((line) => line.account_number === '4536')?.debit_amount).toBe(9200)
|
||||
@@ -799,7 +807,7 @@ describe('collectKontantmetodCutoff', () => {
|
||||
}) as never, 'co-1', '2026-01-01', '2026-12-31')
|
||||
expect(result.receivables.map((item) => item.outstanding)).toEqual([1250, -1250])
|
||||
expect(result.payables.map((item) => item.outstanding)).toEqual([1250, -1250])
|
||||
const lines = buildCutoffLines(result.receivables, result.payables)
|
||||
const lines = buildCutoffLines(result.receivables, result.payables, 'aktiebolag')
|
||||
expect(lines.receivableLines).toEqual([])
|
||||
expect(lines.payableLines).toEqual([])
|
||||
})
|
||||
@@ -849,6 +857,7 @@ describe('postKontantmetodCutoff', () => {
|
||||
periodEnd: '2026-12-31',
|
||||
receivables: [receivable()],
|
||||
payables: [],
|
||||
entityType: 'aktiebolag' as const,
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -933,7 +942,7 @@ describe('postKontantmetodCutoff', () => {
|
||||
id: 'existing',
|
||||
fiscal_period_id: 'fp-1',
|
||||
description: KONTANTMETOD_CUTOFF_DESCRIPTIONS.receivable,
|
||||
lines: buildCutoffLines([receivable()], []).receivableLines,
|
||||
lines: buildCutoffLines([receivable()], [], 'aktiebolag').receivableLines,
|
||||
}]),
|
||||
'co-1',
|
||||
'user-1',
|
||||
@@ -944,7 +953,7 @@ describe('postKontantmetodCutoff', () => {
|
||||
})
|
||||
|
||||
it('resumes with the missing payable pair after a prior receivable pair succeeded', async () => {
|
||||
const receivableLines = buildCutoffLines([receivable()], []).receivableLines
|
||||
const receivableLines = buildCutoffLines([receivable()], [], 'aktiebolag').receivableLines
|
||||
const existingRows = [
|
||||
{
|
||||
id: 'ar', fiscal_period_id: 'fp-1',
|
||||
@@ -1066,6 +1075,7 @@ describe('buildCutoffLines: omvänd betalningsskyldighet', () => {
|
||||
}],
|
||||
netByAccount: [{ account: '6540', amount: 1000 }],
|
||||
})],
|
||||
'aktiebolag',
|
||||
)
|
||||
expect(payableLines.some((l) => l.account_number === VILANDE_INPUT_VAT_ACCOUNT)).toBe(false)
|
||||
expect(payableLines.find((l) => l.account_number === '2645')?.debit_amount).toBe(250)
|
||||
@@ -1079,7 +1089,7 @@ describe('buildCutoffLines: omvänd betalningsskyldighet', () => {
|
||||
})
|
||||
|
||||
it('still books vilande moms for ordinary (non-RC) supplier invoices', () => {
|
||||
const { payableLines } = buildCutoffLines([], [payable({ reverseCharge: false })])
|
||||
const { payableLines } = buildCutoffLines([], [payable({ reverseCharge: false })], 'aktiebolag')
|
||||
expect(payableLines.find((l) => l.account_number === VILANDE_INPUT_VAT_ACCOUNT)?.debit_amount).toBe(250)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -66,6 +66,26 @@ beforeEach(() => {
|
||||
})
|
||||
|
||||
describe('generateResultAppropriation', () => {
|
||||
it('posts Dr 2069 / Cr 2068 for an ideell förening profit', async () => {
|
||||
results = [{ data: { entity_type: 'ideell_forening' }, error: null }, NO_EXISTING, PERIOD]
|
||||
mockOpeningBalance([{ account_number: '2069', debit: 0, credit: 25000 }])
|
||||
|
||||
const entry = await generateResultAppropriation(makeClient() as never, 'c1', 'u1', 'p1')
|
||||
|
||||
expect(entry).toEqual(FAKE_ENTRY)
|
||||
const input = vi.mocked(createJournalEntry).mock.calls[0][3] as {
|
||||
description: string
|
||||
lines: Array<{ account_number: string; debit_amount: number; credit_amount: number }>
|
||||
}
|
||||
expect(input.description).toContain('2069 → 2068')
|
||||
expect(input.lines).toContainEqual(
|
||||
expect.objectContaining({ account_number: '2069', debit_amount: 25000, credit_amount: 0 })
|
||||
)
|
||||
expect(input.lines).toContainEqual(
|
||||
expect.objectContaining({ account_number: '2068', debit_amount: 0, credit_amount: 25000 })
|
||||
)
|
||||
})
|
||||
|
||||
it('posts Dr 2099 / Cr 2098 for a profit (AB)', async () => {
|
||||
results = [AB, NO_EXISTING, PERIOD]
|
||||
mockOpeningBalance([{ account_number: '2099', debit: 0, credit: 100000 }])
|
||||
@@ -163,8 +183,8 @@ describe('generateResultAppropriation', () => {
|
||||
expect(createJournalEntry).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('defaults missing company_settings to aktiebolag and posts', async () => {
|
||||
results = [NO_EXISTING /* settings missing */, NO_EXISTING, PERIOD]
|
||||
it('falls back to companies.entity_type when company_settings is missing and posts', async () => {
|
||||
results = [NO_EXISTING /* settings missing */, AB /* companies fallback */, NO_EXISTING, PERIOD]
|
||||
mockOpeningBalance([{ account_number: '2099', debit: 0, credit: 5000 }])
|
||||
|
||||
const entry = await generateResultAppropriation(makeClient() as never, 'c1', 'u1', 'p1')
|
||||
|
||||
@@ -714,7 +714,7 @@ describe('validateYearEndReadiness: kontantmetoden cut-off gate', () => {
|
||||
const expected = buildCutoffLines([{
|
||||
id: 'inv-1', reference: 'F-1', vatTreatment: 'standard_25',
|
||||
outstanding: 1250, vat: 250,
|
||||
}], [])
|
||||
}], [], 'aktiebolag')
|
||||
const markers = [
|
||||
{
|
||||
id: 'cutoff', company_id: 'company-1', fiscal_period_id: 'fp-1',
|
||||
|
||||
@@ -231,7 +231,7 @@ function signedLine(
|
||||
export function buildCutoffLines(
|
||||
receivables: CutoffReceivable[],
|
||||
payables: CutoffPayable[],
|
||||
entityType: EntityType = 'aktiebolag',
|
||||
entityType: EntityType,
|
||||
): CutoffLines {
|
||||
const receivableLines: CreateJournalEntryLineInput[] = []
|
||||
const payableLines: CreateJournalEntryLineInput[] = []
|
||||
@@ -959,7 +959,7 @@ export async function assessKontantmetodCutoff(
|
||||
companyId: string,
|
||||
period: { id: string; period_start: string; period_end: string },
|
||||
nextFiscalPeriodId: string,
|
||||
entityType: EntityType = 'aktiebolag',
|
||||
entityType: EntityType,
|
||||
): Promise<KontantmetodCutoffAssessment> {
|
||||
const collection = sortedCutoffCollection(await collectKontantmetodCutoff(
|
||||
supabase,
|
||||
@@ -1069,7 +1069,7 @@ export async function postKontantmetodCutoff(
|
||||
periodEnd: string
|
||||
receivables: CutoffReceivable[]
|
||||
payables: CutoffPayable[]
|
||||
entityType?: EntityType
|
||||
entityType: EntityType
|
||||
/** Refuse if any invoice lacked a vat_treatment (see CutoffCollection). */
|
||||
unknownVatTreatment?: string[]
|
||||
/** Refuse if any invoice carried moms on a zero-rate treatment. */
|
||||
|
||||
@@ -171,7 +171,9 @@ export function classifyHistoricalResultRepair(
|
||||
reason: Exclude<HistoricalResultRepairReason, 'ready'>,
|
||||
): HistoricalResultRepairAssessment => ({ ...base, status, reason, plan: null })
|
||||
|
||||
if ((snapshot.entityType ?? 'aktiebolag') !== 'aktiebolag') {
|
||||
// An unknown form is NOT assumed to be an aktiebolag: the repair only ever
|
||||
// applies to the 2099 -> 2098 chain, so anything else is skipped.
|
||||
if (snapshot.entityType !== 'aktiebolag') {
|
||||
return finish('skipped', 'non_aktiebolag')
|
||||
}
|
||||
if (snapshot.isClosed) return finish('skipped', 'period_closed')
|
||||
@@ -276,7 +278,7 @@ export async function assessHistoricalResultRepair(
|
||||
}
|
||||
|
||||
if (
|
||||
(baseSnapshot.entityType ?? 'aktiebolag') !== 'aktiebolag' ||
|
||||
baseSnapshot.entityType !== 'aktiebolag' ||
|
||||
baseSnapshot.isClosed ||
|
||||
baseSnapshot.lockedAt ||
|
||||
baseSnapshot.existingPostedAppropriation ||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
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'
|
||||
@@ -17,9 +18,13 @@ export interface ResultAppropriationPlan {
|
||||
periodName: string
|
||||
/** entry_date for the omföring: the new period's first day. */
|
||||
periodStart: string
|
||||
/** Net 2099 balance, credit-positive (a profit is > 0, a loss is < 0). */
|
||||
/** 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 2099 and 2098. */
|
||||
/** Absolute, öre-rounded amount that moves between the two accounts. */
|
||||
amount: number
|
||||
direction: 'profit' | 'loss'
|
||||
/** Balanced lines for the omföring verifikat. */
|
||||
@@ -55,8 +60,14 @@ export async function planResultAppropriation(
|
||||
.select('entity_type')
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
const entityType = settings?.entity_type ?? 'aktiebolag'
|
||||
if (entityType !== 'aktiebolag') return null
|
||||
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
|
||||
@@ -91,38 +102,38 @@ export async function planResultAppropriation(
|
||||
// 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 ib2099 = balances.get(RESULT_ACCOUNT)
|
||||
const net = ib2099 ? roundOre(ib2099.credit - ib2099.debit) : 0
|
||||
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 2099 onto 2098.
|
||||
// Profit: move the credit balance off the result account onto the carry.
|
||||
{
|
||||
account_number: RESULT_ACCOUNT,
|
||||
account_number: resultAccount,
|
||||
debit_amount: amount,
|
||||
credit_amount: 0,
|
||||
line_description: 'Omföring av föregående års resultat',
|
||||
},
|
||||
{
|
||||
account_number: PRIOR_RESULT_ACCOUNT,
|
||||
account_number: priorResultAccount,
|
||||
debit_amount: 0,
|
||||
credit_amount: amount,
|
||||
line_description: 'Föregående års resultat',
|
||||
},
|
||||
]
|
||||
: [
|
||||
// Loss: move the debit balance off 2099 onto 2098.
|
||||
// Loss: move the debit balance off the result account onto the carry.
|
||||
{
|
||||
account_number: PRIOR_RESULT_ACCOUNT,
|
||||
account_number: priorResultAccount,
|
||||
debit_amount: amount,
|
||||
credit_amount: 0,
|
||||
line_description: 'Föregående års resultat',
|
||||
},
|
||||
{
|
||||
account_number: RESULT_ACCOUNT,
|
||||
account_number: resultAccount,
|
||||
debit_amount: 0,
|
||||
credit_amount: amount,
|
||||
line_description: 'Omföring av föregående års resultat',
|
||||
@@ -133,6 +144,8 @@ export async function planResultAppropriation(
|
||||
periodId,
|
||||
periodName: period.name,
|
||||
periodStart: period.period_start,
|
||||
resultAccount,
|
||||
priorResultAccount,
|
||||
net,
|
||||
amount,
|
||||
direction: net > 0 ? 'profit' : 'loss',
|
||||
@@ -178,7 +191,7 @@ export async function generateResultAppropriation(
|
||||
const entry = await createJournalEntry(supabase, companyId, userId, {
|
||||
fiscal_period_id: periodId,
|
||||
entry_date: plan.periodStart,
|
||||
description: `Omföring av föregående års resultat (${RESULT_ACCOUNT} → ${PRIOR_RESULT_ACCOUNT})`,
|
||||
description: `Omföring av föregående års resultat (${plan.resultAccount} → ${plan.priorResultAccount})`,
|
||||
source_type: 'result_appropriation',
|
||||
voucher_series: 'A',
|
||||
lines: plan.lines,
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
} from '@/lib/bookkeeping/currency-revaluation'
|
||||
import { validateBalanceContinuity } from '@/lib/reports/continuity-check'
|
||||
import { assessKontantmetodCutoff } from './kontantmetod-cutoff'
|
||||
import { resolveCompanyEntityType, resultClosingAccounts } from '@/lib/company/entity-type'
|
||||
import type {
|
||||
YearEndValidation,
|
||||
YearEndBlocker,
|
||||
@@ -368,7 +369,7 @@ export async function validateYearEndReadiness(
|
||||
companyId,
|
||||
period,
|
||||
nextPeriod.id,
|
||||
settings.entity_type ?? 'aktiebolag',
|
||||
await resolveCompanyEntityType(supabase, companyId, settings.entity_type),
|
||||
)
|
||||
const invalidCount =
|
||||
assessment.collection.unknownVatTreatment.length +
|
||||
@@ -465,12 +466,8 @@ export async function previewYearEndClosing(
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
const entityType = settings?.entity_type ?? 'aktiebolag'
|
||||
const closingAccount = entityType === 'enskild_firma' ? '2010' : '2099'
|
||||
const closingAccountName =
|
||||
entityType === 'enskild_firma'
|
||||
? 'Eget kapital'
|
||||
: 'Årets resultat'
|
||||
const entityType = await resolveCompanyEntityType(supabase, companyId, settings?.entity_type)
|
||||
const { closing: closingAccount, closingName: closingAccountName } = resultClosingAccounts(entityType)
|
||||
|
||||
// Get trial balance for individual account balances in class 3-8
|
||||
const { rows } = await generateTrialBalance(supabase, companyId, fiscalPeriodId, { closingEntry: 'include' })
|
||||
|
||||
Reference in New Issue
Block a user