diff --git a/apps/api/internal/billing/content_credits.go b/apps/api/internal/billing/content_credits.go index 860eca8..4d0df0e 100644 --- a/apps/api/internal/billing/content_credits.go +++ b/apps/api/internal/billing/content_credits.go @@ -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 } diff --git a/apps/api/internal/billing/content_credits_test.go b/apps/api/internal/billing/content_credits_test.go index a7ac76d..9f7be8c 100644 --- a/apps/api/internal/billing/content_credits_test.go +++ b/apps/api/internal/billing/content_credits_test.go @@ -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) } } diff --git a/apps/api/internal/httpapi/admin_processing_costs_handlers.go b/apps/api/internal/httpapi/admin_processing_costs_handlers.go index 26d0259..7787daf 100644 --- a/apps/api/internal/httpapi/admin_processing_costs_handlers.go +++ b/apps/api/internal/httpapi/admin_processing_costs_handlers.go @@ -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 diff --git a/apps/api/internal/httpapi/processing_handlers.go b/apps/api/internal/httpapi/processing_handlers.go index 8c82ade..31803b6 100644 --- a/apps/api/internal/httpapi/processing_handlers.go +++ b/apps/api/internal/httpapi/processing_handlers.go @@ -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) { diff --git a/apps/api/internal/httpapi/v1_process_handlers.go b/apps/api/internal/httpapi/v1_process_handlers.go index d29e9cb..af44af4 100644 --- a/apps/api/internal/httpapi/v1_process_handlers.go +++ b/apps/api/internal/httpapi/v1_process_handlers.go @@ -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) } diff --git a/apps/api/internal/processing/pipeline.go b/apps/api/internal/processing/pipeline.go index a2a8330..46fb68b 100644 --- a/apps/api/internal/processing/pipeline.go +++ b/apps/api/internal/processing/pipeline.go @@ -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 } diff --git a/apps/api/internal/processing/pipeline_language_scope_test.go b/apps/api/internal/processing/pipeline_language_scope_test.go new file mode 100644 index 0000000..eb4d0b7 --- /dev/null +++ b/apps/api/internal/processing/pipeline_language_scope_test.go @@ -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) + } + } +} diff --git a/apps/api/internal/processing/upsert_processed_product_test.go b/apps/api/internal/processing/upsert_processed_product_test.go index abb9e91..2594e30 100644 --- a/apps/api/internal/processing/upsert_processed_product_test.go +++ b/apps/api/internal/processing/upsert_processed_product_test.go @@ -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 diff --git a/apps/api/sql/schema/055_processing_job_language.sql b/apps/api/sql/schema/055_processing_job_language.sql new file mode 100644 index 0000000..3277a4f --- /dev/null +++ b/apps/api/sql/schema/055_processing_job_language.sql @@ -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; diff --git a/apps/web/src/lib/components/products/ProductProcessingActions.svelte b/apps/web/src/lib/components/products/ProductProcessingActions.svelte index db308cf..6317f1c 100644 --- a/apps/web/src/lib/components/products/ProductProcessingActions.svelte +++ b/apps/web/src/lib/components/products/ProductProcessingActions.svelte @@ -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 { PROCESSING_OPTIONS, type ProcessingType, type ProductRow } from "./types"; + import { CONTENT_LANGUAGES } from "$lib/content-languages"; let { selectedCount, @@ -17,7 +16,9 @@ isProcessing = false, inline = false, hideClear = false, - canUseAI = true, + primaryLanguage = "en", + contentLanguages = ["en"], + canUseAI = true, canProcessAITitles = canUseAI, canProcessAIDescriptions = canUseAI, onClear, @@ -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([]); let pendingCredits = $state(null); let pendingCount = $state(0); - let selectedTypes = $state([]); - let effectiveCosts = $state>({ 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(["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; - }>("/api/billing/processing-costs"); - if (serial !== requestSerial) return; - const keys: Array = 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) }) ); @@ -196,20 +161,13 @@ {/if} {#if activeTab !== "processed"} - {#if pricingError} -
- {i18n.t("processing.actions.estimateUnavailable")} - -
- {/if} +
{/each} - {/if}
@@ -314,14 +273,14 @@
{/if}
- {i18n.t("processing.actions.totalCredits", { count: selectedCount })} - {totalCredits === null ? i18n.t("processing.actions.estimateUnknown") : totalCredits.toFixed(2)} + {"Total credits"} + {totalCredits} {i18n.t("processing.actions.creditsUnit")}