* fix(reports): stabilize fetchAllRows paging to stop doubled/dropped balances (#790, #791) PostgREST `.range()` paging is only correct when the underlying query has a stable TOTAL order. Several aggregating report queries (general ledger, trial balance, grundbok, supplier/AR ledgers, etc.) paginated without `.order()`, so on datasets larger than one 1000-row page Postgres could return rows in a different order between requests — silently DUPLICATING or SKIPPING rows on a page boundary and doubling or dropping financial totals. - fetch-all.ts: document the ordering invariant and add an optional `dedupeBy` defense-in-depth that drops cross-page duplicates and warns when it fires (surfaces a missing `.order()` in logs instead of corrupting money). - Add a stable `.order()` (line PK or account_number) to every paginated query in lib/reports/ and the account-balances route; pass `dedupeBy` on the money-aggregating line queries. - Add fetch-all unit tests and update report test fixtures to carry row ids. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(api): declare the real { data, meta } envelope on v1 single/write/204 endpoints (#794) The OpenAPI generator derives each endpoint's documented body purely from its registered `response.success` Zod schema, and that schema is never validated at runtime — so a route could advertise a shape its handler never sends. #802 fixed this for list endpoints; the same drift was latent on single-resource and write endpoints, which declared the bare resource schema instead of the `{ data, meta }` envelope the handlers actually return. - registry.ts: extend `ResponseMetaSchema` with the optional `audit` block and `partial_expansions` list that writes/expansions emit; add the `NoBodyResponse` sentinel so 204 DELETE handlers document a bare 204 instead of a phantom 200. - Wrap every single/write endpoint's `response.success` in `dataEnvelope(...)` (or `NoBodyResponse` for 204s) across the v1 routes. - Add a response-envelope contract test that fails CI if any JSON endpoint forgets to wrap its schema, with binary downloads and 204s as the only exemptions. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(reports): extend paging dedupeBy to rc-basis-gaps and opening-balances Address PR review: these two money-aggregating line queries already had the stable `.order('id')` (so paging was correct) but didn't carry `id` in the select, so they couldn't use the `dedupeBy` defense-in-depth that general-ledger and trial-balance got. Select `id` and pass `dedupeBy: r => r.id` so the whole report layer applies the ordering invariant consistently. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
335 lines
10 KiB
TypeScript
335 lines
10 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
|
|
// ============================================================
|
|
// Mock — sequential result queue
|
|
// ============================================================
|
|
|
|
let resultIdx: number
|
|
let results: Array<{ data?: unknown; error?: unknown }>
|
|
|
|
function makeBuilder() {
|
|
const b: Record<string, unknown> = {}
|
|
for (const m of ['select', 'eq', 'in', 'order', 'range']) {
|
|
b[m] = vi.fn().mockReturnValue(b)
|
|
}
|
|
b.single = vi.fn().mockImplementation(async () => results[resultIdx++] ?? { data: null, error: null })
|
|
b.then = (resolve: (v: unknown) => void) => resolve(results[resultIdx++] ?? { data: null, error: null })
|
|
return b
|
|
}
|
|
|
|
function makeClient() {
|
|
return {
|
|
from: vi.fn().mockImplementation(() => makeBuilder()),
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
} as any
|
|
}
|
|
|
|
import { generateSupplierLedger } from '../supplier-ledger'
|
|
|
|
let supabase: ReturnType<typeof makeClient>
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
resultIdx = 0
|
|
results = []
|
|
supabase = makeClient()
|
|
})
|
|
|
|
describe('generateSupplierLedger', () => {
|
|
it('returns empty report when no invoices found', async () => {
|
|
results = [
|
|
{ data: [], error: null },
|
|
]
|
|
|
|
const report = await generateSupplierLedger(supabase, 'company-1')
|
|
expect(report.entries).toEqual([])
|
|
expect(report.total_outstanding).toBe(0)
|
|
expect(report.total_current).toBe(0)
|
|
expect(report.total_overdue).toBe(0)
|
|
expect(report.unpaid_count).toBe(0)
|
|
})
|
|
|
|
it('returns empty report on query error', async () => {
|
|
results = [
|
|
{ data: null, error: { message: 'DB error' } },
|
|
]
|
|
|
|
const report = await generateSupplierLedger(supabase, 'company-1')
|
|
expect(report.entries).toEqual([])
|
|
expect(report.total_outstanding).toBe(0)
|
|
})
|
|
|
|
it('places invoices in correct aging buckets', async () => {
|
|
// Reference date: 2024-06-15
|
|
const asOfDate = '2024-06-15'
|
|
|
|
results = [
|
|
{
|
|
data: [
|
|
// Current: due in the future (days overdue <= 0)
|
|
{
|
|
supplier_id: 'sup-1',
|
|
supplier: { id: 'sup-1', name: 'Leverantör A' },
|
|
due_date: '2024-06-20',
|
|
remaining_amount: 5000,
|
|
},
|
|
// 1-30 days overdue: due_date 2024-06-01 (14 days overdue)
|
|
{
|
|
supplier_id: 'sup-1',
|
|
supplier: { id: 'sup-1', name: 'Leverantör A' },
|
|
due_date: '2024-06-01',
|
|
remaining_amount: 3000,
|
|
},
|
|
// 31-60 days overdue: due_date 2024-05-01 (45 days overdue)
|
|
{
|
|
supplier_id: 'sup-1',
|
|
supplier: { id: 'sup-1', name: 'Leverantör A' },
|
|
due_date: '2024-05-01',
|
|
remaining_amount: 2000,
|
|
},
|
|
// 61-90 days overdue: due_date 2024-04-01 (75 days overdue)
|
|
{
|
|
supplier_id: 'sup-1',
|
|
supplier: { id: 'sup-1', name: 'Leverantör A' },
|
|
due_date: '2024-04-01',
|
|
remaining_amount: 1500,
|
|
},
|
|
// 90+ days overdue: due_date 2024-02-01 (135 days overdue)
|
|
{
|
|
supplier_id: 'sup-1',
|
|
supplier: { id: 'sup-1', name: 'Leverantör A' },
|
|
due_date: '2024-02-01',
|
|
remaining_amount: 1000,
|
|
},
|
|
],
|
|
error: null,
|
|
},
|
|
]
|
|
|
|
const report = await generateSupplierLedger(supabase, 'company-1', asOfDate)
|
|
|
|
expect(report.entries).toHaveLength(1)
|
|
const entry = report.entries[0]
|
|
expect(entry.current).toBe(5000)
|
|
expect(entry.days_1_30).toBe(3000)
|
|
expect(entry.days_31_60).toBe(2000)
|
|
expect(entry.days_61_90).toBe(1500)
|
|
expect(entry.days_90_plus).toBe(1000)
|
|
expect(entry.total_outstanding).toBe(12500)
|
|
})
|
|
|
|
it('groups by supplier and uses fallback name for missing supplier', async () => {
|
|
results = [
|
|
{
|
|
data: [
|
|
{
|
|
supplier_id: 'sup-1',
|
|
supplier: { id: 'sup-1', name: 'Leverantör A' },
|
|
due_date: '2024-07-01',
|
|
remaining_amount: 5000,
|
|
},
|
|
{
|
|
supplier_id: 'sup-2',
|
|
supplier: null,
|
|
due_date: '2024-07-01',
|
|
remaining_amount: 3000,
|
|
},
|
|
],
|
|
error: null,
|
|
},
|
|
]
|
|
|
|
const report = await generateSupplierLedger(supabase, 'company-1', '2024-06-15')
|
|
|
|
expect(report.entries).toHaveLength(2)
|
|
const names = report.entries.map(e => e.supplier_name)
|
|
expect(names).toContain('Leverantör A')
|
|
expect(names).toContain('Okänd leverantör')
|
|
})
|
|
|
|
it('sorts entries by outstanding descending', async () => {
|
|
results = [
|
|
{
|
|
data: [
|
|
{
|
|
supplier_id: 'sup-1',
|
|
supplier: { id: 'sup-1', name: 'Small' },
|
|
due_date: '2024-07-01',
|
|
remaining_amount: 1000,
|
|
},
|
|
{
|
|
supplier_id: 'sup-2',
|
|
supplier: { id: 'sup-2', name: 'Large' },
|
|
due_date: '2024-07-01',
|
|
remaining_amount: 10000,
|
|
},
|
|
{
|
|
supplier_id: 'sup-3',
|
|
supplier: { id: 'sup-3', name: 'Medium' },
|
|
due_date: '2024-07-01',
|
|
remaining_amount: 5000,
|
|
},
|
|
],
|
|
error: null,
|
|
},
|
|
]
|
|
|
|
const report = await generateSupplierLedger(supabase, 'company-1', '2024-06-15')
|
|
|
|
expect(report.entries[0].supplier_name).toBe('Large')
|
|
expect(report.entries[1].supplier_name).toBe('Medium')
|
|
expect(report.entries[2].supplier_name).toBe('Small')
|
|
})
|
|
|
|
it('calculates grand totals correctly', async () => {
|
|
results = [
|
|
{
|
|
data: [
|
|
// Supplier A: current 5000
|
|
{
|
|
supplier_id: 'sup-1',
|
|
supplier: { id: 'sup-1', name: 'A' },
|
|
due_date: '2024-07-01',
|
|
remaining_amount: 5000,
|
|
},
|
|
// Supplier B: 1-30 days overdue 3000
|
|
{
|
|
supplier_id: 'sup-2',
|
|
supplier: { id: 'sup-2', name: 'B' },
|
|
due_date: '2024-06-01',
|
|
remaining_amount: 3000,
|
|
},
|
|
],
|
|
error: null,
|
|
},
|
|
]
|
|
|
|
const report = await generateSupplierLedger(supabase, 'company-1', '2024-06-15')
|
|
|
|
expect(report.total_outstanding).toBe(8000)
|
|
expect(report.total_current).toBe(5000)
|
|
expect(report.total_overdue).toBe(3000) // outstanding - current
|
|
expect(report.unpaid_count).toBe(2)
|
|
})
|
|
|
|
it('converts foreign-currency invoices to SEK using exchange_rate', async () => {
|
|
// Reproduces the production bug: EUR/USD invoices were summed as if SEK,
|
|
// making the ledger total drift from the 2440 GL balance.
|
|
results = [
|
|
{
|
|
data: [
|
|
// 225 EUR at 11.00 → 2 475 SEK
|
|
{
|
|
supplier_id: 'sup-1',
|
|
supplier: { id: 'sup-1', name: 'Anthropic' },
|
|
due_date: '2024-06-01',
|
|
remaining_amount: 225,
|
|
currency: 'EUR',
|
|
exchange_rate: 11,
|
|
},
|
|
// 6.25 USD at 10.00 → 62.50 SEK
|
|
{
|
|
supplier_id: 'sup-1',
|
|
supplier: { id: 'sup-1', name: 'Anthropic' },
|
|
due_date: '2024-06-01',
|
|
remaining_amount: 6.25,
|
|
currency: 'USD',
|
|
exchange_rate: 10,
|
|
},
|
|
// 1 000 SEK (no conversion)
|
|
{
|
|
supplier_id: 'sup-2',
|
|
supplier: { id: 'sup-2', name: 'Svensk leverantör' },
|
|
due_date: '2024-06-01',
|
|
remaining_amount: 1000,
|
|
currency: 'SEK',
|
|
exchange_rate: null,
|
|
},
|
|
],
|
|
error: null,
|
|
},
|
|
]
|
|
|
|
const report = await generateSupplierLedger(supabase, 'company-1', '2024-06-15')
|
|
|
|
// Anthropic: 2 475 + 62.50 = 2 537.50 SEK (all in 1-30 days bucket)
|
|
const anthropic = report.entries.find(e => e.supplier_name === 'Anthropic')!
|
|
expect(anthropic.days_1_30).toBe(2537.5)
|
|
expect(anthropic.total_outstanding).toBe(2537.5)
|
|
|
|
// Swedish supplier unchanged
|
|
const swedish = report.entries.find(e => e.supplier_name === 'Svensk leverantör')!
|
|
expect(swedish.days_1_30).toBe(1000)
|
|
|
|
// Grand total in SEK: 2 537.50 + 1 000 = 3 537.50
|
|
expect(report.total_outstanding).toBe(3537.5)
|
|
})
|
|
|
|
it('excludes FX invoices without exchange_rate from totals and counts them', async () => {
|
|
// Legacy data: an FX invoice without an exchange rate cannot be converted
|
|
// to SEK without falsifying the total. The row is excluded from sums and
|
|
// surfaced via unconverted_fx_count so the UI can warn the user.
|
|
results = [
|
|
{
|
|
data: [
|
|
{
|
|
supplier_id: 'sup-1',
|
|
supplier: { id: 'sup-1', name: 'Legacy' },
|
|
due_date: '2024-06-01',
|
|
remaining_amount: 100,
|
|
currency: 'EUR',
|
|
exchange_rate: null,
|
|
},
|
|
{
|
|
supplier_id: 'sup-2',
|
|
supplier: { id: 'sup-2', name: 'SEK supplier' },
|
|
due_date: '2024-06-01',
|
|
remaining_amount: 500,
|
|
currency: 'SEK',
|
|
exchange_rate: null,
|
|
},
|
|
],
|
|
error: null,
|
|
},
|
|
]
|
|
|
|
const report = await generateSupplierLedger(supabase, 'company-1', '2024-06-15')
|
|
expect(report.total_outstanding).toBe(500)
|
|
expect(report.unconverted_fx_count).toBe(1)
|
|
expect(report.entries.map(e => e.supplier_name)).toEqual(['SEK supplier'])
|
|
})
|
|
|
|
it('uses Math.round for monetary precision', async () => {
|
|
results = [
|
|
{
|
|
data: [
|
|
{
|
|
supplier_id: 'sup-1',
|
|
supplier: { id: 'sup-1', name: 'Test' },
|
|
due_date: '2024-07-01',
|
|
remaining_amount: 33.33,
|
|
},
|
|
{
|
|
supplier_id: 'sup-1',
|
|
supplier: { id: 'sup-1', name: 'Test' },
|
|
due_date: '2024-07-02',
|
|
remaining_amount: 33.33,
|
|
},
|
|
{
|
|
supplier_id: 'sup-1',
|
|
supplier: { id: 'sup-1', name: 'Test' },
|
|
due_date: '2024-07-03',
|
|
remaining_amount: 33.34,
|
|
},
|
|
],
|
|
error: null,
|
|
},
|
|
]
|
|
|
|
const report = await generateSupplierLedger(supabase, 'company-1', '2024-06-15')
|
|
|
|
expect(report.total_outstanding).toBe(100)
|
|
expect(report.total_current).toBe(100)
|
|
})
|
|
})
|