chore: import upstream snapshot with attribution
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:20:55 +08:00
commit d25d482dc2
13754 changed files with 4996608 additions and 0 deletions
@@ -0,0 +1,242 @@
/**
* @vitest-environment node
*/
import { authMockFns, createMockRequest } from '@sim/testing'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { apportionCredits } from '@/lib/billing/credits/conversion'
const { mockGetUserUsageLogs, mockGetUsageCreditsByLogId } = vi.hoisted(() => ({
mockGetUserUsageLogs: vi.fn(),
mockGetUsageCreditsByLogId: vi.fn(),
}))
vi.mock('@/lib/billing/core/usage-log', () => ({
getUserUsageLogs: mockGetUserUsageLogs,
getUsageCreditsByLogId: mockGetUsageCreditsByLogId,
}))
import { GET } from '@/app/api/users/me/usage-logs/export/route'
describe('GET /api/users/me/usage-logs/export', () => {
beforeEach(() => {
vi.clearAllMocks()
authMockFns.mockGetSession.mockResolvedValue({ user: { id: 'user-1' } })
mockGetUsageCreditsByLogId.mockResolvedValue({})
})
it('returns 401 when unauthenticated', async () => {
authMockFns.mockGetSession.mockResolvedValue(null)
const response = await GET(createMockRequest('GET'))
expect(response.status).toBe(401)
})
it('returns a CSV with the header row and one line per log', async () => {
mockGetUserUsageLogs.mockResolvedValueOnce({
logs: [
{
id: 'log-1',
createdAt: '2026-07-01T00:00:00.000Z',
category: 'model',
source: 'copilot',
description: 'claude-opus-4.8',
cost: 0.5,
},
],
summary: { totalCost: 0.5, bySource: { copilot: 0.5 } },
pagination: { hasMore: false },
})
mockGetUsageCreditsByLogId.mockResolvedValue(apportionCredits([{ key: 'log-1', dollars: 0.5 }]))
const response = await GET(createMockRequest('GET'))
const csv = await response.text()
const [header, row] = csv.split('\n')
expect(response.headers.get('Content-Type')).toBe('text/csv; charset=utf-8')
expect(response.headers.get('Content-Disposition')).toContain('attachment; filename=')
expect(response.headers.get('X-Export-Truncated')).toBe('0')
expect(header).toBe('Date,Type,Credits')
expect(row).toBe('2026-07-01T00:00:00.000Z,Chat,100')
})
it('sets X-Export-Truncated when the safety cap is hit with more data remaining', async () => {
mockGetUserUsageLogs.mockResolvedValueOnce({
logs: Array.from({ length: 50000 }, (_, i) => ({
id: `log-${i}`,
createdAt: '2026-07-01T00:00:00.000Z',
source: 'copilot',
cost: 0.1,
})),
summary: { totalCost: 0, bySource: {} },
pagination: { hasMore: true, nextCursor: 'log-49999' },
})
const response = await GET(createMockRequest('GET'))
expect(response.headers.get('X-Export-Truncated')).toBe('1')
})
it('does not request the summary aggregate — the export never reads it', async () => {
mockGetUserUsageLogs.mockResolvedValueOnce({
logs: [],
summary: { totalCost: 0, bySource: {} },
pagination: { hasMore: false },
})
await GET(createMockRequest('GET'))
expect(mockGetUserUsageLogs).toHaveBeenCalledWith(
'user-1',
expect.objectContaining({ includeSummary: false })
)
})
it('names the specific workflow for workflow-sourced rows', async () => {
mockGetUserUsageLogs.mockResolvedValueOnce({
logs: [
{
id: 'log-1',
createdAt: '2026-07-01T00:00:00.000Z',
category: 'fixed',
source: 'workflow',
description: 'execution_fee',
cost: 0.01,
workflowId: 'wf-1',
workflowName: 'ITSM_Prod_main',
},
],
summary: { totalCost: 0.01, bySource: { workflow: 0.01 } },
pagination: { hasMore: false },
})
const response = await GET(createMockRequest('GET'))
const csv = await response.text()
expect(csv).toContain('Workflow: ITSM_Prod_main')
})
it('quotes a Type field that contains a comma', async () => {
mockGetUserUsageLogs.mockResolvedValueOnce({
logs: [
{
id: 'log-1',
createdAt: '2026-07-01T00:00:00.000Z',
category: 'fixed',
source: 'workflow',
description: 'execution_fee',
cost: 0.01,
workflowId: 'wf-1',
workflowName: 'Prod, main',
},
],
summary: { totalCost: 0.01, bySource: { workflow: 0.01 } },
pagination: { hasMore: false },
})
const response = await GET(createMockRequest('GET'))
const csv = await response.text()
expect(csv).toContain('"Workflow: Prod, main"')
})
it('paginates through getUserUsageLogs until hasMore is false', async () => {
mockGetUserUsageLogs
.mockResolvedValueOnce({
logs: [
{
id: 'log-1',
createdAt: '2026-07-01T00:00:00.000Z',
category: 'model',
source: 'copilot',
description: 'claude-opus-4.8',
cost: 0.1,
},
],
summary: { totalCost: 0.2, bySource: { copilot: 0.2 } },
pagination: { hasMore: true, nextCursor: 'log-1' },
})
.mockResolvedValueOnce({
logs: [
{
id: 'log-2',
createdAt: '2026-06-30T00:00:00.000Z',
category: 'model',
source: 'copilot',
description: 'claude-opus-4.8',
cost: 0.1,
},
],
summary: { totalCost: 0.2, bySource: { copilot: 0.2 } },
pagination: { hasMore: false },
})
const response = await GET(createMockRequest('GET'))
const csv = await response.text()
expect(mockGetUserUsageLogs).toHaveBeenCalledTimes(2)
expect(mockGetUserUsageLogs).toHaveBeenNthCalledWith(
2,
'user-1',
expect.objectContaining({
cursor: 'log-1',
cursorCreatedAt: new Date('2026-07-01T00:00:00.000Z'),
})
)
expect(csv.split('\n')).toHaveLength(3)
})
it('apportions credits once over the whole filtered set, not per page', async () => {
mockGetUserUsageLogs
.mockResolvedValueOnce({
logs: [
{ id: 'log-1', createdAt: '2026-07-01T00:00:00.000Z', source: 'copilot', cost: 0.002 },
],
summary: { totalCost: 0, bySource: {} },
pagination: { hasMore: true, nextCursor: 'log-1' },
})
.mockResolvedValueOnce({
logs: [
{ id: 'log-2', createdAt: '2026-06-30T00:00:00.000Z', source: 'copilot', cost: 0.002 },
],
summary: { totalCost: 0, bySource: {} },
pagination: { hasMore: false },
})
mockGetUsageCreditsByLogId.mockResolvedValue(
apportionCredits([
{ key: 'log-1', dollars: 0.002 },
{ key: 'log-2', dollars: 0.002 },
])
)
await GET(createMockRequest('GET'))
expect(mockGetUsageCreditsByLogId).toHaveBeenCalledTimes(1)
})
it('stops at exactly the safety cap without an extra wasted page fetch', async () => {
mockGetUserUsageLogs.mockResolvedValueOnce({
logs: Array.from({ length: 50000 }, (_, i) => ({
id: `log-${i}`,
createdAt: '2026-07-01T00:00:00.000Z',
source: 'copilot',
cost: 0.1,
})),
summary: { totalCost: 0, bySource: {} },
pagination: { hasMore: true, nextCursor: 'log-49999' },
})
await GET(createMockRequest('GET'))
expect(mockGetUserUsageLogs).toHaveBeenCalledTimes(1)
})
it('rejects "custom" period without a startDate', async () => {
const response = await GET(
createMockRequest('GET', undefined, {}, 'http://localhost:3000/api/test?period=custom')
)
expect(response.status).toBe(400)
expect(mockGetUserUsageLogs).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,109 @@
import { createLogger } from '@sim/logger'
import { type NextRequest, NextResponse } from 'next/server'
import { exportUsageLogsContract } from '@/lib/api/contracts/user'
import { parseRequest } from '@/lib/api/server'
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
import {
getUsageCreditsByLogId,
getUserUsageLogs,
type UsageLogSource,
} from '@/lib/billing/core/usage-log'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { formatCsvValue, toCsvRow } from '@/lib/table/export-format'
import { resolveDateRange } from '@/app/api/users/me/usage-logs/shared'
import { USAGE_LOG_SOURCE_LABELS } from '@/app/api/users/me/usage-logs/source-labels'
const logger = createLogger('UsageLogsExportAPI')
/**
* Circuit breaker, not a UX boundary — a personal credit ledger is bounded by
* the user's own usage history and should never realistically approach this.
* Exists only to keep a pathological account (or a bug upstream) from paging
* forever; hitting it is worth alerting on, not a normal truncation case.
*/
const EXPORT_SAFETY_CAP = 50000
const EXPORT_PAGE_SIZE = 1000
const CSV_HEADER = toCsvRow(['Date', 'Type', 'Credits'])
/**
* Downloads every usage log matching the current filter as CSV — unlike the
* paginated list route, this fetches every matching row in one response
* rather than a single page, since a user's own credit ledger is bounded
* (unlike, say, a workspace's full execution history).
*/
export const GET = withRouteHandler(async (request: NextRequest) => {
const auth = await checkSessionOrInternalAuth(request, { requireWorkflowId: false })
if (!auth.success || !auth.userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const parsed = await parseRequest(exportUsageLogsContract, request, {})
if (!parsed.success) return parsed.response
const { source, workspaceId, period, startDate, endDate } = parsed.data.query
const dateRange = resolveDateRange(period, startDate, endDate)
const filter = {
source: source as UsageLogSource | undefined,
workspaceId,
startDate: dateRange.startDate,
endDate: dateRange.endDate,
}
const rows: Awaited<ReturnType<typeof getUserUsageLogs>>['logs'] = []
let cursor: string | undefined
let cursorCreatedAt: Date | undefined
let truncated = false
while (rows.length < EXPORT_SAFETY_CAP) {
const page = await getUserUsageLogs(auth.userId, {
...filter,
limit: Math.min(EXPORT_PAGE_SIZE, EXPORT_SAFETY_CAP - rows.length),
cursor,
cursorCreatedAt,
includeSummary: false,
})
rows.push(...page.logs)
if (!page.pagination.hasMore) break
truncated = rows.length >= EXPORT_SAFETY_CAP
cursor = page.pagination.nextCursor
const lastRow = page.logs[page.logs.length - 1]
cursorCreatedAt = lastRow ? new Date(lastRow.createdAt) : undefined
}
const creditsByLogId = await getUsageCreditsByLogId(auth.userId, filter)
if (truncated) {
logger.error('Usage log export hit the safety cap — investigate this account', {
userId: auth.userId,
period,
cap: EXPORT_SAFETY_CAP,
})
}
const csvLines = rows.map((log) => {
const type =
log.source === 'workflow' && log.workflowName
? `Workflow: ${log.workflowName}`
: USAGE_LOG_SOURCE_LABELS[log.source]
return toCsvRow([
formatCsvValue(log.createdAt),
formatCsvValue(type),
formatCsvValue(creditsByLogId[log.id]),
])
})
const csv = [CSV_HEADER, ...csvLines].join('\n')
const filename = `credit-usage-${period}-${new Date().toISOString().slice(0, 10)}.csv`
logger.info('Exported usage logs', { userId: auth.userId, period, rowCount: rows.length })
return new NextResponse(csv, {
status: 200,
headers: {
'Content-Type': 'text/csv; charset=utf-8',
'Content-Disposition': `attachment; filename="${filename}"`,
'Cache-Control': 'no-cache',
'X-Export-Truncated': truncated ? '1' : '0',
},
})
})
@@ -0,0 +1,186 @@
/**
* @vitest-environment node
*/
import { authMockFns, createMockRequest } from '@sim/testing'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { apportionCredits } from '@/lib/billing/credits/conversion'
const { mockGetUserUsageLogs, mockGetUsageCreditsByLogId } = vi.hoisted(() => ({
mockGetUserUsageLogs: vi.fn(),
mockGetUsageCreditsByLogId: vi.fn(),
}))
vi.mock('@/lib/billing/core/usage-log', () => ({
getUserUsageLogs: mockGetUserUsageLogs,
getUsageCreditsByLogId: mockGetUsageCreditsByLogId,
}))
import { GET } from '@/app/api/users/me/usage-logs/route'
describe('GET /api/users/me/usage-logs', () => {
beforeEach(() => {
vi.clearAllMocks()
authMockFns.mockGetSession.mockResolvedValue({ user: { id: 'user-1' } })
mockGetUserUsageLogs.mockResolvedValue({
logs: [
{
id: 'log-1',
createdAt: '2026-07-01T00:00:00.000Z',
category: 'model',
source: 'workflow',
description: 'gpt-4o',
cost: 0.5,
},
],
summary: { totalCost: 0.5, bySource: { workflow: 0.5 } },
pagination: { hasMore: false },
})
mockGetUsageCreditsByLogId.mockResolvedValue(apportionCredits([{ key: 'log-1', dollars: 0.5 }]))
})
it('returns 401 when unauthenticated', async () => {
authMockFns.mockGetSession.mockResolvedValue(null)
const response = await GET(createMockRequest('GET'))
expect(response.status).toBe(401)
})
it('converts dollar costs to credits in the logs and summary', async () => {
const response = await GET(createMockRequest('GET'))
const body = await response.json()
expect(body.logs).toEqual([
{
id: 'log-1',
createdAt: '2026-07-01T00:00:00.000Z',
source: 'workflow',
workflowName: null,
creditCost: 100,
dollarCost: 0.5,
},
])
expect(body.summary).toEqual({
totalCredits: 100,
bySourceCredits: { workflow: 100 },
})
})
it('passes through the workflow name for workflow-sourced rows', async () => {
mockGetUserUsageLogs.mockResolvedValue({
logs: [
{
id: 'log-1',
createdAt: '2026-07-01T00:00:00.000Z',
category: 'fixed',
source: 'workflow',
description: 'execution_fee',
cost: 0.01,
workflowId: 'wf-1',
workflowName: 'ITSM_Prod_main',
},
],
summary: { totalCost: 0.01, bySource: { workflow: 0.01 } },
pagination: { hasMore: false },
})
mockGetUsageCreditsByLogId.mockResolvedValue(
apportionCredits([{ key: 'log-1', dollars: 0.01 }])
)
const response = await GET(createMockRequest('GET'))
const body = await response.json()
expect(body.logs[0].workflowName).toBe('ITSM_Prod_main')
})
it('rejects "custom" period without a startDate', async () => {
const response = await GET(
createMockRequest('GET', undefined, {}, 'http://localhost:3000/api/test?period=custom')
)
expect(response.status).toBe(400)
expect(mockGetUserUsageLogs).not.toHaveBeenCalled()
})
it('apportions row credits so they sum exactly to the page total, instead of rounding each row independently', async () => {
mockGetUserUsageLogs.mockResolvedValue({
logs: [
{ id: 'log-a', createdAt: '2026-07-01T00:00:00.000Z', source: 'workflow', cost: 0.002 },
{ id: 'log-b', createdAt: '2026-07-01T00:00:00.000Z', source: 'workflow', cost: 0.002 },
{ id: 'log-c', createdAt: '2026-07-01T00:00:00.000Z', source: 'workflow', cost: 0.002 },
].map((log) => ({ ...log, category: 'model', description: 'gpt-4o' })),
summary: { totalCost: 0.006, bySource: { workflow: 0.006 } },
pagination: { hasMore: false },
})
mockGetUsageCreditsByLogId.mockResolvedValue(
apportionCredits([
{ key: 'log-a', dollars: 0.002 },
{ key: 'log-b', dollars: 0.002 },
{ key: 'log-c', dollars: 0.002 },
])
)
const response = await GET(createMockRequest('GET'))
const body = await response.json()
const rowCreditSum = body.logs.reduce(
(sum: number, log: { creditCost: number }) => sum + log.creditCost,
0
)
expect(rowCreditSum).toBe(body.summary.totalCredits)
})
it('rejects an invalid period', async () => {
const response = await GET(
createMockRequest('GET', undefined, {}, 'http://localhost:3000/api/test?period=1y')
)
expect(response.status).toBe(400)
expect(mockGetUserUsageLogs).not.toHaveBeenCalled()
})
it('skips the whole-filter credit apportionment scan when includeCredits=false', async () => {
await GET(
createMockRequest(
'GET',
undefined,
{},
'http://localhost:3000/api/test?limit=1&includeCredits=false'
)
)
expect(mockGetUsageCreditsByLogId).not.toHaveBeenCalled()
})
it('defaults creditCost to 0 (not undefined) when credits were skipped', async () => {
const response = await GET(
createMockRequest(
'GET',
undefined,
{},
'http://localhost:3000/api/test?limit=1&includeCredits=false'
)
)
const body = await response.json()
expect(body.logs[0].creditCost).toBe(0)
})
it('resolves the start date from the period filter', async () => {
await GET(createMockRequest('GET', undefined, {}, 'http://localhost:3000/api/test?period=7d'))
expect(mockGetUserUsageLogs).toHaveBeenCalledWith(
'user-1',
expect.objectContaining({ startDate: expect.any(Date) })
)
})
it('omits the start date for the "all" period', async () => {
await GET(createMockRequest('GET', undefined, {}, 'http://localhost:3000/api/test?period=all'))
expect(mockGetUserUsageLogs).toHaveBeenCalledWith(
'user-1',
expect.objectContaining({ startDate: undefined })
)
})
})
@@ -0,0 +1,81 @@
import { createLogger } from '@sim/logger'
import { type NextRequest, NextResponse } from 'next/server'
import { getUsageLogsContract } from '@/lib/api/contracts/user'
import { parseRequest } from '@/lib/api/server'
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
import {
getUsageCreditsByLogId,
getUserUsageLogs,
type UsageLogSource,
} from '@/lib/billing/core/usage-log'
import { dollarsToCredits } from '@/lib/billing/credits/conversion'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { resolveDateRange } from '@/app/api/users/me/usage-logs/shared'
const logger = createLogger('UsageLogsAPI')
/**
* Lists the authenticated user's credit-consuming usage events (model, tool,
* and fixed charges), converted to credits for display in Billing settings.
*/
export const GET = withRouteHandler(async (request: NextRequest) => {
const auth = await checkSessionOrInternalAuth(request, { requireWorkflowId: false })
if (!auth.success || !auth.userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const parsed = await parseRequest(getUsageLogsContract, request, {})
if (!parsed.success) return parsed.response
const { source, workspaceId, period, startDate, endDate, limit, cursor, includeCredits } =
parsed.data.query
const dateRange = resolveDateRange(period, startDate, endDate)
const filter = {
source: source as UsageLogSource | undefined,
workspaceId,
startDate: dateRange.startDate,
endDate: dateRange.endDate,
}
const [result, creditsByLogId] = await Promise.all([
getUserUsageLogs(auth.userId, { ...filter, limit, cursor }),
includeCredits
? getUsageCreditsByLogId(auth.userId, filter)
: Promise.resolve<Record<string, number>>({}),
])
const logs = result.logs.map((log) => ({
id: log.id,
createdAt: log.createdAt,
source: log.source,
workflowName: log.workflowName ?? null,
creditCost: creditsByLogId[log.id] ?? 0,
dollarCost: log.cost,
}))
const bySourceCredits = Object.fromEntries(
Object.entries(result.summary.bySource).map(([sourceKey, cost]) => [
sourceKey,
dollarsToCredits(cost),
])
)
logger.debug('Retrieved usage logs', {
userId: auth.userId,
source,
period,
logCount: logs.length,
hasMore: result.pagination.hasMore,
})
return NextResponse.json({
success: true,
logs,
summary: {
totalCredits: dollarsToCredits(result.summary.totalCost),
bySourceCredits,
},
pagination: result.pagination,
})
})
@@ -0,0 +1,41 @@
/**
* @vitest-environment node
*/
import { describe, expect, it } from 'vitest'
import { resolveDateRange } from '@/app/api/users/me/usage-logs/shared'
describe('resolveDateRange', () => {
it('throws when period is "custom" without a startDate', () => {
expect(() => resolveDateRange('custom', undefined, undefined)).toThrow(
'startDate is required when period is "custom"'
)
})
it('defaults endDate to now when omitted for a custom period', () => {
const range = resolveDateRange('custom', '2026-01-01T00:00', undefined)
expect(range.startDate).toEqual(new Date('2026-01-01T00:00'))
expect(range.endDate.getTime()).toBeCloseTo(Date.now(), -3)
})
it('uses both bounds when provided for a custom period', () => {
const range = resolveDateRange('custom', '2026-01-01T00:00', '2026-01-31T00:00')
expect(range.startDate).toEqual(new Date('2026-01-01T00:00'))
expect(range.endDate).toEqual(new Date('2026-01-31T00:00'))
})
it('omits startDate for the "all" period', () => {
const range = resolveDateRange('all', undefined, undefined)
expect(range.startDate).toBeUndefined()
})
it('resolves a startDate N days back for a preset period', () => {
const range = resolveDateRange('7d', undefined, undefined)
const expected = new Date()
expected.setDate(expected.getDate() - 7)
expect(range.startDate?.toDateString()).toBe(expected.toDateString())
})
})
@@ -0,0 +1,28 @@
import type { UsageLogPeriod } from '@/lib/api/contracts/user'
const PERIOD_TO_DAYS: Record<'1d' | '7d' | '30d', number> = { '1d': 1, '7d': 7, '30d': 30 }
interface ResolvedDateRange {
startDate: Date | undefined
endDate: Date
}
/** Shared by the list and export routes so their date-filtering can never drift. */
export function resolveDateRange(
period: UsageLogPeriod,
customStartDate: string | undefined,
customEndDate: string | undefined
): ResolvedDateRange {
if (period === 'custom') {
if (!customStartDate) throw new Error('startDate is required when period is "custom"')
return {
startDate: new Date(customStartDate),
endDate: customEndDate ? new Date(customEndDate) : new Date(),
}
}
if (period === 'all') return { startDate: undefined, endDate: new Date() }
const startDate = new Date()
startDate.setDate(startDate.getDate() - PERIOD_TO_DAYS[period])
return { startDate, endDate: new Date() }
}
@@ -0,0 +1,20 @@
import type { UsageLogSource } from '@/lib/api/contracts/user'
/**
* Humanized labels for `usage_log.source`, shared by the Credit usage page's
* row rendering and the CSV export so both read identically. Avoids the
* internal "copilot" / "mothership" naming — the agent is always "Sim", the
* surface is "Chat". Pure data, no server-only imports, so it's safe from
* both the client page and the export route.
*/
export const USAGE_LOG_SOURCE_LABELS: Record<UsageLogSource, string> = {
workflow: 'Workflow',
wand: 'Wand',
copilot: 'Chat',
'workspace-chat': 'Chat',
mcp_copilot: 'Chat (MCP)',
mothership_block: 'Agent block',
'knowledge-base': 'Knowledge Base',
'voice-input': 'Voice input',
enrichment: 'Enrichment',
}