Add cost dashboard to the master panel (tokens + storage, USD/MXN)
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.
This commit is contained in:
1 parent
c82c0f2108
commit
ceac688fa8
18 files changed
+790
-3
No files matched your search
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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');
|
||||
@@ -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
|
||||
}
|
||||
+23
-1
@@ -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 <AdminPanel initialRestaurants={restaurants.map((r) => ({ ...r, createdAt: r.createdAt.toISOString() }))} baseUrl={baseUrl} />;
|
||||
return (
|
||||
<>
|
||||
<AdminPanel
|
||||
initialRestaurants={restaurants.map((r) => ({ ...r, createdAt: r.createdAt.toISOString() }))}
|
||||
baseUrl={baseUrl}
|
||||
/>
|
||||
{costs && (
|
||||
<div className="mx-auto max-w-3xl px-4 pb-16">
|
||||
<CostsDashboard data={costs} />
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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<string | null>(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 (
|
||||
<section className="glass mb-6 mt-2 rounded-3xl p-5">
|
||||
<div className="mb-1 flex items-center justify-between gap-2">
|
||||
<h2 className="display text-xl font-semibold">{t('title')}</h2>
|
||||
<span className="text-xs text-[var(--text)]/55">{data.monthLabel}</span>
|
||||
</div>
|
||||
|
||||
{/* Context */}
|
||||
<p className="mb-4 text-xs text-[var(--text)]/55">
|
||||
{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')}
|
||||
</p>
|
||||
|
||||
{/* Global totals */}
|
||||
<div className="mb-4 grid grid-cols-2 gap-2 sm:grid-cols-4">
|
||||
<Stat label={t('totalMonth')} value={usd(totals.grandUsd)} sub={`${mxn(totals.grandUsd, rate)} MXN`} />
|
||||
<Stat label={t('restaurantsTokens')} value={usd(totals.restaurantsTokenUsd)} sub={`${mxn(totals.restaurantsTokenUsd, rate)} MXN`} />
|
||||
<Stat label={t('storage')} value={usd(totals.storageUsd)} sub={`${mxn(totals.storageUsd, rate)} MXN`} />
|
||||
<Stat label={t('avgPerRestaurant')} value={usd(totals.avgPerRestaurantUsd)} sub={`${mxn(totals.avgPerRestaurantUsd, rate)} MXN`} />
|
||||
</div>
|
||||
|
||||
{/* Operativo Collina (separate) */}
|
||||
<div className="mb-4 rounded-2xl bg-amber-50/60 px-4 py-2 text-sm text-amber-800">
|
||||
{t('operativo')}: <strong>{usd(totals.operativoTokenUsd)}</strong> · {mxn(totals.operativoTokenUsd, rate)} MXN
|
||||
<span className="ml-1 text-xs">({t('operativoHint')})</span>
|
||||
</div>
|
||||
|
||||
{/* Controls */}
|
||||
<div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
|
||||
<div className="flex items-end gap-2">
|
||||
<label className="flex flex-col gap-1 text-xs">
|
||||
{t('costPerGb')} (USD)
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
step="0.01"
|
||||
value={costPerGb}
|
||||
onChange={(e) => setCostPerGb(e.target.value)}
|
||||
className="glass-soft w-24 rounded-xl px-2 py-1.5 text-sm outline-none"
|
||||
/>
|
||||
</label>
|
||||
<button onClick={saveCostPerGb} disabled={busy} className="glass-pill rounded-full px-4 py-2 text-sm disabled:opacity-50">
|
||||
{t('save')}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => updatePrices()}
|
||||
disabled={busy}
|
||||
className="rounded-full bg-[var(--accent)] px-4 py-2 text-sm font-medium text-white disabled:opacity-50"
|
||||
>
|
||||
{busy ? t('updating') : t('updatePrices')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{msg && <p className="mb-3 text-sm text-[var(--text)]/70">{msg}</p>}
|
||||
{pasteOpen && (
|
||||
<div className="mb-4 flex flex-col gap-2">
|
||||
<textarea
|
||||
value={pasteText}
|
||||
onChange={(e) => setPasteText(e.target.value)}
|
||||
rows={4}
|
||||
placeholder={t('pastePlaceholder')}
|
||||
className="glass-soft rounded-2xl px-3 py-2 text-sm outline-none"
|
||||
/>
|
||||
<button
|
||||
onClick={() => pasteText.trim() && updatePrices(pasteText.trim())}
|
||||
disabled={busy || !pasteText.trim()}
|
||||
className="self-start rounded-full bg-[var(--accent)] px-4 py-2 text-sm font-medium text-white disabled:opacity-50"
|
||||
>
|
||||
{t('processText')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Per-restaurant breakdown */}
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="text-left text-xs text-[var(--text)]/55">
|
||||
<th className="py-1">{t('restaurant')}</th>
|
||||
<th className="py-1 text-right">{t('tokens')} (USD/MXN)</th>
|
||||
<th className="py-1 text-right">GB</th>
|
||||
<th className="py-1 text-right">{t('projected')} (USD/MXN)</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.restaurants.map((r) => (
|
||||
<tr key={r.id} className="border-t border-white/40">
|
||||
<td className="py-1.5">
|
||||
{r.name}
|
||||
{!r.active && <span className="ml-1 text-xs text-[var(--text)]/40">({t('inactive')})</span>}
|
||||
</td>
|
||||
<td className="py-1.5 text-right">
|
||||
{usd(r.tokenCostUsd)} <span className="text-[var(--text)]/50">/ {mxn(r.tokenCostUsd, rate)}</span>
|
||||
</td>
|
||||
<td className="py-1.5 text-right">{r.gb.toFixed(3)}</td>
|
||||
<td className="py-1.5 text-right">
|
||||
{usd(r.storageCostUsd)} <span className="text-[var(--text)]/50">/ {mxn(r.storageCostUsd, rate)}</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function Stat({ label, value, sub }: { label: string; value: string; sub: string }) {
|
||||
return (
|
||||
<div className="glass-soft rounded-2xl px-3 py-2">
|
||||
<div className="text-[11px] text-[var(--text)]/55">{label}</div>
|
||||
<div className="text-lg font-semibold">{value}</div>
|
||||
<div className="text-[11px] text-[var(--text)]/50">{sub}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { prisma } from './prisma';
|
||||
|
||||
// Generic key/value config helpers (AppConfig table).
|
||||
export async function getConfig(key: string, fallback = ''): Promise<string> {
|
||||
const row = await prisma.appConfig.findUnique({ where: { key } });
|
||||
return row?.value ?? fallback;
|
||||
}
|
||||
|
||||
export async function setConfig(key: string, value: string): Promise<void> {
|
||||
await prisma.appConfig.upsert({
|
||||
where: { key },
|
||||
update: { value },
|
||||
create: { key, value },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getCostPerGb(): Promise<number> {
|
||||
const v = Number(await getConfig('costPerGb', '0'));
|
||||
return Number.isFinite(v) ? v : 0;
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { prisma } from './prisma';
|
||||
import { getUsdMxn } from './exchange';
|
||||
import { getCostPerGb } from './config';
|
||||
import { storageBySlug, BYTES_PER_GB } from './storage';
|
||||
|
||||
export type RestaurantCost = {
|
||||
id: string;
|
||||
slug: string;
|
||||
name: string;
|
||||
active: boolean;
|
||||
tokenCostUsd: number;
|
||||
gb: number;
|
||||
storageCostUsd: number;
|
||||
};
|
||||
|
||||
export type CostDashboard = {
|
||||
monthLabel: string; // YYYY-MM
|
||||
exchange: { rate: number; date: string; stale: boolean };
|
||||
costPerGb: number;
|
||||
pricesUpdatedAt: string | null;
|
||||
restaurants: RestaurantCost[];
|
||||
totals: {
|
||||
restaurantsTokenUsd: number;
|
||||
storageUsd: number;
|
||||
operativoTokenUsd: number;
|
||||
grandUsd: number; // restaurants tokens + storage + operativo
|
||||
avgPerRestaurantUsd: number; // restaurants tokens ÷ active count
|
||||
};
|
||||
};
|
||||
|
||||
function tokenCost(
|
||||
inputTokens: number,
|
||||
outputTokens: number,
|
||||
price: { inputPricePerMTok: number; outputPricePerMTok: number } | undefined,
|
||||
): number {
|
||||
if (!price) return 0;
|
||||
return (inputTokens / 1_000_000) * price.inputPricePerMTok + (outputTokens / 1_000_000) * price.outputPricePerMTok;
|
||||
}
|
||||
|
||||
// Compute the current-month cost dashboard. Token cost per usage row uses the
|
||||
// editable ModelPrice; storage uses measured GB × configurable cost/GB.
|
||||
export async function getCostDashboard(): Promise<CostDashboard> {
|
||||
const now = new Date();
|
||||
const monthStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
|
||||
const monthLabel = monthStart.toISOString().slice(0, 7);
|
||||
|
||||
const [restaurants, usage, prices, exchange, costPerGb] = await Promise.all([
|
||||
prisma.restaurant.findMany({
|
||||
orderBy: { name: 'asc' },
|
||||
select: { id: true, slug: true, name: true, active: true },
|
||||
}),
|
||||
prisma.tokenUsage.findMany({ where: { createdAt: { gte: monthStart } } }),
|
||||
prisma.modelPrice.findMany(),
|
||||
getUsdMxn(),
|
||||
getCostPerGb(),
|
||||
]);
|
||||
|
||||
const priceByModel = new Map(prices.map((p) => [p.model, p]));
|
||||
|
||||
// Token cost per restaurant (and operational for null restaurantId).
|
||||
const tokenByRestaurant = new Map<string, number>();
|
||||
let operativoTokenUsd = 0;
|
||||
for (const u of usage) {
|
||||
const cost = tokenCost(u.inputTokens, u.outputTokens, priceByModel.get(u.model));
|
||||
if (u.restaurantId) {
|
||||
tokenByRestaurant.set(u.restaurantId, (tokenByRestaurant.get(u.restaurantId) ?? 0) + cost);
|
||||
} else {
|
||||
operativoTokenUsd += cost;
|
||||
}
|
||||
}
|
||||
|
||||
const gbBySlug = await storageBySlug(restaurants.map((r) => r.slug));
|
||||
|
||||
const rows: RestaurantCost[] = restaurants.map((r) => {
|
||||
const gb = (gbBySlug[r.slug] ?? 0) / BYTES_PER_GB;
|
||||
return {
|
||||
id: r.id,
|
||||
slug: r.slug,
|
||||
name: r.name,
|
||||
active: r.active,
|
||||
tokenCostUsd: tokenByRestaurant.get(r.id) ?? 0,
|
||||
gb,
|
||||
storageCostUsd: gb * costPerGb,
|
||||
};
|
||||
});
|
||||
|
||||
const restaurantsTokenUsd = rows.reduce((s, r) => s + r.tokenCostUsd, 0);
|
||||
const storageUsd = rows.reduce((s, r) => s + r.storageCostUsd, 0);
|
||||
const activeCount = rows.filter((r) => r.active).length;
|
||||
|
||||
const pricesUpdatedAt = prices.reduce<Date | null>(
|
||||
(max, p) => (!max || p.updatedAt > max ? p.updatedAt : max),
|
||||
null,
|
||||
);
|
||||
|
||||
return {
|
||||
monthLabel,
|
||||
exchange,
|
||||
costPerGb,
|
||||
pricesUpdatedAt: pricesUpdatedAt ? pricesUpdatedAt.toISOString() : null,
|
||||
restaurants: rows,
|
||||
totals: {
|
||||
restaurantsTokenUsd,
|
||||
storageUsd,
|
||||
operativoTokenUsd,
|
||||
grandUsd: restaurantsTokenUsd + storageUsd + operativoTokenUsd,
|
||||
avgPerRestaurantUsd: activeCount ? restaurantsTokenUsd / activeCount : 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { prisma } from './prisma';
|
||||
|
||||
// Sane fallback if there's no cached rate AND the API fails — never show $0.
|
||||
const FALLBACK_USD_MXN = 17;
|
||||
|
||||
function todayKey(): string {
|
||||
return new Date().toISOString().slice(0, 10); // YYYY-MM-DD
|
||||
}
|
||||
|
||||
// USD→MXN rate, cached once per day. Uses Frankfurter (no API key). On failure,
|
||||
// falls back to the most recent stored rate, then to a constant. Returns the rate
|
||||
// and the date it corresponds to so the dashboard can show context.
|
||||
export async function getUsdMxn(): Promise<{ rate: number; date: string; stale: boolean }> {
|
||||
const today = todayKey();
|
||||
|
||||
const cached = await prisma.exchangeRate.findUnique({ where: { date: today } });
|
||||
if (cached) return { rate: cached.rate, date: cached.date, stale: false };
|
||||
|
||||
try {
|
||||
const res = await fetch('https://api.frankfurter.app/latest?from=USD&to=MXN', {
|
||||
// 24h revalidate hint; we also dedupe via the DB cache above.
|
||||
next: { revalidate: 86400 },
|
||||
});
|
||||
if (!res.ok) throw new Error(`exchange ${res.status}`);
|
||||
const data = await res.json();
|
||||
const rate = Number(data?.rates?.MXN);
|
||||
if (!Number.isFinite(rate) || rate <= 0) throw new Error('no rate');
|
||||
await prisma.exchangeRate.create({ data: { date: today, rate } });
|
||||
return { rate, date: today, stale: false };
|
||||
} catch (err) {
|
||||
console.error('getUsdMxn error', err);
|
||||
const last = await prisma.exchangeRate.findFirst({ orderBy: { date: 'desc' } });
|
||||
if (last) return { rate: last.rate, date: last.date, stale: true };
|
||||
return { rate: FALLBACK_USD_MXN, date: today, stale: true };
|
||||
}
|
||||
}
|
||||
+5
-1
@@ -2,6 +2,7 @@ import * as XLSX from 'xlsx';
|
||||
import Anthropic from '@anthropic-ai/sdk';
|
||||
import { getAnthropic, HAIKU_MODEL, SONNET_MODEL } from './anthropic';
|
||||
import { parseLenientJson } from './json';
|
||||
import { recordUsage } from './usage';
|
||||
import type { Locale } from '@/i18n/config';
|
||||
|
||||
// Structure returned for review (NOT yet applied to the draft).
|
||||
@@ -153,6 +154,7 @@ export async function resolveSource(input: {
|
||||
export async function extractMenu(
|
||||
source: Source,
|
||||
defaultLocale: Locale,
|
||||
restaurantId?: string,
|
||||
): Promise<ImportResult> {
|
||||
const client = getAnthropic();
|
||||
|
||||
@@ -173,12 +175,14 @@ export async function extractMenu(
|
||||
content.push({ type: 'text', text: `MENU SOURCE:\n${source.text}` });
|
||||
}
|
||||
|
||||
const model = source.visual ? SONNET_MODEL : HAIKU_MODEL;
|
||||
const msg = await client.messages.create({
|
||||
model: source.visual ? SONNET_MODEL : HAIKU_MODEL,
|
||||
model,
|
||||
max_tokens: 8000,
|
||||
system: systemPrompt(defaultLocale),
|
||||
messages: [{ role: 'user', content }],
|
||||
});
|
||||
await recordUsage({ restaurantId: restaurantId ?? null, model, feature: 'import', usage: msg.usage });
|
||||
|
||||
const text = msg.content.find((c) => c.type === 'text')?.text ?? '{}';
|
||||
const parsed = parseLenientJson<{ sections?: unknown }>(text);
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import { prisma } from './prisma';
|
||||
import { getAnthropic, HAIKU_MODEL } from './anthropic';
|
||||
import { recordUsage } from './usage';
|
||||
import { parseLenientJson } from './json';
|
||||
|
||||
export type PriceChange = {
|
||||
model: string;
|
||||
oldInput: number;
|
||||
newInput: number;
|
||||
oldOutput: number;
|
||||
newOutput: number;
|
||||
};
|
||||
|
||||
// Pretty marketing name from a model id, to help the model find it in the page.
|
||||
function prettyName(model: string): string {
|
||||
return model
|
||||
.replace(/^claude-/, 'Claude ')
|
||||
.replace(/-/g, ' ')
|
||||
.replace(/\b(\w)/g, (m) => m.toUpperCase())
|
||||
.replace(/(\d) (\d)/, '$1.$2'); // "4 5" -> "4.5"
|
||||
}
|
||||
|
||||
function stripHtml(html: string): string {
|
||||
return html
|
||||
.replace(/<script[\s\S]*?<\/script>/gi, ' ')
|
||||
.replace(/<style[\s\S]*?<\/style>/gi, ' ')
|
||||
.replace(/<[^>]+>/g, ' ')
|
||||
.replace(/ /g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
.slice(0, 24000);
|
||||
}
|
||||
|
||||
// Try to fetch Anthropic's public pricing page text. Throws on failure so the
|
||||
// caller can offer the manual-paste fallback.
|
||||
export async function fetchAnthropicPricingText(): Promise<string> {
|
||||
const urls = ['https://www.anthropic.com/pricing', 'https://claude.com/pricing'];
|
||||
let lastErr: unknown;
|
||||
for (const url of urls) {
|
||||
try {
|
||||
const res = await fetch(url, { headers: { 'User-Agent': 'SmartMenuPricing/1.0' } });
|
||||
if (!res.ok) throw new Error(`${res.status}`);
|
||||
const text = stripHtml(await res.text());
|
||||
if (text.length > 200) return text;
|
||||
} catch (err) {
|
||||
lastErr = err;
|
||||
}
|
||||
}
|
||||
throw lastErr ?? new Error('fetch_failed');
|
||||
}
|
||||
|
||||
// Extract prices from the given text with Haiku (ONLY from the text, never from
|
||||
// memory), update changed models, and log each change. Calls are recorded as
|
||||
// operational (restaurantId null, feature 'precios-update').
|
||||
export async function updatePricesFromText(
|
||||
text: string,
|
||||
source: 'anthropic' | 'manual',
|
||||
): Promise<PriceChange[]> {
|
||||
const current = await prisma.modelPrice.findMany();
|
||||
if (current.length === 0) return [];
|
||||
|
||||
const wanted = current.map((c) => `- id "${c.model}" (marketing name: "${prettyName(c.model)}")`).join('\n');
|
||||
const system =
|
||||
'You extract model pricing from the provided pricing text ONLY (never from prior knowledge). ' +
|
||||
'Find input and output price in USD PER MILLION TOKENS for each requested model. ' +
|
||||
'If a model is NOT clearly present in the text, OMIT it (do not guess). ' +
|
||||
'Reply ONLY with JSON: { "<id>": { "input": number, "output": number } } using the exact ids requested.';
|
||||
|
||||
const client = getAnthropic();
|
||||
const msg = await client.messages.create({
|
||||
model: HAIKU_MODEL,
|
||||
max_tokens: 600,
|
||||
system,
|
||||
messages: [{ role: 'user', content: `MODELS:\n${wanted}\n\nPRICING TEXT:\n${text}` }],
|
||||
});
|
||||
await recordUsage({ restaurantId: null, model: HAIKU_MODEL, feature: 'precios-update', usage: msg.usage });
|
||||
|
||||
const reply = msg.content.find((c) => c.type === 'text')?.text ?? '{}';
|
||||
const parsed = parseLenientJson<Record<string, { input?: unknown; output?: unknown }>>(reply) ?? {};
|
||||
|
||||
const changes: PriceChange[] = [];
|
||||
for (const row of current) {
|
||||
const found = parsed[row.model];
|
||||
if (!found) continue;
|
||||
const newInput = Number(found.input);
|
||||
const newOutput = Number(found.output);
|
||||
if (!Number.isFinite(newInput) || !Number.isFinite(newOutput) || newInput <= 0 || newOutput <= 0) {
|
||||
continue;
|
||||
}
|
||||
if (newInput === row.inputPricePerMTok && newOutput === row.outputPricePerMTok) continue;
|
||||
|
||||
await prisma.modelPrice.update({
|
||||
where: { model: row.model },
|
||||
data: { inputPricePerMTok: newInput, outputPricePerMTok: newOutput, updatedAt: new Date() },
|
||||
});
|
||||
await prisma.priceUpdateLog.create({
|
||||
data: {
|
||||
model: row.model,
|
||||
oldInput: row.inputPricePerMTok,
|
||||
newInput,
|
||||
oldOutput: row.outputPricePerMTok,
|
||||
newOutput,
|
||||
source,
|
||||
},
|
||||
});
|
||||
changes.push({
|
||||
model: row.model,
|
||||
oldInput: row.inputPricePerMTok,
|
||||
newInput,
|
||||
oldOutput: row.outputPricePerMTok,
|
||||
newOutput,
|
||||
});
|
||||
}
|
||||
return changes;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import { UPLOAD_DIR } from './upload';
|
||||
|
||||
// Recursively sum file sizes under a directory (bytes). Missing dir → 0.
|
||||
async function dirSize(dir: string): Promise<number> {
|
||||
let total = 0;
|
||||
let entries: import('fs').Dirent[];
|
||||
try {
|
||||
entries = await fs.readdir(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
for (const e of entries) {
|
||||
const full = path.join(dir, e.name);
|
||||
try {
|
||||
if (e.isDirectory()) total += await dirSize(full);
|
||||
else if (e.isFile()) total += (await fs.stat(full)).size;
|
||||
} catch {
|
||||
/* skip unreadable entries */
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
// Bytes consumed by each restaurant's uploads, keyed by slug.
|
||||
export async function storageBySlug(slugs: string[]): Promise<Record<string, number>> {
|
||||
const out: Record<string, number> = {};
|
||||
await Promise.all(
|
||||
slugs.map(async (slug) => {
|
||||
out[slug] = await dirSize(path.join(UPLOAD_DIR, slug));
|
||||
}),
|
||||
);
|
||||
return out;
|
||||
}
|
||||
|
||||
export const BYTES_PER_GB = 1024 ** 3;
|
||||
@@ -0,0 +1,26 @@
|
||||
import { prisma } from './prisma';
|
||||
|
||||
type Usage = { input_tokens?: number; output_tokens?: number } | null | undefined;
|
||||
|
||||
// Record one Anthropic API call's token usage. Fire-and-forget: never let logging
|
||||
// break the feature that made the call. restaurantId null = Collina operational.
|
||||
export async function recordUsage(params: {
|
||||
restaurantId: string | null;
|
||||
model: string;
|
||||
feature: string;
|
||||
usage: Usage;
|
||||
}): Promise<void> {
|
||||
try {
|
||||
await prisma.tokenUsage.create({
|
||||
data: {
|
||||
restaurantId: params.restaurantId,
|
||||
model: params.model,
|
||||
feature: params.feature,
|
||||
inputTokens: params.usage?.input_tokens ?? 0,
|
||||
outputTokens: params.usage?.output_tokens ?? 0,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('recordUsage error', err);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user