(executionId: string)
| 21 | type LookupColumn = 'id' | 'executionId' |
| 22 | |
| 23 | async function buildCostLedger(executionId: string): Promise<CostLedger | null> { |
| 24 | const rows = await db |
| 25 | .select({ |
| 26 | category: usageLog.category, |
| 27 | description: usageLog.description, |
| 28 | cost: usageLog.cost, |
| 29 | metadata: usageLog.metadata, |
| 30 | }) |
| 31 | .from(usageLog) |
| 32 | .where(and(eq(usageLog.executionId, executionId), eq(usageLog.source, 'workflow'))) |
| 33 | |
| 34 | if (rows.length === 0) return null |
| 35 | |
| 36 | type LedgerItem = CostLedger['items'][number] |
| 37 | const byKey = new Map<string, LedgerItem>() |
| 38 | for (const row of rows) { |
| 39 | const metadata = (row.metadata ?? {}) as { inputTokens?: number; outputTokens?: number } |
| 40 | const category = row.category as LedgerItem['category'] |
| 41 | const key = `${category}::${row.description}` |
| 42 | const existing = byKey.get(key) |
| 43 | if (existing) { |
| 44 | existing.cost += Number(row.cost) |
| 45 | if (typeof metadata.inputTokens === 'number') { |
| 46 | existing.inputTokens = Math.max(existing.inputTokens ?? 0, metadata.inputTokens) |
| 47 | } |
| 48 | if (typeof metadata.outputTokens === 'number') { |
| 49 | existing.outputTokens = Math.max(existing.outputTokens ?? 0, metadata.outputTokens) |
| 50 | } |
| 51 | } else { |
| 52 | byKey.set(key, { |
| 53 | category, |
| 54 | description: row.description, |
| 55 | cost: Number(row.cost), |
| 56 | ...(typeof metadata.inputTokens === 'number' ? { inputTokens: metadata.inputTokens } : {}), |
| 57 | ...(typeof metadata.outputTokens === 'number' |
| 58 | ? { outputTokens: metadata.outputTokens } |
| 59 | : {}), |
| 60 | }) |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | const items = [...byKey.values()] |
| 65 | const total = items.reduce((sum, item) => sum + item.cost, 0) |
| 66 | return { total, items } |
| 67 | } |
| 68 | |
| 69 | export function jobCostTotal(raw: unknown): { total: number } | null { |
| 70 | const total = (raw as { total?: unknown } | null | undefined)?.total |
no test coverage detected