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 (
|
INSERT INTO ai_call_logs (
|
||||||
company_id, user_id, job_id, raw_product_id, role, provider_mode, model,
|
company_id, user_id, job_id, raw_product_id, role, provider_mode, model,
|
||||||
system_prompt, user_prompt, response_text, error, finish_reason,
|
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 (
|
VALUES (
|
||||||
$1, $2, $3, $4, $5, $6, $7,
|
$1, $2, $3, $4, $5, $6, $7,
|
||||||
$8, $9, $10, $11, $12,
|
$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
|
// 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.
|
// 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)
|
writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
||||||
defer cancel()
|
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,
|
_, err := r.pool.Exec(writeCtx, insertCallSQL,
|
||||||
nullUUID(c.CompanyID), nullUUID(c.UserID), nullUUID(c.JobID), nullUUID(c.RawProductID),
|
nullUUID(c.CompanyID), nullUUID(c.UserID), nullUUID(c.JobID), nullUUID(c.RawProductID),
|
||||||
c.Role, c.ProviderMode, c.Model,
|
c.Role, c.ProviderMode, c.Model,
|
||||||
clamp(c.System), clamp(c.User), clamp(c.Response), clamp(c.Error), c.FinishReason,
|
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.PromptTokens, c.OutputTokens, c.TotalTokens, int(c.Duration.Milliseconds()),
|
||||||
|
c.CachedPromptTokens, recordedCost,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
r.noteFailure(err)
|
r.noteFailure(err)
|
||||||
|
|||||||
@@ -74,3 +74,11 @@ func TestClamp_boundsBody(t *testing.T) {
|
|||||||
t.Fatal("clamped body must say it was truncated")
|
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"))
|
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 ''
|
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'), ''), '')
|
ELSE COALESCE(NULLIF(BTRIM(r.mapped_data->>'category'), ''), NULLIF(BTRIM(r.mapped_data->>'category_unique_id'), ''), '')
|
||||||
END`
|
END`
|
||||||
processedHasNameSQL = `(` + processedPreferredNameSQL + ` <> '')`
|
processedHasNameSQL = `(` + processedPreferredNameSQL + ` <> '')`
|
||||||
processedHasDescriptionSQL = `(` + processedPreferredDescriptionSQL + ` <> '')`
|
processedHasDescriptionSQL = `(` + processedPreferredDescriptionSQL + ` <> '')`
|
||||||
processedHasCategorySQL = `(COALESCE(NULLIF(p.category, ''), '') <> '' AND lower(p.category) <> 'none')`
|
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.
|
// Resolve display name / canonical unique_id when products store unique_id, UUID id, or name.
|
||||||
processedCategoryResolveJoin = `
|
processedCategoryResolveJoin = `
|
||||||
LEFT JOIN LATERAL (
|
LEFT JOIN LATERAL (
|
||||||
@@ -1071,6 +1071,20 @@ func appendProcessedProductFilters(f ProductFilter, args []any, where []string)
|
|||||||
n, n, n, n, n))
|
n, n, n, n, n))
|
||||||
}
|
}
|
||||||
if f.Status != "" {
|
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).
|
// needs_review includes legacy pipeline status "processed" (pre-P0-8).
|
||||||
if f.Status == "needs_review" {
|
if f.Status == "needs_review" {
|
||||||
where = append(where, "p.status IN ('needs_review', 'processed')")
|
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 companyID, companyName, userID, userEmail, jobID, rawProductID string
|
||||||
var role, providerMode, model, callErr, finishReason string
|
var role, providerMode, model, callErr, finishReason string
|
||||||
var promptTokens, completionTokens, totalTokens, durationMS int
|
var promptTokens, completionTokens, totalTokens, durationMS int
|
||||||
|
var cachedTokens *int
|
||||||
|
var costMicros *int64
|
||||||
var createdAt time.Time
|
var createdAt time.Time
|
||||||
var sysLen, userLen, respLen int
|
var sysLen, userLen, respLen int
|
||||||
var userPreview, respPreview string
|
var userPreview, respPreview string
|
||||||
if err := rows.Scan(&id, &companyID, &companyName, &userID, &userEmail,
|
if err := rows.Scan(&id, &companyID, &companyName, &userID, &userEmail,
|
||||||
&jobID, &rawProductID, &role, &providerMode, &model, &callErr, &finishReason,
|
&jobID, &rawProductID, &role, &providerMode, &model, &callErr, &finishReason,
|
||||||
&promptTokens, &completionTokens, &totalTokens, &durationMS, &createdAt,
|
&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")
|
Error(w, http.StatusInternalServerError, "scan ai calls failed")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -132,29 +135,31 @@ func (s *Server) handleAdminListAICalls(w http.ResponseWriter, r *http.Request)
|
|||||||
outcome = "failed"
|
outcome = "failed"
|
||||||
}
|
}
|
||||||
items = append(items, map[string]any{
|
items = append(items, map[string]any{
|
||||||
"id": id,
|
"id": id,
|
||||||
"company_id": companyID,
|
"company_id": companyID,
|
||||||
"company_name": companyName,
|
"company_name": companyName,
|
||||||
"user_id": userID,
|
"user_id": userID,
|
||||||
"user_email": userEmail,
|
"user_email": userEmail,
|
||||||
"job_id": jobID,
|
"job_id": jobID,
|
||||||
"raw_product_id": rawProductID,
|
"raw_product_id": rawProductID,
|
||||||
"role": role,
|
"role": role,
|
||||||
"provider_mode": providerMode,
|
"provider_mode": providerMode,
|
||||||
"model": model,
|
"model": model,
|
||||||
"outcome": outcome,
|
"outcome": outcome,
|
||||||
"error": callErr,
|
"error": callErr,
|
||||||
"finish_reason": finishReason,
|
"finish_reason": finishReason,
|
||||||
"prompt_tokens": promptTokens,
|
"prompt_tokens": promptTokens,
|
||||||
"completion_tokens": completionTokens,
|
"completion_tokens": completionTokens,
|
||||||
"total_tokens": totalTokens,
|
"total_tokens": totalTokens,
|
||||||
"duration_ms": durationMS,
|
"cached_prompt_tokens": cachedTokens,
|
||||||
"created_at": createdAt,
|
"cost_micros": costMicros,
|
||||||
"system_length": sysLen,
|
"duration_ms": durationMS,
|
||||||
"user_length": userLen,
|
"created_at": createdAt,
|
||||||
"response_length": respLen,
|
"system_length": sysLen,
|
||||||
"user_preview": userPreview,
|
"user_length": userLen,
|
||||||
"response_preview": respPreview,
|
"response_length": respLen,
|
||||||
|
"user_preview": userPreview,
|
||||||
|
"response_preview": respPreview,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
if err := rows.Err(); err != nil {
|
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,
|
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),
|
length(l.system_prompt), length(l.user_prompt), length(l.response_text),
|
||||||
left(l.user_prompt, ` + preview + `),
|
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
|
FROM ai_call_logs l
|
||||||
LEFT JOIN companies c ON c.id = l.company_id
|
LEFT JOIN companies c ON c.id = l.company_id
|
||||||
LEFT JOIN users u ON u.id = l.user_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 role, providerMode, model, callErr, finishReason string
|
||||||
var systemPrompt, userPrompt, responseText string
|
var systemPrompt, userPrompt, responseText string
|
||||||
var promptTokens, completionTokens, totalTokens, durationMS int
|
var promptTokens, completionTokens, totalTokens, durationMS int
|
||||||
|
var cachedTokens *int
|
||||||
|
var costMicros *int64
|
||||||
var createdAt time.Time
|
var createdAt time.Time
|
||||||
err = s.Pool.QueryRow(ctx, `
|
err = s.Pool.QueryRow(ctx, `
|
||||||
SELECT COALESCE(l.company_id::text, ''), COALESCE(c.name, ''),
|
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, ''),
|
COALESCE(l.job_id::text, ''), COALESCE(l.raw_product_id::text, ''),
|
||||||
l.role, l.provider_mode, l.model, l.error, l.finish_reason,
|
l.role, l.provider_mode, l.model, l.error, l.finish_reason,
|
||||||
l.system_prompt, l.user_prompt, l.response_text,
|
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
|
FROM ai_call_logs l
|
||||||
LEFT JOIN companies c ON c.id = l.company_id
|
LEFT JOIN companies c ON c.id = l.company_id
|
||||||
LEFT JOIN users u ON u.id = l.user_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,
|
Scan(&companyID, &companyName, &userID, &userEmail, &jobID, &rawProductID,
|
||||||
&role, &providerMode, &model, &callErr, &finishReason,
|
&role, &providerMode, &model, &callErr, &finishReason,
|
||||||
&systemPrompt, &userPrompt, &responseText,
|
&systemPrompt, &userPrompt, &responseText,
|
||||||
&promptTokens, &completionTokens, &totalTokens, &durationMS, &createdAt)
|
&promptTokens, &completionTokens, &totalTokens, &durationMS, &createdAt,
|
||||||
|
&cachedTokens, &costMicros)
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
// Expired rows are the common case here, so say so rather than a bare 404.
|
// 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 "+
|
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"
|
outcome = "failed"
|
||||||
}
|
}
|
||||||
JSON(w, http.StatusOK, map[string]any{
|
JSON(w, http.StatusOK, map[string]any{
|
||||||
"id": id,
|
"id": id,
|
||||||
"company_id": companyID,
|
"company_id": companyID,
|
||||||
"company_name": companyName,
|
"company_name": companyName,
|
||||||
"user_id": userID,
|
"user_id": userID,
|
||||||
"user_email": userEmail,
|
"user_email": userEmail,
|
||||||
"job_id": jobID,
|
"job_id": jobID,
|
||||||
"raw_product_id": rawProductID,
|
"raw_product_id": rawProductID,
|
||||||
"role": role,
|
"role": role,
|
||||||
"provider_mode": providerMode,
|
"provider_mode": providerMode,
|
||||||
"model": model,
|
"model": model,
|
||||||
"outcome": outcome,
|
"outcome": outcome,
|
||||||
"error": callErr,
|
"error": callErr,
|
||||||
"finish_reason": finishReason,
|
"finish_reason": finishReason,
|
||||||
"system_prompt": systemPrompt,
|
"system_prompt": systemPrompt,
|
||||||
"user_prompt": userPrompt,
|
"user_prompt": userPrompt,
|
||||||
"response_text": responseText,
|
"response_text": responseText,
|
||||||
"prompt_tokens": promptTokens,
|
"prompt_tokens": promptTokens,
|
||||||
"completion_tokens": completionTokens,
|
"completion_tokens": completionTokens,
|
||||||
"total_tokens": totalTokens,
|
"total_tokens": totalTokens,
|
||||||
"duration_ms": durationMS,
|
"cached_prompt_tokens": cachedTokens,
|
||||||
"created_at": createdAt,
|
"cost_micros": costMicros,
|
||||||
"retention_days": aiaudit.RetentionDays,
|
"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("unprocessed"), { kind: "raw", status: "unprocessed" });
|
||||||
assert.deepEqual(tabToApiParams("processing"), { kind: "raw", status: "processing" });
|
assert.deepEqual(tabToApiParams("processing"), { kind: "raw", status: "processing" });
|
||||||
assert.deepEqual(tabToApiParams("needs_review"), { kind: "processed", status: "needs_review" });
|
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" });
|
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" };
|
return { kind: "raw", status: "processing" };
|
||||||
case "processed":
|
case "processed":
|
||||||
default:
|
default:
|
||||||
return { kind: "processed", status: "completed" };
|
return { kind: "processed", status: "generated" };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
CardDescription,
|
CardDescription,
|
||||||
CardHeader,
|
CardHeader,
|
||||||
CardTitle,
|
CardTitle,
|
||||||
|
Dialog,
|
||||||
TableBody,
|
TableBody,
|
||||||
TableCell,
|
TableCell,
|
||||||
TableHead,
|
TableHead,
|
||||||
@@ -42,6 +43,8 @@
|
|||||||
error?: string;
|
error?: string;
|
||||||
finish_reason?: string;
|
finish_reason?: string;
|
||||||
prompt_tokens?: number;
|
prompt_tokens?: number;
|
||||||
|
cached_prompt_tokens?: number | null;
|
||||||
|
cost_micros?: number | null;
|
||||||
completion_tokens?: number;
|
completion_tokens?: number;
|
||||||
total_tokens?: number;
|
total_tokens?: number;
|
||||||
duration_ms?: number;
|
duration_ms?: number;
|
||||||
@@ -82,6 +85,7 @@
|
|||||||
let search = $state("");
|
let search = $state("");
|
||||||
|
|
||||||
let selected = $state<CallDetail | null>(null);
|
let selected = $state<CallDetail | null>(null);
|
||||||
|
let detailOpen = $state(false);
|
||||||
let detailLoading = $state(false);
|
let detailLoading = $state(false);
|
||||||
|
|
||||||
const ROLES = ["all", "processing", "categorize", "seo_meta", "campaign", "support", "other"];
|
const ROLES = ["all", "processing", "categorize", "seo_meta", "campaign", "support", "other"];
|
||||||
@@ -131,6 +135,8 @@
|
|||||||
|
|
||||||
async function openDetail(id: string) {
|
async function openDetail(id: string) {
|
||||||
detailLoading = true;
|
detailLoading = true;
|
||||||
|
detailOpen = true;
|
||||||
|
selected = null;
|
||||||
error = "";
|
error = "";
|
||||||
try {
|
try {
|
||||||
selected = await api<CallDetail>(`/api/admin/ai-calls/${id}`);
|
selected = await api<CallDetail>(`/api/admin/ai-calls/${id}`);
|
||||||
@@ -162,7 +168,8 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
onMount(async () => {
|
onMount(async () => {
|
||||||
if (!(await requirePlatformAdmin())) {
|
const gate = await requirePlatformAdmin();
|
||||||
|
if (!gate.ok) {
|
||||||
accessDenied = true;
|
accessDenied = true;
|
||||||
loading = false;
|
loading = false;
|
||||||
return;
|
return;
|
||||||
@@ -174,6 +181,7 @@
|
|||||||
} catch {
|
} catch {
|
||||||
// Company list is a convenience filter; the page still works without it.
|
// Company list is a convenience filter; the page still works without it.
|
||||||
}
|
}
|
||||||
|
jobId = new URLSearchParams(window.location.search).get("job_id") ?? "";
|
||||||
await load();
|
await load();
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
@@ -302,16 +310,15 @@
|
|||||||
<TableHead>{i18n.t("admin.aiCalls.colRole")}</TableHead>
|
<TableHead>{i18n.t("admin.aiCalls.colRole")}</TableHead>
|
||||||
<TableHead>{i18n.t("admin.aiCalls.colOutcome")}</TableHead>
|
<TableHead>{i18n.t("admin.aiCalls.colOutcome")}</TableHead>
|
||||||
<TableHead>{i18n.t("admin.aiCalls.colPrompt")}</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">{i18n.t("admin.aiCalls.colTime")}</TableHead>
|
||||||
|
<TableHead class="text-right">Details</TableHead>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
</TableHeader>
|
</TableHeader>
|
||||||
<TableBody>
|
<TableBody>
|
||||||
{#each rows as row (row.id)}
|
{#each rows as row (row.id)}
|
||||||
<TableRow
|
<TableRow>
|
||||||
class="cursor-pointer"
|
|
||||||
onclick={() => openDetail(row.id)}
|
|
||||||
>
|
|
||||||
<TableCell class="whitespace-nowrap text-xs">{formatDate(row.created_at)}</TableCell>
|
<TableCell class="whitespace-nowrap text-xs">{formatDate(row.created_at)}</TableCell>
|
||||||
<TableCell class="text-xs">{row.company_name || "—"}</TableCell>
|
<TableCell class="text-xs">{row.company_name || "—"}</TableCell>
|
||||||
<TableCell class="text-xs">{row.user_email || "—"}</TableCell>
|
<TableCell class="text-xs">{row.user_email || "—"}</TableCell>
|
||||||
@@ -322,8 +329,10 @@
|
|||||||
<TableCell class="max-w-md truncate text-xs text-muted-foreground">
|
<TableCell class="max-w-md truncate text-xs text-muted-foreground">
|
||||||
{row.user_preview}
|
{row.user_preview}
|
||||||
</TableCell>
|
</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 text-xs">{ms(row.duration_ms)}</TableCell>
|
||||||
|
<TableCell class="text-right"><Button variant="outline" size="sm" onclick={() => openDetail(row.id)}>View</Button></TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
{/each}
|
{/each}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
@@ -338,12 +347,11 @@
|
|||||||
{/if}
|
{/if}
|
||||||
{/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}
|
{#if detailLoading}
|
||||||
<Spinner />
|
<Spinner />
|
||||||
{/if}
|
{:else if selected}
|
||||||
|
<Card class="border-0 shadow-none">
|
||||||
{#if selected}
|
|
||||||
<Card class="mt-4">
|
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<div class="flex items-start justify-between gap-2">
|
<div class="flex items-start justify-between gap-2">
|
||||||
<div>
|
<div>
|
||||||
@@ -353,7 +361,7 @@
|
|||||||
{selected.model || "—"} ({selected.provider_mode || "—"})
|
{selected.model || "—"} ({selected.provider_mode || "—"})
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</div>
|
</div>
|
||||||
<Button variant="ghost" size="sm" onclick={() => (selected = null)}>
|
<Button variant="ghost" size="sm" onclick={() => (detailOpen = false)}>
|
||||||
<X class="size-4" />
|
<X class="size-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
@@ -370,16 +378,28 @@
|
|||||||
{selected.prompt_tokens ?? 0} in / {selected.completion_tokens ?? 0} out
|
{selected.prompt_tokens ?? 0} in / {selected.completion_tokens ?? 0} out
|
||||||
</dd>
|
</dd>
|
||||||
</div>
|
</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>
|
<div>
|
||||||
<dt class="text-muted-foreground">{i18n.t("admin.aiCalls.colTime")}</dt>
|
<dt class="text-muted-foreground">{i18n.t("admin.aiCalls.colTime")}</dt>
|
||||||
<dd>{ms(selected.duration_ms)} · {selected.finish_reason || "—"}</dd>
|
<dd>{ms(selected.duration_ms)} · {selected.finish_reason || "—"}</dd>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<dt class="text-muted-foreground">{i18n.t("admin.aiCalls.jobId")}</dt>
|
<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>
|
</div>
|
||||||
</dl>
|
</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}
|
{#if selected.error}
|
||||||
<Alert tone="error" message={selected.error} />
|
<Alert tone="error" message={selected.error} />
|
||||||
{/if}
|
{/if}
|
||||||
@@ -405,5 +425,6 @@
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
{/if}
|
{/if}
|
||||||
|
</Dialog>
|
||||||
{/if}
|
{/if}
|
||||||
</PageShell>
|
</PageShell>
|
||||||
@@ -72,6 +72,54 @@
|
|||||||
term: string;
|
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 => ({
|
const emptyPlanForm = (): PlanFormState => ({
|
||||||
id: 0,
|
id: 0,
|
||||||
name: "",
|
name: "",
|
||||||
@@ -176,6 +224,7 @@
|
|||||||
const [p, c] = await Promise.all([fetchAdminPlansList(), fetchAdminCompaniesList()]);
|
const [p, c] = await Promise.all([fetchAdminPlansList(), fetchAdminCompaniesList()]);
|
||||||
plans = p;
|
plans = p;
|
||||||
companies = c;
|
companies = c;
|
||||||
|
await loadCreditRules();
|
||||||
}
|
}
|
||||||
|
|
||||||
async function reload() {
|
async function reload() {
|
||||||
@@ -184,6 +233,8 @@
|
|||||||
|
|
||||||
function openCreatePlan() {
|
function openCreatePlan() {
|
||||||
planForm = emptyPlanForm();
|
planForm = emptyPlanForm();
|
||||||
|
creditForm = emptyCreditForm();
|
||||||
|
creditOriginal = emptyCreditForm();
|
||||||
planFormOpen = true;
|
planFormOpen = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -204,6 +255,8 @@
|
|||||||
is_custom: Boolean(plan.is_custom),
|
is_custom: Boolean(plan.is_custom),
|
||||||
term: plan.term || "monthly"
|
term: plan.term || "monthly"
|
||||||
};
|
};
|
||||||
|
creditForm = planCredits(Number(plan.id));
|
||||||
|
creditOriginal = { ...creditForm };
|
||||||
planFormOpen = true;
|
planFormOpen = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -231,7 +284,11 @@
|
|||||||
error = "";
|
error = "";
|
||||||
success = "";
|
success = "";
|
||||||
try {
|
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");
|
success = planFormMode === "edit" ? i18n.t("admin.billing.planUpdated") : i18n.t("admin.billing.planCreated");
|
||||||
planFormOpen = false;
|
planFormOpen = false;
|
||||||
planForm = emptyPlanForm();
|
planForm = emptyPlanForm();
|
||||||
@@ -598,6 +655,21 @@
|
|||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
</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">
|
<div class="flex items-start gap-3 rounded-md border border-border p-3">
|
||||||
<Checkbox id="plan-custom" bind:checked={planForm.is_custom} />
|
<Checkbox id="plan-custom" bind:checked={planForm.is_custom} />
|
||||||
<div class="space-y-1">
|
<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">
|
<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">
|
<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} />
|
<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>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
|
|
||||||
|
|||||||
@@ -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.
|
||||||
Reference in new issue
Block a user