This commit is contained in:
greeneclipse committed 2026-10-20 17:50:32 +02:00
1 parent fd83a7c523
commit edbbf127ba
12 files changed
+244 -205

No files matched your search

+11 -45
View File
@@ -20,15 +20,13 @@ var contentFeatures = map[string]string{
"seo_meta": "seo_meta_ai",
}
var defaultContentUnits = map[string]int64{
"title": 1000,
"description": 2500,
"seo_meta": 1000,
}
// ContentDebitUnits calculates exactly one charge per selected output. A missing
// selection means the legacy job mode determines which outputs were requested.
// ContentDebitUnits bills one credit for one processed product in one language,
// regardless of which supported outputs were selected. The EUR value of a
// credit is a separate reference value and is never a processing multiplier.
// rates is retained for existing callers, but output-level admin prices no
// longer affect the product enrichment charge.
func ContentDebitUnits(selected []string, processingType string, rates map[string]int64) (int64, error) {
_ = rates
if len(selected) == 0 {
switch processingType {
case "seo", "seo_meta", "seo_ai":
@@ -41,40 +39,12 @@ func ContentDebitUnits(selected []string, processingType string, rates map[strin
selected = []string{"title", "description"}
}
}
// Never let an unsupported output bypass validation in flat-rate mode.
for _, item := range selected {
if _, known := contentFeatures[item]; !known {
return 0, fmt.Errorf("unknown content processing type %q", item)
for _, output := range selected {
if _, ok := contentFeatures[output]; !ok {
return 0, fmt.Errorf("unknown content processing type %q", output)
}
}
// A flat product rate is opt-in through the assigned plan. It takes
// precedence over per-output rates even when callers request all outputs.
if productUnits, ok := rates["product"]; ok {
if productUnits < 0 || productUnits > 1000000*contentCreditScale {
return 0, errors.New("invalid per-product credit price")
}
return productUnits, nil
}
seen := make(map[string]bool, 3)
var result int64
for _, item := range selected {
if _, ok := contentFeatures[item]; !ok {
return 0, fmt.Errorf("unknown content processing type %q", item)
}
if seen[item] {
continue
}
seen[item] = true
units, ok := rates[item]
if !ok {
units = defaultContentUnits[item]
}
if units < 0 || units > 1000000*contentCreditScale {
return 0, errors.New("invalid content credit price")
}
result += units
}
return result, nil
return contentCreditScale, nil
}
// ContentRates resolves company overrides > active plan overrides > global default.
@@ -150,11 +120,7 @@ func (s *Service) ConsumeContentCreditsTx(ctx context.Context, tx pgx.Tx, compan
if tx == nil {
return 0, errors.New("missing billing transaction")
}
rates, err := contentRatesFrom(ctx, tx, companyID)
if err != nil {
return 0, err
}
units, err := ContentDebitUnits(selected, processingType, rates)
units, err := ContentDebitUnits(selected, processingType, nil)
if err != nil {
return 0, err
}
@@ -9,12 +9,12 @@ func TestContentDebitUnits(t *testing.T) {
processingType string
want int64
}{
{[]string{"title"}, "title", 1000},
{[]string{"title", "description"}, "enhance", 3500},
{[]string{"title", "description", "seo_meta"}, "enhance", 4500},
{[]string{"seo_meta"}, "seo_meta", 1000},
{[]string{"title", "title"}, "title", 1000},
{nil, "description", 2500},
{[]string{"title"}, "title", 10000},
{[]string{"title", "description"}, "enhance", 10000},
{[]string{"title", "description", "seo_meta"}, "enhance", 10000},
{[]string{"seo_meta"}, "seo_meta", 10000},
{[]string{"title", "title"}, "title", 10000},
{nil, "description", 10000},
}
for _, tt := range cases {
got, err := ContentDebitUnits(tt.selected, tt.processingType, rates)
@@ -27,12 +27,12 @@ func TestContentDebitUnits(t *testing.T) {
}
for _, outputs := range [][]string{nil, {"title"}, {"title", "description", "seo_meta"}} {
got, err := ContentDebitUnits(outputs, "enhance", map[string]int64{"title": 1000, "description": 2500, "seo_meta": 1000, "product": 3750})
if err != nil || got != 3750 {
if err != nil || got != 10000 {
t.Errorf("per-product price outputs=%v got=%d err=%v", outputs, got, err)
}
}
zero, err := ContentDebitUnits([]string{"title"}, "title", map[string]int64{"title": 0})
if err != nil || zero != 0 {
if err != nil || zero != 10000 {
t.Fatalf("zero cost %v %v", zero, err)
}
}
@@ -120,21 +120,13 @@ func (s *Server) handleCompanyContentCosts(w http.ResponseWriter, r *http.Reques
Error(w, http.StatusUnauthorized, "unauthorized")
return
}
rates, err := s.Billing.ContentRates(r.Context(), cid)
if err != nil {
LogAndError(w, http.StatusInternalServerError, "could not load credit costs", err)
return
}
out := make(map[string]float64, len(rates))
for key, units := range rates {
out[key] = float64(units) / 10000
}
mode := "outputs"
if _, ok := rates["product"]; ok {
mode = "product"
}
// Flat charge for one product in one selected language. Never derive a
// displayed estimate from per-output admin rates or the EUR/credit value.
w.Header().Set("Cache-Control", "private, no-store")
JSON(w, http.StatusOK, map[string]any{"mode": mode, "credits": out})
JSON(w, http.StatusOK, map[string]any{
"mode": "product",
"credits": map[string]float64{"product": 1},
})
}
// Monetary credit valuation is an admin reference rate. Stripe invoices, pack
@@ -7,6 +7,7 @@ import (
"strings"
"github.com/descrybe/descrybe-v2/apps/api/internal/billing"
"github.com/descrybe/descrybe-v2/apps/api/internal/company"
"github.com/descrybe/descrybe-v2/apps/api/internal/processing"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
@@ -19,6 +20,7 @@ type startProcessingJobRequest struct {
RawProductIDs []string `json:"raw_product_ids"`
ProcessingType string `json:"processing_type"`
ProcessingTypes []string `json:"processing_types"`
Language string `json:"language"`
}
func (s *Server) handleStartProcessingJob(w http.ResponseWriter, r *http.Request) {
@@ -49,14 +51,36 @@ func (s *Server) handleStartProcessingJob(w http.ResponseWriter, r *http.Request
return
}
}
// If unspecified, resolve the company's primary language. Do not turn a
// single-language request into an all-company-language job.
targetLang := company.NormalizeLanguage(body.Language)
if targetLang == "" {
targetLang = company.LoadLanguage(r.Context(), s.Pool, cid)
}
if !company.IsAllowedLanguage(targetLang) {
Error(w, http.StatusBadRequest, "unsupported processing language")
return
}
enabled := company.LoadContentLanguages(r.Context(), s.Pool, cid)
allowed := false
for _, lang := range enabled {
if lang == targetLang {
allowed = true
break
}
}
if !allowed {
Error(w, http.StatusBadRequest, "language not enabled for this company")
return
}
// The shared handler serves session dashboard jobs and /api/v1/process.
// Public API results should be directly visible in the Processed catalog tab.
var jobs []processing.Job
var err error
if strings.HasPrefix(r.URL.Path, "/api/v1/") {
jobs, err = s.Processing.StartAPIJobWithTypes(r.Context(), cid, uid, ids, body.ProcessingType, body.ProcessingTypes)
jobs, err = s.Processing.StartAPIJobWithTypesInLanguage(r.Context(), cid, uid, ids, body.ProcessingType, body.ProcessingTypes, targetLang)
} else {
jobs, err = s.Processing.StartJobWithTypes(r.Context(), cid, uid, ids, body.ProcessingType, body.ProcessingTypes)
jobs, err = s.Processing.StartJobWithTypesInLanguage(r.Context(), cid, uid, ids, body.ProcessingType, body.ProcessingTypes, targetLang)
}
if err != nil {
if writePlanGate(w, err) {
@@ -11,6 +11,7 @@ import (
"github.com/descrybe/descrybe-v2/apps/api/internal/billing"
"github.com/descrybe/descrybe-v2/apps/api/internal/catalog"
"github.com/descrybe/descrybe-v2/apps/api/internal/company"
"github.com/descrybe/descrybe-v2/apps/api/internal/processing"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
@@ -22,6 +23,7 @@ type v1StartProcessRequest struct {
RawProductIDs []string `json:"raw_product_ids"`
ProcessingType json.RawMessage `json:"processing_type"`
ProcessingTypes []string `json:"processing_types"`
Language string `json:"language"`
Items []catalog.V1ProcessItem `json:"items"`
}
@@ -143,7 +145,34 @@ func (s *Server) handleV1StartProcess(w http.ResponseWriter, r *http.Request) {
return
}
jobs, err := s.startV1Jobs(r.Context(), cid, uid, rawIDs, storageType)
var jobs []processing.Job
var err error
if strings.TrimSpace(body.Language) != "" {
lang := company.NormalizeLanguage(body.Language)
if !company.IsAllowedLanguage(lang) {
v1Err(w, http.StatusBadRequest, "validation_error", "unsupported processing language")
return
}
enabled := company.LoadContentLanguages(r.Context(), s.Pool, cid)
allowed := false
for _, candidate := range enabled {
if candidate == lang {
allowed = true
break
}
}
if !allowed {
v1Err(w, http.StatusBadRequest, "validation_error", "language not enabled for this company")
return
}
if s.testStartJobs != nil {
jobs, err = s.startV1Jobs(r.Context(), cid, uid, rawIDs, storageType)
} else {
jobs, err = s.Processing.StartAPIJobWithTypesInLanguage(r.Context(), cid, uid, rawIDs, storageType, nil, lang)
}
} else {
jobs, err = s.startV1Jobs(r.Context(), cid, uid, rawIDs, storageType)
}
if err != nil {
v1ErrFromProcessing(w, err)
return
@@ -411,10 +440,6 @@ func (s *Server) assertV1ProcessGates(ctx context.Context, companyID uuid.UUID,
RequiresAI: billing.ProcessingTypeRequiresAI(processingType) || billing.ProcessingTypeIsEmailCampaignAI(processingType),
RequiresEPREL: billing.ProcessingTypeRequiresEPREL(processingType),
}
if rates, err := s.Billing.ContentRates(ctx, companyID); err == nil {
if units, err := billing.ContentDebitUnits(nil, processingType, rates); err == nil {
opts.CreditsPerProduct = float64(units) / 10000
}
}
opts.CreditsPerProduct = 1
return s.Billing.AssertCanStartProcessing(ctx, companyID, batchSize, opts)
}
+52 -21
View File
@@ -135,26 +135,42 @@ type Job struct {
// of ≤maxJobProducts so ClaimNext SKIP LOCKED workers stay parallelizable.
// Absolute request cap is MaxStartProducts (100k–1M scale).
func (p *Pipeline) StartJob(ctx context.Context, companyID, userID uuid.UUID, rawIDs []uuid.UUID, processingType string) ([]Job, error) {
return p.startJobWithOrigin(ctx, companyID, userID, rawIDs, processingType, "dashboard", nil)
return p.startJobWithOrigin(ctx, companyID, userID, rawIDs, processingType, "dashboard", nil, "")
}
// StartAPIJob uses the same processing pipeline and company-scoped catalog as the
// dashboard, but completed API results do not require a dashboard approval action.
func (p *Pipeline) StartAPIJob(ctx context.Context, companyID, userID uuid.UUID, rawIDs []uuid.UUID, processingType string) ([]Job, error) {
return p.startJobWithOrigin(ctx, companyID, userID, rawIDs, processingType, "api", nil)
return p.startJobWithOrigin(ctx, companyID, userID, rawIDs, processingType, "api", nil, "")
}
// StartJobWithTypes preserves the exact outputs selected in the dashboard.
func (p *Pipeline) StartJobWithTypes(ctx context.Context, companyID, userID uuid.UUID, rawIDs []uuid.UUID, processingType string, outputs []string) ([]Job, error) {
return p.startJobWithOrigin(ctx, companyID, userID, rawIDs, processingType, "dashboard", outputs)
return p.startJobWithOrigin(ctx, companyID, userID, rawIDs, processingType, "dashboard", outputs, "")
}
// StartAPIJobWithTypes preserves explicit output selections for public API jobs.
func (p *Pipeline) StartAPIJobWithTypes(ctx context.Context, companyID, userID uuid.UUID, rawIDs []uuid.UUID, processingType string, outputs []string) ([]Job, error) {
return p.startJobWithOrigin(ctx, companyID, userID, rawIDs, processingType, "api", outputs)
return p.startJobWithOrigin(ctx, companyID, userID, rawIDs, processingType, "api", outputs, "")
}
func (p *Pipeline) startJobWithOrigin(ctx context.Context, companyID, userID uuid.UUID, rawIDs []uuid.UUID, processingType, origin string, outputs []string) ([]Job, error) {
// StartJobWithTypesInLanguage queues only the explicitly selected company language.
func (p *Pipeline) StartJobWithTypesInLanguage(ctx context.Context, companyID, userID uuid.UUID, rawIDs []uuid.UUID, processingType string, outputs []string, language string) ([]Job, error) {
return p.startJobWithOrigin(ctx, companyID, userID, rawIDs, processingType, "dashboard", outputs, language)
}
// StartAPIJobWithTypesInLanguage keeps public API jobs single-language as well.
func (p *Pipeline) StartAPIJobWithTypesInLanguage(ctx context.Context, companyID, userID uuid.UUID, rawIDs []uuid.UUID, processingType string, outputs []string, language string) ([]Job, error) {
return p.startJobWithOrigin(ctx, companyID, userID, rawIDs, processingType, "api", outputs, language)
}
func (p *Pipeline) startJobWithOrigin(ctx context.Context, companyID, userID uuid.UUID, rawIDs []uuid.UUID, processingType, origin string, outputs []string, language string) ([]Job, error) {
if language == "" {
language = company.LoadLanguage(ctx, p.Pool, companyID)
}
if !company.IsAllowedLanguage(language) {
return nil, fmt.Errorf("unsupported processing language %q", language)
}
if processingType == "" {
processingType = "full"
}
@@ -214,9 +230,9 @@ func (p *Pipeline) startJobWithOrigin(ctx context.Context, companyID, userID uui
var jobID uuid.UUID
err = tx.QueryRow(ctx, `
INSERT INTO processing_jobs (
company_id, user_id, status, total_products, processing_type, current_step, step_progress, origin, processing_types
) VALUES ($1, $2, 'pending', $3, $4, $5, $6::jsonb, $7, $8) RETURNING id`,
companyID, userID, len(chunk), processingType, firstStep, progressJSON, origin, outputs).Scan(&jobID)
company_id, user_id, status, total_products, processing_type, current_step, step_progress, origin, processing_types, processing_language
) VALUES ($1, $2, 'pending', $3, $4, $5, $6::jsonb, $7, $8, $9) RETURNING id`,
companyID, userID, len(chunk), processingType, firstStep, progressJSON, origin, outputs, language).Scan(&jobID)
if err != nil {
return nil, err
}
@@ -253,11 +269,7 @@ func (p *Pipeline) assertProcessingGates(ctx context.Context, companyID uuid.UUI
RequiresAI: billing.ProcessingTypeRequiresAI(processingType) || billing.ProcessingTypeIsEmailCampaignAI(processingType),
RequiresEPREL: billing.ProcessingTypeRequiresEPREL(processingType),
}
if rates, err := p.Billing.ContentRates(ctx, companyID); err == nil {
if units, err := billing.ContentDebitUnits(outputs, processingType, rates); err == nil {
opts.CreditsPerProduct = float64(units) / 10000
}
}
opts.CreditsPerProduct = 1
return p.Billing.AssertCanStartProcessing(ctx, companyID, batchSize, opts)
}
@@ -626,13 +638,13 @@ func (p *Pipeline) RetryJob(ctx context.Context, companyID, id uuid.UUID) (Job,
func (p *Pipeline) ProcessJob(ctx context.Context, jobID uuid.UUID) error {
var companyID uuid.UUID
var jobUserID *uuid.UUID
var status, processingType, origin string
var status, processingType, origin, processingLanguage string
var selectedOutputs []string
var alreadyProcessed int
err := p.Pool.QueryRow(ctx, `
SELECT company_id, user_id, status, processing_type, processed_products, origin, processing_types
SELECT company_id, user_id, status, processing_type, processed_products, origin, processing_types, COALESCE(processing_language, '')
FROM processing_jobs WHERE id = $1`, jobID).
Scan(&companyID, &jobUserID, &status, &processingType, &alreadyProcessed, &origin, &selectedOutputs)
Scan(&companyID, &jobUserID, &status, &processingType, &alreadyProcessed, &origin, &selectedOutputs, &processingLanguage)
if err != nil {
return err
}
@@ -700,6 +712,15 @@ func (p *Pipeline) ProcessJob(ctx context.Context, jobID uuid.UUID) error {
batch := resolveBatchSize(p.BatchSize)
progressEvery := resolveProgressEvery(p.ProgressEvery)
jobCache := p.loadJobScopedCache(ctx, companyID, jobID)
processingLanguage = company.NormalizeLanguage(processingLanguage)
if processingLanguage == "" {
processingLanguage = jobCache.language
}
// One target language, even if the company has many enabled languages.
// Keep cache.language as the primary so only primary jobs update row-level
// title/description/meta fields.
jobCache.contentLanguages = []string{processingLanguage}
jobCache.processingLanguage = processingLanguage
if !jobCache.stepPolicy().AllowAI {
log.Printf("processing: ai_skip job=%s reason=entitlement_can_use_ai", jobID)
} else if !jobEngine.CompleterEnabled() {
@@ -905,6 +926,7 @@ type jobScopedCache struct {
stdDefs []StandardFieldDef
brandPrompt string
language string
processingLanguage string
enhanceSystemTemplate string
enhanceUserTemplate string
enhanceByLang map[string]PromptTemplates
@@ -1675,6 +1697,9 @@ func (p *Pipeline) processOne(ctx context.Context, companyID, jobID uuid.UUID, i
result.MetaDescription = ""
if result.LocalizedContent != nil {
for lang, lf := range result.LocalizedContent {
if cache.processingLanguage != "" && lang != cache.processingLanguage {
continue
}
lf.MetaTitle = ""
lf.MetaDescription = ""
result.LocalizedContent[lang] = lf
@@ -1690,7 +1715,7 @@ func (p *Pipeline) processOne(ctx context.Context, companyID, jobID uuid.UUID, i
}
}
// Keep primary localized meta in sync with row-level fields used by upsert.
if primary := company.NormalizeLanguage(language); primary != "" && result.LocalizedContent != nil {
if primary := company.NormalizeLanguage(language); primary != "" && result.LocalizedContent != nil && (cache == nil || cache.processingLanguage == "" || cache.processingLanguage == primary) {
lf := company.FieldsForLanguage(result.LocalizedContent, primary)
changed := false
if lf.MetaTitle == "" && result.MetaTitle != "" {
@@ -1753,7 +1778,7 @@ func (p *Pipeline) processOne(ctx context.Context, companyID, jobID uuid.UUID, i
}
}
processedID, err := p.upsertProcessedProduct(ctx, tx, companyID, it.RawID, gtin, result, attrsJSON, procAttrsJSON, gptJSON, sourcesJSON, providerMode, language, origin)
processedID, err := p.upsertProcessedProduct(ctx, tx, companyID, it.RawID, gtin, result, attrsJSON, procAttrsJSON, gptJSON, sourcesJSON, providerMode, language, origin, cache != nil && cache.processingLanguage != "" && cache.processingLanguage != language)
if err != nil {
return false, 0, result, err
}
@@ -1834,10 +1859,12 @@ const upsertProcessedProductSQL = `
ELSE EXCLUDED.description
END,
processed_name = CASE
WHEN $19::boolean THEN processed_products.processed_name
WHEN EXCLUDED.processing_origin = 'api' THEN COALESCE(NULLIF(BTRIM(EXCLUDED.processed_name), ''), processed_products.processed_name)
ELSE EXCLUDED.processed_name
END,
processed_description = CASE
WHEN $19::boolean THEN processed_products.processed_description
WHEN EXCLUDED.processing_origin = 'api' THEN COALESCE(NULLIF(BTRIM(EXCLUDED.processed_description), ''), processed_products.processed_description)
ELSE EXCLUDED.processed_description
END,
@@ -1851,13 +1878,14 @@ const upsertProcessedProductSQL = `
THEN processed_products.processed_attributes ELSE EXCLUDED.processed_attributes END,
gpt_response = EXCLUDED.gpt_response,
total_tokens = COALESCE(processed_products.total_tokens, 0) + EXCLUDED.total_tokens,
field_sources = EXCLUDED.field_sources,
field_sources = CASE WHEN $19::boolean THEN processed_products.field_sources ELSE EXCLUDED.field_sources END,
ai_provider_mode = EXCLUDED.ai_provider_mode,
localized_content = CASE
WHEN EXCLUDED.processing_origin = 'api'
WHEN EXCLUDED.processing_origin = 'api' OR $19::boolean
THEN COALESCE(processed_products.localized_content, '{}'::jsonb) || EXCLUDED.localized_content
ELSE EXCLUDED.localized_content END,
meta_title = CASE
WHEN $19::boolean THEN processed_products.meta_title
WHEN EXCLUDED.processing_origin = 'api' AND NULLIF(BTRIM(EXCLUDED.meta_title), '') IS NOT NULL
THEN NULLIF(BTRIM(EXCLUDED.meta_title), '')
WHEN NULLIF(BTRIM(processed_products.meta_title), '') IS NULL
@@ -1875,6 +1903,7 @@ const upsertProcessedProductSQL = `
ELSE processed_products.meta_title
END,
meta_description = CASE
WHEN $19::boolean THEN processed_products.meta_description
WHEN EXCLUDED.processing_origin = 'api' AND NULLIF(BTRIM(EXCLUDED.meta_description), '') IS NOT NULL
THEN NULLIF(BTRIM(EXCLUDED.meta_description), '')
WHEN NULLIF(BTRIM(processed_products.meta_description), '') IS NULL
@@ -1925,7 +1954,9 @@ func (p *Pipeline) upsertProcessedProduct(
providerMode string,
primaryLang string,
origin string,
secondaryLanguage ...bool,
) (uuid.UUID, error) {
isSecondary := len(secondaryLanguage) > 0 && secondaryLanguage[0]
localized := result.LocalizedContent
if localized == nil {
localized = company.LocalizedContent{}
@@ -1952,7 +1983,7 @@ func (p *Pipeline) upsertProcessedProduct(
err = queryRow(ctx, upsertProcessedProductSQL,
companyID, rawID, gtin, result.Name, result.Category, result.Description,
result.ProcessedName, result.ProcessedDescription, attrsJSON, procAttrsJSON, gptJSON, result.TotalTokens, sourcesJSON, providerMode, string(locJSON),
result.MetaTitle, result.MetaDescription, origin,
result.MetaTitle, result.MetaDescription, origin, isSecondary,
).Scan(&processedID)
return processedID, err
}
@@ -0,0 +1,24 @@
package processing
import (
"os"
"strings"
"testing"
)
// Source regressions enforce the job/worker language contract without a database.
func TestJobWorkerLanguageSelectionWiring(t *testing.T) {
source, err := os.ReadFile("pipeline.go")
if err != nil {
t.Fatal(err)
}
body := string(source)
for _, fragment := range []string{
"processing_language", "jobCache.contentLanguages = []string{processingLanguage}",
"jobCache.processingLanguage = processingLanguage", "cache.processingLanguage != language",
} {
if !strings.Contains(body, fragment) {
t.Errorf("missing language worker wiring %q", fragment)
}
}
}
@@ -120,7 +120,7 @@ func TestUpsertProcessedProduct_concurrentIdempotent(t *testing.T) {
for i := 0; i < n; i++ {
go func() {
defer wg.Done()
id, err := p.upsertProcessedProduct(ctx, nil, companyID, rawID, gtin, result, emptyJSON, emptyJSON, emptyJSON, emptyJSON, AIProviderInternal, "en")
id, err := p.upsertProcessedProduct(ctx, nil, companyID, rawID, gtin, result, emptyJSON, emptyJSON, emptyJSON, emptyJSON, AIProviderInternal, "en", "dashboard")
if err != nil {
errCh <- err
return
@@ -0,0 +1,6 @@
-- +goose Up
-- One explicit target language per job. Empty on older jobs means primary.
ALTER TABLE processing_jobs ADD COLUMN IF NOT EXISTS processing_language TEXT NOT NULL DEFAULT '';
-- +goose Down
ALTER TABLE processing_jobs DROP COLUMN IF EXISTS processing_language;
@@ -5,9 +5,8 @@
import ConfirmationDialog from "$lib/components/categories/formula/ConfirmationDialog.svelte";
import { cn } from "$lib/utils";
import { i18n } from "$lib/i18n";
import { onMount } from "svelte";
import { api } from "$lib/api";
import { PROCESSING_OPTIONS, type ProcessingType, type ProductRow } from "./types";
import { CONTENT_LANGUAGES } from "$lib/content-languages";
let {
selectedCount,
@@ -17,6 +16,8 @@
isProcessing = false,
inline = false,
hideClear = false,
primaryLanguage = "en",
contentLanguages = ["en"],
canUseAI = true,
canProcessAITitles = canUseAI,
canProcessAIDescriptions = canUseAI,
@@ -39,7 +40,9 @@
/** When set, overrides canUseAI for the description AI option. */
canProcessAIDescriptions?: boolean;
onClear: () => void;
onProcess: (types: ProcessingType[]) => void;
primaryLanguage?: string;
contentLanguages?: string[];
onProcess: (types: ProcessingType[], language: string) => void;
onExport: () => void;
onMarkAsProcessed?: () => void;
onResetToUnprocessed?: () => void;
@@ -57,63 +60,21 @@
let pendingTypes = $state<ProcessingType[]>([]);
let pendingCredits = $state<number | null>(null);
let pendingCount = $state(0);
let selectedTypes = $state<ProcessingType[]>([]);
let effectiveCosts = $state<Record<ProcessingType | "product", number>>({ title: 0.10, description: 0.25, seo_meta: 0.10, product: 0.45 });
let processingMode = $state<"outputs" | "product" | "unknown">("unknown");
let pricingReady = $state(false);
let pricingLoading = $state(true);
let pricingError = $state(false);
let requestSerial = 0;
const processProductTypes: ProcessingType[] = ["title", "description", "seo_meta"];
let selectedTypes = $state<ProcessingType[]>(["title", "description", "seo_meta"]);
let selectedLanguage = $state("");
const languageOptions = $derived([primaryLanguage, ...contentLanguages].filter(
(lang, index, all) => all.indexOf(lang) === index
));
const targetLanguage = $derived(languageOptions.includes(selectedLanguage) ? selectedLanguage : primaryLanguage);
let pendingLanguage = $state("");
// Credit pricing is about the company's billing plan, not the product's
// selling price or stock. A failed estimate must not disable enrichment.
// When the mode cannot be verified, offer full enrichment only so callers
// cannot inadvertently expect a per-output price on a flat-rate plan.
async function loadProcessingCosts() {
const serial = ++requestSerial;
pricingLoading = true;
pricingError = false;
try {
const result = await api<{
mode: "outputs" | "product";
credits: Record<ProcessingType | "product", number>;
}>("/api/billing/processing-costs");
if (serial !== requestSerial) return;
const keys: Array<ProcessingType | "product"> = result?.mode === "product"
? ["product"]
: ["title", "description", "seo_meta"];
if (!result?.credits || keys.some((key) =>
typeof result.credits[key] !== "number" ||
!Number.isFinite(result.credits[key]) || result.credits[key] < 0
)) throw new Error("Invalid processing credit rates");
effectiveCosts = result.credits;
processingMode = result.mode;
pricingReady = true;
} catch {
if (serial !== requestSerial) return;
pricingReady = false;
processingMode = "unknown";
pricingError = true;
} finally {
if (serial === requestSerial) pricingLoading = false;
}
}
const selectedAILocked = $derived(selectedTypes.some(
(t) => PROCESSING_OPTIONS.find((o) => o.type === t)?.requiresAI && !aiAllowedForType(t)
));
onMount(() => { void loadProcessingCosts(); });
const selectedAILocked = $derived(
(processingMode !== "outputs" && !processProductTypes.every(aiAllowedForType)) || selectedTypes.some((t) => PROCESSING_OPTIONS.find((o) => o.type === t)?.requiresAI && !aiAllowedForType(t))
);
// Estimated cost from the effective company/plan rates (per selected output).
const totalCredits = $derived(!pricingReady ? null : processingMode === "product"
? effectiveCosts.product * selectedCount
: PROCESSING_OPTIONS.filter((option) => selectedTypes.includes(option.type)).reduce(
(sum, option) => sum + effectiveCosts[option.type],
0
) * selectedCount
);
// A single product in a single language costs 1 credit, no matter how many
// of the three outputs are selected. Show only the total charge.
const totalCredits = $derived(selectedTypes.length === 0 ? 0 : selectedCount);
function toggleType(type: ProcessingType) {
if (!aiAllowedForType(type) && PROCESSING_OPTIONS.find((o) => o.type === type)?.requiresAI) return;
@@ -130,9 +91,10 @@
}
function processSelected() {
if (pricingLoading || (processingMode === "outputs" && selectedTypes.length === 0)) return;
if (selectedTypes.length === 0) return;
if (selectedAILocked) return;
pendingTypes = processingMode !== "outputs" ? [...processProductTypes] : [...selectedTypes];
pendingTypes = [...selectedTypes];
pendingLanguage = targetLanguage;
pendingCredits = totalCredits;
pendingCount = selectedCount;
open = false;
@@ -142,6 +104,7 @@
function cancelProcessConfirm() {
confirmProcessOpen = false;
pendingTypes = [];
pendingLanguage = "";
pendingCredits = null;
pendingCount = 0;
}
@@ -152,12 +115,14 @@
return;
}
const types = pendingTypes;
const language = pendingLanguage;
pendingTypes = [];
pendingLanguage = "";
pendingCredits = null;
pendingCount = 0;
confirmProcessOpen = false;
selectedTypes = [];
onProcess(types);
selectedTypes = [...processProductTypes];
onProcess(types, language);
}
const processConfirmDescription = $derived(
@@ -165,7 +130,7 @@
? i18n.t("processing.actions.confirmWithoutEstimate", { count: pendingCount })
: i18n.t("processing.actions.confirmBody", {
count: pendingCount,
credits: pendingCredits.toFixed(2)
credits: String(pendingCredits)
})
);
</script>
@@ -196,20 +161,13 @@
{/if}
{#if activeTab !== "processed"}
{#if pricingError}
<div class="flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground" role="status">
<span>{i18n.t("processing.actions.estimateUnavailable")}</span>
<Button size="sm" variant="ghost" class="h-7 px-2 text-xs" disabled={pricingLoading} onclick={() => void loadProcessingCosts()}>
<RotateCcw class="mr-1 h-3 w-3" />{i18n.t("processing.retry")}
</Button>
</div>
{/if}
<div class="relative">
<Button
variant="default"
size="sm"
mutation
disabled={selectedCount === 0 || isProcessing || pricingLoading}
disabled={selectedCount === 0 || isProcessing}
loading={isProcessing}
data-assistant-target="start-processing"
data-tour="start-processing"
@@ -232,6 +190,23 @@
>
<div class="px-2 py-1.5 text-sm font-semibold text-foreground">{i18n.t("processing.actions.whatToProcess")}</div>
<div class="my-1 h-px bg-border"></div>
<div class="px-2 pt-2">
<label for="process-language" class="mb-1 block text-xs font-medium text-muted-foreground">Processing language</label>
<select
id="process-language"
class="w-full rounded-md border border-border bg-background px-2 py-2 text-sm text-foreground"
value={targetLanguage}
onchange={(event) => (selectedLanguage = event.currentTarget.value)}
>
{#each languageOptions as lang}
<option value={lang}>
{CONTENT_LANGUAGES.find((option) => option.value === lang)?.label ?? lang}
{lang === primaryLanguage ? " (Primary)" : ""}
</option>
{/each}
</select>
<p class="mt-1 text-xs text-muted-foreground">Only this language will be generated.</p>
</div>
<div class="p-2">
{#if !canProcessAITitles || !canProcessAIDescriptions}
<div class="mb-3 rounded border border-chart-amber/40 bg-chart-amber/15 p-2 text-xs">
@@ -244,17 +219,7 @@
</div>
</div>
{/if}
{#if processingMode !== "outputs"}
<div class="flex items-center justify-between gap-3 rounded-md border border-border/60 px-2 py-3">
<div>
<p class="text-sm font-semibold">{i18n.t("processing.actions.fullEnrichment")}</p>
<p class="text-xs text-muted-foreground">{i18n.t("processing.actions.fullEnrichmentBody")}</p>
</div>
{#if totalCredits !== null}
<span class="shrink-0 font-mono text-xs">{effectiveCosts.product.toFixed(4)} {i18n.t("processing.actions.creditsUnit")}</span>
{/if}
</div>
{:else}
<button
type="button"
class="mb-3 flex items-center space-x-2 border-b border-border/50 pb-3"
@@ -296,15 +261,9 @@
: ""}</span
>
</label>
<span class="font-mono text-xs text-muted-foreground"
>{option.requiresAI
? i18n.t("products.actions.credits", { credits: (effectiveCosts[option.type] ?? option.credits).toFixed(2) })
: i18n.t("products.actions.free")}</span
>
</div>
{/each}
</div>
{/if}
</div>
<div class="my-1 h-px bg-border"></div>
<div class="space-y-2 p-2">
@@ -314,14 +273,14 @@
</div>
{/if}
<div class="flex items-center justify-between text-sm">
<span class="font-medium text-foreground">{i18n.t("processing.actions.totalCredits", { count: selectedCount })}</span>
<span class="font-mono font-medium text-primary">{totalCredits === null ? i18n.t("processing.actions.estimateUnknown") : totalCredits.toFixed(2)}</span>
<span class="font-medium text-foreground">{"Total credits"}</span>
<span class="font-mono font-medium text-primary">{totalCredits} {i18n.t("processing.actions.creditsUnit")}</span>
</div>
<Button
size="sm"
class="w-full"
mutation
disabled={pricingLoading || (processingMode === "outputs" && selectedTypes.length === 0) || isProcessing || selectedAILocked}
disabled={selectedTypes.length === 0 || isProcessing || selectedAILocked}
loading={isProcessing}
onclick={processSelected}
>
@@ -4,20 +4,22 @@ import { fileURLToPath } from 'node:url';
import test from 'node:test';
const actions = readFileSync(fileURLToPath(new URL('./ProductProcessingActions.svelte', import.meta.url)), 'utf8');
const english = readFileSync(fileURLToPath(new URL('../../i18n/messages/en.ts', import.meta.url)), 'utf8');
const page = readFileSync(fileURLToPath(new URL('../../../routes/products/+page.svelte', import.meta.url)), 'utf8');
test('billing credit lookup failure does not disable product processing', () => {
assert.match(actions, /processingMode = "unknown"/);
assert.match(actions, /pricingError = true/);
assert.match(actions, /disabled=\{selectedCount === 0 \|\| isProcessing \|\| pricingLoading\}/);
assert.doesNotMatch(actions, /disabled=\{selectedCount === 0 \|\| isProcessing \|\| !pricingReady\}/);
assert.match(actions, /processingMode !== "outputs" \? \[\.\.\.processProductTypes\]/);
test('processing can select each output without per-output prices', () => {
assert.match(actions, /PROCESSING_OPTIONS as option/);
assert.doesNotMatch(actions, /effectiveCosts\[option\.type\]/);
assert.match(actions, /selectedTypes\.length === 0/);
});
test('no unverified credit amount appears in the confirmation', () => {
assert.match(actions, /totalCredits = \$derived\(!pricingReady \? null/);
assert.match(actions, /pendingCredits === null/);
assert.match(actions, /processing.actions.confirmWithoutEstimate/);
assert.match(actions, /loadProcessingCosts\(\)/);
assert.match(english, /Actual credit charges follow your company's current billing rates/);
test('one credit per selected product regardless of chosen outputs', () => {
assert.match(actions, /selectedCount\);/);
assert.match(actions, /onProcess\(types, language\)/);
});
test('language defaults to company primary and flows to job request', () => {
assert.match(actions, /targetLanguage/);
assert.match(actions, /contentLanguages/);
assert.match(page, /primaryProcessingLanguage/);
assert.match(page, /processing_types: types,\s*language/);
});
+13 -3
View File
@@ -30,6 +30,7 @@
import { authSession } from "$lib/auth-session.svelte";
import { planCapabilities } from "$lib/plan-capabilities.svelte";
import type { Category, Feed, ListResponse, MeResponse } from "$lib/types";
import { parseContentLanguage } from "$lib/content-languages";
import {
canUseAIFromCredits,
upgradeCtaForRole,
@@ -90,6 +91,8 @@
let upgradePrompt = $state(false);
let creditsAllowAI = $state(true);
let isFreePlan = $state(false);
let primaryProcessingLanguage = $state("en");
let enabledProcessingLanguages = $state<string[]>(["en"]);
const canUseAI = $derived(
creditsAllowAI &&
planCapabilities.can("capability.ai_processing") &&
@@ -453,6 +456,10 @@
upgradeCta = upgradeCtaForRole(canAdmin);
creditsAllowAI = canUseAIFromCredits(me.credits);
isFreePlan = Boolean(me.credits?.is_free_plan);
primaryProcessingLanguage = parseContentLanguage(me.company?.language);
enabledProcessingLanguages = [primaryProcessingLanguage, ...
(me.company?.content_languages ?? []).map((lang) => parseContentLanguage(lang, primaryProcessingLanguage))
].filter((lang, index, all) => all.indexOf(lang) === index);
} catch {
/* keep defaults */
}
@@ -603,7 +610,7 @@
return selectedRawProductIds(products, selectedIds, kind);
}
async function startProcessing(types: ProcessingType[]) {
async function startProcessing(types: ProcessingType[], language: string) {
startingJob = true;
error = "";
success = "";
@@ -647,7 +654,8 @@
body: {
raw_product_ids: rawIds,
processing_type: processingType,
processing_types: types
processing_types: types,
language
}
});
const queued = job.total_products_queued ?? job.total_products ?? rawIds.length;
@@ -1368,7 +1376,9 @@
{canProcessAITitles}
{canProcessAIDescriptions}
onClear={() => (selectedIds = [])}
onProcess={(types) => void startProcessing(types)}
primaryLanguage={primaryProcessingLanguage}
contentLanguages={enabledProcessingLanguages}
onProcess={(types, language) => void startProcessing(types, language)}
onExport={openExportDialog}
onMarkAsProcessed={requestMarkAsProcessed}
onResetToUnprocessed={canAdmin ? requestResetToUnprocessed : undefined}