* 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>
333 lines
12 KiB
TypeScript
333 lines
12 KiB
TypeScript
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
|
import { createQueuedMockSupabase, makeInvoice } from '@/tests/helpers'
|
|
import type { SupabaseClient } from '@supabase/supabase-js'
|
|
|
|
const eventsList = vi.fn()
|
|
|
|
vi.mock('@/lib/stripe/client', () => ({
|
|
getStripe: () => ({ events: { list: eventsList } }),
|
|
}))
|
|
|
|
vi.mock('@/lib/invoices/settle-invoice-payment', () => ({
|
|
settleInvoicePayment: vi.fn(),
|
|
}))
|
|
|
|
import { settleInvoicePayment } from '@/lib/invoices/settle-invoice-payment'
|
|
import { eventBus } from '@/lib/events/bus'
|
|
import { syncStripeConnection } from '../lib/sync'
|
|
import type { StripeConnection } from '../types'
|
|
|
|
const CONNECTION: StripeConnection = {
|
|
id: 'conn-1',
|
|
company_id: 'company-1',
|
|
user_id: 'user-1',
|
|
stripe_account_id: 'acct_1',
|
|
livemode: false,
|
|
status: 'active',
|
|
oauth_state: null,
|
|
display_name: 'Test AB',
|
|
last_event_created_at: null,
|
|
last_event_id: null,
|
|
transaction_sync_enabled: false,
|
|
last_balance_txn_synced_at: null,
|
|
error_message: null,
|
|
connected_at: '2026-07-01T00:00:00.000Z',
|
|
disconnected_at: null,
|
|
created_at: '2026-07-01T00:00:00.000Z',
|
|
updated_at: '2026-07-01T00:00:00.000Z',
|
|
}
|
|
|
|
function makeSession(overrides: Record<string, unknown> = {}) {
|
|
return {
|
|
id: 'cs_1',
|
|
payment_link: 'plink_1',
|
|
payment_intent: 'pi_1',
|
|
amount_total: 125000, // 1250.00 SEK in öre
|
|
currency: 'sek',
|
|
payment_status: 'paid',
|
|
livemode: false,
|
|
metadata: { invoice_id: 'inv-1', company_id: 'company-1' },
|
|
...overrides,
|
|
}
|
|
}
|
|
|
|
function makeEvent(session: Record<string, unknown>, overrides: Record<string, unknown> = {}) {
|
|
return {
|
|
id: 'evt_1',
|
|
type: 'checkout.session.completed',
|
|
created: 1_767_000_000,
|
|
data: { object: session },
|
|
...overrides,
|
|
}
|
|
}
|
|
|
|
function stubEvents(events: unknown[]) {
|
|
eventsList.mockReturnValue({
|
|
autoPagingToArray: vi.fn().mockResolvedValue(events),
|
|
})
|
|
}
|
|
|
|
function payableInvoice(overrides: Record<string, unknown> = {}) {
|
|
return {
|
|
...makeInvoice({
|
|
id: 'inv-1',
|
|
status: 'sent',
|
|
currency: 'SEK',
|
|
total: 1250,
|
|
}),
|
|
remaining_amount: 1250,
|
|
paid_amount: 0,
|
|
stripe_payment_link_id: 'plink_1',
|
|
customer: { name: 'Kund AB' },
|
|
items: [],
|
|
...overrides,
|
|
}
|
|
}
|
|
|
|
describe('syncStripeConnection', () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
eventBus.clear()
|
|
vi.stubEnv('STRIPE_SECRET_KEY', 'sk_test_123')
|
|
vi.stubEnv('STRIPE_CONNECT_CLIENT_ID', 'ca_test_123')
|
|
vi.mocked(settleInvoicePayment).mockResolvedValue({
|
|
ok: true,
|
|
newStatus: 'paid',
|
|
newPaidAmount: 1250,
|
|
newRemaining: 0,
|
|
journalEntryId: 'je-9',
|
|
paidAt: '2026-07-12T00:00:00.000Z',
|
|
})
|
|
})
|
|
|
|
afterEach(() => {
|
|
vi.unstubAllEnvs()
|
|
})
|
|
|
|
it('settles a deterministic match against 1686 and advances the cursor', async () => {
|
|
stubEvents([makeEvent(makeSession())])
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({ data: [{ id: 'spe-1' }] }) // claim insert
|
|
enqueue({ data: payableInvoice() }) // invoice by payment link
|
|
enqueue({ data: { accounting_method: 'accrual', entity_type: 'aktiebolag' } })
|
|
enqueue({ data: null }) // event row finalize
|
|
enqueue({ data: null }) // cursor update
|
|
|
|
const summary = await syncStripeConnection(supabase as unknown as SupabaseClient, CONNECTION)
|
|
|
|
expect(summary).toMatchObject({ fetched: 1, settled: 1, needsReview: 0, ignored: 0 })
|
|
expect(vi.mocked(settleInvoicePayment)).toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
'company-1',
|
|
'user-1',
|
|
expect.objectContaining({
|
|
paymentAmountInInvoiceCurrency: 1250,
|
|
settlementAccountNumber: '1686',
|
|
accountingMethod: 'accrual',
|
|
entityType: 'aktiebolag',
|
|
paymentDate: new Date(1_767_000_000 * 1000).toISOString().split('T')[0],
|
|
}),
|
|
)
|
|
})
|
|
|
|
it('records amount drift as needs_review and never settles', async () => {
|
|
stubEvents([makeEvent(makeSession({ amount_total: 100000 }))]) // 1000 vs 1250 remaining
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({ data: [{ id: 'spe-1' }] })
|
|
enqueue({ data: payableInvoice() })
|
|
enqueue({ data: null }) // event row finalize
|
|
enqueue({ data: null }) // cursor update
|
|
|
|
const summary = await syncStripeConnection(supabase as unknown as SupabaseClient, CONNECTION)
|
|
|
|
expect(summary).toMatchObject({ settled: 0, needsReview: 1 })
|
|
expect(vi.mocked(settleInvoicePayment)).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('records an already-paid invoice as needs_review (double payment)', async () => {
|
|
stubEvents([makeEvent(makeSession())])
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({ data: [{ id: 'spe-1' }] })
|
|
enqueue({ data: payableInvoice({ status: 'paid' }) })
|
|
enqueue({ data: null })
|
|
enqueue({ data: null })
|
|
|
|
const summary = await syncStripeConnection(supabase as unknown as SupabaseClient, CONNECTION)
|
|
|
|
expect(summary.needsReview).toBe(1)
|
|
expect(vi.mocked(settleInvoicePayment)).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('records non-SEK invoices as needs_review (v1 automation scope)', async () => {
|
|
stubEvents([makeEvent(makeSession({ currency: 'eur', amount_total: 50000 }))])
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({ data: [{ id: 'spe-1' }] })
|
|
enqueue({
|
|
data: payableInvoice({ currency: 'EUR', total: 500, remaining_amount: 500 }),
|
|
})
|
|
enqueue({ data: null })
|
|
enqueue({ data: null })
|
|
|
|
const summary = await syncStripeConnection(supabase as unknown as SupabaseClient, CONNECTION)
|
|
|
|
expect(summary.needsReview).toBe(1)
|
|
expect(vi.mocked(settleInvoicePayment)).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('ignores test-mode events on a live-mode connection', async () => {
|
|
stubEvents([makeEvent(makeSession({ livemode: false }))])
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({ data: [{ id: 'spe-1' }] })
|
|
enqueue({ data: null }) // event row finalize
|
|
enqueue({ data: null }) // cursor update
|
|
|
|
const summary = await syncStripeConnection(
|
|
supabase as unknown as SupabaseClient,
|
|
{ ...CONNECTION, livemode: true },
|
|
)
|
|
|
|
expect(summary).toMatchObject({ settled: 0, needsReview: 0, ignored: 1 })
|
|
})
|
|
|
|
it('skips events already claimed by an earlier run', async () => {
|
|
stubEvents([makeEvent(makeSession())])
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({ data: [] }) // claim conflict
|
|
enqueue({ data: [] }) // reclaim: not stale
|
|
enqueue({ data: null }) // cursor update
|
|
|
|
const summary = await syncStripeConnection(supabase as unknown as SupabaseClient, CONNECTION)
|
|
|
|
expect(summary).toMatchObject({ alreadyProcessed: 1, settled: 0 })
|
|
expect(vi.mocked(settleInvoicePayment)).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('marks the connection revoked when Stripe reports severed access', async () => {
|
|
eventsList.mockReturnValue({
|
|
autoPagingToArray: vi
|
|
.fn()
|
|
.mockRejectedValue(
|
|
Object.assign(new Error('The account acct_1 is not connected to your platform'), {
|
|
type: 'StripePermissionError',
|
|
}),
|
|
),
|
|
})
|
|
const disconnected = vi.fn()
|
|
eventBus.on('stripe.disconnected', disconnected)
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({ data: null }) // connection status update
|
|
|
|
const summary = await syncStripeConnection(supabase as unknown as SupabaseClient, CONNECTION)
|
|
|
|
expect(summary.revoked).toBe(true)
|
|
expect(summary.settled).toBe(0)
|
|
// Auto-detected revocation must reach the audit trail, mirroring the
|
|
// user-initiated disconnect emission.
|
|
expect(disconnected).toHaveBeenCalledWith({
|
|
connectionId: 'conn-1',
|
|
stripeAccountId: 'acct_1',
|
|
reason: 'revoked_upstream',
|
|
userId: 'user-1',
|
|
companyId: 'company-1',
|
|
})
|
|
})
|
|
|
|
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
|
|
|
|
const summary = await syncStripeConnection(supabase as unknown as SupabaseClient, CONNECTION)
|
|
|
|
expect(summary.settled).toBe(1)
|
|
expect(vi.mocked(settleInvoicePayment)).toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
'company-1',
|
|
'user-1',
|
|
expect.objectContaining({
|
|
accountingMethod: 'accrual',
|
|
entityType: 'enskild_firma',
|
|
}),
|
|
)
|
|
})
|
|
|
|
it('stops mid-batch at the deadline and persists the cursor only over processed events', async () => {
|
|
let now = 1_000
|
|
const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now)
|
|
try {
|
|
// Settling the first event burns the remaining time budget.
|
|
vi.mocked(settleInvoicePayment).mockImplementation(async () => {
|
|
now = 10_000
|
|
return {
|
|
ok: true,
|
|
newStatus: 'paid',
|
|
newPaidAmount: 1250,
|
|
newRemaining: 0,
|
|
journalEntryId: 'je-9',
|
|
paidAt: '2026-07-12T00:00:00.000Z',
|
|
}
|
|
})
|
|
stubEvents([
|
|
makeEvent(makeSession()),
|
|
makeEvent(makeSession({ id: 'cs_2' }), { id: 'evt_2', created: 1_767_000_100 }),
|
|
])
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({ data: [{ id: 'spe-1' }] }) // claim insert (evt_1)
|
|
enqueue({ data: payableInvoice() }) // invoice by payment link
|
|
enqueue({ data: { accounting_method: 'accrual', entity_type: 'aktiebolag' } })
|
|
enqueue({ data: null }) // event row finalize (evt_1)
|
|
enqueue({ data: null }) // cursor update
|
|
|
|
const summary = await syncStripeConnection(
|
|
supabase as unknown as SupabaseClient,
|
|
CONNECTION,
|
|
undefined,
|
|
5_000, // deadline passes between the first and second event
|
|
)
|
|
|
|
expect(summary).toMatchObject({
|
|
fetched: 2,
|
|
settled: 1,
|
|
needsReview: 0,
|
|
deadlineReached: true,
|
|
})
|
|
expect(vi.mocked(settleInvoicePayment)).toHaveBeenCalledTimes(1)
|
|
// evt_2 was never claimed and the cursor advanced only over evt_1, so
|
|
// the next run refetches evt_2 (cursor overlap) and processes it then.
|
|
expect(vi.mocked(supabase.from).mock.calls.map((c) => c[0])).toEqual([
|
|
'stripe_payment_events', // claim evt_1
|
|
'invoices',
|
|
'company_settings',
|
|
'stripe_payment_events', // finalize evt_1
|
|
'stripe_connections', // cursor persisted up to evt_1
|
|
])
|
|
} finally {
|
|
nowSpy.mockRestore()
|
|
}
|
|
})
|
|
|
|
it('records a settle failure (e.g. locked period) as needs_review', async () => {
|
|
vi.mocked(settleInvoicePayment).mockResolvedValue({
|
|
ok: false,
|
|
code: 'BOOKKEEPING_ERROR',
|
|
error: new Error('Cannot write to locked/closed fiscal period'),
|
|
})
|
|
stubEvents([makeEvent(makeSession())])
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({ data: [{ id: 'spe-1' }] })
|
|
enqueue({ data: payableInvoice() })
|
|
enqueue({ data: { accounting_method: 'accrual', entity_type: 'aktiebolag' } })
|
|
enqueue({ data: null })
|
|
enqueue({ data: null })
|
|
|
|
const summary = await syncStripeConnection(supabase as unknown as SupabaseClient, CONNECTION)
|
|
|
|
expect(summary.needsReview).toBe(1)
|
|
})
|
|
})
|