From ceac688fa8795f62d3f2843d7aee0355b86310f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorem=20Ju=C3=A1rez?= Date: Thu, 18 Jun 2026 07:27:46 -0600 Subject: [PATCH] Add cost dashboard to the master panel (tokens + storage, USD/MXN) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Superadmin view in /admin showing operating cost with per-restaurant breakdown. Models (migration 0012): - TokenUsage(restaurantId?, model, feature, inputTokens, outputTokens, createdAt) - ModelPrice(model, inputPricePerMTok, outputPricePerMTok, updatedAt) — seeded Haiku 4.5 1/5, Sonnet 4.6 3/15, Opus 4.8 5/25 (USD per million) - PriceUpdateLog(model, old/new input+output, source, createdAt) - ExchangeRate(date, rate) — daily USD→MXN cache - AppConfig(key,value) — seeded costPerGb=0 B1 Instrumentation: recordUsage() (fire-and-forget) logs every Anthropic call with its model/feature/restaurant and the response usage tokens — wired into the consultor (ai-consult), translation, and menu import. restaurantId null = Collina operational. B2 Price update: 'Update prices from Anthropic' button → fetches the public pricing page, Haiku extracts prices FROM THE PAGE TEXT ONLY (omits any not found), updates ModelPrice and writes a PriceUpdateLog (old→new). If the fetch is blocked, the UI offers a manual paste box processed the same way. These calls log as feature 'precios-update', restaurantId null. B3 Exchange: getUsdMxn() caches once/day via Frankfurter (no key); on failure falls back to the last stored rate, then a constant — never /bin/zsh; shows the rate's date. B4 Storage: measures GB per restaurant from /data/uploads/{slug}; configurable costPerGb (editable) projects a storage cost. B5 Dashboard (CostsDashboard): month total in USD + MXN, per-restaurant token cost (USD/MXN) + GB + projected storage cost, average per active restaurant, a separate 'Operativo Collina' line for restaurantId-null calls, and context (exchange rate + date, last price update). i18n es/en at parity. Verified (build passes; migration 0012 applies; seeds present): a usage row records model/tokens/restaurant; dashboard shows USD + MXN with the day's rate (Frankfurter live 17.21, cached); token cost math correct (/bin/zsh.04 for 20k/4k Haiku); storage GB + projected cost with cost/GB=0.10; operational calls isolated; price endpoint guarded (401) and graceful without key (502); PriceUpdateLog records old→new. --- messages/en.json | 27 +++ messages/es.json | 27 +++ .../0012_cost_dashboard/migration.sql | 60 ++++++ prisma/schema.prisma | 51 +++++ src/app/admin/page.tsx | 24 ++- src/app/api/[slug]/ai-consult/route.ts | 2 + src/app/api/[slug]/import/route.ts | 6 +- src/app/api/[slug]/translate/route.ts | 2 + src/app/api/admin/config/route.ts | 18 ++ src/app/api/admin/prices/update/route.ts | 38 ++++ src/components/admin/CostsDashboard.tsx | 188 ++++++++++++++++++ src/lib/config.ts | 20 ++ src/lib/costs.ts | 110 ++++++++++ src/lib/exchange.ts | 36 ++++ src/lib/import.ts | 6 +- src/lib/prices.ts | 115 +++++++++++ src/lib/storage.ts | 37 ++++ src/lib/usage.ts | 26 +++ 18 files changed, 790 insertions(+), 3 deletions(-) create mode 100644 prisma/migrations/0012_cost_dashboard/migration.sql create mode 100644 src/app/api/admin/config/route.ts create mode 100644 src/app/api/admin/prices/update/route.ts create mode 100644 src/components/admin/CostsDashboard.tsx create mode 100644 src/lib/config.ts create mode 100644 src/lib/costs.ts create mode 100644 src/lib/exchange.ts create mode 100644 src/lib/prices.ts create mode 100644 src/lib/storage.ts create mode 100644 src/lib/usage.ts diff --git a/messages/en.json b/messages/en.json index ee38520..3ef1809 100644 --- a/messages/en.json +++ b/messages/en.json @@ -226,6 +226,33 @@ "invalid": "Wrong username or password", "invalidLink": "Invalid access link" }, + "costs": { + "title": "Costs", + "exchangeRate": "Exchange rate", + "stale": "last available", + "pricesUpdated": "Prices updated", + "never": "never", + "totalMonth": "Month total", + "restaurantsTokens": "Restaurant tokens", + "storage": "Storage", + "avgPerRestaurant": "Average per restaurant", + "operativo": "Collina operational", + "operativoHint": "calls not attributable to a restaurant", + "costPerGb": "Cost per GB", + "save": "Save", + "updatePrices": "Update prices from Anthropic", + "updating": "Updating…", + "pricesUpdatedN": "Prices updated: {n} changes", + "pricesNoChange": "No price changes", + "fetchFailed": "Couldn't read the page. Paste the pricing text below:", + "updateFailed": "Couldn't update", + "pastePlaceholder": "Paste Anthropic's pricing page text here…", + "processText": "Process text", + "restaurant": "Restaurant", + "tokens": "Tokens", + "projected": "Projected storage", + "inactive": "inactive" + }, "admin": { "title": "Collina master panel", "newRestaurant": "New restaurant", diff --git a/messages/es.json b/messages/es.json index a9948ee..05c4f5e 100644 --- a/messages/es.json +++ b/messages/es.json @@ -226,6 +226,33 @@ "invalid": "Usuario o contraseña incorrectos", "invalidLink": "Link de acceso inválido" }, + "costs": { + "title": "Costos", + "exchangeRate": "Tipo de cambio", + "stale": "último disponible", + "pricesUpdated": "Precios actualizados", + "never": "nunca", + "totalMonth": "Total del mes", + "restaurantsTokens": "Tokens restaurantes", + "storage": "Almacenamiento", + "avgPerRestaurant": "Promedio por restaurante", + "operativo": "Operativo Collina", + "operativoHint": "llamadas no atribuibles a un restaurante", + "costPerGb": "Costo por GB", + "save": "Guardar", + "updatePrices": "Actualizar precios desde Anthropic", + "updating": "Actualizando…", + "pricesUpdatedN": "Precios actualizados: {n} cambios", + "pricesNoChange": "Sin cambios en los precios", + "fetchFailed": "No se pudo leer la página. Pega el texto de precios abajo:", + "updateFailed": "No se pudo actualizar", + "pastePlaceholder": "Pega aquí el texto de la página de precios de Anthropic…", + "processText": "Procesar texto", + "restaurant": "Restaurante", + "tokens": "Tokens", + "projected": "Proyectado almacenamiento", + "inactive": "inactivo" + }, "admin": { "title": "Panel maestro Collina", "newRestaurant": "Nuevo restaurante", diff --git a/prisma/migrations/0012_cost_dashboard/migration.sql b/prisma/migrations/0012_cost_dashboard/migration.sql new file mode 100644 index 0000000..6fed998 --- /dev/null +++ b/prisma/migrations/0012_cost_dashboard/migration.sql @@ -0,0 +1,60 @@ +-- CreateTable +CREATE TABLE "TokenUsage" ( + "id" TEXT NOT NULL, + "restaurantId" TEXT, + "model" TEXT NOT NULL, + "feature" TEXT NOT NULL, + "inputTokens" INTEGER NOT NULL DEFAULT 0, + "outputTokens" INTEGER NOT NULL DEFAULT 0, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "TokenUsage_pkey" PRIMARY KEY ("id") +); +CREATE INDEX "TokenUsage_createdAt_idx" ON "TokenUsage"("createdAt"); +CREATE INDEX "TokenUsage_restaurantId_createdAt_idx" ON "TokenUsage"("restaurantId", "createdAt"); + +-- CreateTable +CREATE TABLE "ModelPrice" ( + "model" TEXT NOT NULL, + "inputPricePerMTok" DOUBLE PRECISION NOT NULL, + "outputPricePerMTok" DOUBLE PRECISION NOT NULL, + "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "ModelPrice_pkey" PRIMARY KEY ("model") +); + +-- CreateTable +CREATE TABLE "PriceUpdateLog" ( + "id" TEXT NOT NULL, + "model" TEXT NOT NULL, + "oldInput" DOUBLE PRECISION, + "newInput" DOUBLE PRECISION, + "oldOutput" DOUBLE PRECISION, + "newOutput" DOUBLE PRECISION, + "source" TEXT NOT NULL DEFAULT 'anthropic', + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "PriceUpdateLog_pkey" PRIMARY KEY ("id") +); +CREATE INDEX "PriceUpdateLog_createdAt_idx" ON "PriceUpdateLog"("createdAt"); + +-- CreateTable +CREATE TABLE "ExchangeRate" ( + "date" TEXT NOT NULL, + "rate" DOUBLE PRECISION NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "ExchangeRate_pkey" PRIMARY KEY ("date") +); + +-- CreateTable +CREATE TABLE "AppConfig" ( + "key" TEXT NOT NULL, + "value" TEXT NOT NULL, + CONSTRAINT "AppConfig_pkey" PRIMARY KEY ("key") +); + +-- Seed current verified model prices (USD per million tokens). +INSERT INTO "ModelPrice" ("model","inputPricePerMTok","outputPricePerMTok","updatedAt") VALUES + ('claude-haiku-4-5', 1, 5, CURRENT_TIMESTAMP), + ('claude-sonnet-4-6', 3, 15, CURRENT_TIMESTAMP), + ('claude-opus-4-8', 5, 25, CURRENT_TIMESTAMP); + +-- Seed configurable cost per GB (default 0 = no projected storage cost yet). +INSERT INTO "AppConfig" ("key","value") VALUES ('costPerGb', '0'); diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 611ece5..2f476f3 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -116,3 +116,54 @@ model Order { @@index([restaurantId, status]) } + +// ── Cost dashboard (superadmin) ────────────────────────────────────────────── + +// One row per Anthropic API call. restaurantId null = Collina operational calls. +model TokenUsage { + id String @id @default(cuid()) + restaurantId String? // null = operational (e.g. price-update button) + model String + feature String // consultor | traduccion | import | precios-update + inputTokens Int @default(0) + outputTokens Int @default(0) + createdAt DateTime @default(now()) + + @@index([createdAt]) + @@index([restaurantId, createdAt]) +} + +// Editable per-model pricing (USD per million tokens). +model ModelPrice { + model String @id + inputPricePerMTok Float + outputPricePerMTok Float + updatedAt DateTime @default(now()) +} + +// Audit trail of price changes (old → new). +model PriceUpdateLog { + id String @id @default(cuid()) + model String + oldInput Float? + newInput Float? + oldOutput Float? + newOutput Float? + source String @default("anthropic") // anthropic | manual + createdAt DateTime @default(now()) + + @@index([createdAt]) +} + +// Daily USD→MXN exchange rate cache. +model ExchangeRate { + date String @id // YYYY-MM-DD + rate Float + createdAt DateTime @default(now()) +} + +// Generic key/value app config (e.g. costPerGb). +model AppConfig { + key String @id + value String +} diff --git a/src/app/admin/page.tsx b/src/app/admin/page.tsx index 8b764ff..4683a29 100644 --- a/src/app/admin/page.tsx +++ b/src/app/admin/page.tsx @@ -1,7 +1,9 @@ import { isAdminAuthed } from '@/lib/auth'; import { prisma } from '@/lib/prisma'; +import { getCostDashboard } from '@/lib/costs'; import AdminLogin from '@/components/admin/AdminLogin'; import AdminPanel from '@/components/admin/AdminPanel'; +import CostsDashboard from '@/components/admin/CostsDashboard'; export const dynamic = 'force-dynamic'; @@ -22,6 +24,26 @@ export default async function AdminPage() { }, }); + // Cost dashboard data (computed server-side). Never block the panel on it. + let costs = null; + try { + costs = await getCostDashboard(); + } catch (err) { + console.error('cost dashboard error', err); + } + const baseUrl = process.env.APP_BASE_URL || ''; - return ({ ...r, createdAt: r.createdAt.toISOString() }))} baseUrl={baseUrl} />; + return ( + <> + ({ ...r, createdAt: r.createdAt.toISOString() }))} + baseUrl={baseUrl} + /> + {costs && ( +
+ +
+ )} + + ); } diff --git a/src/app/api/[slug]/ai-consult/route.ts b/src/app/api/[slug]/ai-consult/route.ts index c5c9704..7ae4232 100644 --- a/src/app/api/[slug]/ai-consult/route.ts +++ b/src/app/api/[slug]/ai-consult/route.ts @@ -1,6 +1,7 @@ import { NextResponse } from 'next/server'; import { prisma } from '@/lib/prisma'; import { getAnthropic, HAIKU_MODEL } from '@/lib/anthropic'; +import { recordUsage } from '@/lib/usage'; import { parseLenientJson } from '@/lib/json'; import { pickText } from '@/lib/text'; import type { Locale } from '@/i18n/config'; @@ -120,6 +121,7 @@ export async function POST(req: Request, { params }: { params: { slug: string } system: [{ type: 'text', text: cacheable, cache_control: { type: 'ephemeral' } }], messages: [{ role: 'user', content: question }], }); + await recordUsage({ restaurantId: restaurant.id, model: HAIKU_MODEL, feature: 'consultor', usage: msg.usage }); const text = msg.content.find((c) => c.type === 'text')?.text ?? '{}'; // Lenient parse (shared with import): tolerates prose/fences/truncation so a diff --git a/src/app/api/[slug]/import/route.ts b/src/app/api/[slug]/import/route.ts index 01d4de8..9d8cb49 100644 --- a/src/app/api/[slug]/import/route.ts +++ b/src/app/api/[slug]/import/route.ts @@ -28,7 +28,11 @@ export async function POST(req: Request, { params }: { params: { slug: string } link: String(form.get('link') ?? ''), text: String(form.get('text') ?? ''), }); - const result = await extractMenu(source, guard.restaurant.defaultLocale as Locale); + const result = await extractMenu( + source, + guard.restaurant.defaultLocale as Locale, + guard.restaurant.id, + ); if (result.sections.length === 0) { return NextResponse.json({ error: 'nothing_found' }, { status: 422 }); } diff --git a/src/app/api/[slug]/translate/route.ts b/src/app/api/[slug]/translate/route.ts index f35f174..609c1ed 100644 --- a/src/app/api/[slug]/translate/route.ts +++ b/src/app/api/[slug]/translate/route.ts @@ -1,6 +1,7 @@ import { NextResponse } from 'next/server'; import { requireEditor } from '@/lib/guard'; import { getAnthropic, HAIKU_MODEL } from '@/lib/anthropic'; +import { recordUsage } from '@/lib/usage'; // Translate a single field with Claude Haiku to fill the missing locale. export async function POST(req: Request, { params }: { params: { slug: string } }) { @@ -23,6 +24,7 @@ export async function POST(req: Request, { params }: { params: { slug: string } `Keep it natural and appetizing. Reply with ONLY the translation, no quotes, no notes.`, messages: [{ role: 'user', content: text }], }); + await recordUsage({ restaurantId: guard.restaurant.id, model: HAIKU_MODEL, feature: 'traduccion', usage: msg.usage }); const translated = msg.content.find((c) => c.type === 'text')?.text?.trim() ?? ''; return NextResponse.json({ translation: translated, to }); } catch (err) { diff --git a/src/app/api/admin/config/route.ts b/src/app/api/admin/config/route.ts new file mode 100644 index 0000000..3fe1f49 --- /dev/null +++ b/src/app/api/admin/config/route.ts @@ -0,0 +1,18 @@ +import { NextResponse } from 'next/server'; +import { isAdminAuthed } from '@/lib/auth'; +import { setConfig } from '@/lib/config'; + +export const dynamic = 'force-dynamic'; + +// Update superadmin config (currently: costPerGb for projected storage cost). +export async function PATCH(req: Request) { + if (!(await isAdminAuthed())) { + return NextResponse.json({ error: 'unauthorized' }, { status: 401 }); + } + const body = await req.json().catch(() => null); + if (body?.costPerGb !== undefined) { + const v = Math.max(0, Number(body.costPerGb) || 0); + await setConfig('costPerGb', String(v)); + } + return NextResponse.json({ ok: true }); +} diff --git a/src/app/api/admin/prices/update/route.ts b/src/app/api/admin/prices/update/route.ts new file mode 100644 index 0000000..f058815 --- /dev/null +++ b/src/app/api/admin/prices/update/route.ts @@ -0,0 +1,38 @@ +import { NextResponse } from 'next/server'; +import { isAdminAuthed } from '@/lib/auth'; +import { fetchAnthropicPricingText, updatePricesFromText } from '@/lib/prices'; + +export const dynamic = 'force-dynamic'; +export const maxDuration = 60; + +// Update model prices from Anthropic's pricing page (Haiku extracts from the page +// text), or from manually pasted text when the fetch is blocked. +export async function POST(req: Request) { + if (!(await isAdminAuthed())) { + return NextResponse.json({ error: 'unauthorized' }, { status: 401 }); + } + + const body = await req.json().catch(() => ({})); + const manualText = typeof body?.text === 'string' ? body.text.trim() : ''; + + let text = manualText; + let source: 'anthropic' | 'manual' = manualText ? 'manual' : 'anthropic'; + if (!text) { + try { + text = await fetchAnthropicPricingText(); + source = 'anthropic'; + } catch (err) { + console.error('pricing fetch failed', err); + // Tell the UI to offer the manual-paste fallback. + return NextResponse.json({ error: 'fetch_failed' }, { status: 502 }); + } + } + + try { + const changes = await updatePricesFromText(text, source); + return NextResponse.json({ ok: true, changes }); + } catch (err) { + console.error('price update failed', err); + return NextResponse.json({ error: 'update_failed' }, { status: 502 }); + } +} diff --git a/src/components/admin/CostsDashboard.tsx b/src/components/admin/CostsDashboard.tsx new file mode 100644 index 0000000..159f669 --- /dev/null +++ b/src/components/admin/CostsDashboard.tsx @@ -0,0 +1,188 @@ +'use client'; + +import { useState } from 'react'; +import { useRouter } from 'next/navigation'; +import { useTranslations } from 'next-intl'; +import type { CostDashboard } from '@/lib/costs'; + +function usd(n: number): string { + return `$${n.toFixed(n >= 1 ? 2 : 4)}`; +} +function mxn(n: number, rate: number): string { + const v = n * rate; + return `$${v.toFixed(v >= 1 ? 2 : 4)}`; +} + +export default function CostsDashboard({ data }: { data: CostDashboard }) { + const t = useTranslations('costs'); + const router = useRouter(); + const rate = data.exchange.rate; + + const [costPerGb, setCostPerGb] = useState(String(data.costPerGb)); + const [busy, setBusy] = useState(false); + const [msg, setMsg] = useState(null); + const [pasteOpen, setPasteOpen] = useState(false); + const [pasteText, setPasteText] = useState(''); + + async function updatePrices(text?: string) { + setBusy(true); + setMsg(null); + try { + const r = await fetch('/api/admin/prices/update', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(text ? { text } : {}), + }); + const d = await r.json().catch(() => ({})); + if (r.ok) { + const n = d.changes?.length ?? 0; + setMsg(n > 0 ? t('pricesUpdatedN', { n }) : t('pricesNoChange')); + setPasteOpen(false); + setPasteText(''); + router.refresh(); + } else if (d.error === 'fetch_failed') { + setPasteOpen(true); + setMsg(t('fetchFailed')); + } else { + setMsg(t('updateFailed')); + } + } finally { + setBusy(false); + } + } + + async function saveCostPerGb() { + setBusy(true); + try { + await fetch('/api/admin/config', { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ costPerGb: Number(costPerGb) || 0 }), + }); + router.refresh(); + } finally { + setBusy(false); + } + } + + const { totals } = data; + + return ( +
+
+

{t('title')}

+ {data.monthLabel} +
+ + {/* Context */} +

+ {t('exchangeRate')}: 1 USD = {rate.toFixed(2)} MXN · {data.exchange.date} + {data.exchange.stale ? ` (${t('stale')})` : ''} ·{' '} + {t('pricesUpdated')}:{' '} + {data.pricesUpdatedAt ? new Date(data.pricesUpdatedAt).toLocaleDateString() : t('never')} +

+ + {/* Global totals */} +
+ + + + +
+ + {/* Operativo Collina (separate) */} +
+ {t('operativo')}: {usd(totals.operativoTokenUsd)} · {mxn(totals.operativoTokenUsd, rate)} MXN + ({t('operativoHint')}) +
+ + {/* Controls */} +
+
+ + +
+ +
+ + {msg &&

{msg}

} + {pasteOpen && ( +
+