Files
accounted/lib/reports/opening-balances.ts
T
Jakob WennbergandClaude Sonnet 5 ec27228a8e style: remove em/en dashes repo-wide, add CLAUDE.md rule against them (#890)
Em dashes (—) and en dashes (–) had spread across comments, docs, tests,
and a few UI strings, reading as AI-generated boilerplate rather than
house style. Replaced each with punctuation matching its context: colon
for explanatory clauses, comma for asides, plain hyphen for numeric/legal
ranges (e.g. "21-23§"), "to"/"till" for date ranges, parentheses for
paired-dash asides. messages/en.json and messages/sv.json were fixed by
hand together to keep sv/en in sync.

Left untouched where the dash is the functional subject rather than
decorative punctuation: date-range-parser.ts's separator regex,
charset-repair.ts's CP1252 byte-mapping table (and its test), the SIE
encoding mojibake docs, generic-csv.ts's minus-sign normalizer, the
agent system-prompt files that already instruct against em dashes, and
a golden iXBRL test fixture compared byte-for-byte.

Also fixes two bugs surfaced along the way: an off-by-one in
ApiKeysPanel's scope-label split (a leftover from an earlier partial
pass), and a charset-repair test that had lost the literal en-dash it
exists to verify.

Regenerated the agent atom seed migration (skills:generate) since 27
SKILL.md files changed. Added a CLAUDE.md rule against em/en dashes,
with an explicit carve-out for the functional-dash cases above.

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-04 15:58:06 +02:00

94 lines
3.6 KiB
TypeScript

import type { SupabaseClient } from '@supabase/supabase-js'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
/**
* Get opening balances (ingående balans) for a fiscal period.
*
* Uses the opening_balance_entry set by year-end closing when available
* (O(accounts): typically ~50 rows). Falls back to a server-side
* aggregate via the compute_prior_opening_balances RPC when no OB entry
* is set, which returns one row per balance-sheet account (class 1-2)
* regardless of how many prior journal lines there are.
*
* Returns per-account debit/credit opening balances and the OB entry ID
* (if any) so the caller can exclude it from period queries to prevent
* double-counting.
*
* NOTE: The account range filter (accountFrom/accountTo in the GL) is
* applied post-hoc by the caller, not here. This is consistent with the
* existing behavior and avoids complicating the queries for the common
* unfiltered case.
*/
export async function getOpeningBalances(
supabase: SupabaseClient,
companyId: string,
period: { period_start: string; opening_balance_entry_id: string | null } | null
): Promise<{
balances: Map<string, { debit: number; credit: number }>
obEntryId: string | null
}> {
const balances = new Map<string, { debit: number; credit: number }>()
if (!period) {
return { balances, obEntryId: null }
}
const obEntryId = period.opening_balance_entry_id
if (obEntryId) {
// Use the explicit opening balance entry (set by year-end closing).
// Typically ~50 rows: one per balance sheet account. Uses fetchAllRows
// for consistency (avoids silent truncation) and joins journal_entries
// to enforce company_id ownership (defense in depth alongside RLS).
const obLines = await fetchAllRows<{
id: string
account_number: string
debit_amount: number
credit_amount: number
}>(({ from, to }) =>
supabase
.from('journal_entry_lines')
.select('id, account_number, debit_amount, credit_amount, journal_entries!inner(company_id)')
.eq('journal_entry_id', obEntryId)
.eq('journal_entries.company_id', companyId)
// Stable total order for correct paging (see fetch-all.ts).
.order('id', { ascending: true })
.range(from, to),
{ dedupeBy: (r) => r.id }
)
for (const line of obLines) {
const existing = balances.get(line.account_number) || { debit: 0, credit: 0 }
existing.debit += Number(line.debit_amount) || 0
existing.credit += Number(line.credit_amount) || 0
balances.set(line.account_number, existing)
}
} else {
// Fallback: server-side aggregate of all prior posted/reversed lines.
// The RPC filters to balance-sheet accounts (class 1-2) and returns
// one row per account. P&L accounts (class 3-8) reset to zero at each
// year transition: their balances are absorbed into årets resultat
// (2099) and rolled into equity, so carrying them forward as IB would
// violate BFNAR 2013:2. Filtering them in SQL keeps the payload small
// and the round-trip count at one regardless of history size.
const { data: priorRows, error } = await supabase.rpc('compute_prior_opening_balances', {
p_company_id: companyId,
p_period_start: period.period_start,
})
if (error) throw new Error(error.message)
for (const row of (priorRows ?? []) as Array<{
account_number: string
debit: number | string
credit: number | string
}>) {
balances.set(row.account_number, {
debit: Number(row.debit) || 0,
credit: Number(row.credit) || 0,
})
}
}
return { balances, obEntryId }
}