From 486502852efc3d09349ec639492c354358499caa Mon Sep 17 00:00:00 2001 From: GreenEclipse Date: Fri, 16 Oct 2026 13:48:51 +0200 Subject: [PATCH] fix --- README_SESTANEK_SL.md | 61 ++++++ README_V19.md | 18 ++ README_V20.md | 8 + apps/api/internal/billing/content_credits.go | 205 ++++++++++++++++++ .../internal/billing/content_credits_test.go | 38 ++++ apps/api/internal/billing/entitlements.go | 2 +- apps/api/internal/billing/service.go | 59 +++-- apps/api/internal/catalog/import_csv.go | 71 +++--- apps/api/internal/catalog/import_language.go | 56 +++++ .../internal/catalog/import_language_test.go | 24 ++ apps/api/internal/catalog/service.go | 21 +- apps/api/internal/feeds/service.go | 12 +- apps/api/internal/feeds/sync.go | 80 +++++-- .../feeds/sync_import_language_test.go | 25 +++ .../admin_processing_costs_handlers.go | 102 +++++++-- .../httpapi/billing_usage_export_handlers.go | 18 +- apps/api/internal/httpapi/catalog_handlers.go | 33 ++- .../httpapi/catalog_import_handlers.go | 43 +++- .../httpapi/catalog_import_language_test.go | 21 ++ apps/api/internal/httpapi/feeds_handlers.go | 20 ++ .../internal/httpapi/processing_handlers.go | 13 +- apps/api/internal/httpapi/server.go | 3 + apps/api/internal/httpapi/v1_feeds.go | 13 ++ apps/api/internal/httpapi/v1_openapi.go | 7 + .../internal/httpapi/v1_process_handlers.go | 5 + apps/api/internal/processing/pipeline.go | 64 ++++-- .../sql/schema/053_content_credit_rates.sql | 31 +++ .../schema/054_catalog_import_languages.sql | 12 + .../src/lib/admin-plan-credit-costs.test.ts | 22 ++ .../feeds/RemoteCatalogImport.svelte | 10 +- .../products/ProductProcessingActions.svelte | 51 ++++- .../products/per-product-plan.test.ts | 23 ++ .../src/routes/admin/analytics/+page.svelte | 8 +- .../web/src/routes/admin/billing/+page.svelte | 115 ++++++++-- apps/web/src/routes/attributes/+page.svelte | 15 +- apps/web/src/routes/categories/+page.svelte | 17 +- apps/web/src/routes/feeds/+page.svelte | 29 ++- docs/V18_CONTENT_CREDITS.md | 9 + docs/V19_PER_PRODUCT_PLAN_MODE.md | 20 ++ docs/V20_CREDIT_VALUE_AND_IMPORT_LANGUAGES.md | 65 ++++++ .../sestanek-dobavitelji-onboarding-sl.md | 121 ++++------- 41 files changed, 1311 insertions(+), 259 deletions(-) create mode 100644 README_SESTANEK_SL.md create mode 100644 README_V19.md create mode 100644 README_V20.md create mode 100644 apps/api/internal/billing/content_credits.go create mode 100644 apps/api/internal/billing/content_credits_test.go create mode 100644 apps/api/internal/catalog/import_language.go create mode 100644 apps/api/internal/catalog/import_language_test.go create mode 100644 apps/api/internal/feeds/sync_import_language_test.go create mode 100644 apps/api/internal/httpapi/catalog_import_language_test.go create mode 100644 apps/api/sql/schema/053_content_credit_rates.sql create mode 100644 apps/api/sql/schema/054_catalog_import_languages.sql create mode 100644 apps/web/src/lib/admin-plan-credit-costs.test.ts create mode 100644 apps/web/src/lib/components/products/per-product-plan.test.ts create mode 100644 docs/V18_CONTENT_CREDITS.md create mode 100644 docs/V19_PER_PRODUCT_PLAN_MODE.md create mode 100644 docs/V20_CREDIT_VALUE_AND_IMPORT_LANGUAGES.md diff --git a/README_SESTANEK_SL.md b/README_SESTANEK_SL.md new file mode 100644 index 0000000..6ac398d --- /dev/null +++ b/README_SESTANEK_SL.md @@ -0,0 +1,61 @@ +# JAGER × Descrybe – 30-minutni sestanek + +**Cilj:** na dejanskih izdelkih pokazati pot od dobaviteljevega vira do slovenskega naziva, opisa, SEO podatkov in izvoza. Na koncu potrdimo, ali je Descrybe za JAGER primeren, kaj potrebujejo in kakšna je ponudba. **Brez tehničnega razvoja po meri.** + +## Potek (30 minut) + +| Čas | Tema | Kaj naredimo | +|---|---|---| +| **0–5 min** | Potrebe | Vprašamo, koliko **različnih EAN-ov** imajo v katalogu in koliko **obdelav mesečno** (omenjenih ~1.000); koliko jezikov in kam bodo izvažali. | +| **5–15 min** | Živ prikaz | Odpremo **GROHE CSV** in **EMOS XML**, pokažemo preslikavo, kategorije/atribute ter izbor 5–10 njihovih EAN-ov. Če je pripravljen, pogledamo še **Sanotechnik JSON**. | +| **15–20 min** | AI | Obdelamo 1–2 izdelka: naslov, slovenski HTML opis in SEO meta. Pokažemo pregled, popravek in porabo kreditov. Prikaz izvedemo le s testnimi krediti. | +| **20–25 min** | Rezultat | Izvoz razpoložljivih polj v CSV/XML/JSON; pokažemo, kako lahko sami urejajo vir. | +| **25–30 min** | Dogovor | Povzamemo primeren paket, ceno začetne nastavitve in podatke, ki jih še potrebujemo; dogovorimo se za naslednji korak. | + +## Šest vprašanj, ki jih moramo dobiti odgovorjenih + +1. **Koliko aktivnih, unikatnih EAN-ov imate skupaj?** Je 1.000 število novih/ponovno AI-obdelanih izdelkov *na mesec* ali velikost celotnega kataloga? +2. **Kateri dobavitelji so prva prioriteta?** Predlagamo GROHE, EMOS in Sanotechnik. Ali imajo za KOOPMAN, TRBOVC in Groupe SEB dejanski CSV/XML/JSON? +3. **Katere podatke želite izboljšati?** Naslov, opis, SEO meta ali vse; kateri jezik oziroma jeziki? +4. **Kam se bo vsebina izvažala?** Potrebujemo vzorec formata in zahtevana polja (EAN, SKU, kategorija, atributi, slike, opisi …). +5. **Kdo bo upravljal vire in potrjeval vsebino?** Sami ali želite plačljivo začetno pomoč? +6. **Kdaj želite začeti?** Kdo odobri naročnino in enkratno nastavitev? + +## Kaj potrebujemo pred začetkom + +- Njihov **seznam EAN-ov v TXT/CSV** in 5–10 EAN-ov za demo. +- Povezave ali datoteke **CSV/XML/JSON** in dostopne podatke, če so potrebni. +- Želeni **jezik, izvozni format in primer pričakovanega rezultata**. +- Odgovorno kontaktno osebo za preverjanje rezultatov. + +## Kaj ponujamo in česa ne + +**Vključeno v aplikacijo:** uvoz in sinhronizacija podprtih strukturiranih virov; preslikava polj; kategorije in atributi iz razpoložljivih podatkov; AI nazivi/opisi/SEO; pregled rezultatov; izvoz CSV/XML/JSON in uporaba ustreznih energetskih podatkov, ko so preverljivo na voljo. + +**Ni del standardne storitve:** branje PDF katalogov; scraping spletnih strani; ročno prepisovanje produktov; razvoj prilagojenih ERP konektorjev; ustvarjanje manjkajočih slik, energetskih nalepk ali slovenskih dokumentov; jamstvo, da bodo podatki dobavitelja popolni. Pri KOOPMAN energijske podatke in slovenske listine preverimo pri dobavitelju/EPREL. + +## Ponudba (predlog, brez DDV) + +| Možnost | Enkratna cena | Kaj je vključeno | +|---|---:|---| +| **Samostojno** | **0 €** | Naročnik sam nastavi vire po navodilih; brez vključenih ur uvajanja. | +| **Prvi vir** | **199 €** | Do 1 strukturiranega vira, osnovna preslikava, test; do 30 min uvoda, približno 1–2 delovna dneva. | +| **3 dobavitelji – priporočeno za začetek** | **649 €** | Do 3 standardni viri, preslikave, osnovne kategorije/atributi, test in izvoz; do 1 h usposabljanja, približno 3–5 delovnih dni. | +| **Poslovni zagon** | **1.490 €** | Do 5 standardnih virov, uskladitev izvoznega profila; do 2 h usposabljanja, približno 5–10 delovnih dni. | +| **Večji standardni katalog** | **2.490 €** | Do 8 podprtih virov, več preslikav, QA; do 3 h usposabljanja, približno 2–3 tedne. | + +**Naročnina ločeno:** Growth **299 €/mes.** (do 1.200 SKU, 5 virov, 1.200 kreditov); Business **499 €/mes.** (do 4.000 SKU, 8 virov, 4.000 kreditov). Za ~1.000 izdelkov na mesec ne izberemo avtomatsko Business: potrebo določajo **aktivni SKU + število virov + konfigurirana poraba kreditov**. Pri standardnih treh operacijah je primer **0,10 + 0,25 + 0,10 = 0,45 kredita/izdelek**; pri posebnem paketu *Per product* velja njegova ročno nastavljena cena. Za 1.000 izdelkov je to pri 0,45 približno **450 kreditov**, če ni dodatnih obdelav ali jezikov. Pred ponudbo preverimo realno porabo in omogočene funkcije. Cene v EUR veljajo po potrditvi ustreznih cen v Stripe. + +**Podpora:** paketi vključujejo tehnično podporo skladno s cenikom, **ne** pa neomejenih ur nastavitev ali svetovanja. Ure v tabeli so enkratne. Ni dodatnih storitev brez dogovora. + +## Kratki odgovori in zaključek + +- **»Ali se lahko povežemo sami?«** Da, če dobavitelj zagotavlja ustrezen CSV, XML ali JSON in deluje z obstoječimi preslikavami. +- **»Zakaj GROHE še nima prevoda?«** Uvoz ni AI obdelava. Preverimo jezik, pravila in kreditno stanje ter na srečanju izvedemo test. +- **»Kaj pa PDF TRBOVC?«** PDF katalogov ne obdelujemo; dobavitelj mora dati strukturirane podatke. +- **»Ali lahko preizkusimo pred nakupom?«** Da, ponudimo kratek prikaz na 5–10 njihovih EAN-ih s posebej odobrenimi testnimi krediti. +- **»Kaj pa energijski listi?«** Uporabimo preverjene dobaviteljske/EPREL podatke; manjkajočih dokumentov ne izdelujemo. + +**Zaključni stavek:** »Predlagam, da najprej brezplačno preizkusimo nekaj vaših EAN-ov, skupaj pogledamo kakovost slovenskih opisov in izvoz. Če ste zadovoljni, vam nastavimo prve tri dobavitelje za 649 € in izberemo naročnino glede na dejansko velikost kataloga ter mesečno porabo.« + +**Po sestanku zapišemo:** potrjeni dobavitelji · EAN število · število obdelav · jeziki · zahtevana izvozna polja · odgovor odgovorne osebe · dogovorjeni naslednji korak. diff --git a/README_V19.md b/README_V19.md new file mode 100644 index 0000000..2bfc0eb --- /dev/null +++ b/README_V19.md @@ -0,0 +1,18 @@ +# Descrybe v19 — Per-product plan pricing + JAGER meeting + +## Changes + +- Admin > Billing > Create/Edit plan: **Processing mode** dropdown (`Choose outputs` or `Per product`). +- `Per product` sets a flat, decimal credit charge for one product process; it replaces the 3 output checkboxes in Product Management **only for companies assigned to such plans**. +- Per-output pricing remains the default for all existing plans. Legacy plans can opt in by editing them. +- The effective customer/company price is used for display, preflight balance checks, and actual debits, including public API processing. +- Updated concise 30-minute Slovenian JAGER meeting in `README_JAGER_SESTANEK_SL.md`, `README_SESTANEK_SL.md`, and `docs/client/`. +- Detailed acceptance checks: `docs/V19_PER_PRODUCT_PLAN_MODE.md`. + +## Deployment + +Commit this source to Git and run the existing deployment. Requires the previously applied migrations 049 and 053. No new migration is needed. Deploy frontend/API/worker together. + +## Verification + +Passed: isolated Go 1.23 test of the exact flat-rate debit function; 4 focused Node frontend tests; changed Go source formatting, Svelte script parsing, and Svelte control-flow balance checks. Full Go 1.25, Svelte production build, and live PostgreSQL/Stripe tests were not available in this environment. diff --git a/README_V20.md b/README_V20.md new file mode 100644 index 0000000..2624995 --- /dev/null +++ b/README_V20.md @@ -0,0 +1,8 @@ +# Descrybe v20 + +- Admin-editable EUR-per-credit **reference** value (kept separate from checkout/invoices). +- Per-language CSV/JSON catalog imports and XML/CSV/JSON feed-sync language selection. +- Catalog translation storage isolated by tenant, entity key and language. +- Database migration 054 required. + +See `docs/V20_CREDIT_VALUE_AND_IMPORT_LANGUAGES.md` for API request examples and safe deployment notes. diff --git a/apps/api/internal/billing/content_credits.go b/apps/api/internal/billing/content_credits.go new file mode 100644 index 0000000..860eca8 --- /dev/null +++ b/apps/api/internal/billing/content_credits.go @@ -0,0 +1,205 @@ +package billing + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" +) + +// Content credit rates use fixed four-decimal units (1 credit = 10,000 units). +// They are independent of provider token billing and cannot be rounded to an int. +const contentCreditScale int64 = 10000 + +var contentFeatures = map[string]string{ + "title": "title_ai", + "description": "description_ai", + "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. +func ContentDebitUnits(selected []string, processingType string, rates map[string]int64) (int64, error) { + if len(selected) == 0 { + switch processingType { + case "seo", "seo_meta", "seo_ai": + selected = []string{"seo_meta"} + case "title": + selected = []string{"title"} + case "description": + selected = []string{"description"} + default: + 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) + } + } + // 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 +} + +// ContentRates resolves company overrides > active plan overrides > global default. +// Postgres computes fixed-point integers, avoiding floating-point money arithmetic. +type contentRateQuerier interface { + Query(context.Context, string, ...any) (pgx.Rows, error) +} + +func (s *Service) ContentRates(ctx context.Context, companyID uuid.UUID) (map[string]int64, error) { + return contentRatesFrom(ctx, s.Pool, companyID) +} + +func contentRatesFrom(ctx context.Context, source contentRateQuerier, companyID uuid.UUID) (map[string]int64, error) { + rows, err := source.Query(ctx, ` + SELECT f.output, COALESCE( + (SELECT (cost_per_unit * 10000)::bigint FROM company_processing_costs + WHERE company_id=$1 AND feature_name=f.feature), + (SELECT (pc.cost_per_unit * 10000)::bigint FROM plan_processing_costs pc + JOIN company_plans cp ON cp.plan_id=pc.plan_id + WHERE cp.company_id=$1 AND cp.is_active=true AND pc.feature_name=f.feature + ORDER BY cp.created_at DESC LIMIT 1), + (SELECT (cost_per_unit * 10000)::bigint FROM processing_costs + WHERE feature_name=f.feature AND is_active=true), + f.fallback) + FROM (VALUES + ('title'::text,'title_ai'::text,1000::bigint), + ('description'::text,'description_ai'::text,2500::bigint), + ('seo_meta'::text,'seo_meta_ai'::text,1000::bigint) + ) AS f(output,feature,fallback) + UNION ALL + SELECT 'product'::text, COALESCE( + (SELECT (cc.cost_per_unit * 10000)::bigint FROM company_processing_costs cc + WHERE cc.company_id=$1 AND cc.feature_name='product_ai'), + (SELECT (pc.cost_per_unit * 10000)::bigint FROM plan_processing_costs pc + WHERE pc.plan_id=(SELECT cp.plan_id FROM company_plans cp + WHERE cp.company_id=$1 AND cp.is_active=true + ORDER BY cp.created_at DESC LIMIT 1) + AND pc.feature_name='product_ai')) + WHERE EXISTS ( + SELECT 1 FROM plan_processing_costs pc + WHERE pc.plan_id=(SELECT cp.plan_id FROM company_plans cp + WHERE cp.company_id=$1 AND cp.is_active=true + ORDER BY cp.created_at DESC LIMIT 1) + AND pc.feature_name='product_ai' + )`, companyID) + if err != nil { + return nil, err + } + defer rows.Close() + rates := make(map[string]int64, 3) + for rows.Next() { + var output string + var units int64 + if err := rows.Scan(&output, &units); err != nil { + return nil, err + } + rates[output] = units + } + if err := rows.Err(); err != nil { + return nil, err + } + for name := range contentFeatures { + if _, ok := rates[name]; !ok { + return nil, errors.New("incomplete content pricing rules") + } + } + return rates, nil +} + +// ConsumeContentCreditsTx atomically debits the fractional wallet and the current +// billing cycle in the caller's product transaction. It never overdraws credits. +func (s *Service) ConsumeContentCreditsTx(ctx context.Context, tx pgx.Tx, companyID uuid.UUID, selected []string, processingType string) (float64, error) { + 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) + if err != nil { + return 0, err + } + if units == 0 { + return 0, nil + } + // Lock credit_balances once. Both integer legacy debits and fractional debits + // account for this column when checking remaining capacity. + _, err = tx.Exec(ctx, `INSERT INTO credit_balances (company_id) VALUES ($1) ON CONFLICT DO NOTHING`, companyID) + if err != nil { + return 0, err + } + var allowed bool + err = tx.QueryRow(ctx, ` + UPDATE credit_balances SET fractional_credits_used=fractional_credits_used+($2::numeric/10000), updated_at=now() + WHERE company_id=$1 AND (total_credits-used_credits-fractional_credits_used)>=($2::numeric/10000) + RETURNING true`, companyID, units).Scan(&allowed) + if errors.Is(err, pgx.ErrNoRows) { + return 0, ErrInsufficientCredits + } + if err != nil { + return 0, err + } + tag, err := tx.Exec(ctx, ` + UPDATE billing_cycles SET fractional_credits_used=fractional_credits_used+($2::numeric/10000), + products_processed=products_processed+1, updated_at=now() + WHERE id=(SELECT id FROM billing_cycles WHERE company_id=$1 AND end_date>now() ORDER BY start_date DESC LIMIT 1)`, companyID, units) + if err != nil { + return 0, err + } + if tag.RowsAffected() == 0 { + var start, end time.Time + err = tx.QueryRow(ctx, `SELECT billing_cycle_start,next_billing_date FROM company_plans + WHERE company_id=$1 AND is_active=true ORDER BY created_at DESC LIMIT 1`, companyID).Scan(&start, &end) + if errors.Is(err, pgx.ErrNoRows) { + start = time.Now().UTC() + end = start.AddDate(0, 1, 0) + } else if err != nil { + return 0, err + } + _, err = tx.Exec(ctx, `INSERT INTO billing_cycles (company_id,start_date,end_date,credits_used,fractional_credits_used,products_processed) + VALUES ($1,$2,$3,0,$4::numeric/10000,1)`, companyID, start, end, units) + if err != nil { + return 0, err + } + } + return float64(units) / float64(contentCreditScale), nil +} diff --git a/apps/api/internal/billing/content_credits_test.go b/apps/api/internal/billing/content_credits_test.go new file mode 100644 index 0000000..a7ac76d --- /dev/null +++ b/apps/api/internal/billing/content_credits_test.go @@ -0,0 +1,38 @@ +package billing + +import "testing" + +func TestContentDebitUnits(t *testing.T) { + rates := map[string]int64{"title": 1000, "description": 2500, "seo_meta": 1000} + cases := []struct { + selected []string + 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}, + } + for _, tt := range cases { + got, err := ContentDebitUnits(tt.selected, tt.processingType, rates) + if err != nil || got != tt.want { + t.Errorf("%v/%s => %d, %v; expected %d", tt.selected, tt.processingType, got, err, tt.want) + } + } + if _, err := ContentDebitUnits([]string{"campaign_copy"}, "full", rates); err == nil { + t.Fatal("unknown type accepted") + } + 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 { + 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 { + t.Fatalf("zero cost %v %v", zero, err) + } +} diff --git a/apps/api/internal/billing/entitlements.go b/apps/api/internal/billing/entitlements.go index b9f9665..d6e5cf8 100644 --- a/apps/api/internal/billing/entitlements.go +++ b/apps/api/internal/billing/entitlements.go @@ -131,7 +131,7 @@ func ComputeEntitlements(planName string, monthlyCredits, remaining int, isTrial func (s *Service) EntitlementsForCompany(ctx context.Context, companyID uuid.UUID) (Entitlements, error) { var total, used int err := s.Pool.QueryRow(ctx, ` - SELECT total_credits, used_credits FROM credit_balances WHERE company_id = $1`, companyID). + SELECT total_credits, (total_credits - CEIL(GREATEST(0,total_credits-used_credits-fractional_credits_used)))::integer FROM credit_balances WHERE company_id = $1`, companyID). Scan(&total, &used) if errors.Is(err, pgx.ErrNoRows) { total, used = 0, 0 diff --git a/apps/api/internal/billing/service.go b/apps/api/internal/billing/service.go index 29aaf81..0a6a064 100644 --- a/apps/api/internal/billing/service.go +++ b/apps/api/internal/billing/service.go @@ -36,9 +36,9 @@ const featureGatesCacheTTL = 30 * time.Second type CreditsOverview struct { TotalCredits int `json:"total_credits"` - UsedCredits int `json:"used_credits"` - Remaining int `json:"remaining"` - RemainingCredits int `json:"remaining_credits"` + UsedCredits float64 `json:"used_credits"` + Remaining float64 `json:"remaining"` + RemainingCredits float64 `json:"remaining_credits"` LowCredits bool `json:"low_credits"` LowCreditsThreshold int `json:"low_credits_threshold"` ProductCount int `json:"product_count"` @@ -69,9 +69,10 @@ func (s *Service) CreditsOverview(ctx context.Context, companyID uuid.UUID, lowT lowThreshold = 100 } var total, used int + var fractional float64 err := s.Pool.QueryRow(ctx, ` - SELECT total_credits, used_credits FROM credit_balances WHERE company_id = $1`, companyID). - Scan(&total, &used) + SELECT total_credits, used_credits, fractional_credits_used::double precision FROM credit_balances WHERE company_id = $1`, companyID). + Scan(&total, &used, &fractional) if errors.Is(err, pgx.ErrNoRows) { _, _ = s.Pool.Exec(ctx, `INSERT INTO credit_balances (company_id) VALUES ($1) ON CONFLICT DO NOTHING`, companyID) total, used = 0, 0 @@ -79,10 +80,13 @@ func (s *Service) CreditsOverview(ctx context.Context, companyID uuid.UUID, lowT return CreditsOverview{}, err } - remaining := RemainingCreditsClamped(total, used) + remaining := float64(total-used) - fractional + if remaining < 0 { + remaining = 0 + } out := CreditsOverview{ TotalCredits: total, - UsedCredits: used, + UsedCredits: float64(used) + fractional, Remaining: remaining, RemainingCredits: remaining, LowCreditsThreshold: lowThreshold, @@ -157,7 +161,7 @@ func (s *Service) CreditsOverview(ctx context.Context, companyID uuid.UUID, lowT planName = "Free" featuresRaw = []byte("{}") } - ent := ComputeEntitlements(planName, monthlyVal, remaining, isTrial) + ent := ComputeEntitlements(planName, monthlyVal, int(remaining+0.9999), isTrial) out.CanUseAI = ent.CanUseAI out.CanUseEPREL = ent.CanUseEPREL out.IsFreePlan = ent.IsFreePlan @@ -214,6 +218,9 @@ func (s *Service) AIBrandApplyAllowed(ctx context.Context, companyID uuid.UUID) type ProcessingGateOpts struct { // RequiresAI when true enforces can_use_ai + credit wallet (AI-only job types). RequiresAI bool + // CreditsPerProduct is the effective per-output rate for this job. + // Zero retains legacy one-credit minimum for callers without content pricing. + CreditsPerProduct float64 // RequiresEPREL when true enforces can_use_eprel (EPREL-only job types). RequiresEPREL bool } @@ -239,9 +246,15 @@ func (s *Service) AssertCanStartProcessing(ctx context.Context, companyID uuid.U if ent.RemainingCredits < 1 { return fmt.Errorf("%w: no credits remaining — upgrade your plan to continue AI processing", ErrInsufficientCredits) } - if ent.RemainingCredits < batchSize { - return fmt.Errorf("%w: need at least %d credits for this batch (have %d) — upgrade or select fewer products", - ErrInsufficientCredits, batchSize, ent.RemainingCredits) + needed := float64(batchSize) + if opts.CreditsPerProduct > 0 { + needed *= opts.CreditsPerProduct + } + // The wallet debit uses precise fractional values and remains authoritative. + // The coarse entitlement is rounded up, so avoid rejecting a valid sub-credit job. + if float64(ent.RemainingCredits)+0.000001 < needed { + return fmt.Errorf("%w: need about %.2f credits for this batch (up to %d whole-credit units available)", + ErrInsufficientCredits, needed, ent.RemainingCredits) } } @@ -385,7 +398,7 @@ func (s *Service) applyCreditDebit(ctx context.Context, tx pgx.Tx, companyID uui WITH upd AS ( UPDATE credit_balances SET used_credits = used_credits + $2, updated_at = now() - WHERE company_id = $1 AND (total_credits - used_credits) >= $2 + WHERE company_id = $1 AND (total_credits - used_credits - fractional_credits_used) >= $2 RETURNING company_id ), cyc AS ( @@ -462,7 +475,7 @@ func (s *Service) lookupCost(ctx context.Context, feature string, fallback int) var cost int err := s.Pool.QueryRow(ctx, ` - SELECT cost_per_unit FROM processing_costs + SELECT cost_per_unit::integer FROM processing_costs WHERE feature_name = $1 AND is_active = true`, feature).Scan(&cost) if err != nil || cost <= 0 { return fallback @@ -884,7 +897,7 @@ func (s *Service) AssignPlan(ctx context.Context, companyID uuid.UUID, planID in _, err = tx.Exec(ctx, ` INSERT INTO credit_balances (company_id, total_credits, used_credits, updated_at) VALUES ($1, $2, 0, now()) - ON CONFLICT (company_id) DO UPDATE SET total_credits = EXCLUDED.total_credits, used_credits = 0, updated_at = now()`, + ON CONFLICT (company_id) DO UPDATE SET total_credits = EXCLUDED.total_credits, used_credits = 0, fractional_credits_used = 0, updated_at = now()`, companyID, alloc) if err != nil { return err @@ -931,9 +944,9 @@ type UsageDayPoint struct { type UsageSummary struct { CompanyID uuid.UUID `json:"company_id"` Range string `json:"range"` - CreditsUsed int `json:"credits_used"` + CreditsUsed float64 `json:"credits_used"` CreditsTotal int `json:"credits_total"` - CreditsRemaining int `json:"credits_remaining"` + CreditsRemaining float64 `json:"credits_remaining"` ProductsProcessed int `json:"products_processed"` ProductsTotal int `json:"products_total"` Tokens int64 `json:"tokens"` @@ -969,17 +982,21 @@ func (s *Service) UsageSummary(ctx context.Context, companyID uuid.UUID, rangeRa } var total, used int + var fractional float64 err := s.Pool.QueryRow(ctx, ` - SELECT total_credits, used_credits FROM credit_balances WHERE company_id = $1`, companyID). - Scan(&total, &used) + SELECT total_credits, used_credits, fractional_credits_used::double precision FROM credit_balances WHERE company_id = $1`, companyID). + Scan(&total, &used, &fractional) if errors.Is(err, pgx.ErrNoRows) { total, used = 0, 0 } else if err != nil { return out, err } out.CreditsTotal = total - out.CreditsUsed = used - out.CreditsRemaining = RemainingCreditsClamped(total, used) + out.CreditsUsed = float64(used) + fractional + out.CreditsRemaining = float64(total-used) - fractional + if out.CreditsRemaining < 0 { + out.CreditsRemaining = 0 + } out.Notes = append(out.Notes, "Credits are the live wallet (credit_balances). Daily credit history is not ledgered yet — range filters apply to products and tokens only.") @@ -1250,7 +1267,7 @@ func (s *Service) claimAndRollDueCompanyPlan(ctx context.Context, rowID int64) ( _, err = tx.Exec(ctx, ` INSERT INTO credit_balances (company_id, total_credits, used_credits, updated_at) VALUES ($1, $2, 0, now()) - ON CONFLICT (company_id) DO UPDATE SET total_credits = EXCLUDED.total_credits, used_credits = 0, updated_at = now()`, + ON CONFLICT (company_id) DO UPDATE SET total_credits = EXCLUDED.total_credits, used_credits = 0, fractional_credits_used = 0, updated_at = now()`, companyID, monthly) if err != nil { return false, err diff --git a/apps/api/internal/catalog/import_csv.go b/apps/api/internal/catalog/import_csv.go index daaca61..a55c06b 100644 --- a/apps/api/internal/catalog/import_csv.go +++ b/apps/api/internal/catalog/import_csv.go @@ -124,6 +124,7 @@ func (s *Service) flushCategoryBatch(ctx context.Context, companyID uuid.UUID, b if len(batch) == 0 { return nil } + lang, primary := s.importLanguage(ctx, companyID) byUID := make(map[string]categoryCSVRow, len(batch)) order := make([]string, 0, len(batch)) @@ -184,12 +185,15 @@ func (s *Service) flushCategoryBatch(ctx context.Context, companyID uuid.UUID, b if len(updIDs) > 0 { _, err = tx.Exec(ctx, ` UPDATE categories AS c SET - name = v.name, - description = CASE WHEN v.description <> '' THEN v.description ELSE c.description END, + name = CASE WHEN $5 THEN v.name ELSE c.name END, + description = CASE WHEN $5 AND v.description <> '' THEN v.description ELSE c.description END, + localized_fields = jsonb_set(COALESCE(c.localized_fields, '{}'::jsonb), ARRAY[$6::text], + COALESCE(c.localized_fields -> ($6::text), '{}'::jsonb) || + jsonb_strip_nulls(jsonb_build_object('name', NULLIF(v.name,''), 'description',NULLIF(v.description,''))), true), updated_at = now() FROM unnest($2::uuid[], $3::text[], $4::text[]) AS v(id, name, description) WHERE c.id = v.id AND c.company_id = $1`, - companyID, updIDs, updNames, updDescs) + companyID, updIDs, updNames, updDescs, primary, lang) if err != nil { return err } @@ -228,12 +232,13 @@ func (s *Service) flushCategoryBatch(ctx context.Context, companyID uuid.UUID, b } rows, err := tx.Query(ctx, ` - INSERT INTO categories (company_id, name, unique_id, parent_unique_id, description, path, level) - SELECT $1, v.name, v.unique_id, NULLIF(v.parent_unique_id, ''), NULLIF(v.description, ''), v.path, v.level + INSERT INTO categories (company_id, name, unique_id, parent_unique_id, description, path, level, localized_fields) + SELECT $1, v.name, v.unique_id, NULLIF(v.parent_unique_id, ''), NULLIF(v.description, ''), v.path, v.level, + jsonb_build_object($8::text, jsonb_strip_nulls(jsonb_build_object('name',v.name,'description',NULLIF(v.description,'')))) FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::int[]) AS v(name, unique_id, parent_unique_id, description, path, level) RETURNING id, unique_id, COALESCE(path, ''), level`, - companyID, insNames, insUIDs, insParents, insDescs, insPaths, insLevels) + companyID, insNames, insUIDs, insParents, insDescs, insPaths, insLevels, lang) if err != nil { return err } @@ -396,6 +401,7 @@ func (s *Service) flushAttributeBatch(ctx context.Context, companyID uuid.UUID, if len(batch) == 0 { return nil } + lang, primary := s.importLanguage(ctx, companyID) byKey := make(map[string]attributeCSVRow, len(batch)) order := make([]string, 0, len(batch)) @@ -465,12 +471,14 @@ func (s *Service) flushAttributeBatch(ctx context.Context, companyID uuid.UUID, if len(updIDs) > 0 { _, err = tx.Exec(ctx, ` UPDATE attributes AS a SET - name = CASE WHEN v.name <> '' THEN v.name ELSE a.name END, + name = CASE WHEN $5 AND v.name <> '' THEN v.name ELSE a.name END, value_type = CASE WHEN v.value_type <> '' THEN v.value_type ELSE a.value_type END, + localized_fields = jsonb_set(COALESCE(a.localized_fields,'{}'::jsonb), ARRAY[$6::text], + COALESCE(a.localized_fields -> ($6::text),'{}'::jsonb) || jsonb_build_object('name',v.name), true), updated_at = now() FROM unnest($2::uuid[], $3::text[], $4::text[]) AS v(id, name, value_type) WHERE a.id = v.id AND a.company_id = $1`, - companyID, updIDs, updNames, updTypes) + companyID, updIDs, updNames, updTypes, primary, lang) if err != nil { return err } @@ -479,12 +487,13 @@ func (s *Service) flushAttributeBatch(ctx context.Context, companyID uuid.UUID, if len(insKeys) > 0 { ct, err := tx.Exec(ctx, ` - INSERT INTO attributes (company_id, attribute_key, name, value_type, unit, example, parent_key) + INSERT INTO attributes (company_id, attribute_key, name, value_type, unit, example, parent_key, localized_fields) SELECT $1, v.attribute_key, v.name, v.value_type, - NULLIF(v.unit, ''), NULLIF(v.example, ''), NULLIF(v.parent_key, '') + NULLIF(v.unit, ''), NULLIF(v.example, ''), NULLIF(v.parent_key, ''), + jsonb_build_object($8::text, jsonb_build_object('name',v.name)) FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[]) AS v(attribute_key, name, value_type, unit, example, parent_key)`, - companyID, insKeys, insNames, insTypes, insUnits, insExamples, insParents) + companyID, insKeys, insNames, insTypes, insUnits, insExamples, insParents, lang) if err != nil { return err } @@ -508,6 +517,7 @@ type productCSVRow struct { func (s *Service) ImportProductsCSV(ctx context.Context, companyID uuid.UUID, r io.Reader, fileID *uuid.UUID) (ImportResult, error) { res := ImportResult{} + lang, primary := s.importLanguage(ctx, companyID) merge, err := s.MergeProductsByGTIN(ctx, companyID) if err != nil { return res, err @@ -566,7 +576,7 @@ func (s *Service) ImportProductsCSV(ctx context.Context, companyID uuid.UUID, r batch = append(batch, productCSVRow{ gtin: gtin, productID: productID, name: name, category: category, desc: desc, status: status, rawJSON: string(rawData), - mergeable: merge && !strings.HasPrefix(gtin, "nogtin-"), + mergeable: (merge || lang != primary) && !strings.HasPrefix(gtin, "nogtin-"), }) if len(batch) >= importCSVBatchSize { if err := s.flushProductBatch(ctx, companyID, fileID, batch, &res); err != nil { @@ -585,6 +595,7 @@ func (s *Service) flushProductBatch(ctx context.Context, companyID uuid.UUID, fi if len(batch) == 0 { return nil } + lang, primary := s.importLanguage(ctx, companyID) // Last row wins per GTIN so a single INSERT cannot hit the same unique key twice. byGTIN := make(map[string]productCSVRow, len(batch)) @@ -677,13 +688,15 @@ func (s *Service) flushProductBatch(ctx context.Context, companyID uuid.UUID, fi if len(updRawIDs) > 0 { _, err = tx.Exec(ctx, ` UPDATE raw_products AS r SET - raw_data = v.raw_data::jsonb, - mapped_data = v.raw_data::jsonb, + raw_data = CASE WHEN $6 THEN v.raw_data::jsonb ELSE r.raw_data END, + mapped_data = CASE WHEN $6 THEN v.raw_data::jsonb ELSE r.mapped_data END, + source_localizations = jsonb_set(COALESCE(r.source_localizations,'{}'::jsonb), ARRAY[$5::text], + COALESCE(r.source_localizations -> ($5::text),'{}'::jsonb) || v.raw_data::jsonb, true), file_id = COALESCE($3, r.file_id), updated_at = now() FROM unnest($2::uuid[], $4::text[]) AS v(id, raw_data) WHERE r.id = v.id AND r.company_id = $1`, - companyID, updRawIDs, fileID, updRawJSON) + companyID, updRawIDs, fileID, updRawJSON, lang, primary) if err != nil { return err } @@ -694,12 +707,13 @@ func (s *Service) flushProductBatch(ctx context.Context, companyID uuid.UUID, fi if len(insGTINs) > 0 { rows, err := tx.Query(ctx, ` - INSERT INTO raw_products (company_id, gtin, raw_data, mapped_data, processing_status, file_id) - SELECT $1, v.gtin, v.raw_data::jsonb, v.raw_data::jsonb, 'unprocessed', $2 + INSERT INTO raw_products (company_id, gtin, raw_data, mapped_data, processing_status, file_id, source_localizations) + SELECT $1, v.gtin, v.raw_data::jsonb, v.raw_data::jsonb, 'unprocessed', $2, + jsonb_build_object($5::text, v.raw_data::jsonb) FROM unnest($3::text[], $4::text[]) AS v(gtin, raw_data) ON CONFLICT (company_id, gtin) DO NOTHING RETURNING id, gtin`, - companyID, fileID, insGTINs, insJSON) + companyID, fileID, insGTINs, insJSON, lang) if err != nil { return err } @@ -803,15 +817,18 @@ func (s *Service) flushProductBatch(ctx context.Context, companyID uuid.UUID, fi _, err = tx.Exec(ctx, ` UPDATE processed_products AS p SET product_id = COALESCE(NULLIF(v.product_id, ''), p.product_id), - name = COALESCE(NULLIF(v.name, ''), p.name), - category = COALESCE(NULLIF(v.category, ''), p.category), - description = COALESCE(NULLIF(v.description, ''), p.description), - status = COALESCE(NULLIF(v.status, ''), p.status), + name = CASE WHEN $9 THEN COALESCE(NULLIF(v.name, ''), p.name) ELSE p.name END, + category = CASE WHEN $9 THEN COALESCE(NULLIF(v.category, ''), p.category) ELSE p.category END, + description = CASE WHEN $9 THEN COALESCE(NULLIF(v.description, ''), p.description) ELSE p.description END, + status = CASE WHEN $9 THEN COALESCE(NULLIF(v.status, ''), p.status) ELSE p.status END, + source_localizations = jsonb_set(COALESCE(p.source_localizations,'{}'::jsonb), ARRAY[$8::text], + COALESCE(p.source_localizations -> ($8::text),'{}'::jsonb) || jsonb_strip_nulls(jsonb_build_object( + 'name',NULLIF(v.name,''),'category',NULLIF(v.category,''),'description',NULLIF(v.description,''))),true), updated_at = now() FROM unnest($2::uuid[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[]) AS v(id, product_id, name, category, description, status) WHERE p.id = v.id AND p.company_id = $1`, - companyID, updProcIDs, updPIDs, updNames, updCats, updDescs, updStatuses) + companyID, updProcIDs, updPIDs, updNames, updCats, updDescs, updStatuses, lang, primary) if err != nil { return err } @@ -820,13 +837,15 @@ func (s *Service) flushProductBatch(ctx context.Context, companyID uuid.UUID, fi if len(insRawIDs) > 0 { _, err = tx.Exec(ctx, ` - INSERT INTO processed_products (company_id, product_id, name, category, description, status, raw_product_id) + INSERT INTO processed_products (company_id, product_id, name, category, description, status, raw_product_id, source_localizations) SELECT $1, NULLIF(v.product_id, ''), NULLIF(v.name, ''), NULLIF(v.category, ''), - NULLIF(v.description, ''), v.status, v.raw_product_id + NULLIF(v.description, ''), v.status, v.raw_product_id, + jsonb_build_object($8::text, jsonb_strip_nulls(jsonb_build_object( + 'name', NULLIF(v.name,''), 'category',NULLIF(v.category,''), 'description',NULLIF(v.description,'')))) FROM unnest($2::uuid[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[]) AS v(raw_product_id, product_id, name, category, description, status)`, - companyID, insRawIDs, insPIDs, insNames, insCats, insDescs, insStatuses) + companyID, insRawIDs, insPIDs, insNames, insCats, insDescs, insStatuses, lang) if err != nil { return err } diff --git a/apps/api/internal/catalog/import_language.go b/apps/api/internal/catalog/import_language.go new file mode 100644 index 0000000..06014cf --- /dev/null +++ b/apps/api/internal/catalog/import_language.go @@ -0,0 +1,56 @@ +package catalog + +import ( + "context" + "encoding/json" + + "github.com/descrybe/descrybe-v2/apps/api/internal/company" + "github.com/google/uuid" +) + +type importLanguageContextKey struct{} + +// WithImportLanguage marks the language of a supplier import. An empty code means +// the company primary language. The HTTP layer validates explicit codes. +func WithImportLanguage(ctx context.Context, lang string) context.Context { + return context.WithValue(ctx, importLanguageContextKey{}, lang) +} + +func (s *Service) importLanguage(ctx context.Context, companyID uuid.UUID) (string, bool) { + primary := company.LoadLanguage(ctx, s.Pool, companyID) + lang, _ := ctx.Value(importLanguageContextKey{}).(string) + if lang == "" { + lang = primary + } + return lang, lang == primary +} + +// localizeCatalogImportNames changes presentation only; it never overwrites +// the primary-language columns in storage. The full translations map remains +// present in API responses for clients that need several languages. +func localizeCatalogImportNames(ctx context.Context, items []map[string]any) { + lang, _ := ctx.Value(importLanguageContextKey{}).(string) + if lang == "" { + return + } + for _, item := range items { + var all map[string]map[string]string + switch raw := item["localized_fields"].(type) { + case []byte: + _ = json.Unmarshal(raw, &all) + case string: + _ = json.Unmarshal([]byte(raw), &all) + default: + b, _ := json.Marshal(raw) + _ = json.Unmarshal(b, &all) + } + if fields := all[lang]; fields != nil { + if val := fields["name"]; val != "" { + item["name"] = val + } + if val := fields["description"]; val != "" { + item["description"] = val + } + } + } +} diff --git a/apps/api/internal/catalog/import_language_test.go b/apps/api/internal/catalog/import_language_test.go new file mode 100644 index 0000000..c59669d --- /dev/null +++ b/apps/api/internal/catalog/import_language_test.go @@ -0,0 +1,24 @@ +package catalog + +import ( + "context" + "testing" +) + +func TestLocalizedImportViewPreservesPrimary(t *testing.T) { + rows := []map[string]any{{ + "name": "Shower mixer", "description": "Chrome mixer", + "localized_fields": map[string]any{ + "en": map[string]any{"name": "Shower mixer", "description": "Chrome mixer"}, + "sl": map[string]any{"name": "Armatura za prho", "description": "Kromirana armatura"}, + }, + }} + localizeCatalogImportNames(WithImportLanguage(context.Background(), "sl"), rows) + if rows[0]["name"] != "Armatura za prho" || rows[0]["description"] != "Kromirana armatura" { + t.Fatalf("wrong Slovenian fields: %+v", rows[0]) + } + localizeCatalogImportNames(WithImportLanguage(context.Background(), "en"), rows) + if rows[0]["name"] != "Shower mixer" { + t.Fatalf("English label not restored: %+v", rows[0]) + } +} diff --git a/apps/api/internal/catalog/service.go b/apps/api/internal/catalog/service.go index 41c3ae7..f035129 100644 --- a/apps/api/internal/catalog/service.go +++ b/apps/api/internal/catalog/service.go @@ -94,7 +94,7 @@ func (s *Service) ListCategories(ctx context.Context, companyID uuid.UUID, f Lis off := len(args) rows, err := s.Pool.Query(ctx, fmt.Sprintf(` SELECT id, name, unique_id, parent_unique_id, path, level, position, is_active, description, - title_template, description_template, + title_template, description_template, COALESCE(localized_fields,'{}'::jsonb) AS localized_fields, (title_template IS NOT NULL AND jsonb_typeof(title_template) = 'object' AND COALESCE(jsonb_array_length(title_template->'elements'), 0) > 0) AS has_title_formula, (description_template IS NOT NULL AND jsonb_typeof(description_template) = 'object' @@ -113,12 +113,13 @@ func (s *Service) ListCategories(ctx context.Context, companyID uuid.UUID, f Lis defer rows.Close() items, err := scanMaps(rows, []string{ "id", "name", "unique_id", "parent_unique_id", "path", "level", "position", "is_active", "description", - "title_template", "description_template", "has_title_formula", "has_description_formula", "has_prompt", + "title_template", "description_template", "localized_fields", "has_title_formula", "has_description_formula", "has_prompt", "created_at", "updated_at", }) if err != nil { return nil, 0, err } + localizeCatalogImportNames(ctx, items) if total, ok := exactTotalFromPage(f.Offset, f.Limit, len(items)); ok { return items, total, nil } @@ -186,15 +187,16 @@ func (s *Service) GetCategory(ctx context.Context, companyID, id uuid.UUID) (map SELECT 1 FROM jsonb_each_text(COALESCE(prompt, '{}'::jsonb)) kv WHERE length(trim(kv.value)) > 0 )) AS has_prompt, - title_template, description_template, created_at, updated_at + title_template, description_template, COALESCE(localized_fields,'{}'::jsonb), created_at, updated_at FROM categories WHERE id = $1 AND company_id = $2`, id, companyID) item, err := scanMap(row, []string{ "id", "name", "unique_id", "parent_unique_id", "path", "level", "position", "is_active", "description", - "prompts", "has_prompt", "title_template", "description_template", "created_at", "updated_at", + "prompts", "has_prompt", "title_template", "description_template", "localized_fields", "created_at", "updated_at", }) if err != nil { return nil, err } + localizeCatalogImportNames(ctx, []map[string]any{item}) return enrichCategoryPrompts(ctx, s.Pool, companyID, item) } @@ -377,8 +379,8 @@ func (s *Service) ListAttributes(ctx context.Context, companyID uuid.UUID, f Lis args := []any{companyID} where := []string{"a.company_id = $1"} from := "attributes a" - selectCols := "a.id, a.attribute_key, a.name, a.value_type, a.unit, a.example, a.parent_key, a.created_at, a.updated_at" - scanCols := []string{"id", "attribute_key", "name", "value_type", "unit", "example", "parent_key", "created_at", "updated_at"} + selectCols := "a.id, a.attribute_key, a.name, a.value_type, a.unit, a.example, a.parent_key, COALESCE(a.localized_fields,'{}'::jsonb), a.created_at, a.updated_at" + scanCols := []string{"id", "attribute_key", "name", "value_type", "unit", "example", "parent_key", "localized_fields", "created_at", "updated_at"} if f.Category != "" { from = `attributes a INNER JOIN category_attributes ca @@ -417,6 +419,7 @@ func (s *Service) ListAttributes(ctx context.Context, companyID uuid.UUID, f Lis if err != nil { return nil, 0, err } + localizeCatalogImportNames(ctx, items) if total, ok := exactTotalFromPage(f.Offset, f.Limit, len(items)); ok { return items, total, nil } @@ -1324,6 +1327,7 @@ func (s *Service) GetProcessedProduct(ctx context.Context, companyID, id uuid.UU `+processedHasProcessedAttributesSQL+` AS has_processed_attributes, `+processedHasEprelSQL+` AS has_eprel, COALESCE(p.localized_content, '{}'::jsonb) AS localized_content, + COALESCE(r.source_localizations, '{}'::jsonb) || COALESCE(p.source_localizations, '{}'::jsonb) AS source_localizations, p.created_at, p.updated_at FROM processed_products p LEFT JOIN raw_products r ON r.id = p.raw_product_id @@ -1338,7 +1342,7 @@ func (s *Service) GetProcessedProduct(ctx context.Context, companyID, id uuid.UU "feed_id", "feed_name", "feed_last_synced_at", "raw_updated_at", "has_processed_name", "has_processed_description", "has_attributes", "has_processed_attributes", "has_eprel", - "localized_content", + "localized_content", "source_localizations", "created_at", "updated_at", }) if err != nil { @@ -1384,6 +1388,7 @@ func (s *Service) GetRawProduct(ctx context.Context, companyID, id uuid.UUID) (m false AS has_processed_attributes, `+strings.ReplaceAll(processedHasEprelSQL, "r.mapped_data", "rp.mapped_data")+` AS has_eprel, '{}'::jsonb AS localized_content, + COALESCE(rp.source_localizations, '{}'::jsonb) AS source_localizations, rp.created_at, rp.updated_at, (COALESCE(NULLIF(trim(rp.mapped_data->>'name'), ''), NULLIF(trim(rp.mapped_data->>'title'), ''), '') <> '') AS has_name, (COALESCE(NULLIF(trim(rp.mapped_data->>'description'), ''), '') <> '') AS has_description, @@ -1399,7 +1404,7 @@ func (s *Service) GetRawProduct(ctx context.Context, companyID, id uuid.UUID) (m "feed_id", "feed_name", "feed_last_synced_at", "raw_updated_at", "has_processed_name", "has_processed_description", "has_attributes", "has_processed_attributes", "has_eprel", - "localized_content", + "localized_content", "source_localizations", "created_at", "updated_at", "has_name", "has_description", "has_category", "is_processed", "processing_status", diff --git a/apps/api/internal/feeds/service.go b/apps/api/internal/feeds/service.go index 34a00bc..84371cc 100644 --- a/apps/api/internal/feeds/service.go +++ b/apps/api/internal/feeds/service.go @@ -29,6 +29,7 @@ type CreateInput struct { SyncFrequencyHours int // legacy alias; converted to minutes when SyncIntervalMinutes unset Options map[string]any RequestHeaders map[string]string + ContentLanguage string } func (s *Service) List(ctx context.Context, companyID uuid.UUID, limit, offset int, q string) ([]map[string]any, int64, int64, int64, error) { @@ -121,6 +122,9 @@ func (s *Service) Create(ctx context.Context, companyID uuid.UUID, in CreateInpu if opts == nil { opts = map[string]any{} } + if in.ContentLanguage != "" { + opts["content_language"] = in.ContentLanguage + } if len(in.RequestHeaders) > 0 { encrypted, err := encryptFeedHeaders(in.RequestHeaders) if err != nil { @@ -336,6 +340,10 @@ func (s *Service) Update(ctx context.Context, companyID, id uuid.UUID, body map[ } } + contentLanguage := "" + if raw, ok := body["content_language"].(string); ok { + contentLanguage = strings.ToLower(strings.TrimSpace(raw)) + } var encryptedHeaders *string if rawHeaders, exists := body["request_headers"]; exists { headers := map[string]string{} @@ -364,10 +372,10 @@ func (s *Service) Update(ctx context.Context, companyID, id uuid.UUID, body map[ (CASE WHEN $8 <> '' THEN COALESCE(options, '{}'::jsonb) || jsonb_build_object('item_path', to_jsonb($8::text)) ELSE COALESCE(options, '{}'::jsonb) END) - 'request_headers_encrypted' ELSE (CASE WHEN $8 <> '' THEN COALESCE(options, '{}'::jsonb) || jsonb_build_object('item_path', to_jsonb($8::text)) ELSE COALESCE(options, '{}'::jsonb) END) || jsonb_build_object('request_headers_encrypted', $9::text) - END, + END || CASE WHEN $10::text <> '' THEN jsonb_build_object('content_language', $10::text) ELSE '{}'::jsonb END, updated_at = now() WHERE id = $1 AND company_id = $2`, - id, companyID, name, url, status, feedType, interval, strings.TrimSpace(itemPath), encryptedHeaders) + id, companyID, name, url, status, feedType, interval, strings.TrimSpace(itemPath), encryptedHeaders, contentLanguage) if err != nil { return nil, err } diff --git a/apps/api/internal/feeds/sync.go b/apps/api/internal/feeds/sync.go index 904bec0..5dd3961 100644 --- a/apps/api/internal/feeds/sync.go +++ b/apps/api/internal/feeds/sync.go @@ -11,6 +11,7 @@ import ( "strconv" "strings" + "github.com/descrybe/descrybe-v2/apps/api/internal/company" "github.com/google/uuid" "github.com/jackc/pgx/v5" ) @@ -268,6 +269,14 @@ func (s *Service) ListSyncJobs(ctx context.Context, companyID, feedID uuid.UUID, func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUID, feed map[string]any) (syncStats, error) { var stats syncStats + primaryLanguage := company.LoadLanguage(ctx, s.Pool, companyID) + feedLanguage := primaryLanguage + if opts, ok := feed["options"].(map[string]any); ok { + if code, ok := opts["content_language"].(string); ok && company.IsAllowedLanguage(code) { + feedLanguage = company.NormalizeLanguage(code) + } + } + ctx = context.WithValue(ctx, syncLocaleKey{}, syncLocale{code: feedLanguage, primary: feedLanguage == primaryLanguage}) urlStr, _ := feed["url"].(string) feedType, _ := feed["feed_type"].(string) @@ -291,7 +300,7 @@ func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUI if len(mappings) == 0 { return stats, ClientMsg("no field mappings defined for feed") } - stats.MappingHash = sha256Hex([]byte(mustJSON(mappingsRaw))) + stats.MappingHash = sha256Hex([]byte(mustJSON(mappingsRaw) + "|language=" + feedLanguage)) prev, err := s.lastSuccessfulSync(ctx, feedID) if err != nil { @@ -439,9 +448,16 @@ func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUI return stats, nil } +type syncLocaleKey struct{} +type syncLocale struct { + code string + primary bool +} + type existingProduct struct { - ID uuid.UUID - MappedData []byte + ID uuid.UUID + MappedData []byte + SourceLocalizations []byte } const ( @@ -450,17 +466,19 @@ const ( upsertSQLInsertSet = ` INSERT INTO raw_products ( company_id, gtin, feed_id, raw_data, mapped_data, sync_job_id, - is_processed, processing_status, updated_at + is_processed, processing_status, updated_at, source_localizations ) - SELECT $1, v.gtin, $2, v.raw_data::jsonb, v.mapped_data::jsonb, $3, false, 'unprocessed', now() + SELECT $1, v.gtin, $2, v.raw_data::jsonb, v.mapped_data::jsonb, $3, false, 'unprocessed', now(), + jsonb_build_object($7::text, v.mapped_data::jsonb) FROM unnest($4::text[], $5::text[], $6::text[]) AS v(gtin, raw_data, mapped_data) ON CONFLICT (company_id, gtin) DO UPDATE SET feed_id = EXCLUDED.feed_id, - raw_data = EXCLUDED.raw_data, - mapped_data = EXCLUDED.mapped_data, + raw_data = CASE WHEN $8 THEN EXCLUDED.raw_data ELSE raw_products.raw_data END, + mapped_data = CASE WHEN $8 THEN EXCLUDED.mapped_data ELSE raw_products.mapped_data END, + source_localizations = jsonb_set(COALESCE(raw_products.source_localizations,'{}'::jsonb),ARRAY[$7::text],EXCLUDED.mapped_data,true), sync_job_id = EXCLUDED.sync_job_id, - is_processed = false, - processing_status = 'unprocessed', + is_processed = CASE WHEN $8 THEN false ELSE raw_products.is_processed END, + processing_status = CASE WHEN $8 THEN 'unprocessed' ELSE raw_products.processing_status END, updated_at = now()` upsertSQLTouchSet = ` UPDATE raw_products SET sync_job_id = $3, feed_id = $4, updated_at = now() @@ -468,11 +486,12 @@ const ( upsertSQLUpdateSet = ` UPDATE raw_products AS r SET feed_id = $2, - raw_data = v.raw_data::jsonb, - mapped_data = v.mapped_data::jsonb, + raw_data = CASE WHEN $8 THEN v.raw_data::jsonb ELSE r.raw_data END, + mapped_data = CASE WHEN $8 THEN v.mapped_data::jsonb ELSE r.mapped_data END, + source_localizations = jsonb_set(COALESCE(r.source_localizations,'{}'::jsonb),ARRAY[$7::text],v.mapped_data::jsonb,true), sync_job_id = $3, - is_processed = false, - processing_status = 'unprocessed', + is_processed = CASE WHEN $8 THEN false ELSE r.is_processed END, + processing_status = CASE WHEN $8 THEN 'unprocessed' ELSE r.processing_status END, updated_at = now() FROM unnest($4::uuid[], $5::text[], $6::text[]) AS v(id, raw_data, mapped_data) WHERE r.id = v.id AND r.company_id = $1` @@ -499,7 +518,7 @@ type upsertOp struct { // can be applied with set-based UNNEST statements (≤3) in one pgx.Batch round-trip. // Touch keeps is_processed/processing_status when mapped_data is equal (canonical JSON). // Updates/inserts stamp mapped_data._sync_changes for seller filters (price/stock/…). -func classifyUpsertOps(chunk []pendingProduct, existing map[string]existingProduct) (ops []upsertOp, skipped int) { +func classifyUpsertOps(chunk []pendingProduct, existing map[string]existingProduct, locale ...syncLocale) (ops []upsertOp, skipped int) { ops = make([]upsertOp, 0, len(chunk)) for _, p := range chunk { rawJSON, err := json.Marshal(p.RawData) @@ -523,17 +542,28 @@ func classifyUpsertOps(chunk []pendingProduct, existing map[string]existingProdu continue } // Category (and similar extras) live outside feed mappings — keep them. - cleanMapped = preserveSyncedExtras(ex.MappedData, cleanMapped) + existingMapped := ex.MappedData + if len(locale) > 0 && !locale[0].primary { + var all map[string]json.RawMessage + if json.Unmarshal(ex.SourceLocalizations, &all) == nil { + if val, exists := all[locale[0].code]; exists { + existingMapped = val + } else { + existingMapped = nil + } + } + } + cleanMapped = preserveSyncedExtras(existingMapped, cleanMapped) plainJSON, err := json.Marshal(cleanMapped) if err != nil { skipped++ continue } - if bytesEqualJSON(stripSyncChangesBytes(ex.MappedData), plainJSON) { + if bytesEqualJSON(stripSyncChangesBytes(existingMapped), plainJSON) { ops = append(ops, upsertOp{kind: upsertOpTouch, id: ex.ID}) continue } - changes := detectMappedChanges(ex.MappedData, cleanMapped) + changes := detectMappedChanges(existingMapped, cleanMapped) withFlags := withSyncChanges(cleanMapped, changes) mappedJSON, err := json.Marshal(withFlags) if err != nil { @@ -615,7 +645,11 @@ func (s *Service) upsertChunk(ctx context.Context, companyID, feedID, jobID uuid return 0, 0, 0, deltas, err } - ops, skipped := classifyUpsertOps(chunk, existing) + locale, ok := ctx.Value(syncLocaleKey{}).(syncLocale) + if !ok { + locale = syncLocale{code: company.LoadLanguage(ctx, s.Pool, companyID), primary: true} + } + ops, skipped := classifyUpsertOps(chunk, existing, locale) if len(ops) == 0 { deltas.Skipped = skipped return 0, 0, skipped, deltas, nil @@ -634,7 +668,7 @@ func (s *Service) upsertChunk(ctx context.Context, companyID, feedID, jobID uuid mappedCol[i] = string(op.mappedJSON) deltas.addChanges(op.changes) } - batch.Queue(upsertSQLInsertSet, companyID, feedID, jobID, gtinCol, rawCol, mappedCol) + batch.Queue(upsertSQLInsertSet, companyID, feedID, jobID, gtinCol, rawCol, mappedCol, locale.code, locale.primary) queued++ } if len(touches) > 0 { @@ -655,7 +689,7 @@ func (s *Service) upsertChunk(ctx context.Context, companyID, feedID, jobID uuid mappedCol[i] = string(op.mappedJSON) deltas.addChanges(op.changes) } - batch.Queue(upsertSQLUpdateSet, companyID, feedID, jobID, ids, rawCol, mappedCol) + batch.Queue(upsertSQLUpdateSet, companyID, feedID, jobID, ids, rawCol, mappedCol, locale.code, locale.primary) queued++ } @@ -669,7 +703,7 @@ func (s *Service) upsertChunk(ctx context.Context, companyID, feedID, jobID uuid // Content inserts/updates stamp raw as unprocessed — drop catalog rows so // processed_products cannot outlive that reset (matches resetRawProducts). // Touches keep processing_status and must not invalidate catalog. - if len(inserts) > 0 || len(updates) > 0 { + if (len(inserts) > 0 || len(updates) > 0) && locale.primary { invalidateIDs := make([]uuid.UUID, 0, len(updates)) for _, op := range updates { invalidateIDs = append(invalidateIDs, op.id) @@ -704,7 +738,7 @@ func (s *Service) loadExistingByGTIN(ctx context.Context, companyID uuid.UUID, g return out, nil } rows, err := s.Pool.Query(ctx, ` - SELECT id, gtin, mapped_data FROM raw_products + SELECT id, gtin, mapped_data, COALESCE(source_localizations,'{}'::jsonb) FROM raw_products WHERE company_id = $1 AND gtin = ANY($2::text[])`, companyID, gtins) if err != nil { return nil, err @@ -713,7 +747,7 @@ func (s *Service) loadExistingByGTIN(ctx context.Context, companyID uuid.UUID, g for rows.Next() { var ex existingProduct var gtin string - if err := rows.Scan(&ex.ID, >in, &ex.MappedData); err != nil { + if err := rows.Scan(&ex.ID, >in, &ex.MappedData, &ex.SourceLocalizations); err != nil { return nil, err } out[gtin] = ex diff --git a/apps/api/internal/feeds/sync_import_language_test.go b/apps/api/internal/feeds/sync_import_language_test.go new file mode 100644 index 0000000..8658e11 --- /dev/null +++ b/apps/api/internal/feeds/sync_import_language_test.go @@ -0,0 +1,25 @@ +package feeds + +import ( + "github.com/google/uuid" + "testing" +) + +func TestFeedLocaleSameProductIndependentMappings(t *testing.T) { + id := uuid.MustParse("12345678-1234-1234-1234-123456789abc") + old := map[string]existingProduct{"100": { + ID: id, + MappedData: []byte(`{"name":"English name"}`), + SourceLocalizations: []byte(`{"en":{"name":"English name"},"sl":{"name":"Slovensko ime"}}`), + }} + same := []pendingProduct{{GTIN: "100", RawData: map[string]string{"EAN": "100"}, MappedData: map[string]any{"name": "Slovensko ime"}}} + ops, skip := classifyUpsertOps(same, old, syncLocale{code: "sl", primary: false}) + if skip != 0 || len(ops) != 1 || ops[0].kind != upsertOpTouch { + t.Fatalf("unchanged localized product should be touched, got %+v, skipped %d", ops, skip) + } + changed := []pendingProduct{{GTIN: "100", RawData: map[string]string{"EAN": "100"}, MappedData: map[string]any{"name": "Novejše ime"}}} + ops, skip = classifyUpsertOps(changed, old, syncLocale{code: "sl", primary: false}) + if skip != 0 || len(ops) != 1 || ops[0].kind != upsertOpUpdate { + t.Fatalf("changed localized product should update, got %+v, skipped %d", ops, skip) + } +} diff --git a/apps/api/internal/httpapi/admin_processing_costs_handlers.go b/apps/api/internal/httpapi/admin_processing_costs_handlers.go index 857bb12..cae099b 100644 --- a/apps/api/internal/httpapi/admin_processing_costs_handlers.go +++ b/apps/api/internal/httpapi/admin_processing_costs_handlers.go @@ -1,6 +1,7 @@ package httpapi import ( + "math" "net/http" "strconv" "strings" @@ -9,19 +10,19 @@ import ( ) var editableCostFeatures = map[string]bool{ - "product_processing": true, - "openai_token_k": true, - "seo_meta_ai": true, - "campaign_copy": true, + "title_ai": true, + "description_ai": true, + "seo_meta_ai": true, + "product_ai": true, // presence of a plan rule enables per-product pricing } func (s *Server) handleAdminGetProcessingCosts(w http.ResponseWriter, r *http.Request) { rows, err := s.Pool.Query(r.Context(), ` - SELECT 'default', '', feature_name, cost_per_unit FROM processing_costs WHERE is_active = true + SELECT 'default', '', feature_name, cost_per_unit FROM processing_costs WHERE is_active = true AND feature_name IN ('title_ai','description_ai','seo_meta_ai','product_ai') UNION ALL - SELECT 'plan', plan_id::text, feature_name, cost_per_unit FROM plan_processing_costs + SELECT 'plan', plan_id::text, feature_name, cost_per_unit FROM plan_processing_costs WHERE feature_name IN ('title_ai','description_ai','seo_meta_ai','product_ai') UNION ALL - SELECT 'company', company_id::text, feature_name, cost_per_unit FROM company_processing_costs + SELECT 'company', company_id::text, feature_name, cost_per_unit FROM company_processing_costs WHERE feature_name IN ('title_ai','description_ai','seo_meta_ai','product_ai') ORDER BY 1, 2, 3`) if err != nil { LogAndError(w, http.StatusInternalServerError, "could not load processing costs", err) @@ -31,7 +32,7 @@ func (s *Server) handleAdminGetProcessingCosts(w http.ResponseWriter, r *http.Re out := make([]map[string]any, 0, 16) for rows.Next() { var scope, id, feature string - var cost int + var cost float64 if err := rows.Scan(&scope, &id, &feature, &cost); err != nil { LogAndError(w, http.StatusInternalServerError, "could not scan processing costs", err) return @@ -48,10 +49,10 @@ func (s *Server) handleAdminGetProcessingCosts(w http.ResponseWriter, r *http.Re func (s *Server) handleAdminPutProcessingCost(w http.ResponseWriter, r *http.Request) { var body struct { - Scope string `json:"scope"` - ID string `json:"id"` - Feature string `json:"feature"` - Cost *int `json:"cost_per_unit"` // null removes an override; cannot remove global rule + Scope string `json:"scope"` + ID string `json:"id"` + Feature string `json:"feature"` + Cost *float64 `json:"cost_per_unit"` // null removes an override; cannot remove global rule } if err := DecodeJSON(r, &body); err != nil { Error(w, http.StatusBadRequest, "invalid json") @@ -59,7 +60,7 @@ func (s *Server) handleAdminPutProcessingCost(w http.ResponseWriter, r *http.Req } body.Scope = strings.TrimSpace(strings.ToLower(body.Scope)) body.Feature = strings.TrimSpace(body.Feature) - if !editableCostFeatures[body.Feature] || (body.Cost != nil && (*body.Cost < 1 || *body.Cost > 1000000)) { + if !editableCostFeatures[body.Feature] || (body.Cost != nil && (math.IsNaN(*body.Cost) || math.IsInf(*body.Cost, 0) || *body.Cost < 0 || *body.Cost > 1000000 || math.Abs(*body.Cost*10000-math.Round(*body.Cost*10000)) > 0.000001)) { Error(w, http.StatusBadRequest, "invalid feature or credit cost") return } @@ -101,3 +102,78 @@ func (s *Server) handleAdminPutProcessingCost(w http.ResponseWriter, r *http.Req w.Header().Set("Cache-Control", "private, no-store") JSON(w, http.StatusOK, map[string]any{"status": "ok"}) } + +// handleCompanyContentCosts returns effective plan/company rates to the dashboard. +// Never disclose other companies' pricing overrides. +func (s *Server) handleCompanyContentCosts(w http.ResponseWriter, r *http.Request) { + cid, ok := CompanyIDFromContext(r.Context()) + if !ok || cid == uuid.Nil { + 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" + } + w.Header().Set("Cache-Control", "private, no-store") + JSON(w, http.StatusOK, map[string]any{"mode": mode, "credits": out}) +} + +// Monetary credit valuation is an admin reference rate. Stripe invoices, pack +// checkout prices and historic wallet ledger values are not changed by it. +const creditValueEURSetting = "billing.reference_eur_per_credit" + +func (s *Server) handleAdminCreditValueEUR(w http.ResponseWriter, r *http.Request) { + if s.PlatformSettings == nil { + Error(w, http.StatusServiceUnavailable, "platform settings unavailable") + return + } + if r.Method == http.MethodGet { + saved, ok, err := s.PlatformSettings.GetKV(r.Context(), creditValueEURSetting) + if err != nil { + LogAndError(w, http.StatusInternalServerError, "unable to load credit valuation", err) + return + } + var amount any + if ok && strings.TrimSpace(saved) != "" { + parsed, err := strconv.ParseFloat(saved, 64) + if err != nil { + LogAndError(w, http.StatusInternalServerError, "invalid stored credit valuation", err) + return + } + amount = parsed + } + w.Header().Set("Cache-Control", "private, no-store") + JSON(w, http.StatusOK, map[string]any{"eur_per_credit": amount, "currency": "EUR", "note": "Reference valuation only; actual customer charges follow Stripe invoices and purchased credit pack prices."}) + return + } + if r.Method != http.MethodPut { + Error(w, http.StatusMethodNotAllowed, "method not allowed") + return + } + var body struct { + Value *float64 `json:"eur_per_credit"` + } + if err := DecodeJSON(r, &body); err != nil { + Error(w, http.StatusBadRequest, "invalid json") + return + } + if body.Value == nil || math.IsNaN(*body.Value) || math.IsInf(*body.Value, 0) || *body.Value < 0 || *body.Value > 10000 || math.Abs(*body.Value*1000000-math.Round(*body.Value*1000000)) > 0.000001 { + Error(w, http.StatusBadRequest, "EUR per credit must be between 0 and 10000 with up to six decimals") + return + } + if err := s.PlatformSettings.SetKV(r.Context(), creditValueEURSetting, strconv.FormatFloat(*body.Value, 'f', -1, 64)); err != nil { + LogAndError(w, http.StatusInternalServerError, "unable to save credit valuation", err) + return + } + JSON(w, http.StatusOK, map[string]any{"status": "ok", "eur_per_credit": *body.Value}) +} diff --git a/apps/api/internal/httpapi/billing_usage_export_handlers.go b/apps/api/internal/httpapi/billing_usage_export_handlers.go index 24ce035..2fcd15f 100644 --- a/apps/api/internal/httpapi/billing_usage_export_handlers.go +++ b/apps/api/internal/httpapi/billing_usage_export_handlers.go @@ -27,19 +27,19 @@ func (s *Server) handleBillingUsageExport(w http.ResponseWriter, r *http.Request _ = out.Write([]string{"company_id", "range", "metric", "value", "notes"}) rows := []struct { label string - value int64 + value float64 notes string }{ - {"ai_calls", usage.AICalls, "Recorded provider calls in period"}, - {"input_tokens", usage.InputTokens, "Includes cached input"}, - {"cached_input_tokens", usage.CachedInputTokens, "Subset of input"}, - {"output_tokens", usage.OutputTokens, ""}, - {"products_processed", int64(usage.ProductsProcessed), "Period"}, - {"credits_used_wallet", int64(usage.CreditsUsed), "All-time wallet balance, not period credits"}, - {"credits_remaining", int64(usage.CreditsRemaining), "Current wallet"}, + {"ai_calls", float64(usage.AICalls), "Recorded provider calls in period"}, + {"input_tokens", float64(usage.InputTokens), "Includes cached input"}, + {"cached_input_tokens", float64(usage.CachedInputTokens), "Subset of input"}, + {"output_tokens", float64(usage.OutputTokens), ""}, + {"products_processed", float64(usage.ProductsProcessed), "Period"}, + {"credits_used_wallet", usage.CreditsUsed, "All-time wallet balance, not period credits"}, + {"credits_remaining", usage.CreditsRemaining, "Current wallet"}, } for _, v := range rows { - _ = out.Write([]string{cid.String(), usage.Range, v.label, strconv.FormatInt(v.value, 10), v.notes}) + _ = out.Write([]string{cid.String(), usage.Range, v.label, strconv.FormatFloat(v.value, 'f', -1, 64), v.notes}) } out.Flush() } diff --git a/apps/api/internal/httpapi/catalog_handlers.go b/apps/api/internal/httpapi/catalog_handlers.go index 611636d..d688380 100644 --- a/apps/api/internal/httpapi/catalog_handlers.go +++ b/apps/api/internal/httpapi/catalog_handlers.go @@ -15,6 +15,15 @@ import ( func (s *Server) handleListCategories(w http.ResponseWriter, r *http.Request) { cid, _ := CompanyIDFromContext(r.Context()) + ctx := r.Context() + if lang := strings.TrimSpace(r.URL.Query().Get("language")); lang != "" { + parsed, err := company.ParseLanguage(lang, false) + if err != nil { + Error(w, http.StatusBadRequest, "unsupported language") + return + } + ctx = catalog.WithImportLanguage(ctx, parsed) + } max := maxPageLimit if r.URL.Query().Get("tree") == "1" { max = maxTreePageLimit @@ -25,7 +34,7 @@ func (s *Server) handleListCategories(w http.ResponseWriter, r *http.Request) { Limit: limit, Offset: offset, } - items, total, err := s.Catalog.ListCategories(r.Context(), cid, f) + items, total, err := s.Catalog.ListCategories(ctx, cid, f) if err != nil { Error(w, http.StatusInternalServerError, "list failed") return @@ -55,12 +64,21 @@ func (s *Server) handleCreateCategory(w http.ResponseWriter, r *http.Request) { func (s *Server) handleGetCategory(w http.ResponseWriter, r *http.Request) { cid, _ := CompanyIDFromContext(r.Context()) + ctx := r.Context() + if lang := strings.TrimSpace(r.URL.Query().Get("language")); lang != "" { + parsed, err := company.ParseLanguage(lang, false) + if err != nil { + Error(w, http.StatusBadRequest, "unsupported language") + return + } + ctx = catalog.WithImportLanguage(ctx, parsed) + } id, err := uuid.Parse(chi.URLParam(r, "id")) if err != nil { Error(w, http.StatusBadRequest, "invalid id") return } - item, err := s.Catalog.GetCategory(r.Context(), cid, id) + item, err := s.Catalog.GetCategory(ctx, cid, id) if err != nil { Error(w, http.StatusNotFound, "not found") return @@ -256,6 +274,15 @@ func (s *Server) handleDeleteVariable(w http.ResponseWriter, r *http.Request) { func (s *Server) handleListAttributes(w http.ResponseWriter, r *http.Request) { cid, _ := CompanyIDFromContext(r.Context()) + ctx := r.Context() + if lang := strings.TrimSpace(r.URL.Query().Get("language")); lang != "" { + parsed, err := company.ParseLanguage(lang, false) + if err != nil { + Error(w, http.StatusBadRequest, "unsupported language") + return + } + ctx = catalog.WithImportLanguage(ctx, parsed) + } limit, offset := ParseLimitOffset(r) f := catalog.ListFilter{ Query: QuerySearch(r), @@ -264,7 +291,7 @@ func (s *Server) handleListAttributes(w http.ResponseWriter, r *http.Request) { RootsOnly: r.URL.Query().Get("roots") == "1", ParentKey: r.URL.Query().Get("parent_key"), } - items, total, err := s.Catalog.ListAttributes(r.Context(), cid, f) + items, total, err := s.Catalog.ListAttributes(ctx, cid, f) if err != nil { Error(w, http.StatusInternalServerError, "list failed") return diff --git a/apps/api/internal/httpapi/catalog_import_handlers.go b/apps/api/internal/httpapi/catalog_import_handlers.go index e946e6c..73bfb13 100644 --- a/apps/api/internal/httpapi/catalog_import_handlers.go +++ b/apps/api/internal/httpapi/catalog_import_handlers.go @@ -2,6 +2,7 @@ package httpapi import ( "encoding/json" + "github.com/descrybe/descrybe-v2/apps/api/internal/company" "github.com/descrybe/descrybe-v2/apps/api/internal/feeds" "io" "net/http" @@ -200,6 +201,7 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) { URL string `json:"url"` RequestHeaders map[string]string `json:"request_headers"` Format string `json:"format"` + Language string `json:"language"` } if err := json.NewDecoder(io.LimitReader(r.Body, 64<<10)).Decode(&req); err != nil { Error(w, http.StatusBadRequest, "invalid JSON request") @@ -209,6 +211,12 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) { Error(w, http.StatusBadRequest, "url required") return } + lang, err := importLanguageParam(req.Language, r.URL.Query().Get("language"), company.LoadLanguage(r.Context(), s.Pool, cid)) + if err != nil { + Error(w, http.StatusBadRequest, err.Error()) + return + } + ctx := catalog.WithImportLanguage(r.Context(), lang) source, err := feeds.DownloadImportSource(r.Context(), req.URL, req.RequestHeaders, catalogMaxUpload) if err != nil { ClientOrLog(w, http.StatusBadRequest, "could not download import URL", err, feeds.ClientError) @@ -226,23 +234,29 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) { var result catalog.ImportResult switch kind { case "categories": - result, err = s.Catalog.ImportCategoriesCSV(r.Context(), cid, data) + result, err = s.Catalog.ImportCategoriesCSV(ctx, cid, data) case "attributes": - result, err = s.Catalog.ImportAttributesCSV(r.Context(), cid, data) + result, err = s.Catalog.ImportAttributesCSV(ctx, cid, data) case "products": - result, err = s.Catalog.ImportProductsCSV(r.Context(), cid, data, nil) + result, err = s.Catalog.ImportProductsCSV(ctx, cid, data, nil) } if err != nil { ClientOrLog(w, http.StatusBadRequest, "import failed", err, catalog.ClientError) return } - JSON(w, http.StatusOK, map[string]any{"kind": kind, "import": result, "source": "url"}) + JSON(w, http.StatusOK, map[string]any{"kind": kind, "import": result, "source": "url", "language": lang}) return } if err := r.ParseMultipartForm(catalogMaxUpload); err != nil { Error(w, http.StatusBadRequest, "invalid multipart form") return } + lang, langErr := importLanguageParam(r.FormValue("language"), r.URL.Query().Get("language"), company.LoadLanguage(r.Context(), s.Pool, cid)) + if langErr != nil { + Error(w, http.StatusBadRequest, langErr.Error()) + return + } + ctx := catalog.WithImportLanguage(r.Context(), lang) file, header, err := r.FormFile("file") if err != nil { Error(w, http.StatusBadRequest, "file field required") @@ -286,12 +300,12 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) { } switch kind { case "categories": - result, err = s.Catalog.ImportCategoriesCSV(r.Context(), cid, input) + result, err = s.Catalog.ImportCategoriesCSV(ctx, cid, input) case "attributes": - result, err = s.Catalog.ImportAttributesCSV(r.Context(), cid, input) + result, err = s.Catalog.ImportAttributesCSV(ctx, cid, input) case "products": fid := fileID - result, err = s.Catalog.ImportProductsCSV(r.Context(), cid, input, &fid) + result, err = s.Catalog.ImportProductsCSV(ctx, cid, input, &fid) } if err != nil { public := "import failed" @@ -317,7 +331,7 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) { } } meta, _ = s.Catalog.UpdateFileStatus(r.Context(), cid, fileID, "completed", importMeta) - JSON(w, http.StatusOK, map[string]any{"file": meta, "import": result, "kind": kind}) + JSON(w, http.StatusOK, map[string]any{"file": meta, "import": result, "kind": kind, "language": lang}) } func importKindFromPath(r *http.Request) string { @@ -341,3 +355,16 @@ func importKindFromPath(r *http.Request) string { return "" } } + +// importLanguageParam accepts explicit dashboard/API language, otherwise uses the +// company primary language. Never silently import to an unsupported locale. +func importLanguageParam(body, query, primary string) (string, error) { + requested := strings.TrimSpace(body) + if requested == "" { + requested = strings.TrimSpace(query) + } + if requested == "" { + requested = primary + } + return company.ParseLanguage(requested, false) +} diff --git a/apps/api/internal/httpapi/catalog_import_language_test.go b/apps/api/internal/httpapi/catalog_import_language_test.go new file mode 100644 index 0000000..323041b --- /dev/null +++ b/apps/api/internal/httpapi/catalog_import_language_test.go @@ -0,0 +1,21 @@ +package httpapi + +import "testing" + +func TestImportLanguageParam(t *testing.T) { + cases := []struct { + body, query, primary, want string + valid bool + }{ + {"", "", "sl", "sl", true}, + {"hr", "", "sl", "hr", true}, + {"", "JA", "en", "ja", true}, + {"xx", "", "en", "", false}, + } + for _, tc := range cases { + got, err := importLanguageParam(tc.body, tc.query, tc.primary) + if (err == nil) != tc.valid || (tc.valid && got != tc.want) { + t.Fatalf("importLanguageParam(%q,%q,%q) = %q, %v", tc.body, tc.query, tc.primary, got, err) + } + } +} diff --git a/apps/api/internal/httpapi/feeds_handlers.go b/apps/api/internal/httpapi/feeds_handlers.go index d79566b..15fbfe6 100644 --- a/apps/api/internal/httpapi/feeds_handlers.go +++ b/apps/api/internal/httpapi/feeds_handlers.go @@ -9,6 +9,7 @@ import ( "strings" "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/feeds" "github.com/descrybe/descrybe-v2/apps/api/internal/processing" "github.com/go-chi/chi/v5" @@ -53,11 +54,16 @@ func (s *Server) handleCreateFeed(w http.ResponseWriter, r *http.Request) { FeedType string `json:"feed_type"` SyncIntervalMinutes int `json:"sync_interval_minutes"` RequestHeaders map[string]string `json:"request_headers"` + ContentLanguage string `json:"content_language"` } if err := DecodeJSON(r, &body); err != nil { Error(w, http.StatusBadRequest, "invalid json") return } + if body.ContentLanguage != "" && !company.IsAllowedLanguage(body.ContentLanguage) { + Error(w, http.StatusBadRequest, "unsupported content language") + return + } item, err := s.Feeds.Create(r.Context(), cid, feeds.CreateInput{ Name: body.Name, URL: body.URL, @@ -65,6 +71,7 @@ func (s *Server) handleCreateFeed(w http.ResponseWriter, r *http.Request) { FeedType: body.FeedType, SyncIntervalMinutes: body.SyncIntervalMinutes, RequestHeaders: body.RequestHeaders, + ContentLanguage: company.NormalizeLanguage(body.ContentLanguage), }) if err != nil { ClientOrLog(w, http.StatusBadRequest, "could not create feed", err, feeds.ClientError) @@ -84,6 +91,11 @@ func (s *Server) createFeedFromMultipart(w http.ResponseWriter, r *http.Request, feedType := strings.TrimSpace(r.FormValue("feed_type")) itemPath := strings.TrimSpace(r.FormValue("item_path")) interval, _ := strconv.Atoi(strings.TrimSpace(r.FormValue("sync_interval_minutes"))) + contentLanguage := strings.TrimSpace(r.FormValue("content_language")) + if contentLanguage != "" && !company.IsAllowedLanguage(contentLanguage) { + Error(w, http.StatusBadRequest, "unsupported content language") + return + } headers := map[string]string{} if raw := strings.TrimSpace(r.FormValue("request_headers")); raw != "" { if err := json.Unmarshal([]byte(raw), &headers); err != nil { @@ -147,6 +159,7 @@ func (s *Server) createFeedFromMultipart(w http.ResponseWriter, r *http.Request, SyncIntervalMinutes: interval, Options: options, RequestHeaders: headers, + ContentLanguage: company.NormalizeLanguage(contentLanguage), }) if err != nil { ClientOrLog(w, http.StatusBadRequest, "could not create feed", err, feeds.ClientError) @@ -186,6 +199,13 @@ func (s *Server) handleUpdateFeed(w http.ResponseWriter, r *http.Request) { Error(w, http.StatusBadRequest, "invalid json") return } + if raw, exists := body["content_language"]; exists { + code, ok := raw.(string) + if !ok || (code != "" && !company.IsAllowedLanguage(code)) { + Error(w, http.StatusBadRequest, "unsupported content language") + return + } + } item, err := s.Feeds.Update(r.Context(), cid, id, body) if err != nil { if feeds.IsNotFound(err) { diff --git a/apps/api/internal/httpapi/processing_handlers.go b/apps/api/internal/httpapi/processing_handlers.go index 348769d..8c82ade 100644 --- a/apps/api/internal/httpapi/processing_handlers.go +++ b/apps/api/internal/httpapi/processing_handlers.go @@ -2,6 +2,7 @@ package httpapi import ( "errors" + "fmt" "net/http" "strings" @@ -41,14 +42,21 @@ func (s *Server) handleStartProcessingJob(w http.ResponseWriter, r *http.Request } ids = append(ids, id) } + // Do not schedule jobs with unknown outputs (or create orphaned jobs). + for _, requested := range body.ProcessingTypes { + if requested != "title" && requested != "description" && requested != "seo_meta" { + Error(w, http.StatusBadRequest, fmt.Sprintf("unsupported processing output: %s", requested)) + 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.StartAPIJob(r.Context(), cid, uid, ids, body.ProcessingType) + jobs, err = s.Processing.StartAPIJobWithTypes(r.Context(), cid, uid, ids, body.ProcessingType, body.ProcessingTypes) } else { - jobs, err = s.Processing.StartJob(r.Context(), cid, uid, ids, body.ProcessingType) + jobs, err = s.Processing.StartJobWithTypes(r.Context(), cid, uid, ids, body.ProcessingType, body.ProcessingTypes) } if err != nil { if writePlanGate(w, err) { @@ -65,6 +73,7 @@ func (s *Server) handleStartProcessingJob(w http.ResponseWriter, r *http.Request LogAndError(w, http.StatusBadRequest, "could not start processing job", err) return } + // Jobs already store the selected outputs transactionally, before enqueueing. for _, job := range jobs { if err := s.Jobs.EnqueueProcessingJob(r.Context(), job.ID); err != nil { Error(w, http.StatusInternalServerError, "enqueue failed") diff --git a/apps/api/internal/httpapi/server.go b/apps/api/internal/httpapi/server.go index dfc1dfd..5207025 100644 --- a/apps/api/internal/httpapi/server.go +++ b/apps/api/internal/httpapi/server.go @@ -409,6 +409,8 @@ func (s *Server) Router() http.Handler { r.Get("/ai-costs", s.handleAdminAICosts) r.Get("/ai-costs/export", s.handleAdminExportAICosts) r.Get("/billing/invoices/export", s.handleAdminExportCompanyInvoices) + r.Get("/credit-value-eur", s.handleAdminCreditValueEUR) + r.Put("/credit-value-eur", s.handleAdminCreditValueEUR) r.Get("/processing-costs", s.handleAdminGetProcessingCosts) r.Put("/processing-costs", s.handleAdminPutProcessingCost) r.Get("/ai-calls/{id}", s.handleAdminGetAICall) @@ -478,6 +480,7 @@ func (s *Server) Router() http.Handler { r.Delete("/api-keys/{id}", s.handleRevokeAPIKey) r.Get("/billing/credits", s.handleCreditsOverview) + r.Get("/billing/processing-costs", s.handleCompanyContentCosts) r.Get("/billing/capabilities", s.handleGetCapabilities) r.Get("/billing/usage", s.handleBillingUsage) r.Get("/billing/usage/export", s.handleBillingUsageExport) diff --git a/apps/api/internal/httpapi/v1_feeds.go b/apps/api/internal/httpapi/v1_feeds.go index 413276b..edbd3e1 100644 --- a/apps/api/internal/httpapi/v1_feeds.go +++ b/apps/api/internal/httpapi/v1_feeds.go @@ -6,6 +6,7 @@ import ( "strings" "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/feeds" "github.com/go-chi/chi/v5" "github.com/google/uuid" @@ -68,6 +69,7 @@ func (s *Server) handleV1CreateFeed(w http.ResponseWriter, r *http.Request) { FeedType string `json:"feed_type"` SyncIntervalMinutes int `json:"sync_interval_minutes"` SyncFrequency int `json:"sync_frequency"` // legacy hours + ContentLanguage string `json:"content_language"` IsActive *bool `json:"is_active"` } if err := DecodeJSON(r, &body); err != nil { @@ -87,6 +89,10 @@ func (s *Server) handleV1CreateFeed(w http.ResponseWriter, r *http.Request) { return } + if body.ContentLanguage != "" && !company.IsAllowedLanguage(body.ContentLanguage) { + v1Err(w, http.StatusBadRequest, "validation_error", "unsupported content language") + return + } item, err := s.Feeds.Create(r.Context(), cid, feeds.CreateInput{ Name: name, URL: url, @@ -94,6 +100,7 @@ func (s *Server) handleV1CreateFeed(w http.ResponseWriter, r *http.Request) { FeedType: body.FeedType, SyncIntervalMinutes: body.SyncIntervalMinutes, SyncFrequencyHours: body.SyncFrequency, + ContentLanguage: company.NormalizeLanguage(body.ContentLanguage), }) if err != nil { if msg, ok := feeds.ClientError(err); ok { @@ -126,6 +133,11 @@ func (s *Server) createV1FeedFromMultipart(w http.ResponseWriter, r *http.Reques feedType := strings.TrimSpace(r.FormValue("feed_type")) interval, _ := strconv.Atoi(strings.TrimSpace(r.FormValue("sync_interval_minutes"))) freq, _ := strconv.Atoi(strings.TrimSpace(r.FormValue("sync_frequency"))) + contentLanguage := strings.TrimSpace(r.FormValue("content_language")) + if contentLanguage != "" && !company.IsAllowedLanguage(contentLanguage) { + v1Err(w, http.StatusBadRequest, "validation_error", "unsupported content language") + return + } file, header, fileErr := r.FormFile("file") var options map[string]any @@ -187,6 +199,7 @@ func (s *Server) createV1FeedFromMultipart(w http.ResponseWriter, r *http.Reques FeedType: feedType, SyncIntervalMinutes: interval, SyncFrequencyHours: freq, + ContentLanguage: company.NormalizeLanguage(contentLanguage), Options: options, }) if err != nil { diff --git a/apps/api/internal/httpapi/v1_openapi.go b/apps/api/internal/httpapi/v1_openapi.go index 1800b6a..ee72ad5 100644 --- a/apps/api/internal/httpapi/v1_openapi.go +++ b/apps/api/internal/httpapi/v1_openapi.go @@ -2136,6 +2136,12 @@ paths: - csv - json description: Source format. xml, csv or json; defaults to xml when not detected. + content_language: + type: string + description: | + Optional source-language code (e.g. en, sl, hr, de). Defaults to the + company's primary content language. Affects where the synchronized + product's original supplier text is stored; it does not translate. sync_interval_minutes: type: integer minimum: 1 @@ -2156,6 +2162,7 @@ paths: item_path: channel/item url: https://feeds.example.com/nordic/google-merchant.xml feed_type: xml + content_language: sl sync_interval_minutes: 60 is_active: true responses: diff --git a/apps/api/internal/httpapi/v1_process_handlers.go b/apps/api/internal/httpapi/v1_process_handlers.go index bc4ba13..d29e9cb 100644 --- a/apps/api/internal/httpapi/v1_process_handlers.go +++ b/apps/api/internal/httpapi/v1_process_handlers.go @@ -411,5 +411,10 @@ 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 + } + } 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 c72c535..31fc8ba 100644 --- a/apps/api/internal/processing/pipeline.go +++ b/apps/api/internal/processing/pipeline.go @@ -135,16 +135,26 @@ 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") + 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") + return p.startJobWithOrigin(ctx, companyID, userID, rawIDs, processingType, "api", nil) } -func (p *Pipeline) startJobWithOrigin(ctx context.Context, companyID, userID uuid.UUID, rawIDs []uuid.UUID, processingType, origin string) ([]Job, error) { +// 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) +} + +// 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) +} + +func (p *Pipeline) startJobWithOrigin(ctx context.Context, companyID, userID uuid.UUID, rawIDs []uuid.UUID, processingType, origin string, outputs []string) ([]Job, error) { if processingType == "" { processingType = "full" } @@ -174,7 +184,7 @@ func (p *Pipeline) startJobWithOrigin(ctx context.Context, companyID, userID uui } } if p.Billing != nil { - if err := p.assertProcessingGates(ctx, companyID, processingType, len(owned)); err != nil { + if err := p.assertProcessingGates(ctx, companyID, processingType, len(owned), outputs...); err != nil { return nil, err } } @@ -189,6 +199,9 @@ func (p *Pipeline) startJobWithOrigin(ctx context.Context, companyID, userID uui firstStep = progress[0].Step } + if outputs == nil { + outputs = []string{} + } chunks := chunkUUIDs(owned, perJobProductCap()) tx, err := p.Pool.Begin(ctx) if err != nil { @@ -201,9 +214,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 - ) VALUES ($1, $2, 'pending', $3, $4, $5, $6::jsonb, $7) RETURNING id`, - companyID, userID, len(chunk), processingType, firstStep, progressJSON, origin).Scan(&jobID) + 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) if err != nil { return nil, err } @@ -229,7 +242,7 @@ func (p *Pipeline) startJobWithOrigin(ctx context.Context, companyID, userID uui } // assertProcessingGates enforces plan features and credit/SKU caps before starting or retrying work. -func (p *Pipeline) assertProcessingGates(ctx context.Context, companyID uuid.UUID, processingType string, batchSize int) error { +func (p *Pipeline) assertProcessingGates(ctx context.Context, companyID uuid.UUID, processingType string, batchSize int, outputs ...string) error { if p == nil || p.Billing == nil { return nil } @@ -240,6 +253,11 @@ 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 + } + } return p.Billing.AssertCanStartProcessing(ctx, companyID, batchSize, opts) } @@ -545,7 +563,7 @@ func (p *Pipeline) RetryJob(ctx context.Context, companyID, id uuid.UUID) (Job, if p.Limiter != nil && !p.Limiter.Allow(companyID) { return Job{}, ErrRateLimited } - if err := p.assertProcessingGates(ctx, companyID, job.ProcessingType, job.TotalProducts); err != nil { + if err := p.assertProcessingGates(ctx, companyID, job.ProcessingType, job.TotalProducts, selectedOutputs...); err != nil { return Job{}, err } @@ -601,11 +619,12 @@ 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 selectedOutputs []string var alreadyProcessed int err := p.Pool.QueryRow(ctx, ` - SELECT company_id, user_id, status, processing_type, processed_products, origin + SELECT company_id, user_id, status, processing_type, processed_products, origin, processing_types FROM processing_jobs WHERE id = $1`, jobID). - Scan(&companyID, &jobUserID, &status, &processingType, &alreadyProcessed, &origin) + Scan(&companyID, &jobUserID, &status, &processingType, &alreadyProcessed, &origin, &selectedOutputs) if err != nil { return err } @@ -765,7 +784,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, origin, jobEngine, modeLabel, usingBYOK, &jobCache) + ok, tokens, result, itemErr := p.processOne(ctx, companyID, jobID, &items[i], processingType, selectedOutputs, origin, jobEngine, modeLabel, usingBYOK, &jobCache) if itemErr != nil { failed++ if _, err := p.Pool.Exec(ctx, ` @@ -1454,7 +1473,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, origin 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 string, selectedOutputs []string, 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") } @@ -1706,11 +1725,24 @@ func (p *Pipeline) processOne(ctx context.Context, companyID, jobID uuid.UUID, i // Debit before persisting the deliverable so insufficient credits cannot yield free AI output. // BYOK (company key): skip managed credit burn for inference. // Hash-skip (ai_enhance_unchanged): skip flat product_processing debit — no LLM/rework. - if p.Billing != nil && shouldDebitProductProcessing(usingBYOK, result) { - if err := p.Billing.ConsumeCreditsTx(ctx, tx, companyID, result.TotalTokens, "product_processing"); err != nil { + billable := p.Billing != nil && shouldDebitProductProcessing(usingBYOK, result) + if billable && result.TotalTokens == 0 { + // Normalization-only jobs on Free cannot consume managed AI credits. + if ent, entErr := p.Billing.EntitlementsForCompany(ctx, companyID); entErr != nil { + return false, 0, result, entErr + } else if !ent.CanUseAI { + billable = false + } + } + if billable { + debit, err := p.Billing.ConsumeContentCreditsTx(ctx, tx, companyID, selectedOutputs, processingType) + if err != nil { return false, 0, result, err } - cache.noteCreditDebit(p.Billing.EstimateDebitForCompany(ctx, companyID, "product_processing", result.TotalTokens)) + // Cache tracks whole-credit safety only; the database debit checks every fraction. + if debit >= 1 { + cache.noteCreditDebit(int(debit)) + } } processedID, err := p.upsertProcessedProduct(ctx, tx, companyID, it.RawID, gtin, result, attrsJSON, procAttrsJSON, gptJSON, sourcesJSON, providerMode, language, origin) diff --git a/apps/api/sql/schema/053_content_credit_rates.sql b/apps/api/sql/schema/053_content_credit_rates.sql new file mode 100644 index 0000000..15e4d5e --- /dev/null +++ b/apps/api/sql/schema/053_content_credit_rates.sql @@ -0,0 +1,31 @@ +-- +goose Up +-- Product content credits are priced per output, independently of token usage. +-- Historical integer debit columns remain intact. Fractional debit amounts are +-- accumulated separately to preserve compatibility with older integrations. +ALTER TABLE processing_costs ALTER COLUMN cost_per_unit TYPE NUMERIC(14,4); +ALTER TABLE plan_processing_costs DROP CONSTRAINT IF EXISTS plan_processing_costs_cost_per_unit_check; +ALTER TABLE company_processing_costs DROP CONSTRAINT IF EXISTS company_processing_costs_cost_per_unit_check; +ALTER TABLE plan_processing_costs ALTER COLUMN cost_per_unit TYPE NUMERIC(14,4); +ALTER TABLE company_processing_costs ALTER COLUMN cost_per_unit TYPE NUMERIC(14,4); +ALTER TABLE plan_processing_costs ADD CONSTRAINT plan_processing_costs_cost_per_unit_check CHECK (cost_per_unit >= 0 AND cost_per_unit <= 1000000); +ALTER TABLE company_processing_costs ADD CONSTRAINT company_processing_costs_cost_per_unit_check CHECK (cost_per_unit >= 0 AND cost_per_unit <= 1000000); +ALTER TABLE credit_balances ADD COLUMN fractional_credits_used NUMERIC(16,4) NOT NULL DEFAULT 0; +ALTER TABLE billing_cycles ADD COLUMN fractional_credits_used NUMERIC(16,4) NOT NULL DEFAULT 0; +ALTER TABLE processing_jobs ADD COLUMN processing_types TEXT[] NOT NULL DEFAULT '{}'; +INSERT INTO processing_costs (feature_name,cost_per_unit,description,is_active) VALUES +('title_ai',0.10,'AI product title',true), +('description_ai',0.25,'AI product description',true), +('seo_meta_ai',0.10,'SEO meta title and description',true) +ON CONFLICT (feature_name) DO NOTHING; +-- Upgrade only the known legacy SEO default, preserving custom platform pricing. +UPDATE processing_costs SET cost_per_unit=0.10, description='SEO meta title and description' WHERE feature_name='seo_meta_ai' AND cost_per_unit=1; + +-- +goose Down +ALTER TABLE processing_jobs DROP COLUMN IF EXISTS processing_types; +ALTER TABLE billing_cycles DROP COLUMN IF EXISTS fractional_credits_used; +ALTER TABLE credit_balances DROP COLUMN IF EXISTS fractional_credits_used; +DELETE FROM processing_costs WHERE feature_name IN ('title_ai','description_ai'); +DELETE FROM plan_processing_costs WHERE feature_name IN ('title_ai','description_ai'); +DELETE FROM company_processing_costs WHERE feature_name IN ('title_ai','description_ai'); +-- Numeric cost columns deliberately not narrowed on rollback: old schema cannot +-- represent already-saved fractional overrides without data loss. diff --git a/apps/api/sql/schema/054_catalog_import_languages.sql b/apps/api/sql/schema/054_catalog_import_languages.sql new file mode 100644 index 0000000..6e900a5 --- /dev/null +++ b/apps/api/sql/schema/054_catalog_import_languages.sql @@ -0,0 +1,12 @@ +-- +goose Up +-- Supplier data is stored per import language without replacing the company's primary labels. +ALTER TABLE categories ADD COLUMN IF NOT EXISTS localized_fields JSONB NOT NULL DEFAULT '{}'::jsonb; +ALTER TABLE attributes ADD COLUMN IF NOT EXISTS localized_fields JSONB NOT NULL DEFAULT '{}'::jsonb; +ALTER TABLE raw_products ADD COLUMN IF NOT EXISTS source_localizations JSONB NOT NULL DEFAULT '{}'::jsonb; +ALTER TABLE processed_products ADD COLUMN IF NOT EXISTS source_localizations JSONB NOT NULL DEFAULT '{}'::jsonb; + +-- +goose Down +ALTER TABLE processed_products DROP COLUMN IF EXISTS source_localizations; +ALTER TABLE raw_products DROP COLUMN IF EXISTS source_localizations; +ALTER TABLE attributes DROP COLUMN IF EXISTS localized_fields; +ALTER TABLE categories DROP COLUMN IF EXISTS localized_fields; diff --git a/apps/web/src/lib/admin-plan-credit-costs.test.ts b/apps/web/src/lib/admin-plan-credit-costs.test.ts new file mode 100644 index 0000000..7eed004 --- /dev/null +++ b/apps/web/src/lib/admin-plan-credit-costs.test.ts @@ -0,0 +1,22 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import test from 'node:test'; + +const plan = readFileSync(fileURLToPath(new URL('../routes/admin/billing/+page.svelte', import.meta.url)), 'utf8'); +const actions = readFileSync(fileURLToPath(new URL('./components/products/ProductProcessingActions.svelte', import.meta.url)), 'utf8'); +const features = plan.split('const creditFeatures = [', 2)[1]?.split('] as const', 1)[0] ?? ''; + +test('plan processing costs show only the three selectable product outputs', () => { + assert.match(features, /key: 'title_ai'|key: "title_ai"/); + assert.match(features, /key: 'description_ai'|key: "description_ai"/); + assert.match(features, /key: 'seo_meta_ai'|key: "seo_meta_ai"/); + assert.doesNotMatch(features, /openai_token_k|campaign_copy|product_processing/); +}); + +test('decimal values are allowed and loaded from company-effective pricing', () => { + assert.match(plan, /step="0\.0001"/); + assert.match(plan, /\\d\{1,4\}/); + assert.match(actions, /\/api\/billing\/processing-costs/); + assert.match(actions, /effectiveCosts\[option\.type\]/); +}); diff --git a/apps/web/src/lib/components/feeds/RemoteCatalogImport.svelte b/apps/web/src/lib/components/feeds/RemoteCatalogImport.svelte index 4f73403..0c47ead 100644 --- a/apps/web/src/lib/components/feeds/RemoteCatalogImport.svelte +++ b/apps/web/src/lib/components/feeds/RemoteCatalogImport.svelte @@ -1,15 +1,16 @@ @@ -1077,7 +1081,14 @@ {#if canAdmin} - +
+ + +
+
diff --git a/apps/web/src/routes/categories/+page.svelte b/apps/web/src/routes/categories/+page.svelte index d151897..cc5749b 100644 --- a/apps/web/src/routes/categories/+page.svelte +++ b/apps/web/src/routes/categories/+page.svelte @@ -1,5 +1,6 @@ @@ -186,7 +190,14 @@ - {#if canAdmin}{/if} +
+ + +
+ {#if canAdmin}{/if} {#if !loading && promptCount > 0}

@@ -260,7 +271,7 @@ onToggleExpand={toggleExpand} onEdit={async (cat) => { try { - selected = await api(`/api/categories/${cat.id}`); + selected = await api(`/api/categories/${cat.id}${importLanguage ? `?language=${encodeURIComponent(importLanguage)}` : ""}`); } catch { selected = cat; } diff --git a/apps/web/src/routes/feeds/+page.svelte b/apps/web/src/routes/feeds/+page.svelte index 60e123d..5594d30 100644 --- a/apps/web/src/routes/feeds/+page.svelte +++ b/apps/web/src/routes/feeds/+page.svelte @@ -1,5 +1,6 @@