Compare commits
3 commits
main
...
feat/story
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b2bde6934e | ||
|
|
51c8a86be4 | ||
|
|
d81f18149a |
9 changed files with 562 additions and 1 deletions
74
__tests__/lib/insights/token-history.test.ts
Normal file
74
__tests__/lib/insights/token-history.test.ts
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
const { mockQueryRaw } = vi.hoisted(() => ({ mockQueryRaw: vi.fn() }))
|
||||
|
||||
vi.mock('@/lib/prisma', () => ({
|
||||
prisma: { $queryRaw: mockQueryRaw },
|
||||
}))
|
||||
|
||||
import {
|
||||
getSprintTokenHistory,
|
||||
getDayTokenData,
|
||||
getPbiTokenAggregates,
|
||||
} from '@/lib/insights/token-history'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('getSprintTokenHistory', () => {
|
||||
it('returns mapped sprint rows', async () => {
|
||||
mockQueryRaw.mockResolvedValueOnce([
|
||||
{ sprint_id: 'sp-1', sprint_goal: 'Goal A', total_tokens: BigInt(5000), total_cost: 0.1, job_count: BigInt(2) },
|
||||
])
|
||||
const rows = await getSprintTokenHistory('user-1')
|
||||
expect(rows).toHaveLength(1)
|
||||
expect(rows[0].sprintId).toBe('sp-1')
|
||||
expect(rows[0].totalTokens).toBe(5000)
|
||||
expect(rows[0].totalCostUsd).toBe(0.1)
|
||||
expect(rows[0].jobCount).toBe(2)
|
||||
})
|
||||
|
||||
it('returns zero cost when total_cost is null', async () => {
|
||||
mockQueryRaw.mockResolvedValueOnce([
|
||||
{ sprint_id: 'sp-2', sprint_goal: 'Goal B', total_tokens: BigInt(0), total_cost: null, job_count: BigInt(0) },
|
||||
])
|
||||
const rows = await getSprintTokenHistory('user-1')
|
||||
expect(rows[0].totalCostUsd).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getDayTokenData', () => {
|
||||
it('returns empty array for empty sprintId', async () => {
|
||||
const rows = await getDayTokenData('user-1', '')
|
||||
expect(rows).toHaveLength(0)
|
||||
expect(mockQueryRaw).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('maps day rows with ISO date string', async () => {
|
||||
mockQueryRaw.mockResolvedValueOnce([
|
||||
{ day: new Date('2026-05-01T00:00:00Z'), total_tokens: BigInt(2000), total_cost: 0.05 },
|
||||
])
|
||||
const rows = await getDayTokenData('user-1', 'sprint-1')
|
||||
expect(rows).toHaveLength(1)
|
||||
expect(rows[0].day).toBe('2026-05-01')
|
||||
expect(rows[0].totalTokens).toBe(2000)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getPbiTokenAggregates', () => {
|
||||
it('returns empty array for empty sprintId', async () => {
|
||||
const rows = await getPbiTokenAggregates('user-1', '')
|
||||
expect(rows).toHaveLength(0)
|
||||
expect(mockQueryRaw).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('maps pbi rows', async () => {
|
||||
mockQueryRaw.mockResolvedValueOnce([
|
||||
{ pbi_id: 'pbi-1', pbi_code: 'M1', pbi_title: 'First PBI', total_tokens: BigInt(3000), total_cost: 0.08 },
|
||||
])
|
||||
const rows = await getPbiTokenAggregates('user-1', 'sprint-1')
|
||||
expect(rows[0].pbiCode).toBe('M1')
|
||||
expect(rows[0].totalTokens).toBe(3000)
|
||||
})
|
||||
})
|
||||
|
|
@ -91,7 +91,12 @@ export default async function InsightsPage({ searchParams }: InsightsPageProps)
|
|||
|
||||
return (
|
||||
<div className="p-6 space-y-8 max-w-6xl mx-auto w-full">
|
||||
<h1 className="text-2xl font-semibold text-foreground">Insights</h1>
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<h1 className="text-2xl font-semibold text-foreground">Insights</h1>
|
||||
<a href="/insights/tokens" className="text-primary text-sm underline">
|
||||
Historisch token-overzicht →
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{/* Sprint Health */}
|
||||
<section className="space-y-3">
|
||||
|
|
|
|||
3
app/(app)/insights/tokens/components/index.ts
Normal file
3
app/(app)/insights/tokens/components/index.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
export { TokenDayChart } from './token-day-chart'
|
||||
export { SprintTokenHistoryTable } from './sprint-token-history-table'
|
||||
export { PbiTokenTable } from './pbi-token-table'
|
||||
56
app/(app)/insights/tokens/components/pbi-token-table.tsx
Normal file
56
app/(app)/insights/tokens/components/pbi-token-table.tsx
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
'use client'
|
||||
|
||||
import { useState, useMemo } from 'react'
|
||||
import type { PbiTokenRow } from '@/lib/insights/token-history'
|
||||
|
||||
interface Props {
|
||||
rows: PbiTokenRow[]
|
||||
}
|
||||
|
||||
export function PbiTokenTable({ rows }: Props) {
|
||||
const [sortDesc, setSortDesc] = useState(true)
|
||||
|
||||
const sorted = useMemo(
|
||||
() => [...rows].sort((a, b) => sortDesc ? b.totalCostUsd - a.totalCostUsd : a.totalCostUsd - b.totalCostUsd),
|
||||
[rows, sortDesc],
|
||||
)
|
||||
|
||||
if (rows.length === 0) {
|
||||
return <p className="text-muted-foreground text-sm">Geen PBI-data voor deze sprint.</p>
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border bg-muted text-muted-foreground text-xs uppercase tracking-wide">
|
||||
<th className="py-2 pr-4 text-left font-medium">PBI-code</th>
|
||||
<th className="py-2 pr-4 text-left font-medium">Titel</th>
|
||||
<th className="py-2 pr-4 text-right font-medium">Tokens</th>
|
||||
<th
|
||||
className="py-2 text-right font-medium cursor-pointer select-none text-primary"
|
||||
onClick={() => setSortDesc(d => !d)}
|
||||
>
|
||||
Kosten (USD) {sortDesc ? '▾' : '▴'}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sorted.map(r => {
|
||||
const title = r.pbiTitle.length > 60 ? r.pbiTitle.slice(0, 57) + '…' : r.pbiTitle
|
||||
return (
|
||||
<tr key={r.pbiId} className="border-b border-border last:border-0">
|
||||
<td className="py-2 pr-4 text-muted-foreground whitespace-nowrap">{r.pbiCode}</td>
|
||||
<td className="py-2 pr-4 text-foreground">{title}</td>
|
||||
<td className="py-2 pr-4 text-right tabular-nums">{r.totalTokens.toLocaleString()}</td>
|
||||
<td className="py-2 text-right tabular-nums">
|
||||
{r.totalCostUsd > 0 ? `$${r.totalCostUsd.toFixed(4)}` : '—'}
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
'use client'
|
||||
|
||||
import { useRouter } from 'next/navigation'
|
||||
import type { SprintTokenRow } from '@/lib/insights/token-history'
|
||||
|
||||
interface Props {
|
||||
rows: SprintTokenRow[]
|
||||
selectedSprintId: string
|
||||
}
|
||||
|
||||
export function SprintTokenHistoryTable({ rows, selectedSprintId }: Props) {
|
||||
const router = useRouter()
|
||||
|
||||
if (rows.length === 0) {
|
||||
return <p className="text-muted-foreground text-sm">Geen sprint-data met token-registratie.</p>
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border bg-muted text-muted-foreground text-xs uppercase tracking-wide">
|
||||
<th className="py-2 pr-4 text-left font-medium">Sprint goal</th>
|
||||
<th className="py-2 pr-4 text-right font-medium">Tokens</th>
|
||||
<th className="py-2 pr-4 text-right font-medium">Kosten (USD)</th>
|
||||
<th className="py-2 text-right font-medium">Aantal jobs</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map(r => {
|
||||
const goal = r.sprintGoal.length > 40 ? r.sprintGoal.slice(0, 37) + '…' : r.sprintGoal
|
||||
return (
|
||||
<tr
|
||||
key={r.sprintId}
|
||||
className={`border-b border-border last:border-0 cursor-pointer hover:bg-muted/40 ${r.sprintId === selectedSprintId ? 'bg-muted/50' : ''}`}
|
||||
onClick={() => router.push(`/insights/tokens?sprint=${r.sprintId}`)}
|
||||
>
|
||||
<td className="py-2 pr-4 text-foreground">{goal}</td>
|
||||
<td className="py-2 pr-4 text-right tabular-nums">{r.totalTokens.toLocaleString()}</td>
|
||||
<td className="py-2 pr-4 text-right tabular-nums">${r.totalCostUsd.toFixed(4)}</td>
|
||||
<td className="py-2 text-right tabular-nums">{r.jobCount}</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
33
app/(app)/insights/tokens/components/token-day-chart.tsx
Normal file
33
app/(app)/insights/tokens/components/token-day-chart.tsx
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
'use client'
|
||||
|
||||
import { LineChart, Line, XAxis, YAxis, Tooltip, CartesianGrid, ResponsiveContainer } from 'recharts'
|
||||
import type { DayTokenRow } from '@/lib/insights/token-history'
|
||||
|
||||
interface Props {
|
||||
data: DayTokenRow[]
|
||||
}
|
||||
|
||||
export function TokenDayChart({ data }: Props) {
|
||||
if (data.length === 0) {
|
||||
return <p className="text-muted-foreground">Geen dag-data beschikbaar</p>
|
||||
}
|
||||
|
||||
return (
|
||||
<ResponsiveContainer width="100%" height={280}>
|
||||
<LineChart data={data}>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="var(--border)" />
|
||||
<XAxis dataKey="day" tick={{ fontSize: 11 }} tickFormatter={v => (v as string).slice(5).replace('-', '/')} />
|
||||
<YAxis tick={{ fontSize: 11 }} tickFormatter={v => `$${(v as number).toFixed(3)}`} />
|
||||
<Tooltip formatter={(v: unknown) => [`$${Number(v).toFixed(4)}`, 'Kosten']} />
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="totalCostUsd"
|
||||
stroke="var(--color-primary)"
|
||||
strokeWidth={2}
|
||||
dot={false}
|
||||
name="Kosten (USD)"
|
||||
/>
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
)
|
||||
}
|
||||
81
app/(app)/insights/tokens/components/token-selectors.tsx
Normal file
81
app/(app)/insights/tokens/components/token-selectors.tsx
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
'use client'
|
||||
|
||||
import { useRouter, usePathname, useSearchParams } from 'next/navigation'
|
||||
import { useTransition } from 'react'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
|
||||
interface Sprint {
|
||||
id: string
|
||||
sprint_goal: string
|
||||
}
|
||||
|
||||
interface Props {
|
||||
productList: { id: string; name: string }[]
|
||||
sprintList: Sprint[]
|
||||
currentProductId?: string
|
||||
currentSprintId?: string
|
||||
}
|
||||
|
||||
export function TokenSelectors({ productList, sprintList, currentProductId, currentSprintId }: Props) {
|
||||
const router = useRouter()
|
||||
const pathname = usePathname()
|
||||
const searchParams = useSearchParams()
|
||||
const [isPending, startTransition] = useTransition()
|
||||
|
||||
function setParam(key: string, value: string | null) {
|
||||
startTransition(() => {
|
||||
const params = new URLSearchParams(searchParams.toString())
|
||||
if (value === null || value === '') {
|
||||
params.delete(key)
|
||||
} else {
|
||||
params.set(key, value)
|
||||
}
|
||||
router.replace(`${pathname}?${params.toString()}`)
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex gap-3 flex-wrap">
|
||||
{productList.length > 0 && (
|
||||
<Select
|
||||
value={currentProductId ?? '__all__'}
|
||||
onValueChange={v => setParam('product', v === '__all__' ? null : v)}
|
||||
>
|
||||
<SelectTrigger className="w-44" disabled={isPending}>
|
||||
<SelectValue placeholder="Product" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="__all__">Alle producten</SelectItem>
|
||||
{productList.map(p => (
|
||||
<SelectItem key={p.id} value={p.id}>{p.name}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
|
||||
{sprintList.length > 0 && (
|
||||
<Select
|
||||
value={currentSprintId ?? ''}
|
||||
onValueChange={v => setParam('sprint', v)}
|
||||
>
|
||||
<SelectTrigger className="w-64" disabled={isPending}>
|
||||
<SelectValue placeholder="Sprint kiezen" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{sprintList.map(s => (
|
||||
<SelectItem key={s.id} value={s.id}>
|
||||
{s.sprint_goal.length > 50 ? s.sprint_goal.slice(0, 47) + '…' : s.sprint_goal}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
84
app/(app)/insights/tokens/page.tsx
Normal file
84
app/(app)/insights/tokens/page.tsx
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
import { cookies } from 'next/headers'
|
||||
import { getIronSession } from 'iron-session'
|
||||
import { SessionData, sessionOptions } from '@/lib/session'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { productAccessFilter } from '@/lib/product-access'
|
||||
import { getSprintTokenHistory, getDayTokenData, getPbiTokenAggregates } from '@/lib/insights/token-history'
|
||||
import { SprintTokenHistoryTable } from './components/sprint-token-history-table'
|
||||
import { TokenDayChart } from './components/token-day-chart'
|
||||
import { PbiTokenTable } from './components/pbi-token-table'
|
||||
import { TokenSelectors } from './components/token-selectors'
|
||||
|
||||
interface TokensPageProps {
|
||||
searchParams: Promise<{ product?: string; sprint?: string }>
|
||||
}
|
||||
|
||||
export default async function TokensPage({ searchParams }: TokensPageProps) {
|
||||
const session = await getIronSession<SessionData>(await cookies(), sessionOptions)
|
||||
const userId = session.userId!
|
||||
const { product: filterProductId, sprint: filterSprintId } = await searchParams
|
||||
|
||||
const [sprintHistory, productList, activeSprint, allSprints] = await Promise.all([
|
||||
getSprintTokenHistory(userId, filterProductId),
|
||||
prisma.product.findMany({
|
||||
where: productAccessFilter(userId),
|
||||
select: { id: true, name: true },
|
||||
orderBy: { name: 'asc' },
|
||||
}),
|
||||
prisma.sprint.findFirst({
|
||||
where: { status: 'ACTIVE', product: productAccessFilter(userId) },
|
||||
select: { id: true, sprint_goal: true },
|
||||
}),
|
||||
prisma.sprint.findMany({
|
||||
where: { product: productAccessFilter(userId) },
|
||||
select: { id: true, sprint_goal: true },
|
||||
orderBy: { created_at: 'desc' },
|
||||
take: 20,
|
||||
}),
|
||||
])
|
||||
|
||||
const selectedSprintId = filterSprintId ?? activeSprint?.id ?? ''
|
||||
|
||||
const [dayData, pbiData] = selectedSprintId
|
||||
? await Promise.all([
|
||||
getDayTokenData(userId, selectedSprintId),
|
||||
getPbiTokenAggregates(userId, selectedSprintId),
|
||||
])
|
||||
: [[], []]
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-8 max-w-5xl mx-auto w-full">
|
||||
<div className="flex items-center justify-between gap-4 flex-wrap">
|
||||
<h1 className="text-2xl font-semibold text-foreground">Token-gebruik & kosten</h1>
|
||||
<a href="/insights" className="text-primary text-sm underline">
|
||||
← Terug naar Insights
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<TokenSelectors
|
||||
productList={productList}
|
||||
sprintList={allSprints}
|
||||
currentProductId={filterProductId}
|
||||
currentSprintId={selectedSprintId}
|
||||
/>
|
||||
|
||||
{/* Sprint historiek */}
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-lg font-medium text-foreground">Sprint-historiek</h2>
|
||||
<SprintTokenHistoryTable rows={sprintHistory} selectedSprintId={selectedSprintId} />
|
||||
</section>
|
||||
|
||||
{/* Dagelijkse kosten */}
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-lg font-medium text-foreground">Dagelijkse kosten</h2>
|
||||
<TokenDayChart data={dayData} />
|
||||
</section>
|
||||
|
||||
{/* PBI-aggregaat */}
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-lg font-medium text-foreground">Per PBI</h2>
|
||||
<PbiTokenTable rows={pbiData} />
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
176
lib/insights/token-history.ts
Normal file
176
lib/insights/token-history.ts
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
export interface SprintTokenRow {
|
||||
sprintId: string
|
||||
sprintGoal: string
|
||||
totalTokens: number
|
||||
totalCostUsd: number
|
||||
jobCount: number
|
||||
}
|
||||
|
||||
export interface DayTokenRow {
|
||||
day: string
|
||||
totalTokens: number
|
||||
totalCostUsd: number
|
||||
}
|
||||
|
||||
export interface PbiTokenRow {
|
||||
pbiId: string
|
||||
pbiCode: string
|
||||
pbiTitle: string
|
||||
totalTokens: number
|
||||
totalCostUsd: number
|
||||
}
|
||||
|
||||
type RawSprintRow = {
|
||||
sprint_id: string
|
||||
sprint_goal: string
|
||||
total_tokens: bigint
|
||||
total_cost: number | null
|
||||
job_count: bigint
|
||||
}
|
||||
|
||||
type RawDayRow = {
|
||||
day: Date
|
||||
total_tokens: bigint
|
||||
total_cost: number | null
|
||||
}
|
||||
|
||||
type RawPbiRow = {
|
||||
pbi_id: string
|
||||
pbi_code: string
|
||||
pbi_title: string
|
||||
total_tokens: bigint
|
||||
total_cost: number | null
|
||||
}
|
||||
|
||||
export async function getSprintTokenHistory(
|
||||
userId: string,
|
||||
productId?: string,
|
||||
limit = 8,
|
||||
): Promise<SprintTokenRow[]> {
|
||||
const rows = productId
|
||||
? await prisma.$queryRaw<RawSprintRow[]>`
|
||||
SELECT
|
||||
sp.id AS sprint_id,
|
||||
sp.sprint_goal,
|
||||
COALESCE(SUM(cj.input_tokens + cj.output_tokens + cj.cache_read_tokens + cj.cache_write_tokens), 0) AS total_tokens,
|
||||
SUM(
|
||||
cj.input_tokens * mp.input_price_per_1m / 1000000.0
|
||||
+ cj.output_tokens * mp.output_price_per_1m / 1000000.0
|
||||
+ cj.cache_read_tokens * mp.cache_read_price_per_1m / 1000000.0
|
||||
+ cj.cache_write_tokens * mp.cache_write_price_per_1m / 1000000.0
|
||||
) FILTER (WHERE cj.input_tokens IS NOT NULL) AS total_cost,
|
||||
COUNT(*) FILTER (WHERE cj.input_tokens IS NOT NULL) AS job_count
|
||||
FROM claude_jobs cj
|
||||
JOIN tasks t ON cj.task_id = t.id
|
||||
JOIN stories s ON t.story_id = s.id
|
||||
JOIN sprints sp ON s.sprint_id = sp.id
|
||||
LEFT JOIN model_prices mp ON mp.model_id = cj.model_id
|
||||
WHERE cj.user_id = ${userId}
|
||||
AND cj.status = 'DONE'
|
||||
AND cj.product_id = ${productId}
|
||||
GROUP BY sp.id, sp.sprint_goal
|
||||
ORDER BY sp.created_at DESC
|
||||
LIMIT ${limit}
|
||||
`
|
||||
: await prisma.$queryRaw<RawSprintRow[]>`
|
||||
SELECT
|
||||
sp.id AS sprint_id,
|
||||
sp.sprint_goal,
|
||||
COALESCE(SUM(cj.input_tokens + cj.output_tokens + cj.cache_read_tokens + cj.cache_write_tokens), 0) AS total_tokens,
|
||||
SUM(
|
||||
cj.input_tokens * mp.input_price_per_1m / 1000000.0
|
||||
+ cj.output_tokens * mp.output_price_per_1m / 1000000.0
|
||||
+ cj.cache_read_tokens * mp.cache_read_price_per_1m / 1000000.0
|
||||
+ cj.cache_write_tokens * mp.cache_write_price_per_1m / 1000000.0
|
||||
) FILTER (WHERE cj.input_tokens IS NOT NULL) AS total_cost,
|
||||
COUNT(*) FILTER (WHERE cj.input_tokens IS NOT NULL) AS job_count
|
||||
FROM claude_jobs cj
|
||||
JOIN tasks t ON cj.task_id = t.id
|
||||
JOIN stories s ON t.story_id = s.id
|
||||
JOIN sprints sp ON s.sprint_id = sp.id
|
||||
LEFT JOIN model_prices mp ON mp.model_id = cj.model_id
|
||||
WHERE cj.user_id = ${userId}
|
||||
AND cj.status = 'DONE'
|
||||
GROUP BY sp.id, sp.sprint_goal
|
||||
ORDER BY sp.created_at DESC
|
||||
LIMIT ${limit}
|
||||
`
|
||||
|
||||
return rows.map(r => ({
|
||||
sprintId: r.sprint_id,
|
||||
sprintGoal: r.sprint_goal,
|
||||
totalTokens: Number(r.total_tokens),
|
||||
totalCostUsd: Number(r.total_cost ?? 0),
|
||||
jobCount: Number(r.job_count),
|
||||
}))
|
||||
}
|
||||
|
||||
export async function getDayTokenData(userId: string, sprintId: string): Promise<DayTokenRow[]> {
|
||||
if (!sprintId) return []
|
||||
|
||||
const rows = await prisma.$queryRaw<RawDayRow[]>`
|
||||
SELECT
|
||||
DATE(cj.finished_at) AS day,
|
||||
COALESCE(SUM(cj.input_tokens + cj.output_tokens + cj.cache_read_tokens + cj.cache_write_tokens), 0) AS total_tokens,
|
||||
SUM(
|
||||
cj.input_tokens * mp.input_price_per_1m / 1000000.0
|
||||
+ cj.output_tokens * mp.output_price_per_1m / 1000000.0
|
||||
+ cj.cache_read_tokens * mp.cache_read_price_per_1m / 1000000.0
|
||||
+ cj.cache_write_tokens * mp.cache_write_price_per_1m / 1000000.0
|
||||
) FILTER (WHERE cj.input_tokens IS NOT NULL) AS total_cost
|
||||
FROM claude_jobs cj
|
||||
JOIN tasks t ON cj.task_id = t.id
|
||||
JOIN stories s ON t.story_id = s.id
|
||||
LEFT JOIN model_prices mp ON mp.model_id = cj.model_id
|
||||
WHERE cj.user_id = ${userId}
|
||||
AND s.sprint_id = ${sprintId}
|
||||
AND cj.status = 'DONE'
|
||||
AND cj.finished_at IS NOT NULL
|
||||
GROUP BY DATE(cj.finished_at)
|
||||
ORDER BY day ASC
|
||||
`
|
||||
|
||||
return rows.map(r => ({
|
||||
day: r.day.toISOString().slice(0, 10),
|
||||
totalTokens: Number(r.total_tokens),
|
||||
totalCostUsd: Number(r.total_cost ?? 0),
|
||||
}))
|
||||
}
|
||||
|
||||
export async function getPbiTokenAggregates(userId: string, sprintId: string): Promise<PbiTokenRow[]> {
|
||||
if (!sprintId) return []
|
||||
|
||||
const rows = await prisma.$queryRaw<RawPbiRow[]>`
|
||||
SELECT
|
||||
p.id AS pbi_id,
|
||||
p.code AS pbi_code,
|
||||
p.title AS pbi_title,
|
||||
COALESCE(SUM(cj.input_tokens + cj.output_tokens + cj.cache_read_tokens + cj.cache_write_tokens), 0) AS total_tokens,
|
||||
SUM(
|
||||
cj.input_tokens * mp.input_price_per_1m / 1000000.0
|
||||
+ cj.output_tokens * mp.output_price_per_1m / 1000000.0
|
||||
+ cj.cache_read_tokens * mp.cache_read_price_per_1m / 1000000.0
|
||||
+ cj.cache_write_tokens * mp.cache_write_price_per_1m / 1000000.0
|
||||
) FILTER (WHERE cj.input_tokens IS NOT NULL) AS total_cost
|
||||
FROM claude_jobs cj
|
||||
JOIN tasks t ON cj.task_id = t.id
|
||||
JOIN stories s ON t.story_id = s.id
|
||||
JOIN pbis p ON s.pbi_id = p.id
|
||||
LEFT JOIN model_prices mp ON mp.model_id = cj.model_id
|
||||
WHERE cj.user_id = ${userId}
|
||||
AND s.sprint_id = ${sprintId}
|
||||
AND cj.status = 'DONE'
|
||||
GROUP BY p.id, p.code, p.title
|
||||
ORDER BY total_cost DESC
|
||||
`
|
||||
|
||||
return rows.map(r => ({
|
||||
pbiId: r.pbi_id,
|
||||
pbiCode: r.pbi_code,
|
||||
pbiTitle: r.pbi_title,
|
||||
totalTokens: Number(r.total_tokens),
|
||||
totalCostUsd: Number(r.total_cost ?? 0),
|
||||
}))
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue