import type { FinancialCadence, FinancialSurfaceKind } from '@/lib/types'; import { CURRENT_COMPANY_FINANCIAL_BUNDLE_VERSION, getCompanyFinancialBundle, upsertCompanyFinancialBundle } from '@/lib/server/repos/company-financial-bundles'; import type { FilingTaxonomySnapshotRecord } from '@/lib/server/repos/filing-taxonomy'; export function computeSourceSignature(snapshots: FilingTaxonomySnapshotRecord[]) { return snapshots .map((snapshot) => `${snapshot.id}:${snapshot.updated_at}`) .sort((left, right) => left.localeCompare(right)) .join('|'); } export async function readCachedFinancialBundle(input: { ticker: string; surfaceKind: FinancialSurfaceKind; cadence: FinancialCadence; snapshots: FilingTaxonomySnapshotRecord[]; }) { const sourceSignature = computeSourceSignature(input.snapshots); const cached = await getCompanyFinancialBundle({ ticker: input.ticker, surfaceKind: input.surfaceKind, cadence: input.cadence }); if ( !cached || cached.bundle_version !== CURRENT_COMPANY_FINANCIAL_BUNDLE_VERSION || cached.source_signature !== sourceSignature ) { return null; } return cached.payload; } export async function writeFinancialBundle(input: { ticker: string; surfaceKind: FinancialSurfaceKind; cadence: FinancialCadence; snapshots: FilingTaxonomySnapshotRecord[]; payload: Record; }) { return await upsertCompanyFinancialBundle({ ticker: input.ticker, surfaceKind: input.surfaceKind, cadence: input.cadence, sourceSnapshotIds: input.snapshots.map((snapshot) => snapshot.id), sourceSignature: computeSourceSignature(input.snapshots), payload: input.payload }); }