fix(import): SIE bulk-delete on service client + provider/reporting/b… (#724)
* fix(import): SIE bulk-delete on service client + provider/reporting/banking fixes Rebuilt branch onto main as a single commit. - import: run SIE bulk-delete RPCs on the service client to escape the 8s statement_timeout; undo_sie_import now takes an explicit actor (p_user_id) so its owner/admin gate works when auth.uid() is NULL on the service client (migration 20260624120000) + pg-real regression test - providers: distinguish missing Fortnox license from expired connection; provider_consent_tokens PK regression test - reports: include unmapped BAS expense groups in the income statement - enable-banking: reconnect closed/expired bank sessions in place - bookkeeping: surface linked invoices as underlag on the verifikat view - scripts: track BL cleanup/diagnostic tooling; data files (*.csv) are git-ignored and consentId is now a required arg with no silent default Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(import): add Cache-Control header to journal entry references response --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
db8983ba9e
commit
43925bc2d3
@@ -6,6 +6,7 @@ vi.mock('../trial-balance', () => ({
|
||||
|
||||
import { generateIncomeStatement } from '../income-statement'
|
||||
import { generateTrialBalance } from '../trial-balance'
|
||||
import { roundOre } from '@/lib/money'
|
||||
import type { TrialBalanceRow } from '@/types'
|
||||
|
||||
const mockTrialBalance = vi.mocked(generateTrialBalance)
|
||||
@@ -289,4 +290,71 @@ describe('generateIncomeStatement', () => {
|
||||
expect(report.financial_sections).toEqual([])
|
||||
expect(report.total_revenue).toBe(40000)
|
||||
})
|
||||
|
||||
it('includes energikostnader (group 53, e.g. 5310) in expenses and net_result — regression', async () => {
|
||||
// Regression: group '53' was missing from the expense label map, so 53xx
|
||||
// accounts (energy costs like 5310 El för drift) were silently dropped from
|
||||
// total_expenses and net_result. The Resultatrapport (which sums all class
|
||||
// 3–8 rows directly) stayed correct, which is how the discrepancy surfaced.
|
||||
mockTrialBalance.mockResolvedValue({
|
||||
rows: [
|
||||
makeRow({ account_number: '3001', account_name: 'Revenue', account_class: 3, closing_credit: 100000, closing_debit: 0 }),
|
||||
makeRow({ account_number: '5310', account_name: 'El för drift', account_class: 5, closing_debit: 18000, closing_credit: 0 }),
|
||||
],
|
||||
totalDebit: 18000,
|
||||
totalCredit: 100000,
|
||||
isBalanced: false,
|
||||
})
|
||||
|
||||
const report = await generateIncomeStatement(supabase, 'company-1', 'period-1')
|
||||
|
||||
expect(report.total_expenses).toBe(18000) // was 0 before the fix
|
||||
expect(report.net_result).toBe(82000) // was 100000 before the fix
|
||||
const expenseAccounts = report.expense_sections.flatMap((s) => s.rows.map((r) => r.account_number))
|
||||
expect(expenseAccounts).toContain('5310')
|
||||
})
|
||||
|
||||
it('routes accounts from every unmapped group (48, 53, 67) into a catch-all, never dropping them', async () => {
|
||||
mockTrialBalance.mockResolvedValue({
|
||||
rows: [
|
||||
makeRow({ account_number: '3001', account_name: 'Revenue', account_class: 3, closing_credit: 100000, closing_debit: 0 }),
|
||||
makeRow({ account_number: '4810', account_name: 'Energi råvara', account_class: 4, closing_debit: 1000, closing_credit: 0 }),
|
||||
makeRow({ account_number: '5310', account_name: 'El för drift', account_class: 5, closing_debit: 2000, closing_credit: 0 }),
|
||||
makeRow({ account_number: '6710', account_name: 'Lämnade bidrag', account_class: 6, closing_debit: 3000, closing_credit: 0 }),
|
||||
],
|
||||
totalDebit: 6000,
|
||||
totalCredit: 100000,
|
||||
isBalanced: false,
|
||||
})
|
||||
|
||||
const report = await generateIncomeStatement(supabase, 'company-1', 'period-1')
|
||||
|
||||
// All three expense accounts must be counted, regardless of label coverage.
|
||||
expect(report.total_expenses).toBe(6000)
|
||||
expect(report.net_result).toBe(94000)
|
||||
const expenseAccounts = report.expense_sections.flatMap((s) => s.rows.map((r) => r.account_number))
|
||||
expect(expenseAccounts).toEqual(expect.arrayContaining(['4810', '5310', '6710']))
|
||||
})
|
||||
|
||||
it('total_expenses equals the signed sum of every class 4–7 row (no silent drops)', async () => {
|
||||
// Structural invariant guarding the whole class of "missing group label"
|
||||
// bug: the sum of expense-section subtotals must equal Σ(debit - credit)
|
||||
// over all class 4–7 rows, mixing mapped (50, 70) and unmapped (48, 53, 67)
|
||||
// groups.
|
||||
const rows = [
|
||||
makeRow({ account_number: '5010', account_name: 'Lokalhyra', account_class: 5, closing_debit: 8000, closing_credit: 0 }),
|
||||
makeRow({ account_number: '5310', account_name: 'El för drift', account_class: 5, closing_debit: 2500, closing_credit: 0 }),
|
||||
makeRow({ account_number: '4810', account_name: 'Energi', account_class: 4, closing_debit: 1500, closing_credit: 0 }),
|
||||
makeRow({ account_number: '6710', account_name: 'Bidrag', account_class: 6, closing_debit: 500, closing_credit: 0 }),
|
||||
makeRow({ account_number: '7010', account_name: 'Löner', account_class: 7, closing_debit: 40000, closing_credit: 0 }),
|
||||
]
|
||||
mockTrialBalance.mockResolvedValue({ rows, totalDebit: 52500, totalCredit: 0, isBalanced: false })
|
||||
|
||||
const report = await generateIncomeStatement(supabase, 'company-1', 'period-1')
|
||||
|
||||
const expectedTotal = rows.reduce((sum, r) => sum + (r.closing_debit - r.closing_credit), 0)
|
||||
const sectionSum = report.expense_sections.reduce((sum, s) => sum + s.subtotal, 0)
|
||||
expect(report.total_expenses).toBe(expectedTotal) // 52500
|
||||
expect(roundOre(sectionSum)).toBe(expectedTotal)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -47,7 +47,8 @@ export async function generateIncomeStatement(
|
||||
'38': 'Aktiverat arbete',
|
||||
'39': 'Övriga rörelseintäkter',
|
||||
},
|
||||
'credit' // Revenue has credit normal balance
|
||||
'credit', // Revenue has credit normal balance
|
||||
'Övriga intäkter',
|
||||
)
|
||||
|
||||
// Expense sections (class 4-7)
|
||||
@@ -62,10 +63,12 @@ export async function generateIncomeStatement(
|
||||
'45': 'Inköp utlandet',
|
||||
'46': 'Underentreprenader och legoarbeten',
|
||||
'47': 'Erhållna rabatter',
|
||||
'48': 'Andra produktionskostnader',
|
||||
'49': 'Lagerförändringar',
|
||||
'50': 'Lokalkostnader',
|
||||
'51': 'Fastighetskostnader',
|
||||
'52': 'Hyra av tillgångar',
|
||||
'53': 'Energikostnader',
|
||||
'54': 'Förbrukningsinventarier',
|
||||
'55': 'Reparation och underhåll',
|
||||
'56': 'Transportkostnader',
|
||||
@@ -78,6 +81,7 @@ export async function generateIncomeStatement(
|
||||
'63': 'Försäkringar och riskkostnader',
|
||||
'64': 'Förvaltningskostnader',
|
||||
'65': 'Övriga externa tjänster',
|
||||
'67': 'Särskilt för ideella föreningar och stiftelser',
|
||||
'68': 'Inhyrd personal',
|
||||
'69': 'Övriga kostnader',
|
||||
'70': 'Löner kollektivanställda',
|
||||
@@ -90,7 +94,8 @@ export async function generateIncomeStatement(
|
||||
'78': 'Avskrivningar',
|
||||
'79': 'Övriga rörelsekostnader',
|
||||
},
|
||||
'debit' // Expenses have debit normal balance
|
||||
'debit', // Expenses have debit normal balance
|
||||
'Övriga kostnader',
|
||||
)
|
||||
|
||||
// Financial sections (class 8) — exclude 8999 "Årets resultat".
|
||||
@@ -112,7 +117,8 @@ export async function generateIncomeStatement(
|
||||
'88': 'Bokslutsdispositioner',
|
||||
'89': 'Skatter och årets resultat',
|
||||
},
|
||||
'mixed'
|
||||
'mixed',
|
||||
'Övriga finansiella poster',
|
||||
)
|
||||
|
||||
const totalRevenue = revenueSections.reduce((sum, s) => sum + s.subtotal, 0)
|
||||
@@ -132,31 +138,29 @@ export async function generateIncomeStatement(
|
||||
}
|
||||
|
||||
/**
|
||||
* Build report sections from trial balance rows
|
||||
* Build report sections from trial balance rows.
|
||||
*
|
||||
* Every row is assigned to exactly one section: either a known 2-digit group
|
||||
* (from `groupLabels`) or the `fallbackTitle` catch-all for any group not in
|
||||
* the map. The catch-all is what keeps the report complete — without it, an
|
||||
* account whose group code is missing from `groupLabels` (e.g. 53xx
|
||||
* energikostnader, 48xx, 67xx) would be silently dropped from both the
|
||||
* breakdown and the computed subtotal/total/net_result.
|
||||
*/
|
||||
function buildSections(
|
||||
rows: TrialBalanceRow[],
|
||||
groupLabels: Record<string, string>,
|
||||
normalBalance: 'debit' | 'credit' | 'mixed'
|
||||
normalBalance: 'debit' | 'credit' | 'mixed',
|
||||
fallbackTitle: string
|
||||
): IncomeStatementSection[] {
|
||||
const sections: IncomeStatementSection[] = []
|
||||
|
||||
for (const [groupCode, title] of Object.entries(groupLabels)) {
|
||||
const groupRows = rows.filter((r) => r.account_number.startsWith(groupCode))
|
||||
if (groupRows.length === 0) continue
|
||||
|
||||
const makeSection = (title: string, groupRows: TrialBalanceRow[]): IncomeStatementSection => {
|
||||
const sectionRows = groupRows.map((r) => {
|
||||
let amount: number
|
||||
if (normalBalance === 'credit') {
|
||||
// Revenue: credit - debit (positive = revenue)
|
||||
amount = r.closing_credit - r.closing_debit
|
||||
} else if (normalBalance === 'debit') {
|
||||
// Expense: debit - credit (positive = expense)
|
||||
amount = r.closing_debit - r.closing_credit
|
||||
} else {
|
||||
// Mixed: net balance (financial items)
|
||||
amount = r.closing_credit - r.closing_debit
|
||||
}
|
||||
// Expenses (debit) use debit - credit; revenue (credit) and financial
|
||||
// (mixed) use credit - debit.
|
||||
const amount =
|
||||
normalBalance === 'debit'
|
||||
? r.closing_debit - r.closing_credit
|
||||
: r.closing_credit - r.closing_debit
|
||||
|
||||
return {
|
||||
account_number: r.account_number,
|
||||
@@ -167,12 +171,27 @@ function buildSections(
|
||||
|
||||
const subtotal = sectionRows.reduce((sum, r) => sum + r.amount, 0)
|
||||
|
||||
sections.push({
|
||||
return {
|
||||
title,
|
||||
rows: sectionRows.filter((r) => Math.abs(r.amount) > 0.005),
|
||||
subtotal: Math.round(subtotal * 100) / 100,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const sections: IncomeStatementSection[] = []
|
||||
const matched = new Set<string>()
|
||||
|
||||
for (const [groupCode, title] of Object.entries(groupLabels)) {
|
||||
const groupRows = rows.filter((r) => r.account_number.startsWith(groupCode))
|
||||
if (groupRows.length === 0) continue
|
||||
for (const r of groupRows) matched.add(r.account_number)
|
||||
sections.push(makeSection(title, groupRows))
|
||||
}
|
||||
|
||||
// Catch-all: any row whose 2-digit group is not in groupLabels. Guarantees no
|
||||
// account is ever excluded from the subtotal/total/net_result.
|
||||
const orphans = rows.filter((r) => !matched.has(r.account_number))
|
||||
if (orphans.length > 0) sections.push(makeSection(fallbackTitle, orphans))
|
||||
|
||||
return sections
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user