Luigit
repositories / will

will

owned by admin

src/service/usage.test.ts

Raw
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { aggregateTurnUsage, projectUsage } from './usage.ts'

const row = (ts: string, over: object = {}) => ({
  ts,
  payload: {
    provider: 'zai',
    model: 'glm-5.3-flash',
    input: 1_000_000,
    output: 0,
    cacheRead: 0,
    cacheWrite: 0,
    responses: 1,
    ...over,
  },
})

test('cost uses the price table per MTok', () => {
  const report = aggregateTurnUsage([row('2026-09-21T10:00:00Z')], new Date('2026-09-21T18:00:00Z'))
  // 1M input tokens at $0.15/MTok
  assert.ok(Math.abs((report.days[0]?.costUsd ?? 0) - 0.15) < 1e-6)
  assert.ok(Math.abs((report.totals.costUsd ?? 0) - 0.15) < 1e-6)
})

test('unknown model keeps tokens but marks cost unavailable', () => {
  const report = aggregateTurnUsage(
    [row('2026-09-21T10:00:00Z', { provider: 'x', model: 'y' })],
    new Date('2026-09-21T18:00:00Z'),
  )
  assert.equal(report.days[0]?.input, 1_000_000)
  assert.equal(report.days[0]?.costUsd, null)
  assert.equal(report.totals.costUsd, null)
  assert.equal(report.projection.projectedEomUsd, null)
})

test('days are grouped by UTC date and sorted ascending', () => {
  const report = aggregateTurnUsage(
    [row('2026-09-21T23:00:00Z'), row('2026-09-20T01:00:00Z'), row('2026-09-21T01:00:00Z')],
    new Date('2026-09-21T18:00:00Z'),
  )
  assert.deepEqual(
    report.days.map((d) => d.date),
    ['2026-09-20', '2026-09-21'],
  )
  assert.equal(report.days[1]?.responses, 2)
})

test('projection extrapolates today across the remaining month', () => {
  // at 18:00 UTC, 75% of the day elapsed; 1M input/day = $0.15/day rate
  const days = [
    {
      date: '2026-09-20',
      input: 1e6,
      output: 0,
      cacheRead: 0,
      cacheWrite: 0,
      responses: 1,
      costUsd: 0.15,
    },
    {
      date: '2026-09-21',
      input: 1e6,
      output: 0,
      cacheRead: 0,
      cacheWrite: 0,
      responses: 1,
      costUsd: 0.15,
    },
  ]
  const p = projectUsage(days, new Date('2026-09-21T18:00:00Z'))
  assert.ok(Math.abs((p.todayUsd ?? 0) - 0.2) < 1e-9) // 0.15 / 0.75
  assert.ok(Math.abs((p.mtdUsd ?? 0) - 0.3) < 1e-9)
  // 9.25 days remain until Oct 1 => 0.3 + 0.2 * 9.25
  assert.ok(Math.abs((p.projectedEomUsd ?? 0) - 2.15) < 1e-9)
})

test('projection is null without a priced day today', () => {
  const p = projectUsage([], new Date('2026-09-21T18:00:00Z'))
  assert.equal(p.todayUsd, null)
  assert.equal(p.projectedEomUsd, null)
})