This commit is contained in:
greeneclipse committed 2026-10-16 00:34:06 +02:00
1 parent 6586722652
commit 1e7c7bbfbb
65 files changed
+1345 -640

No files matched your search

@@ -0,0 +1,152 @@
package processing
import (
"context"
"fmt"
"os"
"testing"
"time"
"github.com/descrybe/descrybe-v2/apps/api/internal/catalog"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
)
// API jobs and dashboard jobs share one catalog. API completion is immediately
// visible in Processed; dashboard jobs retain explicit Needs review approval.
func TestAPIProcessedProductVisibleInCatalog(t *testing.T) {
dsn := os.Getenv("DATABASE_URL")
if dsn == "" {
t.Skip("DATABASE_URL is not set")
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
pg, err := pgxpool.New(ctx, dsn)
if err != nil {
t.Fatal(err)
}
defer pg.Close()
var userID uuid.UUID
if err := pg.QueryRow(ctx, `SELECT id FROM users LIMIT 1`).Scan(&userID); err != nil {
t.Skipf("test user unavailable: %v", err)
}
companyID := uuid.New()
if _, err := pg.Exec(ctx, `INSERT INTO companies (id,name) VALUES ($1,'API catalog visibility test')`, companyID); err != nil {
t.Fatal(err)
}
defer func() {
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cleanupCancel()
_, _ = pg.Exec(cleanupCtx, `DELETE FROM processing_job_products WHERE job_id IN (SELECT id FROM processing_jobs WHERE company_id=$1)`, companyID)
_, _ = pg.Exec(cleanupCtx, `DELETE FROM processing_jobs WHERE company_id=$1`, companyID)
_, _ = pg.Exec(cleanupCtx, `DELETE FROM processed_products WHERE company_id=$1`, companyID)
_, _ = pg.Exec(cleanupCtx, `DELETE FROM raw_products WHERE company_id=$1`, companyID)
_, _ = pg.Exec(cleanupCtx, `DELETE FROM companies WHERE id=$1`, companyID)
}()
raws := []uuid.UUID{uuid.New(), uuid.New()}
for i, id := range raws {
if _, err := pg.Exec(ctx, `INSERT INTO raw_products (id,company_id,gtin,raw_data,mapped_data,is_processed,processing_status)
VALUES ($1,$2,$3,'{}'::jsonb,'{}'::jsonb,false,'unprocessed')`, id, companyID, []string{"1234567890123", "1234567890124"}[i]); err != nil {
t.Fatal(err)
}
}
p := NewPipeline(pg)
p.Billing = nil
p.Limiter = nil
apiJobs, err := p.StartAPIJob(ctx, companyID, userID, raws[:1], "full")
if err != nil {
t.Fatal(err)
}
uiJobs, err := p.StartJob(ctx, companyID, userID, raws[1:], "full")
if err != nil {
t.Fatal(err)
}
if len(apiJobs) != 1 || len(uiJobs) != 1 {
t.Fatal("expected one job each")
}
for _, check := range []struct {
id uuid.UUID
origin string
}{{apiJobs[0].ID, "api"}, {uiJobs[0].ID, "dashboard"}} {
var actual string
if err := pg.QueryRow(ctx, `SELECT origin FROM processing_jobs WHERE id=$1`, check.id).Scan(&actual); err != nil {
t.Fatal(err)
}
if actual != check.origin {
t.Fatalf("job origin=%q want %q", actual, check.origin)
}
}
for i, origin := range []string{"api", "dashboard"} {
original := "Supplier title"
title := "AI title"
if i == 1 {
title = "Dashboard title"
}
result := StepResult{
Name: original, Description: "Supplier description", ProcessedName: title,
ProcessedDescription: "Updated AI description", MetaTitle: "SEO title", MetaDescription: "SEO description",
Attributes: map[string]any{}, ProcessedAttributes: map[string]any{"power": "5W"},
GPTResponse: map[string]any{}, FieldSources: map[string]any{},
}
_, err := p.upsertProcessedProduct(ctx, nil, companyID, raws[i], []string{"1234567890123", "1234567890124"}[i], result, []byte(`{}`), []byte(`{"power":"5W"}`), []byte(`{}`), []byte(`{}`), "internal", "sl", origin)
if err != nil {
t.Fatal(err)
}
}
svc := &catalog.Service{Pool: pg}
approved, total, err := svc.ListProcessedProducts(ctx, companyID, catalog.ProductFilter{Status: "completed", Limit: 20})
if err != nil {
t.Fatal(err)
}
if total != 1 || len(approved) != 1 {
t.Fatalf("completed total=%d items=%d", total, len(approved))
}
if approved[0]["processing_origin"] != "api" || approved[0]["name"] != "AI title" {
t.Fatalf("API result missing: %+v", approved[0])
}
reviewed, reviewTotal, err := svc.ListProcessedProducts(ctx, companyID, catalog.ProductFilter{Status: "needs_review", Limit: 20})
if err != nil {
t.Fatal(err)
}
if reviewTotal != 1 || len(reviewed) != 1 {
t.Fatalf("review total=%d", reviewTotal)
}
if reviewed[0]["processing_origin"] != "dashboard" {
t.Fatalf("dashboard status changed: %+v", reviewed[0])
}
productID, err := uuid.Parse(fmt.Sprint(approved[0]["id"]))
if err != nil {
t.Fatal(err)
}
// A later API SEO-only run must update SEO fields without erasing an earlier
// AI title, description, category, attributes or localized content.
seo := StepResult{MetaTitle: "Revised SEO title", MetaDescription: "Revised SEO description", Attributes: map[string]any{}, ProcessedAttributes: map[string]any{}, GPTResponse: map[string]any{}, FieldSources: map[string]any{}}
_, err = p.upsertProcessedProduct(ctx, nil, companyID, raws[0], "1234567890123", seo, []byte(`{}`), []byte(`{}`), []byte(`{}`), []byte(`{}`), "internal", "sl", "api")
if err != nil {
t.Fatal(err)
}
// The list must still show the same product once (upsert, not duplicate).
_, afterTotal, err := svc.ListProcessedProducts(ctx, companyID, catalog.ProductFilter{Status: "completed", Limit: 20})
if err != nil || afterTotal != 1 {
t.Fatalf("API reprocess duplicated/missing product total=%d: %v", afterTotal, err)
}
detail, err := svc.GetProcessedProduct(ctx, companyID, productID)
if err != nil {
t.Fatal(err)
}
if detail["processed_description"] != "Updated AI description" {
t.Fatalf("SEO-only pass erased description: %+v", detail)
}
if detail["processed_name"] != "AI title" || detail["meta_title"] != "Revised SEO title" || detail["meta_description"] != "Revised SEO description" {
t.Fatalf("missing processed detail: %+v", detail)
}
otherCompany := uuid.New()
_, otherTotal, err := svc.ListProcessedProducts(ctx, otherCompany, catalog.ProductFilter{Status: "completed", Limit: 20})
if err != nil || otherTotal != 0 {
t.Fatalf("company data leaked: %d %v", otherTotal, err)
}
}
+63 -26
View File
@@ -135,6 +135,16 @@ 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")
}
// 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")
}
func (p *Pipeline) startJobWithOrigin(ctx context.Context, companyID, userID uuid.UUID, rawIDs []uuid.UUID, processingType, origin string) ([]Job, error) {
if processingType == "" {
processingType = "full"
}
@@ -191,9 +201,9 @@ func (p *Pipeline) StartJob(ctx context.Context, companyID, userID uuid.UUID, ra
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
) VALUES ($1, $2, 'pending', $3, $4, $5, $6::jsonb) RETURNING id`,
companyID, userID, len(chunk), processingType, firstStep, progressJSON).Scan(&jobID)
company_id, user_id, status, total_products, processing_type, current_step, step_progress, origin
) VALUES ($1, $2, 'pending', $3, $4, $5, $6::jsonb, $7) RETURNING id`,
companyID, userID, len(chunk), processingType, firstStep, progressJSON, origin).Scan(&jobID)
if err != nil {
return nil, err
}
@@ -590,12 +600,12 @@ 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 string
var status, processingType, origin string
var alreadyProcessed int
err := p.Pool.QueryRow(ctx, `
SELECT company_id, user_id, status, processing_type, processed_products
FROM processing_jobs WHERE id = $1`, jobID).
Scan(&companyID, &jobUserID, &status, &processingType, &alreadyProcessed)
SELECT company_id, user_id, status, processing_type, processed_products, origin
FROM processing_jobs WHERE id = $1`, jobID).
Scan(&companyID, &jobUserID, &status, &processingType, &alreadyProcessed, &origin)
if err != nil {
return err
}
@@ -755,7 +765,7 @@ func (p *Pipeline) ProcessJob(ctx context.Context, jobID uuid.UUID) error {
return fmt.Errorf("processing: check cancel job=%s: %w", jobID, err)
}
}
ok, tokens, result, itemErr := p.processOne(ctx, companyID, jobID, &items[i], processingType, jobEngine, modeLabel, usingBYOK, &jobCache)
ok, tokens, result, itemErr := p.processOne(ctx, companyID, jobID, &items[i], processingType, origin, jobEngine, modeLabel, usingBYOK, &jobCache)
if itemErr != nil {
failed++
if _, err := p.Pool.Exec(ctx, `
@@ -1444,7 +1454,7 @@ func (p *Pipeline) reclaimOrphanedProcessingItems(ctx context.Context, jobID uui
return err
}
func (p *Pipeline) processOne(ctx context.Context, companyID, jobID uuid.UUID, it *jobItem, processingType string, engine *Engine, modeLabel string, usingBYOK bool, cache *jobScopedCache) (bool, int, StepResult, error) {
func (p *Pipeline) processOne(ctx context.Context, companyID, jobID uuid.UUID, it *jobItem, processingType, origin string, engine *Engine, modeLabel string, usingBYOK bool, cache *jobScopedCache) (bool, int, StepResult, error) {
if it == nil {
return false, 0, StepResult{}, fmt.Errorf("processing: nil job item")
}
@@ -1700,10 +1710,10 @@ func (p *Pipeline) processOne(ctx context.Context, companyID, jobID uuid.UUID, i
if err := p.Billing.ConsumeCreditsTx(ctx, tx, companyID, result.TotalTokens, "product_processing"); err != nil {
return false, 0, result, err
}
cache.noteCreditDebit(p.Billing.EstimateDebit(ctx, "product_processing", result.TotalTokens))
cache.noteCreditDebit(p.Billing.EstimateDebitForCompany(ctx, companyID, "product_processing", result.TotalTokens))
}
processedID, err := p.upsertProcessedProduct(ctx, tx, companyID, it.RawID, gtin, result, attrsJSON, procAttrsJSON, gptJSON, sourcesJSON, providerMode, language)
processedID, err := p.upsertProcessedProduct(ctx, tx, companyID, it.RawID, gtin, result, attrsJSON, procAttrsJSON, gptJSON, sourcesJSON, providerMode, language, origin)
if err != nil {
return false, 0, result, err
}
@@ -1765,27 +1775,51 @@ const upsertProcessedProductSQL = `
company_id, raw_product_id, product_id, name, category, description,
processed_name, processed_description, status, attributes, processed_attributes,
gpt_response, total_tokens, field_sources, ai_provider_mode, localized_content,
meta_title, meta_description
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'needs_review',$9,$10,$11,$12,$13,$14,$15::jsonb,$16,$17)
meta_title, meta_description, processing_origin
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,
CASE WHEN $18 = 'api' THEN 'completed' ELSE 'needs_review' END,
$9,$10,$11,$12,$13,$14,$15::jsonb,$16,$17,$18)
ON CONFLICT (company_id, raw_product_id) DO UPDATE SET
product_id = EXCLUDED.product_id,
name = EXCLUDED.name,
category = CASE
name = CASE
WHEN EXCLUDED.processing_origin = 'api' THEN COALESCE(NULLIF(BTRIM(EXCLUDED.name), ''), processed_products.name)
ELSE EXCLUDED.name
END,
category = CASE
WHEN COALESCE(EXCLUDED.field_sources->>'category', '') = 'cleared_invalid' THEN ''
ELSE COALESCE(NULLIF(BTRIM(EXCLUDED.category), ''), processed_products.category)
END,
description = EXCLUDED.description,
processed_name = EXCLUDED.processed_name,
processed_description = EXCLUDED.processed_description,
status = 'needs_review',
attributes = EXCLUDED.attributes,
processed_attributes = EXCLUDED.processed_attributes,
description = CASE
WHEN EXCLUDED.processing_origin = 'api' THEN COALESCE(NULLIF(BTRIM(EXCLUDED.description), ''), processed_products.description)
ELSE EXCLUDED.description
END,
processed_name = CASE
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 EXCLUDED.processing_origin = 'api' THEN COALESCE(NULLIF(BTRIM(EXCLUDED.processed_description), ''), processed_products.processed_description)
ELSE EXCLUDED.processed_description
END,
status = EXCLUDED.status,
processing_origin = EXCLUDED.processing_origin,
attributes = CASE
WHEN EXCLUDED.processing_origin = 'api' AND EXCLUDED.attributes = '{}'::jsonb
THEN processed_products.attributes ELSE EXCLUDED.attributes END,
processed_attributes = CASE
WHEN EXCLUDED.processing_origin = 'api' AND EXCLUDED.processed_attributes = '{}'::jsonb
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,
ai_provider_mode = EXCLUDED.ai_provider_mode,
localized_content = EXCLUDED.localized_content,
meta_title = CASE
localized_content = CASE
WHEN EXCLUDED.processing_origin = 'api'
THEN COALESCE(processed_products.localized_content, '{}'::jsonb) || EXCLUDED.localized_content
ELSE EXCLUDED.localized_content END,
meta_title = CASE
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
THEN NULLIF(BTRIM(EXCLUDED.meta_title), '')
WHEN BTRIM(processed_products.meta_title) ~ '\|\s+[0-9]+$'
@@ -1800,8 +1834,10 @@ const upsertProcessedProductSQL = `
THEN NULLIF(BTRIM(EXCLUDED.meta_title), '')
ELSE processed_products.meta_title
END,
meta_description = CASE
WHEN NULLIF(BTRIM(processed_products.meta_description), '') IS NULL
meta_description = CASE
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
THEN NULLIF(BTRIM(EXCLUDED.meta_description), '')
WHEN LOWER(processed_products.meta_description) LIKE '%prefer 1-3%'
OR LOWER(processed_products.meta_description) LIKE '%short retail title%'
@@ -1848,6 +1884,7 @@ func (p *Pipeline) upsertProcessedProduct(
attrsJSON, procAttrsJSON, gptJSON, sourcesJSON []byte,
providerMode string,
primaryLang string,
origin string,
) (uuid.UUID, error) {
localized := result.LocalizedContent
if localized == nil {
@@ -1875,7 +1912,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,
result.MetaTitle, result.MetaDescription, origin,
).Scan(&processedID)
return processedID, err
}