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',
},
})
})