Files
accounted/lib/reports/income-statement.ts
T
Mattsson 288915c152 Fix/fdb fr usrs (#1125)
* fix(invoices): return attachment filename in delivery history summaries

The 20260723003000 hardening dropped attachment_filename from
list_invoice_delivery_summaries, so the delivery history UI always fell
back to the generic "faktura.pdf" label. Recreate the RPC with the
filename included: it is derived from company name, customer name,
invoice number, and date, all already visible to every company member,
so the minimization boundary is unchanged. Addresses stay masked and
message content, BCC, and checksums stay server-side.

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

* fix(reconciliation): surface own-account transfer legs in match-to-voucher by default

The second (incoming) leg of a transfer between two of the company's own
bank accounts was hidden in the 'Matcha mot befintlig verifikation' dialog
because the voucher counted as 'already matched' once its outgoing leg was
linked, even though the incoming account's line had no settling transaction.
Users read the empty default list as 'the app won't let me link this'.

get_account_gl_lines_for_matching now counts links per settlement account:
a transaction provably on another cash account no longer marks the voucher
as matched for the requested account, so the unsettled transfer leg surfaces
by default (and auto-selects on an exact match). Same-account N:1 stays
behind the 'Visa aven matchade verifikationer' opt-in, and transactions
without a resolvable cash account conservatively keep counting everywhere.
get_unlinked_gl_lines is deliberately untouched (feeds auto-reconcile).

Companion guard: mark_entry_as_opening_balance now refuses entries with
linked bank transactions, since half-settled transfer vouchers became
reachable in the reconciliation view's unmatched table where 'Mark som IB'
renders; re-tagging one would strand its transaction against a movement-
excluded entry. getReconciliationStatus counts unmatched GL lines with the
account-scoped RPC so the status card agrees with the table.

Fixes #1026

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

* perf(api): cut prod p95 latency via local JWT auth, single-RT company resolution, and report aggregate RPCs

Baseline 2026-07-23 (487 prod samples): p50 160ms, p95 480ms, 13% of
requests over 300ms. Target: p95 under 300ms.

- requireAuth: verify JWTs locally via getClaims (ES256/JWKS) instead of
  a second network getUser per request; getUser fallback keeps HS256
  self-hosted and existing test mocks working; middleware still
  revocation-checks every /api request
- resolve_active_company RPC (20260723161000): one round trip replaces
  2-3 queries in getActiveCompanyId and middleware; PGRST202/42501 fall
  back to the legacy query path
- arsredovisning build-data: ~33 sequential round trips down to ~7,
  output byte-identical (snapshot-proven)
- currency rate route: stop bypassing the exchange_rates cache (missing
  supabase arg caused an external Riksbanken call on every request)
- document.get: parallelize row fetch, signed URL and audit event
- list_company_accounts RPC (20260723170000): accounts list in one round
  trip instead of paging past PostgREST's 1000-row cap
- vat-declaration route: drop a dead sequential company_settings query
- get_kpi_report_aggregates RPC (20260723180000): KPI report's three
  full-period line scans collapsed into one aggregate call; dimension-
  filtered path unchanged
- lint: fix 9 baseline errors, downgrade 4 react-hooks compiler rules to
  warn, zero the eslint baseline ratchet

All four gates green: lint 0 errors, 9163 tests, check:guards, build.
Migrations applied idempotently to staging only; prod receives them via
Supabase branching on merge.

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

* fix(review): resolve PR review findings across auth, VAT declaration, and IB retag

- requireAuth getClaims fast path: pin iss (project URL) and aud
  ('authenticated'), log every fallback to getUser (ASVS V9.1 finding)
- remove the ignored accountingMethod parameter from calculateVatDeclaration
  and the dead company_settings.accounting_method reads in xlsx/pdf/eskd
  routes; v1 API keeps accepting the query param but documents it as a no-op
- close the mark_entry_as_opening_balance TOCTOU race with a transactions
  trigger (20260723190000, FOR KEY SHARE on journal_entries) + pg tests;
  applied to staging and smoke-verified both directions
- re-add the 42501 tenant guard to branch-local migration 20260723160000
  (function body had silently reverted to the pre-20260619130100 definition)
- document the buildK3Noter tbFullRows full-TB contract (uppskjuten skatt
  opening balance per BFNAR 2012:1 ch.29)
- add KPI VAT-liability test covering reduced-rate output accounts 2621/2631

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

* fix(db): use NULL-safe caller_is_company_member in opening-balance retag guard

The re-added tenant guard carried the pre-20260703180000 raw
NOT IN (SELECT user_company_ids()) pattern, which the
null-safe-tenant-guards ratchet blocks. Staging re-synced.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 16:16:55 +02:00

218 lines
8.0 KiB
TypeScript

import type { SupabaseClient } from '@supabase/supabase-js'
import { generateTrialBalance } from './trial-balance'
import type { IncomeStatementReport, IncomeStatementSection, TrialBalanceRow } from '@/types'
/**
* Generate Income Statement (Resultaträkning)
*
* Filters to class 3-8 accounts:
* - Rörelseintäkter (3xxx): Revenue
* - Rörelsekostnader (4-7xxx): Operating expenses
* - Finansiella poster (8xxx): Financial items
* - Årets resultat: Net result
*/
export async function generateIncomeStatement(
supabase: SupabaseClient,
companyId: string,
fiscalPeriodId: string,
options?: {
fromDate?: string
toDate?: string
/** SIE dim → code filter ({"6":"P001"}). P&L-safe: see trial-balance.ts. */
dimensions?: Record<string, string>
}
): Promise<IncomeStatementReport> {
// Exclude year-end closing entries: after closing, P&L accounts (3-8) are
// zeroed by the closing verifikat (8999 → 2099). Including them collapses
// the resultaträkning to zero. The income statement must reflect the
// pre-closing activity for the year.
const { rows } = await generateTrialBalance(supabase, companyId, fiscalPeriodId, {
excludeYearEndClosing: true,
fromDate: options?.fromDate,
toDate: options?.toDate,
dimensions: options?.dimensions,
})
return buildIncomeStatementFromRows(rows)
}
/**
* Pure income-statement assembly from trial balance rows. Extracted so
* callers that already hold pre-computed rows (e.g. the KPI route's
* single-round-trip aggregate path) can reuse the section/rounding logic
* without re-fetching journal lines. The rows must come from a trial
* balance generated with excludeYearEndClosing (see generateIncomeStatement
* above for why).
*/
export function buildIncomeStatementFromRows(
rows: TrialBalanceRow[]
): IncomeStatementReport {
// Filter to income/expense accounts (class 3-8)
const incomeExpenseRows = rows.filter(
(r) => r.account_class >= 3 && r.account_class <= 8
)
// Revenue sections (class 3)
const revenueSections = buildSections(
incomeExpenseRows.filter((r) => r.account_class === 3),
{
'30': 'Huvudintäkter',
'31': 'Momsfria intäkter',
'32': 'Förmåner',
'33': 'Försäljning tjänster utanför Sverige',
'34': 'Egna uttag',
'35': 'Fakturerade kostnader',
'36': 'Sidointäkter',
'37': 'Intäktskorrigeringar',
'38': 'Aktiverat arbete',
'39': 'Övriga rörelseintäkter',
},
'credit', // Revenue has credit normal balance
'Övriga intäkter',
)
// Expense sections (class 4-7)
const expenseSections = buildSections(
incomeExpenseRows.filter((r) => r.account_class >= 4 && r.account_class <= 7),
{
'40': 'Varor och material',
'41': 'Förändring lager',
'42': 'Sålda handelsvaror VMB',
'43': 'Råvaror och material',
'44': 'Inköp omvänd betalningsskyldighet',
'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',
'57': 'Frakter och transporter',
'58': 'Resekostnader',
'59': 'Reklam och PR',
'60': 'Övriga försäljningskostnader',
'61': 'Kontorsmateriel',
'62': 'Tele och post',
'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',
'72': 'Löner tjänstemän/företagsledare',
'73': 'Kostnadsersättningar och förmåner',
'74': 'Pensionskostnader',
'75': 'Sociala avgifter',
'76': 'Övriga personalkostnader',
'77': 'Nedskrivningar',
'78': 'Avskrivningar',
'79': 'Övriga rörelsekostnader',
},
'debit', // Expenses have debit normal balance
'Övriga kostnader',
)
// Financial sections (class 8): exclude 8999 "Årets resultat".
// 8999 is a closing account: when year-end posts "8999 debit → 2099 credit"
// to move the computed profit into equity, including 8999's debit balance
// here cancels out the revenue/expense difference and drives net_result to
// zero. The income statement shows the *computed* årets resultat as
// (revenue - expenses + financial), so 8999's own balance must stay out.
const financialSections = buildSections(
incomeExpenseRows.filter(
(r) => r.account_class === 8 && r.account_number !== '8999'
),
{
'80': 'Resultat andelar koncernföretag',
'81': 'Resultat andelar intresseföretag',
'82': 'Resultat övriga värdepapper',
'83': 'Ränteintäkter',
'84': 'Räntekostnader',
'88': 'Bokslutsdispositioner',
'89': 'Skatter och årets resultat',
},
'mixed',
'Övriga finansiella poster',
)
const totalRevenue = revenueSections.reduce((sum, s) => sum + s.subtotal, 0)
const totalExpenses = expenseSections.reduce((sum, s) => sum + s.subtotal, 0)
const totalFinancial = financialSections.reduce((sum, s) => sum + s.subtotal, 0)
return {
revenue_sections: revenueSections.filter((s) => s.rows.length > 0),
total_revenue: Math.round(totalRevenue * 100) / 100,
expense_sections: expenseSections.filter((s) => s.rows.length > 0),
total_expenses: Math.round(totalExpenses * 100) / 100,
financial_sections: financialSections.filter((s) => s.rows.length > 0),
total_financial: Math.round(totalFinancial * 100) / 100,
net_result: Math.round((totalRevenue - totalExpenses + totalFinancial) * 100) / 100,
period: { start: '', end: '' }, // Will be filled by caller
}
}
/**
* 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',
fallbackTitle: string
): IncomeStatementSection[] {
const makeSection = (title: string, groupRows: TrialBalanceRow[]): IncomeStatementSection => {
const sectionRows = groupRows.map((r) => {
// 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,
account_name: r.account_name,
amount: Math.round(amount * 100) / 100,
}
})
const subtotal = sectionRows.reduce((sum, r) => sum + r.amount, 0)
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
}