This commit is contained in:
greeneclipse committed 2026-10-16 00:55:28 +02:00
1 parent 1e7c7bbfbb
commit feebf7d3c1
12 files changed
+248 -70

No files matched your search

+1 -1
View File
@@ -7,7 +7,7 @@ describe("products-search tabs", () => {
assert.deepEqual(tabToApiParams("unprocessed"), { kind: "raw", status: "unprocessed" });
assert.deepEqual(tabToApiParams("processing"), { kind: "raw", status: "processing" });
assert.deepEqual(tabToApiParams("needs_review"), { kind: "processed", status: "needs_review" });
assert.deepEqual(tabToApiParams("processed"), { kind: "processed", status: "completed" });
assert.deepEqual(tabToApiParams("processed"), { kind: "processed", status: "generated" });
assert.deepEqual(tabToApiParams("error"), { kind: "raw", status: "failed" });
});
+1 -1
View File
@@ -19,7 +19,7 @@ export function tabToApiParams(tab: ProductTab): { kind: "processed" | "raw"; st
return { kind: "raw", status: "processing" };
case "processed":
default:
return { kind: "processed", status: "completed" };
return { kind: "processed", status: "generated" };
}
}
+34 -13
View File
@@ -17,6 +17,7 @@
CardDescription,
CardHeader,
CardTitle,
Dialog,
TableBody,
TableCell,
TableHead,
@@ -42,6 +43,8 @@
error?: string;
finish_reason?: string;
prompt_tokens?: number;
cached_prompt_tokens?: number | null;
cost_micros?: number | null;
completion_tokens?: number;
total_tokens?: number;
duration_ms?: number;
@@ -82,6 +85,7 @@
let search = $state("");
let selected = $state<CallDetail | null>(null);
let detailOpen = $state(false);
let detailLoading = $state(false);
const ROLES = ["all", "processing", "categorize", "seo_meta", "campaign", "support", "other"];
@@ -131,6 +135,8 @@
async function openDetail(id: string) {
detailLoading = true;
detailOpen = true;
selected = null;
error = "";
try {
selected = await api<CallDetail>(`/api/admin/ai-calls/${id}`);
@@ -162,7 +168,8 @@
}
onMount(async () => {
if (!(await requirePlatformAdmin())) {
const gate = await requirePlatformAdmin();
if (!gate.ok) {
accessDenied = true;
loading = false;
return;
@@ -174,6 +181,7 @@
} catch {
// Company list is a convenience filter; the page still works without it.
}
jobId = new URLSearchParams(window.location.search).get("job_id") ?? "";
await load();
});
</script>
@@ -302,16 +310,15 @@
<TableHead>{i18n.t("admin.aiCalls.colRole")}</TableHead>
<TableHead>{i18n.t("admin.aiCalls.colOutcome")}</TableHead>
<TableHead>{i18n.t("admin.aiCalls.colPrompt")}</TableHead>
<TableHead class="text-right">{i18n.t("admin.aiCalls.colTokens")}</TableHead>
<TableHead class="text-right">Input / output tokens</TableHead>
<TableHead class="text-right">Provider cost estimate (USD)</TableHead>
<TableHead class="text-right">{i18n.t("admin.aiCalls.colTime")}</TableHead>
<TableHead class="text-right">Details</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{#each rows as row (row.id)}
<TableRow
class="cursor-pointer"
onclick={() => openDetail(row.id)}
>
<TableRow>
<TableCell class="whitespace-nowrap text-xs">{formatDate(row.created_at)}</TableCell>
<TableCell class="text-xs">{row.company_name || "—"}</TableCell>
<TableCell class="text-xs">{row.user_email || "—"}</TableCell>
@@ -322,8 +329,10 @@
<TableCell class="max-w-md truncate text-xs text-muted-foreground">
{row.user_preview}
</TableCell>
<TableCell class="text-right text-xs">{row.total_tokens ?? 0}</TableCell>
<TableCell class="whitespace-nowrap text-right text-xs">{(row.prompt_tokens ?? 0).toLocaleString()} / {(row.completion_tokens ?? 0).toLocaleString()}</TableCell>
<TableCell class="whitespace-nowrap text-right text-xs">{row.cost_micros == null ? "—" : `$${(row.cost_micros / 1000000).toFixed(5)}`}</TableCell>
<TableCell class="text-right text-xs">{ms(row.duration_ms)}</TableCell>
<TableCell class="text-right"><Button variant="outline" size="sm" onclick={() => openDetail(row.id)}>View</Button></TableCell>
</TableRow>
{/each}
</TableBody>
@@ -338,12 +347,11 @@
{/if}
{/if}
<Dialog bind:open={detailOpen} title="AI call details" description="Full request, response, token usage and linked processing job" class="max-w-[min(95vw,1100px)]">
{#if detailLoading}
<Spinner />
{/if}
{#if selected}
<Card class="mt-4">
{:else if selected}
<Card class="border-0 shadow-none">
<CardHeader>
<div class="flex items-start justify-between gap-2">
<div>
@@ -353,7 +361,7 @@
{selected.model || "—"} ({selected.provider_mode || "—"})
</CardDescription>
</div>
<Button variant="ghost" size="sm" onclick={() => (selected = null)}>
<Button variant="ghost" size="sm" onclick={() => (detailOpen = false)}>
<X class="size-4" />
</Button>
</div>
@@ -370,16 +378,28 @@
{selected.prompt_tokens ?? 0} in / {selected.completion_tokens ?? 0} out
</dd>
</div>
<div>
<dt class="text-muted-foreground">Calculated provider cost (USD)</dt>
<dd>{selected.cost_micros == null ? "Not recorded" : `$${(selected.cost_micros / 1000000).toFixed(6)}`}</dd>
<dd class="text-muted-foreground">Cached input: {selected.cached_prompt_tokens == null ? "Not recorded" : selected.cached_prompt_tokens.toLocaleString()}</dd>
</div>
<div>
<dt class="text-muted-foreground">{i18n.t("admin.aiCalls.colTime")}</dt>
<dd>{ms(selected.duration_ms)} · {selected.finish_reason || "—"}</dd>
</div>
<div>
<dt class="text-muted-foreground">{i18n.t("admin.aiCalls.jobId")}</dt>
<dd class="truncate font-mono">{selected.job_id || "—"}</dd>
<dd class="break-all font-mono">{selected.job_id || "—"}</dd>
{#if selected.job_id && selected.company_id}
<a class="text-primary underline" href={`/admin/ai-calls?job_id=${encodeURIComponent(selected.job_id)}`}>Filter calls from this job</a>
{/if}
</div>
</dl>
<p class="text-xs text-muted-foreground">Full prompts are retained for {retentionDays} days. Cost history is aggregated separately. The per-call USD figure is calculated from recorded tokens and the configured model price; it is not a Stripe charge or credits deducted per product.</p>
{#if selected.raw_product_id}
<p class="break-all text-xs">Raw product: <code>{selected.raw_product_id}</code></p>
{/if}
{#if selected.error}
<Alert tone="error" message={selected.error} />
{/if}
@@ -405,5 +425,6 @@
</CardContent>
</Card>
{/if}
</Dialog>
{/if}
</PageShell>
+73 -1
View File
@@ -72,6 +72,54 @@
term: string;
};
type CreditRule = { scope: string; id: string; feature: string; cost_per_unit: number };
const creditFeatures = [
{ key: "product_processing", label: "AI product processing", description: "Base credits for processing a product" },
{ key: "openai_token_k", label: "AI tokens (per 1,000)", description: "Additional token-related credits where charged" },
{ key: "seo_meta_ai", label: "SEO meta generation", description: "Credits charged for SEO metadata" },
{ key: "campaign_copy", label: "Campaign copy", description: "Credits charged for campaign content" }
] as const;
type CreditFeature = (typeof creditFeatures)[number]["key"];
type CreditForm = Record<CreditFeature, string>;
const emptyCreditForm = (): CreditForm => ({
product_processing: "", openai_token_k: "", seo_meta_ai: "", campaign_copy: ""
});
let creditRules = $state<CreditRule[]>([]);
let creditForm = $state<CreditForm>(emptyCreditForm());
let creditOriginal = $state<CreditForm>(emptyCreditForm());
async function loadCreditRules() {
const result = await api<{ rules: CreditRule[] }>("/api/admin/processing-costs");
creditRules = result.rules ?? [];
}
function planCredits(planId: number): CreditForm {
const next = emptyCreditForm();
for (const feature of creditFeatures) {
const match = creditRules.find(r => r.scope === "plan" && r.id === String(planId) && r.feature === feature.key);
if (match) next[feature.key] = String(match.cost_per_unit);
}
return next;
}
function validatePlanCredits(): void {
for (const feature of creditFeatures) {
const raw = String(creditForm[feature.key] ?? "").trim();
if (raw && (!/^\d+$/.test(raw) || Number(raw) < 1 || Number(raw) > 1000000)) {
throw new Error(`${feature.label}: enter 1–1,000,000 credits or leave blank to inherit`);
}
}
}
async function savePlanCredits(planId: number): Promise<void> {
for (const feature of creditFeatures) {
const key = feature.key;
const next = String(creditForm[key] ?? "").trim();
if (next === creditOriginal[key]) continue;
await api("/api/admin/processing-costs", {
method: "PUT",
body: { scope: "plan", id: String(planId), feature: key, cost_per_unit: next === "" ? null : Number(next) }
});
}
}
const emptyPlanForm = (): PlanFormState => ({
id: 0,
name: "",
@@ -176,6 +224,7 @@
const [p, c] = await Promise.all([fetchAdminPlansList(), fetchAdminCompaniesList()]);
plans = p;
companies = c;
await loadCreditRules();
}
async function reload() {
@@ -184,6 +233,8 @@
function openCreatePlan() {
planForm = emptyPlanForm();
creditForm = emptyCreditForm();
creditOriginal = emptyCreditForm();
planFormOpen = true;
}
@@ -204,6 +255,8 @@
is_custom: Boolean(plan.is_custom),
term: plan.term || "monthly"
};
creditForm = planCredits(Number(plan.id));
creditOriginal = { ...creditForm };
planFormOpen = true;
}
@@ -231,7 +284,11 @@
error = "";
success = "";
try {
await upsertAdminPlan(normalizeAdminPlanForm(planForm));
validatePlanCredits();
const saved = await upsertAdminPlan(normalizeAdminPlanForm(planForm));
const id = Number(saved.id || planForm.id);
if (!Number.isSafeInteger(id) || id <= 0) throw new Error("Plan saved but ID not available for credit pricing");
await savePlanCredits(id);
success = planFormMode === "edit" ? i18n.t("admin.billing.planUpdated") : i18n.t("admin.billing.planCreated");
planFormOpen = false;
planForm = emptyPlanForm();
@@ -598,6 +655,21 @@
</Select>
</div>
</div>
<div class="space-y-3 rounded-md border border-border p-3">
<div>
<p class="text-sm font-semibold">Processing credit costs</p>
<p class="text-xs text-muted-foreground">Plan-specific rules. Empty fields inherit platform defaults. Company overrides take precedence. Applies to future processing only.</p>
</div>
<div class="grid gap-3 sm:grid-cols-2">
{#each creditFeatures as feature (feature.key)}
<div class="space-y-1">
<Label for={`plan-cost-${feature.key}`}>{feature.label}</Label>
<Input id={`plan-cost-${feature.key}`} type="number" min="1" max="1000000" step="1" bind:value={creditForm[feature.key]} placeholder="Inherit default" />
<p class="text-xs text-muted-foreground">{feature.description}</p>
</div>
{/each}
</div>
</div>
<div class="flex items-start gap-3 rounded-md border border-border p-3">
<Checkbox id="plan-custom" bind:checked={planForm.is_custom} />
<div class="space-y-1">
@@ -1305,6 +1305,9 @@
<CardHeader class="space-y-0 border-b border-border bg-card p-0 px-3 py-3 sm:px-6 sm:py-4">
<div class="flex min-w-0 flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<ProductTabs bind:activeTab disabled={loading || fetching} onchange={changeTab} />
{#if activeTab === "processed"}
<p class="text-xs text-muted-foreground">Includes previously generated API content. Older results that still need manual review retain their original status until approved.</p>
{/if}
</div>
</CardHeader>