288915c152
* 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>
195 lines
6.6 KiB
TypeScript
195 lines
6.6 KiB
TypeScript
import type { SupabaseClient } from '@supabase/supabase-js'
|
|
import { fetchEntryLines, type EntryLinesQuery } from '@/lib/bookkeeping/entry-lines'
|
|
import { roundOre } from '@/lib/money'
|
|
|
|
export interface MonthlyBreakdownMonth {
|
|
label: string
|
|
income: number
|
|
expenses: number
|
|
net: number
|
|
}
|
|
|
|
export interface MonthlyBreakdown {
|
|
months: MonthlyBreakdownMonth[]
|
|
}
|
|
|
|
const MONTH_LABELS = [
|
|
'Jan', 'Feb', 'Mar', 'Apr', 'Maj', 'Jun',
|
|
'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dec',
|
|
]
|
|
|
|
/** Pre-summed month bucket for assembleMonthlyBreakdown. */
|
|
export interface MonthlyBucket {
|
|
year: number
|
|
/** 0-based month (JS Date convention, indexes MONTH_LABELS). */
|
|
month0: number
|
|
income: number
|
|
expenses: number
|
|
}
|
|
|
|
/**
|
|
* Pure assembly of the monthly breakdown from pre-summed buckets: month
|
|
* range initialization, bucket fill, natural "YYYY-MM" sort, and Swedish
|
|
* month labels. Extracted from generateMonthlyBreakdown so callers that
|
|
* already hold per-month sums (e.g. the KPI route's single-round-trip
|
|
* aggregate path) can reuse the assembly without re-scanning lines.
|
|
*
|
|
* Rounding happens once per bucket (income, expenses, then net over the
|
|
* rounded pair) instead of the old incremental per-line rounding: equal
|
|
* within float epsilon for real öre-denominated amounts.
|
|
*/
|
|
export function assembleMonthlyBreakdown(
|
|
periodStart: string,
|
|
periodEnd: string,
|
|
buckets: MonthlyBucket[]
|
|
): MonthlyBreakdown {
|
|
// Build monthly aggregates using year-aware keys ("2024-03", "2024-04",
|
|
// etc.) to avoid data corruption for non-calendar fiscal years (Apr-Mar).
|
|
const monthMap = new Map<string, { year: number; month: number; income: number; expenses: number }>()
|
|
|
|
// Initialize all months in the period range
|
|
const startDate = new Date(periodStart)
|
|
const endDate = new Date(periodEnd)
|
|
|
|
for (
|
|
let y = startDate.getFullYear(), m = startDate.getMonth();
|
|
y < endDate.getFullYear() || (y === endDate.getFullYear() && m <= endDate.getMonth());
|
|
m === 11 ? (y++, m = 0) : m++
|
|
) {
|
|
const key = `${y}-${String(m).padStart(2, '0')}`
|
|
monthMap.set(key, { year: y, month: m, income: 0, expenses: 0 })
|
|
}
|
|
|
|
for (const bucket of buckets) {
|
|
const key = `${bucket.year}-${String(bucket.month0).padStart(2, '0')}`
|
|
if (!monthMap.has(key)) {
|
|
monthMap.set(key, { year: bucket.year, month: bucket.month0, income: 0, expenses: 0 })
|
|
}
|
|
const target = monthMap.get(key)!
|
|
target.income += bucket.income
|
|
target.expenses += bucket.expenses
|
|
}
|
|
|
|
// Convert to sorted array (keys sort naturally as "YYYY-MM")
|
|
const months: MonthlyBreakdownMonth[] = []
|
|
const sortedKeys = Array.from(monthMap.keys()).sort()
|
|
|
|
for (const key of sortedKeys) {
|
|
const data = monthMap.get(key)!
|
|
const income = roundOre(data.income)
|
|
const expenses = roundOre(data.expenses)
|
|
months.push({
|
|
label: MONTH_LABELS[data.month],
|
|
income,
|
|
expenses,
|
|
net: roundOre(income - expenses),
|
|
})
|
|
}
|
|
|
|
return { months }
|
|
}
|
|
|
|
/**
|
|
* Generate monthly income vs expenses breakdown for a fiscal period.
|
|
*
|
|
* Groups posted journal entry lines by month and account class:
|
|
* - Class 3 (30xx) = revenue (credit side)
|
|
* - Class 4-7 (40xx-79xx) = expenses (debit side)
|
|
*/
|
|
export async function generateMonthlyBreakdown(
|
|
supabase: SupabaseClient,
|
|
companyId: string,
|
|
fiscalPeriodId: string,
|
|
options?: {
|
|
/** SIE dim → code filter ({"6":"P001"}). Without it a dimension-scoped
|
|
* KPI view would silently chart company-wide months. */
|
|
dimensions?: Record<string, string>
|
|
}
|
|
): Promise<MonthlyBreakdown> {
|
|
|
|
// Get the fiscal period date range
|
|
const { data: period, error: periodError } = await supabase
|
|
.from('fiscal_periods')
|
|
.select('period_start, period_end')
|
|
.eq('id', fiscalPeriodId)
|
|
.eq('company_id', companyId)
|
|
.single()
|
|
|
|
if (periodError || !period) {
|
|
return { months: [] }
|
|
}
|
|
|
|
// Get all posted journal entry lines for this period with their entry dates,
|
|
// via the two-step entry-lines fetch (see lib/bookkeeping/entry-lines.ts).
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
let lines: any[]
|
|
try {
|
|
lines = await fetchEntryLines({
|
|
supabase,
|
|
entryColumns: 'entry_date, status, company_id, fiscal_period_id',
|
|
lineColumns: 'account_number, debit_amount, credit_amount',
|
|
filterEntries: (q: EntryLinesQuery) =>
|
|
q
|
|
.eq('fiscal_period_id', fiscalPeriodId)
|
|
.eq('company_id', companyId)
|
|
.eq('status', 'posted'),
|
|
filterLines:
|
|
options?.dimensions && Object.keys(options.dimensions).length > 0
|
|
? // jsonb containment (@>): served by idx_jel_dimensions_gin.
|
|
(q: EntryLinesQuery) => q.contains('dimensions', options.dimensions)
|
|
: undefined,
|
|
// The old embed was aliased: journal_entry:journal_entries!inner(...).
|
|
attachEntriesAs: 'journal_entry',
|
|
})
|
|
} catch {
|
|
return { months: [] }
|
|
}
|
|
|
|
// Sum lines into per-month buckets (raw sums; assembleMonthlyBreakdown
|
|
// rounds once per bucket), keyed year-aware for non-calendar fiscal years.
|
|
const bucketMap = new Map<string, MonthlyBucket>()
|
|
|
|
for (const line of lines) {
|
|
const entry = line.journal_entry as {
|
|
entry_date: string
|
|
status: string
|
|
company_id: string
|
|
fiscal_period_id: string
|
|
}
|
|
const accountClass = parseInt(line.account_number.charAt(0))
|
|
const entryDate = new Date(entry.entry_date)
|
|
const key = `${entryDate.getFullYear()}-${String(entryDate.getMonth()).padStart(2, '0')}`
|
|
|
|
let bucket = bucketMap.get(key)
|
|
if (!bucket) {
|
|
bucket = { year: entryDate.getFullYear(), month0: entryDate.getMonth(), income: 0, expenses: 0 }
|
|
bucketMap.set(key, bucket)
|
|
}
|
|
|
|
if (accountClass === 3) {
|
|
// Revenue accounts: credit side represents revenue
|
|
bucket.income += line.credit_amount - line.debit_amount
|
|
} else if (accountClass >= 4 && accountClass <= 7) {
|
|
// Expense accounts: debit side represents expenses
|
|
bucket.expenses += line.debit_amount - line.credit_amount
|
|
} else if (accountClass === 8 && line.account_number !== '8999') {
|
|
// Financial items (class 8): interest, exchange gains/losses, etc.
|
|
// 8999 "Årets resultat" is a year-end closing account: its debit/credit
|
|
// mirrors the computed profit, so including it here would cancel the
|
|
// period's income-vs-expense signal on the month of closing.
|
|
const amount = line.credit_amount - line.debit_amount
|
|
if (amount >= 0) {
|
|
bucket.income += amount
|
|
} else {
|
|
bucket.expenses += Math.abs(amount)
|
|
}
|
|
}
|
|
}
|
|
|
|
return assembleMonthlyBreakdown(
|
|
period.period_start,
|
|
period.period_end,
|
|
Array.from(bucketMap.values())
|
|
)
|
|
}
|