diff --git a/apps/api/internal/aiaudit/aiaudit.go b/apps/api/internal/aiaudit/aiaudit.go index 6e6d5b3..cf9c51b 100644 --- a/apps/api/internal/aiaudit/aiaudit.go +++ b/apps/api/internal/aiaudit/aiaudit.go @@ -130,11 +130,12 @@ const insertCallSQL = ` INSERT INTO ai_call_logs ( company_id, user_id, job_id, raw_product_id, role, provider_mode, model, system_prompt, user_prompt, response_text, error, finish_reason, - prompt_tokens, completion_tokens, total_tokens, duration_ms) + prompt_tokens, completion_tokens, total_tokens, duration_ms, + cached_prompt_tokens, cost_micros) VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, - $13, $14, $15, $16)` + $13, $14, $15, $16, $17, $18)` // Record persists one call, merging any CallContext on ctx. Capture must never // break the request it is observing: every failure is swallowed after one log line. @@ -167,11 +168,19 @@ func (r *Recorder) Record(ctx context.Context, c Call) { writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) defer cancel() + // Persist the exact model-rate cost at capture time. Historical call rows stay + // NULL rather than displaying a fabricated per-call amount. + price := r.priceFor(ctx, c.Model) + var recordedCost any + if price.InputPerMTok > 0 || price.CachedInputPerMTok > 0 || price.OutputPerMTok > 0 { + recordedCost = CostMicros(price, c.PromptTokens, c.CachedPromptTokens, c.OutputTokens) + } _, err := r.pool.Exec(writeCtx, insertCallSQL, nullUUID(c.CompanyID), nullUUID(c.UserID), nullUUID(c.JobID), nullUUID(c.RawProductID), c.Role, c.ProviderMode, c.Model, clamp(c.System), clamp(c.User), clamp(c.Response), clamp(c.Error), c.FinishReason, c.PromptTokens, c.OutputTokens, c.TotalTokens, int(c.Duration.Milliseconds()), + c.CachedPromptTokens, recordedCost, ) if err != nil { r.noteFailure(err) diff --git a/apps/api/internal/aiaudit/aiaudit_test.go b/apps/api/internal/aiaudit/aiaudit_test.go index 068677d..8bdec23 100644 --- a/apps/api/internal/aiaudit/aiaudit_test.go +++ b/apps/api/internal/aiaudit/aiaudit_test.go @@ -74,3 +74,11 @@ func TestClamp_boundsBody(t *testing.T) { t.Fatal("clamped body must say it was truncated") } } + +func TestCallCapturePersistsCostAndCachedTokens(t *testing.T) { + for _, name := range []string{"cached_prompt_tokens", "cost_micros"} { + if !strings.Contains(insertCallSQL, name) { + t.Fatalf("missing AI call capture field %s", name) + } + } +} diff --git a/apps/api/internal/catalog/filter_test.go b/apps/api/internal/catalog/filter_test.go index 7f02714..a181f62 100644 --- a/apps/api/internal/catalog/filter_test.go +++ b/apps/api/internal/catalog/filter_test.go @@ -412,3 +412,15 @@ func TestSanitizeFileName(t *testing.T) { t.Fatalf("got %q", sanitizeFileName("a b*.csv")) } } + +// Historical API processing predates origin tagging. Generated fields remain +// visible in Processed without silently transitioning review-state records. +func TestGeneratedProductFilterIncludesLegacyContent(t *testing.T) { + _, where := appendProcessedProductFilters(ProductFilter{Status: "generated"}, nil, nil) + joined := strings.Join(where, " ") + for _, value := range []string{"p.status = 'completed'", "p.processed_name", "p.processed_description", "p.meta_title", "p.meta_description", "needs_review"} { + if !strings.Contains(joined, value) { + t.Fatalf("missing %s in generated filter: %s", value, joined) + } + } +} diff --git a/apps/api/internal/catalog/service.go b/apps/api/internal/catalog/service.go index 58ae09e..41c3ae7 100644 --- a/apps/api/internal/catalog/service.go +++ b/apps/api/internal/catalog/service.go @@ -700,9 +700,9 @@ const ( WHEN COALESCE(p.field_sources->>'category', '') IN ('llm', 'vector') THEN '' ELSE COALESCE(NULLIF(BTRIM(r.mapped_data->>'category'), ''), NULLIF(BTRIM(r.mapped_data->>'category_unique_id'), ''), '') END` - processedHasNameSQL = `(` + processedPreferredNameSQL + ` <> '')` - processedHasDescriptionSQL = `(` + processedPreferredDescriptionSQL + ` <> '')` - processedHasCategorySQL = `(COALESCE(NULLIF(p.category, ''), '') <> '' AND lower(p.category) <> 'none')` + processedHasNameSQL = `(` + processedPreferredNameSQL + ` <> '')` + processedHasDescriptionSQL = `(` + processedPreferredDescriptionSQL + ` <> '')` + processedHasCategorySQL = `(COALESCE(NULLIF(p.category, ''), '') <> '' AND lower(p.category) <> 'none')` // Resolve display name / canonical unique_id when products store unique_id, UUID id, or name. processedCategoryResolveJoin = ` LEFT JOIN LATERAL ( @@ -1071,6 +1071,20 @@ func appendProcessedProductFilters(f ProductFilter, args []any, where []string) n, n, n, n, n)) } if f.Status != "" { + // The dashboard's Processed tab must also surface already-generated legacy + // API results. Pre-v16 jobs were not tagged with their origin, so we cannot + // safely approve them in a migration. Include only rows with actual generated + // fields, preserving their original needs_review status and actions. + if f.Status == "generated" { + where = append(where, `(p.status = 'completed' OR + (p.status IN ('needs_review', 'processed') AND ( + NULLIF(BTRIM(COALESCE(p.processed_name, '')), '') IS NOT NULL OR + NULLIF(BTRIM(COALESCE(p.processed_description, '')), '') IS NOT NULL OR + NULLIF(BTRIM(COALESCE(p.meta_title, '')), '') IS NOT NULL OR + NULLIF(BTRIM(COALESCE(p.meta_description, '')), '') IS NOT NULL + )))`) + return args, where + } // needs_review includes legacy pipeline status "processed" (pre-P0-8). if f.Status == "needs_review" { where = append(where, "p.status IN ('needs_review', 'processed')") diff --git a/apps/api/internal/httpapi/admin_ai_calls_handlers.go b/apps/api/internal/httpapi/admin_ai_calls_handlers.go index 35496cb..d9008af 100644 --- a/apps/api/internal/httpapi/admin_ai_calls_handlers.go +++ b/apps/api/internal/httpapi/admin_ai_calls_handlers.go @@ -116,13 +116,16 @@ func (s *Server) handleAdminListAICalls(w http.ResponseWriter, r *http.Request) var companyID, companyName, userID, userEmail, jobID, rawProductID string var role, providerMode, model, callErr, finishReason string var promptTokens, completionTokens, totalTokens, durationMS int + var cachedTokens *int + var costMicros *int64 var createdAt time.Time var sysLen, userLen, respLen int var userPreview, respPreview string if err := rows.Scan(&id, &companyID, &companyName, &userID, &userEmail, &jobID, &rawProductID, &role, &providerMode, &model, &callErr, &finishReason, &promptTokens, &completionTokens, &totalTokens, &durationMS, &createdAt, - &sysLen, &userLen, &respLen, &userPreview, &respPreview); err != nil { + &sysLen, &userLen, &respLen, &userPreview, &respPreview, + &cachedTokens, &costMicros); err != nil { Error(w, http.StatusInternalServerError, "scan ai calls failed") return } @@ -132,29 +135,31 @@ func (s *Server) handleAdminListAICalls(w http.ResponseWriter, r *http.Request) outcome = "failed" } items = append(items, map[string]any{ - "id": id, - "company_id": companyID, - "company_name": companyName, - "user_id": userID, - "user_email": userEmail, - "job_id": jobID, - "raw_product_id": rawProductID, - "role": role, - "provider_mode": providerMode, - "model": model, - "outcome": outcome, - "error": callErr, - "finish_reason": finishReason, - "prompt_tokens": promptTokens, - "completion_tokens": completionTokens, - "total_tokens": totalTokens, - "duration_ms": durationMS, - "created_at": createdAt, - "system_length": sysLen, - "user_length": userLen, - "response_length": respLen, - "user_preview": userPreview, - "response_preview": respPreview, + "id": id, + "company_id": companyID, + "company_name": companyName, + "user_id": userID, + "user_email": userEmail, + "job_id": jobID, + "raw_product_id": rawProductID, + "role": role, + "provider_mode": providerMode, + "model": model, + "outcome": outcome, + "error": callErr, + "finish_reason": finishReason, + "prompt_tokens": promptTokens, + "completion_tokens": completionTokens, + "total_tokens": totalTokens, + "cached_prompt_tokens": cachedTokens, + "cost_micros": costMicros, + "duration_ms": durationMS, + "created_at": createdAt, + "system_length": sysLen, + "user_length": userLen, + "response_length": respLen, + "user_preview": userPreview, + "response_preview": respPreview, }) } if err := rows.Err(); err != nil { @@ -187,7 +192,8 @@ func adminAICallsListSQL(where string, limitArg int) string { l.prompt_tokens, l.completion_tokens, l.total_tokens, l.duration_ms, l.created_at, length(l.system_prompt), length(l.user_prompt), length(l.response_text), left(l.user_prompt, ` + preview + `), - left(l.response_text, ` + preview + `) + left(l.response_text, ` + preview + `), + l.cached_prompt_tokens, l.cost_micros FROM ai_call_logs l LEFT JOIN companies c ON c.id = l.company_id LEFT JOIN users u ON u.id = l.user_id @@ -212,6 +218,8 @@ func (s *Server) handleAdminGetAICall(w http.ResponseWriter, r *http.Request) { var role, providerMode, model, callErr, finishReason string var systemPrompt, userPrompt, responseText string var promptTokens, completionTokens, totalTokens, durationMS int + var cachedTokens *int + var costMicros *int64 var createdAt time.Time err = s.Pool.QueryRow(ctx, ` SELECT COALESCE(l.company_id::text, ''), COALESCE(c.name, ''), @@ -219,7 +227,8 @@ func (s *Server) handleAdminGetAICall(w http.ResponseWriter, r *http.Request) { COALESCE(l.job_id::text, ''), COALESCE(l.raw_product_id::text, ''), l.role, l.provider_mode, l.model, l.error, l.finish_reason, l.system_prompt, l.user_prompt, l.response_text, - l.prompt_tokens, l.completion_tokens, l.total_tokens, l.duration_ms, l.created_at + l.prompt_tokens, l.completion_tokens, l.total_tokens, l.duration_ms, l.created_at, + l.cached_prompt_tokens, l.cost_micros FROM ai_call_logs l LEFT JOIN companies c ON c.id = l.company_id LEFT JOIN users u ON u.id = l.user_id @@ -227,7 +236,8 @@ func (s *Server) handleAdminGetAICall(w http.ResponseWriter, r *http.Request) { Scan(&companyID, &companyName, &userID, &userEmail, &jobID, &rawProductID, &role, &providerMode, &model, &callErr, &finishReason, &systemPrompt, &userPrompt, &responseText, - &promptTokens, &completionTokens, &totalTokens, &durationMS, &createdAt) + &promptTokens, &completionTokens, &totalTokens, &durationMS, &createdAt, + &cachedTokens, &costMicros) if errors.Is(err, pgx.ErrNoRows) { // Expired rows are the common case here, so say so rather than a bare 404. Error(w, http.StatusNotFound, "call not found (captured calls are kept for "+ @@ -244,27 +254,29 @@ func (s *Server) handleAdminGetAICall(w http.ResponseWriter, r *http.Request) { outcome = "failed" } JSON(w, http.StatusOK, map[string]any{ - "id": id, - "company_id": companyID, - "company_name": companyName, - "user_id": userID, - "user_email": userEmail, - "job_id": jobID, - "raw_product_id": rawProductID, - "role": role, - "provider_mode": providerMode, - "model": model, - "outcome": outcome, - "error": callErr, - "finish_reason": finishReason, - "system_prompt": systemPrompt, - "user_prompt": userPrompt, - "response_text": responseText, - "prompt_tokens": promptTokens, - "completion_tokens": completionTokens, - "total_tokens": totalTokens, - "duration_ms": durationMS, - "created_at": createdAt, - "retention_days": aiaudit.RetentionDays, + "id": id, + "company_id": companyID, + "company_name": companyName, + "user_id": userID, + "user_email": userEmail, + "job_id": jobID, + "raw_product_id": rawProductID, + "role": role, + "provider_mode": providerMode, + "model": model, + "outcome": outcome, + "error": callErr, + "finish_reason": finishReason, + "system_prompt": systemPrompt, + "user_prompt": userPrompt, + "response_text": responseText, + "prompt_tokens": promptTokens, + "completion_tokens": completionTokens, + "total_tokens": totalTokens, + "cached_prompt_tokens": cachedTokens, + "cost_micros": costMicros, + "duration_ms": durationMS, + "created_at": createdAt, + "retention_days": aiaudit.RetentionDays, }) } diff --git a/apps/api/sql/schema/052_ai_call_details.sql b/apps/api/sql/schema/052_ai_call_details.sql new file mode 100644 index 0000000..e916fb1 --- /dev/null +++ b/apps/api/sql/schema/052_ai_call_details.sql @@ -0,0 +1,9 @@ +-- +goose Up +-- Exact per-call cost/cached tokens for the short-lived AI call inspector. +-- Nullable because historical rows did not capture per-call costs. +ALTER TABLE ai_call_logs ADD COLUMN IF NOT EXISTS cached_prompt_tokens INTEGER; +ALTER TABLE ai_call_logs ADD COLUMN IF NOT EXISTS cost_micros BIGINT; + +-- +goose Down +ALTER TABLE ai_call_logs DROP COLUMN IF EXISTS cost_micros; +ALTER TABLE ai_call_logs DROP COLUMN IF EXISTS cached_prompt_tokens; diff --git a/apps/web/src/lib/products-search.test.ts b/apps/web/src/lib/products-search.test.ts index 95dc2ef..7b94462 100644 --- a/apps/web/src/lib/products-search.test.ts +++ b/apps/web/src/lib/products-search.test.ts @@ -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" }); }); diff --git a/apps/web/src/lib/products-search.ts b/apps/web/src/lib/products-search.ts index da920ae..51394f8 100644 --- a/apps/web/src/lib/products-search.ts +++ b/apps/web/src/lib/products-search.ts @@ -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" }; } } diff --git a/apps/web/src/routes/admin/ai-calls/+page.svelte b/apps/web/src/routes/admin/ai-calls/+page.svelte index c480011..42e3c92 100644 --- a/apps/web/src/routes/admin/ai-calls/+page.svelte +++ b/apps/web/src/routes/admin/ai-calls/+page.svelte @@ -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(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(`/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(); }); @@ -302,16 +310,15 @@ {i18n.t("admin.aiCalls.colRole")} {i18n.t("admin.aiCalls.colOutcome")} {i18n.t("admin.aiCalls.colPrompt")} - {i18n.t("admin.aiCalls.colTokens")} + Input / output tokens + Provider cost estimate (USD) {i18n.t("admin.aiCalls.colTime")} + Details {#each rows as row (row.id)} - openDetail(row.id)} - > + {formatDate(row.created_at)} {row.company_name || "—"} {row.user_email || "—"} @@ -322,8 +329,10 @@ {row.user_preview} - {row.total_tokens ?? 0} + {(row.prompt_tokens ?? 0).toLocaleString()} / {(row.completion_tokens ?? 0).toLocaleString()} + {row.cost_micros == null ? "—" : `$${(row.cost_micros / 1000000).toFixed(5)}`} {ms(row.duration_ms)} + {/each} @@ -338,12 +347,11 @@ {/if} {/if} + {#if detailLoading} - {/if} - - {#if selected} - + {:else if selected} +
@@ -353,7 +361,7 @@ {selected.model || "—"} ({selected.provider_mode || "—"})
-
@@ -370,16 +378,28 @@ {selected.prompt_tokens ?? 0} in / {selected.completion_tokens ?? 0} out +
+
Calculated provider cost (USD)
+
{selected.cost_micros == null ? "Not recorded" : `$${(selected.cost_micros / 1000000).toFixed(6)}`}
+
Cached input: {selected.cached_prompt_tokens == null ? "Not recorded" : selected.cached_prompt_tokens.toLocaleString()}
+
{i18n.t("admin.aiCalls.colTime")}
{ms(selected.duration_ms)} · {selected.finish_reason || "—"}
{i18n.t("admin.aiCalls.jobId")}
-
{selected.job_id || "—"}
+
{selected.job_id || "—"}
+ {#if selected.job_id && selected.company_id} + Filter calls from this job + {/if}
+

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.

+ {#if selected.raw_product_id} +

Raw product: {selected.raw_product_id}

+ {/if} {#if selected.error} {/if} @@ -405,5 +425,6 @@
{/if} +
{/if} diff --git a/apps/web/src/routes/admin/billing/+page.svelte b/apps/web/src/routes/admin/billing/+page.svelte index baaab8f..c44cb67 100644 --- a/apps/web/src/routes/admin/billing/+page.svelte +++ b/apps/web/src/routes/admin/billing/+page.svelte @@ -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; + const emptyCreditForm = (): CreditForm => ({ + product_processing: "", openai_token_k: "", seo_meta_ai: "", campaign_copy: "" + }); + let creditRules = $state([]); + let creditForm = $state(emptyCreditForm()); + let creditOriginal = $state(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 { + 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 @@ +
+
+

Processing credit costs

+

Plan-specific rules. Empty fields inherit platform defaults. Company overrides take precedence. Applies to future processing only.

+
+
+ {#each creditFeatures as feature (feature.key)} +
+ + +

{feature.description}

+
+ {/each} +
+
diff --git a/apps/web/src/routes/products/+page.svelte b/apps/web/src/routes/products/+page.svelte index f4ebcbf..ee570e2 100644 --- a/apps/web/src/routes/products/+page.svelte +++ b/apps/web/src/routes/products/+page.svelte @@ -1305,6 +1305,9 @@
+ {#if activeTab === "processed"} +

Includes previously generated API content. Older results that still need manual review retain their original status until approved.

+ {/if}
diff --git a/docs/V17_PLAN_CREDITS_LEGACY_API_CALLS.md b/docs/V17_PLAN_CREDITS_LEGACY_API_CALLS.md new file mode 100644 index 0000000..1ce704d --- /dev/null +++ b/docs/V17_PLAN_CREDITS_LEGACY_API_CALLS.md @@ -0,0 +1,18 @@ +# Descrybe v17 – plan credits, historical API results, AI call inspector + +## Changes +- Admin → Billing → Create/Edit plan now contains plan-level credit rules for AI product processing, token increments, SEO meta, and campaigns. Blank = inherit global; company override takes precedence. Changes affect future debits only, not billed history. +- Product Management → Processed now includes old catalog records with actual generated title/description/SEO data even if their original status was `needs_review`. This does **not** approve these records: review workflow and persisted status are unchanged. Pre-v16 API jobs had no reliable origin identifier, so distinguishing historical API vs dashboard records cannot be done safely in SQL. +- Admin → AI Calls has a clearly labeled View action that opens a dialog instead of rendering details below the full table. The list and detail show input/output tokens and model-price-based calculated provider cost (USD) for new calls. Cached input tokens are also recorded. Historical cost/cached values remain NULL, rather than being assigned fake values. +- New migration `052_ai_call_details.sql` is required. Detailed prompts are retained for 7 days, separate from the durable, aggregate provider-usage billing ledger. AI call costs are not customer invoices or per-call credit deductions. + +## Deploy +Use Git as the deployment source of truth. Push changes, run the normal `rb` script. It applies migration 052 before rebuilding the API and worker. Restart both. No backfill of historical per-call costs is attempted. + +## Important verification +- On a test company, process a product by public API and check it appears under Processed with generated content. +- Check a previously generated Needs review product appears in both views, but its review status has **not** been changed. +- Create a test plan with product-processing cost = 3, reopen the dialog, and confirm the override persists; remove the override and confirm it inherits the global rate. +- Make a new provider call; Admin → AI Calls → View should show input, output, cached tokens and provider cost. Compare cumulative expense to the separate AI Cost report; do not use the debugging table for invoicing. + +A full Go 1.25 + Svelte build and PostgreSQL integration run must be completed in deployment/staging: this environment cannot run those complete suites.