fixy
This commit is contained in:
1 parent
1e7c7bbfbb
commit
feebf7d3c1
12 files changed
+248
-70
No files matched your search
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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')")
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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" });
|
||||
});
|
||||
|
||||
|
||||
@@ -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" };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
|
||||
|
||||
Reference in new issue
Block a user