All files / src/utils creditsHistory.ts

98.33% Statements 59/60
98.11% Branches 52/53
100% Functions 10/10
100% Lines 48/48

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168                                                                          3x     38x 30x 24x 22x 20x       39x 39x 39x 39x       8x                                         25x 25x   25x 39x 39x 39x 9x 9x 9x 9x     30x                         39x 39x 39x   25x                                         8x 8x 8x 19x 2x 2x   17x 19x 19x 15x 15x   17x 17x 17x   8x 15x 8x                     8x 8x 5x         25x 25x    
import type { CreditsTransaction, CreditsUsageLine } from '@/stores/credits'
 
/**
 * What the Credits page groups ledger rows into, and the categories it shows
 * them under. The ledger itself is an accounting trail: one row per pool
 * charged, so a single item write is two rows (storage + throughput) and a
 * day of usage up to three (compute, API calls, reads). The page shows one
 * entry per thing the user did or was charged for instead — see
 * flows-api's docs/architecture/USAGE_METERING.md.
 */
 
export type CreditsCategory = 'usage' | 'data' | 'files' | 'automation' | 'adjustment'
 
export interface CreditsPoolAmount {
  pool: string
  amount: number
}
 
export interface CreditsHistoryEntry {
  /** The first row's transactionId: stable across pages, unique per entry */
  id: string
  kind: 'usage' | 'operation'
  category: CreditsCategory
  operation: string
  referenceId: string | null
  flowId: string | null
  /** Sum of the grouped rows */
  amount: number
  /** The newest grouped row's timestamp */
  timestamp: string
  /** The day a usage entry charges (`YYYY-MM-DD`), null otherwise */
  day: string | null
  note: string | null
  pools: CreditsPoolAmount[]
}
 
/** Rows of one write are debited together: further apart, they are separate writes */
const SAME_WRITE_MAX_GAP_MS = 60 * 1000
 
export function categoryOf(operation: string): CreditsCategory {
  if (operation === 'usage_aggregation') return 'usage'
  if (operation === 'admin_grant' || operation === 'admin_deduction') return 'adjustment'
  if (operation === 'file_upload') return 'files'
  if (operation === 'item_wake_up' || operation === 'email_action') return 'automation'
  return 'data'
}
 
function addPool(entry: CreditsHistoryEntry, tx: CreditsTransaction) {
  entry.amount += tx.amount
  const pool = entry.pools.find((p) => p.pool === tx.pool)
  Iif (pool) pool.amount += tx.amount
  else entry.pools.push({ pool: tx.pool, amount: tx.amount })
}
 
function isSameWrite(entry: CreditsHistoryEntry, tx: CreditsTransaction): boolean {
  return (
    entry.kind === 'operation' &&
    entry.referenceId !== null &&
    entry.operation === tx.operation &&
    entry.referenceId === tx.referenceId &&
    entry.flowId === (tx.flowId ?? null) &&
    Math.abs(Date.parse(entry.timestamp) - Date.parse(tx.timestamp)) <= SAME_WRITE_MAX_GAP_MS
  )
}
 
/**
 * Groups newest-first ledger rows into the page's entries, keeping their
 * order: every row of a usage day becomes one entry (its rows can be split
 * across pages, so they are matched by day, not by position), and the rows
 * of one write — same operation, reference and flow, debited within a
 * minute, next to each other — become one entry. Anything else stays its own
 * entry: two edits of the same item an hour apart are two entries.
 */
export function groupCreditsTransactions(
  transactions: CreditsTransaction[]
): CreditsHistoryEntry[] {
  const entries: CreditsHistoryEntry[] = []
  const usageByDay = new Map<string, CreditsHistoryEntry>()
 
  for (const tx of transactions) {
    const isUsage = tx.operation === 'usage_aggregation' && !!tx.referenceId
    const existing = isUsage ? usageByDay.get(tx.referenceId!) : entries[entries.length - 1]
    if (existing && (isUsage || isSameWrite(existing, tx))) {
      addPool(existing, tx)
      if (tx.timestamp > existing.timestamp) existing.timestamp = tx.timestamp
      existing.note = existing.note ?? tx.note
      continue
    }
 
    const entry: CreditsHistoryEntry = {
      id: tx.transactionId,
      kind: isUsage ? 'usage' : 'operation',
      category: categoryOf(tx.operation),
      operation: tx.operation,
      referenceId: tx.referenceId,
      flowId: tx.flowId ?? null,
      amount: 0,
      timestamp: tx.timestamp,
      day: isUsage ? tx.referenceId : null,
      note: tx.note,
      pools: []
    }
    addPool(entry, tx)
    entries.push(entry)
    if (isUsage) usageByDay.set(tx.referenceId!, entry)
  }
  return entries
}
 
export interface CreditsUsageFlowGroup {
  /** null for the calls made outside any flow (account, profile, messages…) */
  flowId: string | null
  events: number
  credits: number
  lines: CreditsUsageLine[]
}
 
/**
 * A usage day's breakdown grouped by flow, the costliest first — what the
 * user recognizes first is the flow they worked in, then what they did in
 * it. The `other` line (everything past the 20 busiest) is not tied to one
 * flow and is returned on its own, to show last.
 */
export function groupUsageByFlow(breakdown: CreditsUsageLine[]): {
  flows: CreditsUsageFlowGroup[]
  other: CreditsUsageLine | null
} {
  const groups = new Map<string, CreditsUsageFlowGroup>()
  let other: CreditsUsageLine | null = null
  for (const line of breakdown) {
    if (line.other) {
      other = line
      continue
    }
    const key = line.flowId ?? ''
    let group = groups.get(key)
    if (!group) {
      group = { flowId: line.flowId, events: 0, credits: 0, lines: [] }
      groups.set(key, group)
    }
    group.events += line.events
    group.credits += line.credits
    group.lines.push(line)
  }
  const flows = [...groups.values()].sort((a, b) => b.credits - a.credits || b.events - a.events)
  for (const group of flows) group.lines.sort((a, b) => b.credits - a.credits)
  return { flows, other }
}
 
export interface SpendingProjection {
  dailyAverage: number
  /** null when nothing was spent: the balance does not run out */
  daysLeft: number | null
}
 
/** How long the balance lasts at the pace of the last `days` days */
export function projectSpending(balance: number, spent: number, days: number): SpendingProjection {
  const dailyAverage = days > 0 ? spent / days : 0
  if (dailyAverage <= 0) return { dailyAverage: 0, daysLeft: null }
  return { dailyAverage, daysLeft: Math.max(0, Math.floor(balance / dailyAverage)) }
}
 
/** `update-lambda-billing` -> `Update lambda billing`: the fallback for an unknown key */
export function humanizeKey(key: string): string {
  const spaced = key.replace(/[_-]+/g, ' ').trim()
  return spaced.charAt(0).toUpperCase() + spaced.slice(1)
}