49 lines
1.5 KiB
TypeScript
49 lines
1.5 KiB
TypeScript
import type { SupabaseClient } from "@supabase/supabase-js";
|
|
import type { DbTransaction } from "@/types/database";
|
|
import {
|
|
applyTransactionToMutableAccumulator,
|
|
createMutableLedgerAccumulator,
|
|
mutableAccumulatorToIntegrity,
|
|
sortedNonZeroUserNetPairs,
|
|
type LedgerGlobalSummary,
|
|
} from "@/lib/ledger-integrity";
|
|
|
|
const PAGE_SIZE = 5000;
|
|
|
|
/**
|
|
* Scans every transaction row (paginated) and builds full integrity + user nets.
|
|
* Server-only — call from Server Components / Route Handlers, not from client components.
|
|
*/
|
|
export async function fetchLedgerGlobalSummary(
|
|
supabase: SupabaseClient,
|
|
): Promise<{ ok: true; data: LedgerGlobalSummary } | { ok: false; message: string }> {
|
|
const acc = createMutableLedgerAccumulator();
|
|
let offset = 0;
|
|
for (;;) {
|
|
const { data, error } = await supabase
|
|
.from("transactions")
|
|
.select("id, created_at, from, to, amount, remarks, match_id")
|
|
.order("id", { ascending: true })
|
|
.range(offset, offset + PAGE_SIZE - 1);
|
|
|
|
if (error) {
|
|
return { ok: false, message: error.message };
|
|
}
|
|
const rows = (data ?? []) as DbTransaction[];
|
|
if (rows.length === 0) {
|
|
break;
|
|
}
|
|
for (const row of rows) {
|
|
applyTransactionToMutableAccumulator(acc, row);
|
|
}
|
|
offset += rows.length;
|
|
if (rows.length < PAGE_SIZE) {
|
|
break;
|
|
}
|
|
}
|
|
|
|
const integrity = mutableAccumulatorToIntegrity(acc);
|
|
const userNetEntries = sortedNonZeroUserNetPairs(acc.net);
|
|
return { ok: true, data: { integrity, userNetEntries } };
|
|
}
|