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

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;