Files
accounted/lib/bookkeeping/accruals/from-invoices.ts
T
31fba5e8f9 fix(accruals): carry origin dimensions onto dissolution entries (#1419)
* fix(accruals): carry origin dimensions onto dissolution entries

A project-tagged deferred invoice line lost its dimensions bag on every
monthly dissolution: the schedule never stored the bag, so dissolution
lines booked untagged and the per-project P&L drifted from the origin.

Persist the merged bag (invoice default_dimensions with the item bag on
top, same merge the origin generators use) on accrual_schedules and
attach it to BOTH dissolution lines: both origin generators tag the
interim 17xx/29xx line too, so per-dimension views of the interim
account keep netting to zero. Pre-existing schedules stay at '{}' and
keep today's untagged behavior; backfill is a separate follow-up.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(accruals): let dissolutions post when the tagged dimension value is archived

Carrying the origin's dimensions bag onto dissolution lines pulled every
monthly periodisering into validateEntryDimensions. With dimensions_enabled,
a project archived after the origin invoice was booked made the validator
reject the dissolution: the accrual service caught the rejection, wrote
last_error and left the installment pending forever. The remaining months of
prepaid cost would never reach 5xxx/6xxx, the interim 17xx/29xx account would
stay overstated, and the trial balance still balances, so no year-end check
fires and the arsredovisning is filed with understated cost.

Add a second, narrow exempt set (DIMENSION_VALIDATION_EXEMPT_SOURCE_TYPES =
{'accrual'}) with an isDimensionValidationExemptSource() helper, and skip the
soft registry validation for it in createDraftEntry. A dissolution is the
mechanical continuation of an already-approved, already-posted decision: the
same category as a storno, which the engine already bypasses.

The tag is kept, never stripped: an archived value still exists in the
registry and the cost genuinely belongs to that project. The rules set
(required/default/fixed) stays untouched, and the other two
validateEntryDimensions call sites keep validating: updateDraftEntry is a
user edit of an editable draft, and replaceOpeningBalanceEntry rejects any
source_type other than opening_balance.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-06 10:04:20 +02:00

212 lines
7.4 KiB
TypeScript

/**
* Bridges invoice flows to accrual schedules: after the registration/revenue
* entry is committed, every line that carries a periodisering period gets a
* schedule (+ synchronous catch-up posting for months that already began).
*
* Idempotent per line: lines already covered by a schedule are skipped, so
* event replays (supplier_invoice.confirmed) can never double-schedule.
* Failures are logged and counted, never thrown: the origin entry is already
* committed and must not be rolled back by a schedule hiccup; the caller
* surfaces a warning instead.
*/
import type { SupabaseClient } from '@supabase/supabase-js'
import type { Invoice, InvoiceItem, SupplierInvoice, SupplierInvoiceItem } from '@/types'
import { resolveSekAmount } from '@/lib/bookkeeping/currency-utils'
import { createAccrualSchedule } from '@/lib/bookkeeping/accruals/service'
import {
coerceDimensionsBag,
mergeDimensionBags,
} from '@/lib/bookkeeping/dimension-resolver'
import {
itemHasAccrual,
suggestBalanceAccount,
} from '@/lib/bookkeeping/accruals/account-suggestions'
import { getRevenueAccount } from '@/lib/bookkeeping/invoice-entries'
import { getVatTreatmentForRate } from '@/lib/invoices/vat-rules'
import type { EntityType } from '@/types'
import { createLogger } from '@/lib/logger'
const log = createLogger('bookkeeping.accruals.from-invoices')
export interface ScheduleCreationResult {
created: number
failed: number
}
export async function createSchedulesForSupplierInvoice(
supabase: SupabaseClient,
companyId: string,
userId: string,
invoice: SupplierInvoice,
items: SupplierInvoiceItem[],
originJournalEntryId: string,
): Promise<ScheduleCreationResult> {
const accrualItems = items.filter(itemHasAccrual)
const result: ScheduleCreationResult = { created: 0, failed: 0 }
if (accrualItems.length === 0) return result
const { data: existing } = await supabase
.from('accrual_schedules')
.select('supplier_invoice_item_id')
.eq('company_id', companyId)
.eq('supplier_invoice_id', invoice.id)
const covered = new Set(
((existing ?? []) as Array<{ supplier_invoice_item_id: string | null }>).map(
(row) => row.supplier_invoice_item_id,
),
)
// Same merge the registration entry used for the item's interim 17xx line
// (groupExpenseBuckets): the schedule's bag must match the origin so the
// dissolutions keep the per-dimension interim balance at zero.
const defaultDimensions = coerceDimensionsBag(invoice.default_dimensions)
for (const item of accrualItems) {
if (item.id && covered.has(item.id)) continue
try {
const totalSek =
Math.round(
resolveSekAmount(item.line_total, null, invoice.currency, invoice.exchange_rate) *
100,
) / 100
await createAccrualSchedule(
supabase,
companyId,
userId,
{
direction: 'expense',
supplierInvoiceId: invoice.id,
supplierInvoiceItemId: item.id ?? null,
balanceAccount:
item.accrual_balance_account ??
suggestBalanceAccount('expense', item.account_number),
targetAccount: item.account_number,
totalAmountSek: totalSek,
periodStart: item.accrual_period_start as string,
periodEnd: item.accrual_period_end as string,
description: `${item.description} (leverantörsfaktura ${invoice.supplier_invoice_number})`,
dimensions: mergeDimensionBags(defaultDimensions, item.dimensions),
},
{
originJournalEntryId,
// The registration entry is dated invoice_date: dissolutions may
// never precede it.
postingFloorDate: invoice.invoice_date,
},
)
result.created++
} catch (error) {
result.failed++
log.error('failed to create accrual schedule for supplier invoice line', error, {
companyId,
entityId: invoice.id,
})
}
}
return result
}
export async function createSchedulesForCustomerInvoice(
supabase: SupabaseClient,
companyId: string,
userId: string,
invoice: Invoice,
items: InvoiceItem[],
originJournalEntryId: string,
entityType: EntityType = 'enskild_firma',
): Promise<ScheduleCreationResult> {
const accrualItems = items.filter(
(item) => itemHasAccrual(item) && item.line_type !== 'text' && !item.deduction_type,
)
const result: ScheduleCreationResult = { created: 0, failed: 0 }
if (accrualItems.length === 0) return result
const { data: existing } = await supabase
.from('accrual_schedules')
.select('invoice_item_id')
.eq('company_id', companyId)
.eq('invoice_id', invoice.id)
const covered = new Set(
((existing ?? []) as Array<{ invoice_item_id: string | null }>).map(
(row) => row.invoice_item_id,
),
)
// Same merge the revenue entry used for the item's interim 29xx line
// (generatePerRateLines): item bag wins per key over the invoice default.
const defaultDimensions = coerceDimensionsBag(invoice.default_dimensions)
for (const item of accrualItems) {
if (item.id && covered.has(item.id)) continue
const target = resolveRevenueTarget(item, invoice.vat_treatment, entityType)
// reverse_charge/export lines keep their statutory account (3308/3305) so
// ruta 39/40 in the momsdeklaration stay correct: never deferred. The
// generator applies the same exclusion, so the net stays on 3308/3305.
if (target.special) continue
try {
const targetAccount = target.account
const totalSek =
Math.round(
resolveSekAmount(item.line_total, null, invoice.currency, invoice.exchange_rate) *
100,
) / 100
await createAccrualSchedule(
supabase,
companyId,
userId,
{
direction: 'revenue',
invoiceId: invoice.id,
invoiceItemId: item.id ?? null,
balanceAccount:
item.accrual_balance_account ?? suggestBalanceAccount('revenue', targetAccount),
targetAccount,
totalAmountSek: totalSek,
periodStart: item.accrual_period_start as string,
periodEnd: item.accrual_period_end as string,
description: `${item.description} (faktura ${invoice.invoice_number ?? ''})`.trim(),
dimensions: mergeDimensionBags(defaultDimensions, item.dimensions),
},
{
originJournalEntryId,
postingFloorDate: invoice.invoice_date,
},
)
result.created++
} catch (error) {
result.failed++
log.error('failed to create accrual schedule for invoice line', error, {
companyId,
entityId: invoice.id,
})
}
}
return result
}
/**
* Resolve a line's revenue account exactly the way generatePerRateLines does:
* per-line override only for ordinary domestic rates; reverse_charge/export
* force the statutory account and are flagged `special` (never deferrable).
*/
function resolveRevenueTarget(
item: InvoiceItem,
invoiceTreatment: Invoice['vat_treatment'],
entityType: EntityType,
): { account: string; special: boolean } {
const rate = item.vat_rate ?? 0
const treatment =
rate === 0 && (invoiceTreatment === 'reverse_charge' || invoiceTreatment === 'export')
? invoiceTreatment
: getVatTreatmentForRate(rate)
const special = treatment === 'reverse_charge' || treatment === 'export'
const account =
!special && item.revenue_account
? item.revenue_account
: getRevenueAccount(treatment, entityType)
return { account, special }
}