This commit is contained in:
greeneclipse committed 2026-10-16 13:48:51 +02:00
1 parent feebf7d3c1
commit 486502852e
41 files changed
+1293 -241

No files matched your search

+61
View File
@@ -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.
+18
View File
@@ -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.
+8
View File
@@ -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.
@@ -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
}
@@ -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)
}
}
+1 -1
View File
@@ -131,7 +131,7 @@ func ComputeEntitlements(planName string, monthlyCredits, remaining int, isTrial
func (s *Service) EntitlementsForCompany(ctx context.Context, companyID uuid.UUID) (Entitlements, error) { func (s *Service) EntitlementsForCompany(ctx context.Context, companyID uuid.UUID) (Entitlements, error) {
var total, used int var total, used int
err := s.Pool.QueryRow(ctx, ` 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) Scan(&total, &used)
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
total, used = 0, 0 total, used = 0, 0
+38 -21
View File
@@ -36,9 +36,9 @@ const featureGatesCacheTTL = 30 * time.Second
type CreditsOverview struct { type CreditsOverview struct {
TotalCredits int `json:"total_credits"` TotalCredits int `json:"total_credits"`
UsedCredits int `json:"used_credits"` UsedCredits float64 `json:"used_credits"`
Remaining int `json:"remaining"` Remaining float64 `json:"remaining"`
RemainingCredits int `json:"remaining_credits"` RemainingCredits float64 `json:"remaining_credits"`
LowCredits bool `json:"low_credits"` LowCredits bool `json:"low_credits"`
LowCreditsThreshold int `json:"low_credits_threshold"` LowCreditsThreshold int `json:"low_credits_threshold"`
ProductCount int `json:"product_count"` ProductCount int `json:"product_count"`
@@ -69,9 +69,10 @@ func (s *Service) CreditsOverview(ctx context.Context, companyID uuid.UUID, lowT
lowThreshold = 100 lowThreshold = 100
} }
var total, used int var total, used int
var fractional float64
err := s.Pool.QueryRow(ctx, ` err := s.Pool.QueryRow(ctx, `
SELECT total_credits, used_credits FROM credit_balances WHERE company_id = $1`, companyID). SELECT total_credits, used_credits, fractional_credits_used::double precision FROM credit_balances WHERE company_id = $1`, companyID).
Scan(&total, &used) Scan(&total, &used, &fractional)
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
_, _ = s.Pool.Exec(ctx, `INSERT INTO credit_balances (company_id) VALUES ($1) ON CONFLICT DO NOTHING`, companyID) _, _ = s.Pool.Exec(ctx, `INSERT INTO credit_balances (company_id) VALUES ($1) ON CONFLICT DO NOTHING`, companyID)
total, used = 0, 0 total, used = 0, 0
@@ -79,10 +80,13 @@ func (s *Service) CreditsOverview(ctx context.Context, companyID uuid.UUID, lowT
return CreditsOverview{}, err return CreditsOverview{}, err
} }
remaining := RemainingCreditsClamped(total, used) remaining := float64(total-used) - fractional
if remaining < 0 {
remaining = 0
}
out := CreditsOverview{ out := CreditsOverview{
TotalCredits: total, TotalCredits: total,
UsedCredits: used, UsedCredits: float64(used) + fractional,
Remaining: remaining, Remaining: remaining,
RemainingCredits: remaining, RemainingCredits: remaining,
LowCreditsThreshold: lowThreshold, LowCreditsThreshold: lowThreshold,
@@ -157,7 +161,7 @@ func (s *Service) CreditsOverview(ctx context.Context, companyID uuid.UUID, lowT
planName = "Free" planName = "Free"
featuresRaw = []byte("{}") featuresRaw = []byte("{}")
} }
ent := ComputeEntitlements(planName, monthlyVal, remaining, isTrial) ent := ComputeEntitlements(planName, monthlyVal, int(remaining+0.9999), isTrial)
out.CanUseAI = ent.CanUseAI out.CanUseAI = ent.CanUseAI
out.CanUseEPREL = ent.CanUseEPREL out.CanUseEPREL = ent.CanUseEPREL
out.IsFreePlan = ent.IsFreePlan out.IsFreePlan = ent.IsFreePlan
@@ -214,6 +218,9 @@ func (s *Service) AIBrandApplyAllowed(ctx context.Context, companyID uuid.UUID)
type ProcessingGateOpts struct { type ProcessingGateOpts struct {
// RequiresAI when true enforces can_use_ai + credit wallet (AI-only job types). // RequiresAI when true enforces can_use_ai + credit wallet (AI-only job types).
RequiresAI bool 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 when true enforces can_use_eprel (EPREL-only job types).
RequiresEPREL bool RequiresEPREL bool
} }
@@ -239,9 +246,15 @@ func (s *Service) AssertCanStartProcessing(ctx context.Context, companyID uuid.U
if ent.RemainingCredits < 1 { if ent.RemainingCredits < 1 {
return fmt.Errorf("%w: no credits remaining — upgrade your plan to continue AI processing", ErrInsufficientCredits) return fmt.Errorf("%w: no credits remaining — upgrade your plan to continue AI processing", ErrInsufficientCredits)
} }
if ent.RemainingCredits < batchSize { needed := float64(batchSize)
return fmt.Errorf("%w: need at least %d credits for this batch (have %d) — upgrade or select fewer products", if opts.CreditsPerProduct > 0 {
ErrInsufficientCredits, batchSize, ent.RemainingCredits) 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 ( WITH upd AS (
UPDATE credit_balances UPDATE credit_balances
SET used_credits = used_credits + $2, updated_at = now() 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 RETURNING company_id
), ),
cyc AS ( cyc AS (
@@ -462,7 +475,7 @@ func (s *Service) lookupCost(ctx context.Context, feature string, fallback int)
var cost int var cost int
err := s.Pool.QueryRow(ctx, ` 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) WHERE feature_name = $1 AND is_active = true`, feature).Scan(&cost)
if err != nil || cost <= 0 { if err != nil || cost <= 0 {
return fallback return fallback
@@ -884,7 +897,7 @@ func (s *Service) AssignPlan(ctx context.Context, companyID uuid.UUID, planID in
_, err = tx.Exec(ctx, ` _, err = tx.Exec(ctx, `
INSERT INTO credit_balances (company_id, total_credits, used_credits, updated_at) INSERT INTO credit_balances (company_id, total_credits, used_credits, updated_at)
VALUES ($1, $2, 0, now()) 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) companyID, alloc)
if err != nil { if err != nil {
return err return err
@@ -931,9 +944,9 @@ type UsageDayPoint struct {
type UsageSummary struct { type UsageSummary struct {
CompanyID uuid.UUID `json:"company_id"` CompanyID uuid.UUID `json:"company_id"`
Range string `json:"range"` Range string `json:"range"`
CreditsUsed int `json:"credits_used"` CreditsUsed float64 `json:"credits_used"`
CreditsTotal int `json:"credits_total"` CreditsTotal int `json:"credits_total"`
CreditsRemaining int `json:"credits_remaining"` CreditsRemaining float64 `json:"credits_remaining"`
ProductsProcessed int `json:"products_processed"` ProductsProcessed int `json:"products_processed"`
ProductsTotal int `json:"products_total"` ProductsTotal int `json:"products_total"`
Tokens int64 `json:"tokens"` Tokens int64 `json:"tokens"`
@@ -969,17 +982,21 @@ func (s *Service) UsageSummary(ctx context.Context, companyID uuid.UUID, rangeRa
} }
var total, used int var total, used int
var fractional float64
err := s.Pool.QueryRow(ctx, ` err := s.Pool.QueryRow(ctx, `
SELECT total_credits, used_credits FROM credit_balances WHERE company_id = $1`, companyID). SELECT total_credits, used_credits, fractional_credits_used::double precision FROM credit_balances WHERE company_id = $1`, companyID).
Scan(&total, &used) Scan(&total, &used, &fractional)
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
total, used = 0, 0 total, used = 0, 0
} else if err != nil { } else if err != nil {
return out, err return out, err
} }
out.CreditsTotal = total out.CreditsTotal = total
out.CreditsUsed = used out.CreditsUsed = float64(used) + fractional
out.CreditsRemaining = RemainingCreditsClamped(total, used) out.CreditsRemaining = float64(total-used) - fractional
if out.CreditsRemaining < 0 {
out.CreditsRemaining = 0
}
out.Notes = append(out.Notes, 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.") "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, ` _, err = tx.Exec(ctx, `
INSERT INTO credit_balances (company_id, total_credits, used_credits, updated_at) INSERT INTO credit_balances (company_id, total_credits, used_credits, updated_at)
VALUES ($1, $2, 0, now()) 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) companyID, monthly)
if err != nil { if err != nil {
return false, err return false, err
+45 -26
View File
@@ -124,6 +124,7 @@ func (s *Service) flushCategoryBatch(ctx context.Context, companyID uuid.UUID, b
if len(batch) == 0 { if len(batch) == 0 {
return nil return nil
} }
lang, primary := s.importLanguage(ctx, companyID)
byUID := make(map[string]categoryCSVRow, len(batch)) byUID := make(map[string]categoryCSVRow, len(batch))
order := make([]string, 0, 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 { if len(updIDs) > 0 {
_, err = tx.Exec(ctx, ` _, err = tx.Exec(ctx, `
UPDATE categories AS c SET UPDATE categories AS c SET
name = v.name, name = CASE WHEN $5 THEN v.name ELSE c.name END,
description = CASE WHEN v.description <> '' THEN v.description ELSE c.description 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() updated_at = now()
FROM unnest($2::uuid[], $3::text[], $4::text[]) AS v(id, name, description) FROM unnest($2::uuid[], $3::text[], $4::text[]) AS v(id, name, description)
WHERE c.id = v.id AND c.company_id = $1`, WHERE c.id = v.id AND c.company_id = $1`,
companyID, updIDs, updNames, updDescs) companyID, updIDs, updNames, updDescs, primary, lang)
if err != nil { if err != nil {
return err return err
} }
@@ -228,12 +232,13 @@ func (s *Service) flushCategoryBatch(ctx context.Context, companyID uuid.UUID, b
} }
rows, err := tx.Query(ctx, ` rows, err := tx.Query(ctx, `
INSERT INTO categories (company_id, name, unique_id, parent_unique_id, description, path, 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 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[]) 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) AS v(name, unique_id, parent_unique_id, description, path, level)
RETURNING id, unique_id, COALESCE(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 { if err != nil {
return err return err
} }
@@ -396,6 +401,7 @@ func (s *Service) flushAttributeBatch(ctx context.Context, companyID uuid.UUID,
if len(batch) == 0 { if len(batch) == 0 {
return nil return nil
} }
lang, primary := s.importLanguage(ctx, companyID)
byKey := make(map[string]attributeCSVRow, len(batch)) byKey := make(map[string]attributeCSVRow, len(batch))
order := make([]string, 0, 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 { if len(updIDs) > 0 {
_, err = tx.Exec(ctx, ` _, err = tx.Exec(ctx, `
UPDATE attributes AS a SET 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, 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() updated_at = now()
FROM unnest($2::uuid[], $3::text[], $4::text[]) AS v(id, name, value_type) FROM unnest($2::uuid[], $3::text[], $4::text[]) AS v(id, name, value_type)
WHERE a.id = v.id AND a.company_id = $1`, WHERE a.id = v.id AND a.company_id = $1`,
companyID, updIDs, updNames, updTypes) companyID, updIDs, updNames, updTypes, primary, lang)
if err != nil { if err != nil {
return err return err
} }
@@ -479,12 +487,13 @@ func (s *Service) flushAttributeBatch(ctx context.Context, companyID uuid.UUID,
if len(insKeys) > 0 { if len(insKeys) > 0 {
ct, err := tx.Exec(ctx, ` 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, 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[]) 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)`, 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 { if err != nil {
return err 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) { func (s *Service) ImportProductsCSV(ctx context.Context, companyID uuid.UUID, r io.Reader, fileID *uuid.UUID) (ImportResult, error) {
res := ImportResult{} res := ImportResult{}
lang, primary := s.importLanguage(ctx, companyID)
merge, err := s.MergeProductsByGTIN(ctx, companyID) merge, err := s.MergeProductsByGTIN(ctx, companyID)
if err != nil { if err != nil {
return res, err return res, err
@@ -566,7 +576,7 @@ func (s *Service) ImportProductsCSV(ctx context.Context, companyID uuid.UUID, r
batch = append(batch, productCSVRow{ batch = append(batch, productCSVRow{
gtin: gtin, productID: productID, name: name, category: category, gtin: gtin, productID: productID, name: name, category: category,
desc: desc, status: status, rawJSON: string(rawData), 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 len(batch) >= importCSVBatchSize {
if err := s.flushProductBatch(ctx, companyID, fileID, batch, &res); err != nil { 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 { if len(batch) == 0 {
return nil return nil
} }
lang, primary := s.importLanguage(ctx, companyID)
// Last row wins per GTIN so a single INSERT cannot hit the same unique key twice. // Last row wins per GTIN so a single INSERT cannot hit the same unique key twice.
byGTIN := make(map[string]productCSVRow, len(batch)) 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 { if len(updRawIDs) > 0 {
_, err = tx.Exec(ctx, ` _, err = tx.Exec(ctx, `
UPDATE raw_products AS r SET UPDATE raw_products AS r SET
raw_data = v.raw_data::jsonb, raw_data = CASE WHEN $6 THEN v.raw_data::jsonb ELSE r.raw_data END,
mapped_data = v.raw_data::jsonb, 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), file_id = COALESCE($3, r.file_id),
updated_at = now() updated_at = now()
FROM unnest($2::uuid[], $4::text[]) AS v(id, raw_data) FROM unnest($2::uuid[], $4::text[]) AS v(id, raw_data)
WHERE r.id = v.id AND r.company_id = $1`, WHERE r.id = v.id AND r.company_id = $1`,
companyID, updRawIDs, fileID, updRawJSON) companyID, updRawIDs, fileID, updRawJSON, lang, primary)
if err != nil { if err != nil {
return err return err
} }
@@ -694,12 +707,13 @@ func (s *Service) flushProductBatch(ctx context.Context, companyID uuid.UUID, fi
if len(insGTINs) > 0 { if len(insGTINs) > 0 {
rows, err := tx.Query(ctx, ` rows, err := tx.Query(ctx, `
INSERT INTO raw_products (company_id, gtin, raw_data, mapped_data, processing_status, file_id) 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 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) FROM unnest($3::text[], $4::text[]) AS v(gtin, raw_data)
ON CONFLICT (company_id, gtin) DO NOTHING ON CONFLICT (company_id, gtin) DO NOTHING
RETURNING id, gtin`, RETURNING id, gtin`,
companyID, fileID, insGTINs, insJSON) companyID, fileID, insGTINs, insJSON, lang)
if err != nil { if err != nil {
return err return err
} }
@@ -803,15 +817,18 @@ func (s *Service) flushProductBatch(ctx context.Context, companyID uuid.UUID, fi
_, err = tx.Exec(ctx, ` _, err = tx.Exec(ctx, `
UPDATE processed_products AS p SET UPDATE processed_products AS p SET
product_id = COALESCE(NULLIF(v.product_id, ''), p.product_id), product_id = COALESCE(NULLIF(v.product_id, ''), p.product_id),
name = COALESCE(NULLIF(v.name, ''), p.name), name = CASE WHEN $9 THEN COALESCE(NULLIF(v.name, ''), p.name) ELSE p.name END,
category = COALESCE(NULLIF(v.category, ''), p.category), category = CASE WHEN $9 THEN COALESCE(NULLIF(v.category, ''), p.category) ELSE p.category END,
description = COALESCE(NULLIF(v.description, ''), p.description), description = CASE WHEN $9 THEN COALESCE(NULLIF(v.description, ''), p.description) ELSE p.description END,
status = COALESCE(NULLIF(v.status, ''), p.status), 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() updated_at = now()
FROM unnest($2::uuid[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[]) FROM unnest($2::uuid[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])
AS v(id, product_id, name, category, description, status) AS v(id, product_id, name, category, description, status)
WHERE p.id = v.id AND p.company_id = $1`, 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 { if err != nil {
return err return err
} }
@@ -820,13 +837,15 @@ func (s *Service) flushProductBatch(ctx context.Context, companyID uuid.UUID, fi
if len(insRawIDs) > 0 { if len(insRawIDs) > 0 {
_, err = tx.Exec(ctx, ` _, 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, SELECT $1,
NULLIF(v.product_id, ''), NULLIF(v.name, ''), NULLIF(v.category, ''), 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[]) 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)`, 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 { if err != nil {
return err return err
} }
@@ -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
}
}
}
}
@@ -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])
}
}
+13 -8
View File
@@ -94,7 +94,7 @@ func (s *Service) ListCategories(ctx context.Context, companyID uuid.UUID, f Lis
off := len(args) off := len(args)
rows, err := s.Pool.Query(ctx, fmt.Sprintf(` rows, err := s.Pool.Query(ctx, fmt.Sprintf(`
SELECT id, name, unique_id, parent_unique_id, path, level, position, is_active, description, 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' (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, 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' (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() defer rows.Close()
items, err := scanMaps(rows, []string{ items, err := scanMaps(rows, []string{
"id", "name", "unique_id", "parent_unique_id", "path", "level", "position", "is_active", "description", "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", "created_at", "updated_at",
}) })
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }
localizeCatalogImportNames(ctx, items)
if total, ok := exactTotalFromPage(f.Offset, f.Limit, len(items)); ok { if total, ok := exactTotalFromPage(f.Offset, f.Limit, len(items)); ok {
return items, total, nil 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 SELECT 1 FROM jsonb_each_text(COALESCE(prompt, '{}'::jsonb)) kv
WHERE length(trim(kv.value)) > 0 WHERE length(trim(kv.value)) > 0
)) AS has_prompt, )) 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) FROM categories WHERE id = $1 AND company_id = $2`, id, companyID)
item, err := scanMap(row, []string{ item, err := scanMap(row, []string{
"id", "name", "unique_id", "parent_unique_id", "path", "level", "position", "is_active", "description", "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 { if err != nil {
return nil, err return nil, err
} }
localizeCatalogImportNames(ctx, []map[string]any{item})
return enrichCategoryPrompts(ctx, s.Pool, companyID, 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} args := []any{companyID}
where := []string{"a.company_id = $1"} where := []string{"a.company_id = $1"}
from := "attributes a" 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" 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", "created_at", "updated_at"} scanCols := []string{"id", "attribute_key", "name", "value_type", "unit", "example", "parent_key", "localized_fields", "created_at", "updated_at"}
if f.Category != "" { if f.Category != "" {
from = `attributes a from = `attributes a
INNER JOIN category_attributes ca INNER JOIN category_attributes ca
@@ -417,6 +419,7 @@ func (s *Service) ListAttributes(ctx context.Context, companyID uuid.UUID, f Lis
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }
localizeCatalogImportNames(ctx, items)
if total, ok := exactTotalFromPage(f.Offset, f.Limit, len(items)); ok { if total, ok := exactTotalFromPage(f.Offset, f.Limit, len(items)); ok {
return items, total, nil return items, total, nil
} }
@@ -1324,6 +1327,7 @@ func (s *Service) GetProcessedProduct(ctx context.Context, companyID, id uuid.UU
`+processedHasProcessedAttributesSQL+` AS has_processed_attributes, `+processedHasProcessedAttributesSQL+` AS has_processed_attributes,
`+processedHasEprelSQL+` AS has_eprel, `+processedHasEprelSQL+` AS has_eprel,
COALESCE(p.localized_content, '{}'::jsonb) AS localized_content, 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 p.created_at, p.updated_at
FROM processed_products p FROM processed_products p
LEFT JOIN raw_products r ON r.id = p.raw_product_id 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", "feed_id", "feed_name", "feed_last_synced_at", "raw_updated_at",
"has_processed_name", "has_processed_description", "has_attributes", "has_processed_attributes", "has_processed_name", "has_processed_description", "has_attributes", "has_processed_attributes",
"has_eprel", "has_eprel",
"localized_content", "localized_content", "source_localizations",
"created_at", "updated_at", "created_at", "updated_at",
}) })
if err != nil { if err != nil {
@@ -1384,6 +1388,7 @@ func (s *Service) GetRawProduct(ctx context.Context, companyID, id uuid.UUID) (m
false AS has_processed_attributes, false AS has_processed_attributes,
`+strings.ReplaceAll(processedHasEprelSQL, "r.mapped_data", "rp.mapped_data")+` AS has_eprel, `+strings.ReplaceAll(processedHasEprelSQL, "r.mapped_data", "rp.mapped_data")+` AS has_eprel,
'{}'::jsonb AS localized_content, '{}'::jsonb AS localized_content,
COALESCE(rp.source_localizations, '{}'::jsonb) AS source_localizations,
rp.created_at, rp.updated_at, 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->>'name'), ''), NULLIF(trim(rp.mapped_data->>'title'), ''), '') <> '') AS has_name,
(COALESCE(NULLIF(trim(rp.mapped_data->>'description'), ''), '') <> '') AS has_description, (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", "feed_id", "feed_name", "feed_last_synced_at", "raw_updated_at",
"has_processed_name", "has_processed_description", "has_attributes", "has_processed_attributes", "has_processed_name", "has_processed_description", "has_attributes", "has_processed_attributes",
"has_eprel", "has_eprel",
"localized_content", "localized_content", "source_localizations",
"created_at", "updated_at", "created_at", "updated_at",
"has_name", "has_description", "has_category", "has_name", "has_description", "has_category",
"is_processed", "processing_status", "is_processed", "processing_status",
+10 -2
View File
@@ -29,6 +29,7 @@ type CreateInput struct {
SyncFrequencyHours int // legacy alias; converted to minutes when SyncIntervalMinutes unset SyncFrequencyHours int // legacy alias; converted to minutes when SyncIntervalMinutes unset
Options map[string]any Options map[string]any
RequestHeaders map[string]string 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) { 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 { if opts == nil {
opts = map[string]any{} opts = map[string]any{}
} }
if in.ContentLanguage != "" {
opts["content_language"] = in.ContentLanguage
}
if len(in.RequestHeaders) > 0 { if len(in.RequestHeaders) > 0 {
encrypted, err := encryptFeedHeaders(in.RequestHeaders) encrypted, err := encryptFeedHeaders(in.RequestHeaders)
if err != nil { 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 var encryptedHeaders *string
if rawHeaders, exists := body["request_headers"]; exists { if rawHeaders, exists := body["request_headers"]; exists {
headers := map[string]string{} 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' (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 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) (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() updated_at = now()
WHERE id = $1 AND company_id = $2`, 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 { if err != nil {
return nil, err return nil, err
} }
+55 -21
View File
@@ -11,6 +11,7 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/descrybe/descrybe-v2/apps/api/internal/company"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/jackc/pgx/v5" "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) { func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUID, feed map[string]any) (syncStats, error) {
var stats syncStats 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) urlStr, _ := feed["url"].(string)
feedType, _ := feed["feed_type"].(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 { if len(mappings) == 0 {
return stats, ClientMsg("no field mappings defined for feed") 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) prev, err := s.lastSuccessfulSync(ctx, feedID)
if err != nil { if err != nil {
@@ -439,9 +448,16 @@ func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUI
return stats, nil return stats, nil
} }
type syncLocaleKey struct{}
type syncLocale struct {
code string
primary bool
}
type existingProduct struct { type existingProduct struct {
ID uuid.UUID ID uuid.UUID
MappedData []byte MappedData []byte
SourceLocalizations []byte
} }
const ( const (
@@ -450,17 +466,19 @@ const (
upsertSQLInsertSet = ` upsertSQLInsertSet = `
INSERT INTO raw_products ( INSERT INTO raw_products (
company_id, gtin, feed_id, raw_data, mapped_data, sync_job_id, 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) FROM unnest($4::text[], $5::text[], $6::text[]) AS v(gtin, raw_data, mapped_data)
ON CONFLICT (company_id, gtin) DO UPDATE SET ON CONFLICT (company_id, gtin) DO UPDATE SET
feed_id = EXCLUDED.feed_id, feed_id = EXCLUDED.feed_id,
raw_data = EXCLUDED.raw_data, raw_data = CASE WHEN $8 THEN EXCLUDED.raw_data ELSE raw_products.raw_data END,
mapped_data = EXCLUDED.mapped_data, 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, sync_job_id = EXCLUDED.sync_job_id,
is_processed = false, is_processed = CASE WHEN $8 THEN false ELSE raw_products.is_processed END,
processing_status = 'unprocessed', processing_status = CASE WHEN $8 THEN 'unprocessed' ELSE raw_products.processing_status END,
updated_at = now()` updated_at = now()`
upsertSQLTouchSet = ` upsertSQLTouchSet = `
UPDATE raw_products SET sync_job_id = $3, feed_id = $4, updated_at = now() UPDATE raw_products SET sync_job_id = $3, feed_id = $4, updated_at = now()
@@ -468,11 +486,12 @@ const (
upsertSQLUpdateSet = ` upsertSQLUpdateSet = `
UPDATE raw_products AS r SET UPDATE raw_products AS r SET
feed_id = $2, feed_id = $2,
raw_data = v.raw_data::jsonb, raw_data = CASE WHEN $8 THEN v.raw_data::jsonb ELSE r.raw_data END,
mapped_data = v.mapped_data::jsonb, 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, sync_job_id = $3,
is_processed = false, is_processed = CASE WHEN $8 THEN false ELSE r.is_processed END,
processing_status = 'unprocessed', processing_status = CASE WHEN $8 THEN 'unprocessed' ELSE r.processing_status END,
updated_at = now() updated_at = now()
FROM unnest($4::uuid[], $5::text[], $6::text[]) AS v(id, raw_data, mapped_data) 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` 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. // 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). // 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/…). // 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)) ops = make([]upsertOp, 0, len(chunk))
for _, p := range chunk { for _, p := range chunk {
rawJSON, err := json.Marshal(p.RawData) rawJSON, err := json.Marshal(p.RawData)
@@ -523,17 +542,28 @@ func classifyUpsertOps(chunk []pendingProduct, existing map[string]existingProdu
continue continue
} }
// Category (and similar extras) live outside feed mappings — keep them. // 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) plainJSON, err := json.Marshal(cleanMapped)
if err != nil { if err != nil {
skipped++ skipped++
continue continue
} }
if bytesEqualJSON(stripSyncChangesBytes(ex.MappedData), plainJSON) { if bytesEqualJSON(stripSyncChangesBytes(existingMapped), plainJSON) {
ops = append(ops, upsertOp{kind: upsertOpTouch, id: ex.ID}) ops = append(ops, upsertOp{kind: upsertOpTouch, id: ex.ID})
continue continue
} }
changes := detectMappedChanges(ex.MappedData, cleanMapped) changes := detectMappedChanges(existingMapped, cleanMapped)
withFlags := withSyncChanges(cleanMapped, changes) withFlags := withSyncChanges(cleanMapped, changes)
mappedJSON, err := json.Marshal(withFlags) mappedJSON, err := json.Marshal(withFlags)
if err != nil { if err != nil {
@@ -615,7 +645,11 @@ func (s *Service) upsertChunk(ctx context.Context, companyID, feedID, jobID uuid
return 0, 0, 0, deltas, err 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 { if len(ops) == 0 {
deltas.Skipped = skipped deltas.Skipped = skipped
return 0, 0, skipped, deltas, nil 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) mappedCol[i] = string(op.mappedJSON)
deltas.addChanges(op.changes) 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++ queued++
} }
if len(touches) > 0 { if len(touches) > 0 {
@@ -655,7 +689,7 @@ func (s *Service) upsertChunk(ctx context.Context, companyID, feedID, jobID uuid
mappedCol[i] = string(op.mappedJSON) mappedCol[i] = string(op.mappedJSON)
deltas.addChanges(op.changes) 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++ 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 // Content inserts/updates stamp raw as unprocessed — drop catalog rows so
// processed_products cannot outlive that reset (matches resetRawProducts). // processed_products cannot outlive that reset (matches resetRawProducts).
// Touches keep processing_status and must not invalidate catalog. // 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)) invalidateIDs := make([]uuid.UUID, 0, len(updates))
for _, op := range updates { for _, op := range updates {
invalidateIDs = append(invalidateIDs, op.id) invalidateIDs = append(invalidateIDs, op.id)
@@ -704,7 +738,7 @@ func (s *Service) loadExistingByGTIN(ctx context.Context, companyID uuid.UUID, g
return out, nil return out, nil
} }
rows, err := s.Pool.Query(ctx, ` 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) WHERE company_id = $1 AND gtin = ANY($2::text[])`, companyID, gtins)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -713,7 +747,7 @@ func (s *Service) loadExistingByGTIN(ctx context.Context, companyID uuid.UUID, g
for rows.Next() { for rows.Next() {
var ex existingProduct var ex existingProduct
var gtin string var gtin string
if err := rows.Scan(&ex.ID, &gtin, &ex.MappedData); err != nil { if err := rows.Scan(&ex.ID, &gtin, &ex.MappedData, &ex.SourceLocalizations); err != nil {
return nil, err return nil, err
} }
out[gtin] = ex out[gtin] = ex
@@ -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)
}
}
@@ -1,6 +1,7 @@
package httpapi package httpapi
import ( import (
"math"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
@@ -9,19 +10,19 @@ import (
) )
var editableCostFeatures = map[string]bool{ var editableCostFeatures = map[string]bool{
"product_processing": true, "title_ai": true,
"openai_token_k": true, "description_ai": true,
"seo_meta_ai": true, "seo_meta_ai": true,
"campaign_copy": true, "product_ai": true, // presence of a plan rule enables per-product pricing
} }
func (s *Server) handleAdminGetProcessingCosts(w http.ResponseWriter, r *http.Request) { func (s *Server) handleAdminGetProcessingCosts(w http.ResponseWriter, r *http.Request) {
rows, err := s.Pool.Query(r.Context(), ` 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 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 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`) ORDER BY 1, 2, 3`)
if err != nil { if err != nil {
LogAndError(w, http.StatusInternalServerError, "could not load processing costs", err) 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) out := make([]map[string]any, 0, 16)
for rows.Next() { for rows.Next() {
var scope, id, feature string var scope, id, feature string
var cost int var cost float64
if err := rows.Scan(&scope, &id, &feature, &cost); err != nil { if err := rows.Scan(&scope, &id, &feature, &cost); err != nil {
LogAndError(w, http.StatusInternalServerError, "could not scan processing costs", err) LogAndError(w, http.StatusInternalServerError, "could not scan processing costs", err)
return return
@@ -51,7 +52,7 @@ func (s *Server) handleAdminPutProcessingCost(w http.ResponseWriter, r *http.Req
Scope string `json:"scope"` Scope string `json:"scope"`
ID string `json:"id"` ID string `json:"id"`
Feature string `json:"feature"` Feature string `json:"feature"`
Cost *int `json:"cost_per_unit"` // null removes an override; cannot remove global rule Cost *float64 `json:"cost_per_unit"` // null removes an override; cannot remove global rule
} }
if err := DecodeJSON(r, &body); err != nil { if err := DecodeJSON(r, &body); err != nil {
Error(w, http.StatusBadRequest, "invalid json") 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.Scope = strings.TrimSpace(strings.ToLower(body.Scope))
body.Feature = strings.TrimSpace(body.Feature) 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") Error(w, http.StatusBadRequest, "invalid feature or credit cost")
return return
} }
@@ -101,3 +102,78 @@ func (s *Server) handleAdminPutProcessingCost(w http.ResponseWriter, r *http.Req
w.Header().Set("Cache-Control", "private, no-store") w.Header().Set("Cache-Control", "private, no-store")
JSON(w, http.StatusOK, map[string]any{"status": "ok"}) 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})
}
@@ -27,19 +27,19 @@ func (s *Server) handleBillingUsageExport(w http.ResponseWriter, r *http.Request
_ = out.Write([]string{"company_id", "range", "metric", "value", "notes"}) _ = out.Write([]string{"company_id", "range", "metric", "value", "notes"})
rows := []struct { rows := []struct {
label string label string
value int64 value float64
notes string notes string
}{ }{
{"ai_calls", usage.AICalls, "Recorded provider calls in period"}, {"ai_calls", float64(usage.AICalls), "Recorded provider calls in period"},
{"input_tokens", usage.InputTokens, "Includes cached input"}, {"input_tokens", float64(usage.InputTokens), "Includes cached input"},
{"cached_input_tokens", usage.CachedInputTokens, "Subset of input"}, {"cached_input_tokens", float64(usage.CachedInputTokens), "Subset of input"},
{"output_tokens", usage.OutputTokens, ""}, {"output_tokens", float64(usage.OutputTokens), ""},
{"products_processed", int64(usage.ProductsProcessed), "Period"}, {"products_processed", float64(usage.ProductsProcessed), "Period"},
{"credits_used_wallet", int64(usage.CreditsUsed), "All-time wallet balance, not period credits"}, {"credits_used_wallet", usage.CreditsUsed, "All-time wallet balance, not period credits"},
{"credits_remaining", int64(usage.CreditsRemaining), "Current wallet"}, {"credits_remaining", usage.CreditsRemaining, "Current wallet"},
} }
for _, v := range rows { 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() out.Flush()
} }
+30 -3
View File
@@ -15,6 +15,15 @@ import (
func (s *Server) handleListCategories(w http.ResponseWriter, r *http.Request) { func (s *Server) handleListCategories(w http.ResponseWriter, r *http.Request) {
cid, _ := CompanyIDFromContext(r.Context()) 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 max := maxPageLimit
if r.URL.Query().Get("tree") == "1" { if r.URL.Query().Get("tree") == "1" {
max = maxTreePageLimit max = maxTreePageLimit
@@ -25,7 +34,7 @@ func (s *Server) handleListCategories(w http.ResponseWriter, r *http.Request) {
Limit: limit, Limit: limit,
Offset: offset, Offset: offset,
} }
items, total, err := s.Catalog.ListCategories(r.Context(), cid, f) items, total, err := s.Catalog.ListCategories(ctx, cid, f)
if err != nil { if err != nil {
Error(w, http.StatusInternalServerError, "list failed") Error(w, http.StatusInternalServerError, "list failed")
return 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) { func (s *Server) handleGetCategory(w http.ResponseWriter, r *http.Request) {
cid, _ := CompanyIDFromContext(r.Context()) 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")) id, err := uuid.Parse(chi.URLParam(r, "id"))
if err != nil { if err != nil {
Error(w, http.StatusBadRequest, "invalid id") Error(w, http.StatusBadRequest, "invalid id")
return return
} }
item, err := s.Catalog.GetCategory(r.Context(), cid, id) item, err := s.Catalog.GetCategory(ctx, cid, id)
if err != nil { if err != nil {
Error(w, http.StatusNotFound, "not found") Error(w, http.StatusNotFound, "not found")
return 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) { func (s *Server) handleListAttributes(w http.ResponseWriter, r *http.Request) {
cid, _ := CompanyIDFromContext(r.Context()) 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) limit, offset := ParseLimitOffset(r)
f := catalog.ListFilter{ f := catalog.ListFilter{
Query: QuerySearch(r), Query: QuerySearch(r),
@@ -264,7 +291,7 @@ func (s *Server) handleListAttributes(w http.ResponseWriter, r *http.Request) {
RootsOnly: r.URL.Query().Get("roots") == "1", RootsOnly: r.URL.Query().Get("roots") == "1",
ParentKey: r.URL.Query().Get("parent_key"), 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 { if err != nil {
Error(w, http.StatusInternalServerError, "list failed") Error(w, http.StatusInternalServerError, "list failed")
return return
@@ -2,6 +2,7 @@ package httpapi
import ( import (
"encoding/json" "encoding/json"
"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/feeds"
"io" "io"
"net/http" "net/http"
@@ -200,6 +201,7 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) {
URL string `json:"url"` URL string `json:"url"`
RequestHeaders map[string]string `json:"request_headers"` RequestHeaders map[string]string `json:"request_headers"`
Format string `json:"format"` Format string `json:"format"`
Language string `json:"language"`
} }
if err := json.NewDecoder(io.LimitReader(r.Body, 64<<10)).Decode(&req); err != nil { if err := json.NewDecoder(io.LimitReader(r.Body, 64<<10)).Decode(&req); err != nil {
Error(w, http.StatusBadRequest, "invalid JSON request") 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") Error(w, http.StatusBadRequest, "url required")
return 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) source, err := feeds.DownloadImportSource(r.Context(), req.URL, req.RequestHeaders, catalogMaxUpload)
if err != nil { if err != nil {
ClientOrLog(w, http.StatusBadRequest, "could not download import URL", err, feeds.ClientError) 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 var result catalog.ImportResult
switch kind { switch kind {
case "categories": case "categories":
result, err = s.Catalog.ImportCategoriesCSV(r.Context(), cid, data) result, err = s.Catalog.ImportCategoriesCSV(ctx, cid, data)
case "attributes": case "attributes":
result, err = s.Catalog.ImportAttributesCSV(r.Context(), cid, data) result, err = s.Catalog.ImportAttributesCSV(ctx, cid, data)
case "products": case "products":
result, err = s.Catalog.ImportProductsCSV(r.Context(), cid, data, nil) result, err = s.Catalog.ImportProductsCSV(ctx, cid, data, nil)
} }
if err != nil { if err != nil {
ClientOrLog(w, http.StatusBadRequest, "import failed", err, catalog.ClientError) ClientOrLog(w, http.StatusBadRequest, "import failed", err, catalog.ClientError)
return 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 return
} }
if err := r.ParseMultipartForm(catalogMaxUpload); err != nil { if err := r.ParseMultipartForm(catalogMaxUpload); err != nil {
Error(w, http.StatusBadRequest, "invalid multipart form") Error(w, http.StatusBadRequest, "invalid multipart form")
return 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") file, header, err := r.FormFile("file")
if err != nil { if err != nil {
Error(w, http.StatusBadRequest, "file field required") Error(w, http.StatusBadRequest, "file field required")
@@ -286,12 +300,12 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) {
} }
switch kind { switch kind {
case "categories": case "categories":
result, err = s.Catalog.ImportCategoriesCSV(r.Context(), cid, input) result, err = s.Catalog.ImportCategoriesCSV(ctx, cid, input)
case "attributes": case "attributes":
result, err = s.Catalog.ImportAttributesCSV(r.Context(), cid, input) result, err = s.Catalog.ImportAttributesCSV(ctx, cid, input)
case "products": case "products":
fid := fileID fid := fileID
result, err = s.Catalog.ImportProductsCSV(r.Context(), cid, input, &fid) result, err = s.Catalog.ImportProductsCSV(ctx, cid, input, &fid)
} }
if err != nil { if err != nil {
public := "import failed" 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) 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 { func importKindFromPath(r *http.Request) string {
@@ -341,3 +355,16 @@ func importKindFromPath(r *http.Request) string {
return "" 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)
}
@@ -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)
}
}
}
@@ -9,6 +9,7 @@ import (
"strings" "strings"
"github.com/descrybe/descrybe-v2/apps/api/internal/catalog" "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/feeds"
"github.com/descrybe/descrybe-v2/apps/api/internal/processing" "github.com/descrybe/descrybe-v2/apps/api/internal/processing"
"github.com/go-chi/chi/v5" "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"` FeedType string `json:"feed_type"`
SyncIntervalMinutes int `json:"sync_interval_minutes"` SyncIntervalMinutes int `json:"sync_interval_minutes"`
RequestHeaders map[string]string `json:"request_headers"` RequestHeaders map[string]string `json:"request_headers"`
ContentLanguage string `json:"content_language"`
} }
if err := DecodeJSON(r, &body); err != nil { if err := DecodeJSON(r, &body); err != nil {
Error(w, http.StatusBadRequest, "invalid json") Error(w, http.StatusBadRequest, "invalid json")
return 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{ item, err := s.Feeds.Create(r.Context(), cid, feeds.CreateInput{
Name: body.Name, Name: body.Name,
URL: body.URL, URL: body.URL,
@@ -65,6 +71,7 @@ func (s *Server) handleCreateFeed(w http.ResponseWriter, r *http.Request) {
FeedType: body.FeedType, FeedType: body.FeedType,
SyncIntervalMinutes: body.SyncIntervalMinutes, SyncIntervalMinutes: body.SyncIntervalMinutes,
RequestHeaders: body.RequestHeaders, RequestHeaders: body.RequestHeaders,
ContentLanguage: company.NormalizeLanguage(body.ContentLanguage),
}) })
if err != nil { if err != nil {
ClientOrLog(w, http.StatusBadRequest, "could not create feed", err, feeds.ClientError) 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")) feedType := strings.TrimSpace(r.FormValue("feed_type"))
itemPath := strings.TrimSpace(r.FormValue("item_path")) itemPath := strings.TrimSpace(r.FormValue("item_path"))
interval, _ := strconv.Atoi(strings.TrimSpace(r.FormValue("sync_interval_minutes"))) 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{} headers := map[string]string{}
if raw := strings.TrimSpace(r.FormValue("request_headers")); raw != "" { if raw := strings.TrimSpace(r.FormValue("request_headers")); raw != "" {
if err := json.Unmarshal([]byte(raw), &headers); err != nil { 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, SyncIntervalMinutes: interval,
Options: options, Options: options,
RequestHeaders: headers, RequestHeaders: headers,
ContentLanguage: company.NormalizeLanguage(contentLanguage),
}) })
if err != nil { if err != nil {
ClientOrLog(w, http.StatusBadRequest, "could not create feed", err, feeds.ClientError) 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") Error(w, http.StatusBadRequest, "invalid json")
return 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) item, err := s.Feeds.Update(r.Context(), cid, id, body)
if err != nil { if err != nil {
if feeds.IsNotFound(err) { if feeds.IsNotFound(err) {
@@ -2,6 +2,7 @@ package httpapi
import ( import (
"errors" "errors"
"fmt"
"net/http" "net/http"
"strings" "strings"
@@ -41,14 +42,21 @@ func (s *Server) handleStartProcessingJob(w http.ResponseWriter, r *http.Request
} }
ids = append(ids, id) 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. // The shared handler serves session dashboard jobs and /api/v1/process.
// Public API results should be directly visible in the Processed catalog tab. // Public API results should be directly visible in the Processed catalog tab.
var jobs []processing.Job var jobs []processing.Job
var err error var err error
if strings.HasPrefix(r.URL.Path, "/api/v1/") { 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 { } 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 err != nil {
if writePlanGate(w, err) { 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) LogAndError(w, http.StatusBadRequest, "could not start processing job", err)
return return
} }
// Jobs already store the selected outputs transactionally, before enqueueing.
for _, job := range jobs { for _, job := range jobs {
if err := s.Jobs.EnqueueProcessingJob(r.Context(), job.ID); err != nil { if err := s.Jobs.EnqueueProcessingJob(r.Context(), job.ID); err != nil {
Error(w, http.StatusInternalServerError, "enqueue failed") Error(w, http.StatusInternalServerError, "enqueue failed")
+3
View File
@@ -409,6 +409,8 @@ func (s *Server) Router() http.Handler {
r.Get("/ai-costs", s.handleAdminAICosts) r.Get("/ai-costs", s.handleAdminAICosts)
r.Get("/ai-costs/export", s.handleAdminExportAICosts) r.Get("/ai-costs/export", s.handleAdminExportAICosts)
r.Get("/billing/invoices/export", s.handleAdminExportCompanyInvoices) 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.Get("/processing-costs", s.handleAdminGetProcessingCosts)
r.Put("/processing-costs", s.handleAdminPutProcessingCost) r.Put("/processing-costs", s.handleAdminPutProcessingCost)
r.Get("/ai-calls/{id}", s.handleAdminGetAICall) 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.Delete("/api-keys/{id}", s.handleRevokeAPIKey)
r.Get("/billing/credits", s.handleCreditsOverview) r.Get("/billing/credits", s.handleCreditsOverview)
r.Get("/billing/processing-costs", s.handleCompanyContentCosts)
r.Get("/billing/capabilities", s.handleGetCapabilities) r.Get("/billing/capabilities", s.handleGetCapabilities)
r.Get("/billing/usage", s.handleBillingUsage) r.Get("/billing/usage", s.handleBillingUsage)
r.Get("/billing/usage/export", s.handleBillingUsageExport) r.Get("/billing/usage/export", s.handleBillingUsageExport)
+13
View File
@@ -6,6 +6,7 @@ import (
"strings" "strings"
"github.com/descrybe/descrybe-v2/apps/api/internal/catalog" "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/feeds"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"github.com/google/uuid" "github.com/google/uuid"
@@ -68,6 +69,7 @@ func (s *Server) handleV1CreateFeed(w http.ResponseWriter, r *http.Request) {
FeedType string `json:"feed_type"` FeedType string `json:"feed_type"`
SyncIntervalMinutes int `json:"sync_interval_minutes"` SyncIntervalMinutes int `json:"sync_interval_minutes"`
SyncFrequency int `json:"sync_frequency"` // legacy hours SyncFrequency int `json:"sync_frequency"` // legacy hours
ContentLanguage string `json:"content_language"`
IsActive *bool `json:"is_active"` IsActive *bool `json:"is_active"`
} }
if err := DecodeJSON(r, &body); err != nil { if err := DecodeJSON(r, &body); err != nil {
@@ -87,6 +89,10 @@ func (s *Server) handleV1CreateFeed(w http.ResponseWriter, r *http.Request) {
return 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{ item, err := s.Feeds.Create(r.Context(), cid, feeds.CreateInput{
Name: name, Name: name,
URL: url, URL: url,
@@ -94,6 +100,7 @@ func (s *Server) handleV1CreateFeed(w http.ResponseWriter, r *http.Request) {
FeedType: body.FeedType, FeedType: body.FeedType,
SyncIntervalMinutes: body.SyncIntervalMinutes, SyncIntervalMinutes: body.SyncIntervalMinutes,
SyncFrequencyHours: body.SyncFrequency, SyncFrequencyHours: body.SyncFrequency,
ContentLanguage: company.NormalizeLanguage(body.ContentLanguage),
}) })
if err != nil { if err != nil {
if msg, ok := feeds.ClientError(err); ok { 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")) feedType := strings.TrimSpace(r.FormValue("feed_type"))
interval, _ := strconv.Atoi(strings.TrimSpace(r.FormValue("sync_interval_minutes"))) interval, _ := strconv.Atoi(strings.TrimSpace(r.FormValue("sync_interval_minutes")))
freq, _ := strconv.Atoi(strings.TrimSpace(r.FormValue("sync_frequency"))) 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") file, header, fileErr := r.FormFile("file")
var options map[string]any var options map[string]any
@@ -187,6 +199,7 @@ func (s *Server) createV1FeedFromMultipart(w http.ResponseWriter, r *http.Reques
FeedType: feedType, FeedType: feedType,
SyncIntervalMinutes: interval, SyncIntervalMinutes: interval,
SyncFrequencyHours: freq, SyncFrequencyHours: freq,
ContentLanguage: company.NormalizeLanguage(contentLanguage),
Options: options, Options: options,
}) })
if err != nil { if err != nil {
+7
View File
@@ -2136,6 +2136,12 @@ paths:
- csv - csv
- json - json
description: Source format. xml, csv or json; defaults to xml when not detected. 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: sync_interval_minutes:
type: integer type: integer
minimum: 1 minimum: 1
@@ -2156,6 +2162,7 @@ paths:
item_path: channel/item item_path: channel/item
url: https://feeds.example.com/nordic/google-merchant.xml url: https://feeds.example.com/nordic/google-merchant.xml
feed_type: xml feed_type: xml
content_language: sl
sync_interval_minutes: 60 sync_interval_minutes: 60
is_active: true is_active: true
responses: responses:
@@ -411,5 +411,10 @@ func (s *Server) assertV1ProcessGates(ctx context.Context, companyID uuid.UUID,
RequiresAI: billing.ProcessingTypeRequiresAI(processingType) || billing.ProcessingTypeIsEmailCampaignAI(processingType), RequiresAI: billing.ProcessingTypeRequiresAI(processingType) || billing.ProcessingTypeIsEmailCampaignAI(processingType),
RequiresEPREL: billing.ProcessingTypeRequiresEPREL(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) return s.Billing.AssertCanStartProcessing(ctx, companyID, batchSize, opts)
} }
+48 -16
View File
@@ -135,16 +135,26 @@ type Job struct {
// of ≤maxJobProducts so ClaimNext SKIP LOCKED workers stay parallelizable. // of ≤maxJobProducts so ClaimNext SKIP LOCKED workers stay parallelizable.
// Absolute request cap is MaxStartProducts (100k–1M scale). // 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) { 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 // StartAPIJob uses the same processing pipeline and company-scoped catalog as the
// dashboard, but completed API results do not require a dashboard approval action. // 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) { 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 == "" { if processingType == "" {
processingType = "full" processingType = "full"
} }
@@ -174,7 +184,7 @@ func (p *Pipeline) startJobWithOrigin(ctx context.Context, companyID, userID uui
} }
} }
if p.Billing != nil { 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 return nil, err
} }
} }
@@ -189,6 +199,9 @@ func (p *Pipeline) startJobWithOrigin(ctx context.Context, companyID, userID uui
firstStep = progress[0].Step firstStep = progress[0].Step
} }
if outputs == nil {
outputs = []string{}
}
chunks := chunkUUIDs(owned, perJobProductCap()) chunks := chunkUUIDs(owned, perJobProductCap())
tx, err := p.Pool.Begin(ctx) tx, err := p.Pool.Begin(ctx)
if err != nil { if err != nil {
@@ -201,9 +214,9 @@ func (p *Pipeline) startJobWithOrigin(ctx context.Context, companyID, userID uui
var jobID uuid.UUID var jobID uuid.UUID
err = tx.QueryRow(ctx, ` err = tx.QueryRow(ctx, `
INSERT INTO processing_jobs ( INSERT INTO processing_jobs (
company_id, user_id, status, total_products, processing_type, current_step, step_progress, origin 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) RETURNING id`, ) VALUES ($1, $2, 'pending', $3, $4, $5, $6::jsonb, $7, $8) RETURNING id`,
companyID, userID, len(chunk), processingType, firstStep, progressJSON, origin).Scan(&jobID) companyID, userID, len(chunk), processingType, firstStep, progressJSON, origin, outputs).Scan(&jobID)
if err != nil { if err != nil {
return nil, err 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. // 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 { if p == nil || p.Billing == nil {
return nil return nil
} }
@@ -240,6 +253,11 @@ func (p *Pipeline) assertProcessingGates(ctx context.Context, companyID uuid.UUI
RequiresAI: billing.ProcessingTypeRequiresAI(processingType) || billing.ProcessingTypeIsEmailCampaignAI(processingType), RequiresAI: billing.ProcessingTypeRequiresAI(processingType) || billing.ProcessingTypeIsEmailCampaignAI(processingType),
RequiresEPREL: billing.ProcessingTypeRequiresEPREL(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) 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) { if p.Limiter != nil && !p.Limiter.Allow(companyID) {
return Job{}, ErrRateLimited 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 return Job{}, err
} }
@@ -601,11 +619,12 @@ func (p *Pipeline) ProcessJob(ctx context.Context, jobID uuid.UUID) error {
var companyID uuid.UUID var companyID uuid.UUID
var jobUserID *uuid.UUID var jobUserID *uuid.UUID
var status, processingType, origin string var status, processingType, origin string
var selectedOutputs []string
var alreadyProcessed int var alreadyProcessed int
err := p.Pool.QueryRow(ctx, ` 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). 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 { if err != nil {
return err 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) 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 { if itemErr != nil {
failed++ failed++
if _, err := p.Pool.Exec(ctx, ` if _, err := p.Pool.Exec(ctx, `
@@ -1454,7 +1473,7 @@ func (p *Pipeline) reclaimOrphanedProcessingItems(ctx context.Context, jobID uui
return err 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 { if it == nil {
return false, 0, StepResult{}, fmt.Errorf("processing: nil job item") 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. // Debit before persisting the deliverable so insufficient credits cannot yield free AI output.
// BYOK (company key): skip managed credit burn for inference. // BYOK (company key): skip managed credit burn for inference.
// Hash-skip (ai_enhance_unchanged): skip flat product_processing debit — no LLM/rework. // Hash-skip (ai_enhance_unchanged): skip flat product_processing debit — no LLM/rework.
if p.Billing != nil && shouldDebitProductProcessing(usingBYOK, result) { billable := p.Billing != nil && shouldDebitProductProcessing(usingBYOK, result)
if err := p.Billing.ConsumeCreditsTx(ctx, tx, companyID, result.TotalTokens, "product_processing"); err != nil { 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 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) processedID, err := p.upsertProcessedProduct(ctx, tx, companyID, it.RawID, gtin, result, attrsJSON, procAttrsJSON, gptJSON, sourcesJSON, providerMode, language, origin)
@@ -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.
@@ -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;
@@ -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\]/);
});
@@ -1,15 +1,16 @@
<script lang="ts"> <script lang="ts">
import { api, failureMessage } from "$lib/api"; import { api, failureMessage } from "$lib/api";
import { notifySuccess } from "$lib/notify"; import { notifySuccess } from "$lib/notify";
import { CONTENT_LANGUAGES } from "$lib/content-languages";
let {kind,onComplete}:{kind:"categories"|"attributes"|"products";onComplete:()=>void|Promise<void>}=$props(); let {kind,onComplete}:{kind:"categories"|"attributes"|"products";onComplete:()=>void|Promise<void>}=$props();
let url=$state(""); let token=$state(""); let authMode=$state("bearer"); let headerName=$state("X-API-Key");let extra=$state("");let busy=$state(false);let error=$state(""); let language=$state(""); let url=$state(""); let token=$state(""); let authMode=$state("bearer"); let headerName=$state("X-API-Key");let extra=$state("");let busy=$state(false);let error=$state("");
async function submit(event:SubmitEvent){ async function submit(event:SubmitEvent){
event.preventDefault();busy=true;error=""; event.preventDefault();busy=true;error="";
try{ try{
const headers:Record<string,string>=extra.trim()?JSON.parse(extra):{}; const headers:Record<string,string>=extra.trim()?JSON.parse(extra):{};
if (!headers||Array.isArray(headers)||typeof headers!=="object"||Object.values(headers).some(v=>typeof v!=="string"))throw new Error("Headers must be a JSON object of strings"); if (!headers||Array.isArray(headers)||typeof headers!=="object"||Object.values(headers).some(v=>typeof v!=="string"))throw new Error("Headers must be a JSON object of strings");
if(token.trim())headers[authMode==="bearer"?"Authorization":headerName.trim()||"X-API-Key"]=authMode==="bearer"?`Bearer ${token.trim()}`:token.trim(); if(token.trim())headers[authMode==="bearer"?"Authorization":headerName.trim()||"X-API-Key"]=authMode==="bearer"?`Bearer ${token.trim()}`:token.trim();
const result=await api<{import?:{created?:number;updated?:number;skipped?:number}}>(`/api/${kind}/import`,{method:"POST",body:{url:url.trim(),format:"json",request_headers:headers}}); const result=await api<{import?:{created?:number;updated?:number;skipped?:number}}>(`/api/${kind}/import`,{method:"POST",body:{url:url.trim(),format:"json",language,request_headers:headers}});
notifySuccess(`Imported ${result.import?.created??0} new and ${result.import?.updated??0} updated ${kind}`); notifySuccess(`Imported ${result.import?.created??0} new and ${result.import?.updated??0} updated ${kind}`);
await onComplete(); await onComplete();
}catch(e){error=failureMessage(e,"JSON import failed")}finally{busy=false} }catch(e){error=failureMessage(e,"JSON import failed")}finally{busy=false}
@@ -18,6 +19,11 @@
<form class="space-y-2 rounded-md border border-border p-3" onsubmit={submit}> <form class="space-y-2 rounded-md border border-border p-3" onsubmit={submit}>
<p class="text-sm font-medium">Import {kind} from JSON URL</p> <p class="text-sm font-medium">Import {kind} from JSON URL</p>
<input class="w-full rounded-md border bg-background p-2 text-sm" type="url" required bind:value={url} placeholder="https://supplier.example/api/products?format=json" /> <input class="w-full rounded-md border bg-background p-2 text-sm" type="url" required bind:value={url} placeholder="https://supplier.example/api/products?format=json" />
<label class="block text-xs font-medium" for="remote-import-language">Import language</label>
<select id="remote-import-language" class="w-full rounded-md border bg-background p-2 text-sm" bind:value={language}>
<option value="">Company primary language (default)</option>
{#each CONTENT_LANGUAGES as lang}<option value={lang.value}>{lang.label}</option>{/each}
</select>
<select class="w-full rounded-md border bg-background p-2 text-sm" bind:value={authMode}><option value="bearer">Bearer token (optional)</option><option value="header">Custom API key header</option></select> <select class="w-full rounded-md border bg-background p-2 text-sm" bind:value={authMode}><option value="bearer">Bearer token (optional)</option><option value="header">Custom API key header</option></select>
{#if authMode==="header"}<input class="w-full rounded-md border bg-background p-2 text-sm" bind:value={headerName} placeholder="X-API-Key" />{/if} {#if authMode==="header"}<input class="w-full rounded-md border bg-background p-2 text-sm" bind:value={headerName} placeholder="X-API-Key" />{/if}
<input class="w-full rounded-md border bg-background p-2 text-sm" type="password" autocomplete="off" bind:value={token} placeholder="API key / token (optional)" /> <input class="w-full rounded-md border bg-background p-2 text-sm" type="password" autocomplete="off" bind:value={token} placeholder="API key / token (optional)" />
@@ -5,6 +5,8 @@
import ConfirmationDialog from "$lib/components/categories/formula/ConfirmationDialog.svelte"; import ConfirmationDialog from "$lib/components/categories/formula/ConfirmationDialog.svelte";
import { cn } from "$lib/utils"; import { cn } from "$lib/utils";
import { i18n } from "$lib/i18n"; import { i18n } from "$lib/i18n";
import { onMount } from "svelte";
import { api } from "$lib/api";
import { PROCESSING_OPTIONS, type ProcessingType, type ProductRow } from "./types"; import { PROCESSING_OPTIONS, type ProcessingType, type ProductRow } from "./types";
let { let {
@@ -56,15 +58,30 @@
let pendingCredits = $state(0); let pendingCredits = $state(0);
let pendingCount = $state(0); let pendingCount = $state(0);
let selectedTypes = $state<ProcessingType[]>([]); let selectedTypes = $state<ProcessingType[]>([]);
let effectiveCosts = $state<Record<ProcessingType | "product", number>>({ title: 0.10, description: 0.25, seo_meta: 0.10, product: 0.45 });
let processingMode = $state<"outputs" | "product">("outputs");
let pricingReady = $state(false);
let pricingError = $state(false);
const processProductTypes: ProcessingType[] = ["title", "description", "seo_meta"];
onMount(() => {
void api<{ mode: "outputs" | "product"; credits: Record<ProcessingType | "product", number> }>("/api/billing/processing-costs")
.then((result) => {
if (result?.credits) effectiveCosts = result.credits;
processingMode = result?.mode === "product" ? "product" : "outputs";
pricingReady = true;
})
.catch(() => { pricingError = true; });
});
const selectedAILocked = $derived( const selectedAILocked = $derived(
selectedTypes.some((t) => PROCESSING_OPTIONS.find((o) => o.type === t)?.requiresAI && !aiAllowedForType(t)) (processingMode === "product" && !processProductTypes.every(aiAllowedForType)) || selectedTypes.some((t) => PROCESSING_OPTIONS.find((o) => o.type === t)?.requiresAI && !aiAllowedForType(t))
); );
// Estimated cost only; actual AI usage is billed from provider tokens. // Estimated cost from the effective company/plan rates (per selected output).
const totalCredits = $derived( const totalCredits = $derived(processingMode === "product"
PROCESSING_OPTIONS.filter((option) => selectedTypes.includes(option.type)).reduce( ? (effectiveCosts.product ?? 0.45) * selectedCount
(sum, option) => sum + option.credits, : PROCESSING_OPTIONS.filter((option) => selectedTypes.includes(option.type)).reduce(
(sum, option) => sum + (effectiveCosts[option.type] ?? option.credits),
0 0
) * selectedCount ) * selectedCount
); );
@@ -84,8 +101,9 @@
} }
function processSelected() { function processSelected() {
if (selectedTypes.length === 0) return; if (!pricingReady || (processingMode === "outputs" && selectedTypes.length === 0)) return;
pendingTypes = [...selectedTypes]; if (selectedAILocked) return;
pendingTypes = processingMode === "product" ? [...processProductTypes] : [...selectedTypes];
pendingCredits = totalCredits; pendingCredits = totalCredits;
pendingCount = selectedCount; pendingCount = selectedCount;
open = false; open = false;
@@ -147,12 +165,15 @@
{/if} {/if}
{#if activeTab !== "processed"} {#if activeTab !== "processed"}
{#if pricingError}
<p class="text-xs text-destructive" role="alert">Unable to load processing prices. Refresh before starting a job.</p>
{/if}
<div class="relative"> <div class="relative">
<Button <Button
variant="default" variant="default"
size="sm" size="sm"
mutation mutation
disabled={selectedCount === 0 || isProcessing} disabled={selectedCount === 0 || isProcessing || !pricingReady}
loading={isProcessing} loading={isProcessing}
data-assistant-target="start-processing" data-assistant-target="start-processing"
data-tour="start-processing" data-tour="start-processing"
@@ -187,6 +208,15 @@
</div> </div>
</div> </div>
{/if} {/if}
{#if processingMode === "product"}
<div class="flex items-center justify-between gap-3 rounded-md border border-border/60 px-2 py-3">
<div>
<p class="text-sm font-semibold">Product processing</p>
<p class="text-xs text-muted-foreground">AI title, description and SEO metadata together. No individual output selection.</p>
</div>
<span class="shrink-0 font-mono text-xs">{(effectiveCosts.product ?? 0.45).toFixed(4)} credits</span>
</div>
{:else}
<button <button
type="button" type="button"
class="mb-3 flex items-center space-x-2 border-b border-border/50 pb-3" class="mb-3 flex items-center space-x-2 border-b border-border/50 pb-3"
@@ -230,12 +260,13 @@
</label> </label>
<span class="font-mono text-xs text-muted-foreground" <span class="font-mono text-xs text-muted-foreground"
>{option.requiresAI >{option.requiresAI
? i18n.t("products.actions.credits", { credits: option.credits.toFixed(2) }) ? i18n.t("products.actions.credits", { credits: (effectiveCosts[option.type] ?? option.credits).toFixed(2) })
: i18n.t("products.actions.free")}</span : i18n.t("products.actions.free")}</span
> >
</div> </div>
{/each} {/each}
</div> </div>
{/if}
</div> </div>
<div class="my-1 h-px bg-border"></div> <div class="my-1 h-px bg-border"></div>
<div class="space-y-2 p-2"> <div class="space-y-2 p-2">
@@ -252,7 +283,7 @@
size="sm" size="sm"
class="w-full" class="w-full"
mutation mutation
disabled={selectedTypes.length === 0 || isProcessing || selectedAILocked} disabled={!pricingReady || (processingMode === "outputs" && selectedTypes.length === 0) || isProcessing || selectedAILocked}
loading={isProcessing} loading={isProcessing}
onclick={processSelected} onclick={processSelected}
> >
@@ -0,0 +1,23 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import test from 'node:test';
const actions = readFileSync(fileURLToPath(new URL('./ProductProcessingActions.svelte', import.meta.url)), 'utf8');
const plan = readFileSync(fileURLToPath(new URL('../../../routes/admin/billing/+page.svelte', import.meta.url)), 'utf8');
test('per-product plan hides individual output choices', () => {
assert.match(actions, /processingMode === "product"/);
assert.match(actions, /\{#if processingMode === "product"\}[\s\S]*?\{:else\}[\s\S]*?\{#each PROCESSING_OPTIONS as option\}/);
assert.match(actions, /pendingTypes = processingMode === "product" \? \[\.\.\.processProductTypes\]/);
assert.match(actions, /effectiveCosts\.product/);
assert.match(actions, /!pricingReady/);
});
test('plan popup opts in explicitly to the one-price-per-product mode', () => {
assert.match(plan, /<option value="outputs">/);
assert.match(plan, /<option value="product">/);
assert.match(plan, /feature: "product_ai"/);
assert.match(plan, /step="0\.0001" bind:value=\{perProductPrice\}/);
assert.match(plan, /planProcessingMode === "product" \? String\(perProductPrice/);
});
@@ -170,7 +170,7 @@
let costRules = $state<CreditCostRule[]>([]); let costRules = $state<CreditCostRule[]>([]);
let priceScope = $state("company"); let priceScope = $state("company");
let priceOwner = $state(""); let priceOwner = $state("");
let priceFeature = $state("product_processing"); let priceFeature = $state("title_ai");
let priceCredits = $state("2"); let priceCredits = $state("2");
let pricingMessage = $state(""); let pricingMessage = $state("");
let pricingSaving = $state(false); let pricingSaving = $state(false);
@@ -192,8 +192,8 @@
async function saveProcessingCost() { async function saveProcessingCost() {
pricingMessage = ""; pricingMessage = "";
const creditCost = Number(priceCredits); const creditCost = Number(priceCredits);
if (!priceOwner.trim() || !Number.isInteger(creditCost) || creditCost < 1 || creditCost > 1000000) { if (!priceOwner.trim() || !Number.isFinite(creditCost) || creditCost < 0 || creditCost > 1000000 || Math.abs(creditCost * 10000 - Math.round(creditCost * 10000)) > 0.000001) {
pricingMessage = "Select a plan/company and enter a positive integer credit amount."; pricingMessage = "Select a plan/company and enter a credit amount with up to four decimal places.";
return; return;
} }
pricingSaving = true; pricingSaving = true;
@@ -399,7 +399,7 @@
{:else} {:else}
<input aria-label="Plan numeric ID" type="text" inputmode="numeric" placeholder="Plan ID" bind:value={priceOwner} class="w-28 rounded border bg-background p-2 text-sm" /> <input aria-label="Plan numeric ID" type="text" inputmode="numeric" placeholder="Plan ID" bind:value={priceOwner} class="w-28 rounded border bg-background p-2 text-sm" />
{/if} {/if}
<select aria-label="Feature" bind:value={priceFeature} class="rounded border bg-background p-2 text-sm"><option value="product_processing">Product base</option><option value="openai_token_k">Per 1K model tokens</option><option value="seo_meta_ai">SEO meta</option><option value="campaign_copy">Campaign</option></select> <select aria-label="Feature" bind:value={priceFeature} class="rounded border bg-background p-2 text-sm"><option value="title_ai">Titles (AI)</option><option value="description_ai">Descriptions (AI)</option><option value="seo_meta_ai">SEO meta title &amp; description</option></select>
<input aria-label="Credit cost" type="text" inputmode="numeric" bind:value={priceCredits} class="w-24 rounded border bg-background p-2 text-sm" /> <input aria-label="Credit cost" type="text" inputmode="numeric" bind:value={priceCredits} class="w-24 rounded border bg-background p-2 text-sm" />
<Button onclick={() => saveProcessingCost()} disabled={pricingSaving}>Save rate</Button> <Button onclick={() => saveProcessingCost()} disabled={pricingSaving}>Save rate</Button>
{#if priceScope === "company" && priceOwner.trim()} {#if priceScope === "company" && priceOwner.trim()}
+83 -16
View File
@@ -74,19 +74,39 @@
type CreditRule = { scope: string; id: string; feature: string; cost_per_unit: number }; type CreditRule = { scope: string; id: string; feature: string; cost_per_unit: number };
const creditFeatures = [ const creditFeatures = [
{ key: "product_processing", label: "AI product processing", description: "Base credits for processing a product" }, { key: "title_ai", label: "Titles (AI)", description: "Credits for generating an AI product title" },
{ key: "openai_token_k", label: "AI tokens (per 1,000)", description: "Additional token-related credits where charged" }, { key: "description_ai", label: "Descriptions (AI)", description: "Credits for generating an AI product description" },
{ key: "seo_meta_ai", label: "SEO meta generation", description: "Credits charged for SEO metadata" }, { key: "seo_meta_ai", label: "SEO meta title & description (AI)", description: "Credits for generating both SEO meta fields" }
{ key: "campaign_copy", label: "Campaign copy", description: "Credits charged for campaign content" }
] as const; ] as const;
type CreditFeature = (typeof creditFeatures)[number]["key"]; type CreditFeature = (typeof creditFeatures)[number]["key"];
type CreditForm = Record<CreditFeature, string>; type CreditForm = Record<CreditFeature | "product_ai", string>;
const emptyCreditForm = (): CreditForm => ({ const emptyCreditForm = (): CreditForm => ({
product_processing: "", openai_token_k: "", seo_meta_ai: "", campaign_copy: "" title_ai: "", description_ai: "", seo_meta_ai: "", product_ai: ""
}); });
let creditRules = $state<CreditRule[]>([]); let creditRules = $state<CreditRule[]>([]);
let creditForm = $state<CreditForm>(emptyCreditForm()); let creditForm = $state<CreditForm>(emptyCreditForm());
let creditOriginal = $state<CreditForm>(emptyCreditForm()); let creditOriginal = $state<CreditForm>(emptyCreditForm());
let planProcessingMode = $state<"outputs" | "product">("outputs");
let perProductPrice = $state<string | number>("0.45");
let euroPerCredit = $state<string | number>("");
let euroPerCreditSaving = $state(false);
async function loadEuroPerCredit() {
const result = await api<{eur_per_credit:number|null}>("/api/admin/credit-value-eur");
euroPerCredit = result.eur_per_credit == null ? "" : String(result.eur_per_credit);
}
async function saveEuroPerCredit() {
const value = String(euroPerCredit ?? "").trim();
if (!/^\d+(?:\.\d{1,6})?$/.test(value) || !Number.isFinite(Number(value)) || Number(value) > 10000) {
error = "Enter a valid EUR amount per credit (up to 6 decimal places).";
return;
}
euroPerCreditSaving = true; error = "";
try {
await api("/api/admin/credit-value-eur", {method:"PUT", body:{eur_per_credit:Number(value)}});
success = "Reference EUR value per credit saved.";
} catch(err) { error = failureMessage(err,"Unable to save credit value"); }
finally { euroPerCreditSaving = false; }
}
async function loadCreditRules() { async function loadCreditRules() {
const result = await api<{ rules: CreditRule[] }>("/api/admin/processing-costs"); const result = await api<{ rules: CreditRule[] }>("/api/admin/processing-costs");
@@ -94,17 +114,21 @@
} }
function planCredits(planId: number): CreditForm { function planCredits(planId: number): CreditForm {
const next = emptyCreditForm(); const next = emptyCreditForm();
for (const feature of creditFeatures) { for (const feature of [...creditFeatures, { key: "product_ai" as const }]) {
const match = creditRules.find(r => r.scope === "plan" && r.id === String(planId) && r.feature === feature.key); const match = creditRules.find(r => r.scope === "plan" && r.id === String(planId) && r.feature === feature.key);
if (match) next[feature.key] = String(match.cost_per_unit); if (match) next[feature.key] = String(match.cost_per_unit);
} }
return next; return next;
} }
function validatePlanCredits(): void { function validatePlanCredits(): void {
for (const feature of creditFeatures) { const selected: ReadonlyArray<{ key: CreditFeature | "product_ai"; label: string }> = planProcessingMode === "product"
const raw = String(creditForm[feature.key] ?? "").trim(); ? [{ key: "product_ai", label: "Product processing" }]
if (raw && (!/^\d+$/.test(raw) || Number(raw) < 1 || Number(raw) > 1000000)) { : creditFeatures;
throw new Error(`${feature.label}: enter 1–1,000,000 credits or leave blank to inherit`); for (const feature of selected) {
const value = feature.key === "product_ai" ? perProductPrice : creditForm[feature.key];
const raw = String(value ?? "").trim();
if ((feature.key === "product_ai" && !raw) || (raw && (!/^(?:\d+)(?:\.\d{1,4})?$/.test(raw) || !Number.isFinite(Number(raw)) || Number(raw) < 0 || Number(raw) > 1000000))) {
throw new Error(`${feature.label}: enter a decimal between 0 and 1,000,000 (up to 4 decimal places), or leave blank to inherit`);
} }
} }
} }
@@ -112,12 +136,21 @@
for (const feature of creditFeatures) { for (const feature of creditFeatures) {
const key = feature.key; const key = feature.key;
const next = String(creditForm[key] ?? "").trim(); const next = String(creditForm[key] ?? "").trim();
if (next === creditOriginal[key]) continue; if (next === String(creditOriginal[key] ?? "").trim()) continue;
await api("/api/admin/processing-costs", { await api("/api/admin/processing-costs", {
method: "PUT", method: "PUT",
body: { scope: "plan", id: String(planId), feature: key, cost_per_unit: next === "" ? null : Number(next) } body: { scope: "plan", id: String(planId), feature: key, cost_per_unit: next === "" ? null : Number(next) }
}); });
} }
// One row is both the plan's mode flag and its flat debit amount.
// Deleting it restores the existing per-output behavior immediately.
const next = planProcessingMode === "product" ? String(perProductPrice ?? "").trim() : "";
if (next !== creditOriginal.product_ai) {
await api("/api/admin/processing-costs", {
method: "PUT",
body: { scope: "plan", id: String(planId), feature: "product_ai", cost_per_unit: next === "" ? null : Number(next) }
});
}
} }
const emptyPlanForm = (): PlanFormState => ({ const emptyPlanForm = (): PlanFormState => ({
@@ -224,7 +257,7 @@
const [p, c] = await Promise.all([fetchAdminPlansList(), fetchAdminCompaniesList()]); const [p, c] = await Promise.all([fetchAdminPlansList(), fetchAdminCompaniesList()]);
plans = p; plans = p;
companies = c; companies = c;
await loadCreditRules(); await Promise.all([loadCreditRules(), loadEuroPerCredit()]);
} }
async function reload() { async function reload() {
@@ -235,6 +268,8 @@
planForm = emptyPlanForm(); planForm = emptyPlanForm();
creditForm = emptyCreditForm(); creditForm = emptyCreditForm();
creditOriginal = emptyCreditForm(); creditOriginal = emptyCreditForm();
planProcessingMode = "outputs";
perProductPrice = "0.45";
planFormOpen = true; planFormOpen = true;
} }
@@ -257,6 +292,8 @@
}; };
creditForm = planCredits(Number(plan.id)); creditForm = planCredits(Number(plan.id));
creditOriginal = { ...creditForm }; creditOriginal = { ...creditForm };
planProcessingMode = creditForm.product_ai !== "" ? "product" : "outputs";
perProductPrice = creditForm.product_ai === "" ? "0.45" : creditForm.product_ai;
planFormOpen = true; planFormOpen = true;
} }
@@ -377,6 +414,21 @@
<Alert message={error} /> <Alert message={error} />
<Alert tone="success" message={success} /> <Alert tone="success" message={success} />
<Card class="mb-4 border-border bg-card">
<CardHeader>
<CardTitle>Reference value of one credit (EUR)</CardTitle>
<CardDescription>Internal estimated value for reporting. This does not change Stripe subscription charges, credit-pack prices or existing invoices.</CardDescription>
</CardHeader>
<CardContent>
<div class="flex flex-wrap items-end gap-3">
<div class="space-y-1">
<Label for="eur-per-credit">EUR / credit</Label>
<Input id="eur-per-credit" type="number" min="0" max="10000" step="0.000001" placeholder="Not configured" bind:value={euroPerCredit} />
</div>
<Button onclick={saveEuroPerCredit} disabled={euroPerCreditSaving || String(euroPerCredit ?? "").trim() === ""}>{euroPerCreditSaving ? "Saving…" : "Save value"}</Button>
</div>
</CardContent>
</Card>
<div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-4"> <div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
<Card class="border-border bg-card"> <Card class="border-border bg-card">
<CardHeader class="flex flex-row items-center justify-between space-y-0 pb-2"> <CardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
@@ -657,18 +709,33 @@
</div> </div>
<div class="space-y-3 rounded-md border border-border p-3"> <div class="space-y-3 rounded-md border border-border p-3">
<div> <div>
<p class="text-sm font-semibold">Processing credit costs</p> <p class="text-sm font-semibold">Processing pricing</p>
<p class="text-xs text-muted-foreground">Plan-specific rules. Empty fields inherit platform defaults. Company overrides take precedence. Applies to future processing only.</p> <p class="text-xs text-muted-foreground">Choose how this plan charges for product processing. Existing plans stay on per-output pricing unless changed.</p>
</div> </div>
<div class="space-y-1">
<Label for="plan-processing-mode">Processing mode</Label>
<Select id="plan-processing-mode" bind:value={planProcessingMode}>
<option value="outputs">Choose outputs (title, description, SEO meta)</option>
<option value="product">Per product (one action, one credit price)</option>
</Select>
</div>
{#if planProcessingMode === "product"}
<div class="space-y-1">
<Label for="plan-cost-product">Credits per processed product</Label>
<Input id="plan-cost-product" type="number" min="0" max="1000000" step="0.0001" bind:value={perProductPrice} required />
<p class="text-xs text-muted-foreground">One charge per product, generating title, description and SEO metadata. Company-specific product price overrides may take precedence. Applies to future processing only.</p>
</div>
{:else}
<div class="grid gap-3 sm:grid-cols-2"> <div class="grid gap-3 sm:grid-cols-2">
{#each creditFeatures as feature (feature.key)} {#each creditFeatures as feature (feature.key)}
<div class="space-y-1"> <div class="space-y-1">
<Label for={`plan-cost-${feature.key}`}>{feature.label}</Label> <Label for={`plan-cost-${feature.key}`}>{feature.label}</Label>
<Input id={`plan-cost-${feature.key}`} type="number" min="1" max="1000000" step="1" bind:value={creditForm[feature.key]} placeholder="Inherit default" /> <Input id={`plan-cost-${feature.key}`} type="number" min="0" max="1000000" step="0.0001" bind:value={creditForm[feature.key]} placeholder="Inherit default" />
<p class="text-xs text-muted-foreground">{feature.description}</p> <p class="text-xs text-muted-foreground">{feature.description}</p>
</div> </div>
{/each} {/each}
</div> </div>
{/if}
</div> </div>
<div class="flex items-start gap-3 rounded-md border border-border p-3"> <div class="flex items-start gap-3 rounded-md border border-border p-3">
<Checkbox id="plan-custom" bind:checked={planForm.is_custom} /> <Checkbox id="plan-custom" bind:checked={planForm.is_custom} />
+12 -1
View File
@@ -1,5 +1,6 @@
<script lang="ts"> <script lang="ts">
import RemoteCatalogImport from "$lib/components/feeds/RemoteCatalogImport.svelte"; import RemoteCatalogImport from "$lib/components/feeds/RemoteCatalogImport.svelte";
import { CONTENT_LANGUAGES } from "$lib/content-languages";
import { i18n } from "$lib/i18n"; import { i18n } from "$lib/i18n";
import { onMount } from "svelte"; import { onMount } from "svelte";
import { goto } from "$app/navigation"; import { goto } from "$app/navigation";
@@ -277,7 +278,7 @@
const params = new URLSearchParams({ limit: String(limit), offset: String(offset), roots: "1" }); const params = new URLSearchParams({ limit: String(limit), offset: String(offset), roots: "1" });
if (searchQuery.trim()) params.set("q", searchQuery.trim()); if (searchQuery.trim()) params.set("q", searchQuery.trim());
const payload = await api<ListResponse<Attr> & { total?: number }>(`/api/attributes?${params}`); const payload = await api<ListResponse<Attr> & { total?: number }>(`/api/attributes?${params}${importLanguage ? `&language=${encodeURIComponent(importLanguage)}` : ""}`);
const items = unwrapList(payload); const items = unwrapList(payload);
attributes = sortItems(items); attributes = sortItems(items);
total = unwrapTotal(payload) ?? attributes.length; total = unwrapTotal(payload) ?? attributes.length;
@@ -465,6 +466,7 @@
try { try {
const form = new FormData(); const form = new FormData();
form.append("file", addFile); form.append("file", addFile);
if (importLanguage) form.append("language", importLanguage);
await api("/api/attributes/import", { method: "POST", body: form }); await api("/api/attributes/import", { method: "POST", body: form });
showAdd = false; showAdd = false;
resetAddForm(); resetAddForm();
@@ -692,6 +694,8 @@
function categoryBadges(attr: Attr): string[] { function categoryBadges(attr: Attr): string[] {
return categoryNamesByAttr[String(attr.id)] ?? []; return categoryNamesByAttr[String(attr.id)] ?? [];
} }
let importLanguage = $state("");
</script> </script>
<PageShell title={i18n.t("attributes.title")} description={i18n.t("attributes.description")}> <PageShell title={i18n.t("attributes.title")} description={i18n.t("attributes.description")}>
@@ -1077,6 +1081,13 @@
{#if canAdmin} {#if canAdmin}
<TabsContent value="bulk" class="mt-4"> <TabsContent value="bulk" class="mt-4">
<div class="flex flex-wrap items-center gap-3 text-sm">
<label for="catalog-import-language">Upload language</label>
<select id="catalog-import-language" class="rounded-md border border-border bg-background p-2" bind:value={importLanguage} onchange={() => void load()}>
<option value="">Company primary language</option>
{#each CONTENT_LANGUAGES as lang}<option value={lang.value}>{lang.label}</option>{/each}
</select>
</div>
<RemoteCatalogImport kind="attributes" onComplete={load}/> <RemoteCatalogImport kind="attributes" onComplete={load}/>
<form class="space-y-4" onsubmit={bulkImport}> <form class="space-y-4" onsubmit={bulkImport}>
<div class="grid gap-2"> <div class="grid gap-2">
+13 -2
View File
@@ -1,5 +1,6 @@
<script lang="ts"> <script lang="ts">
import RemoteCatalogImport from "$lib/components/feeds/RemoteCatalogImport.svelte"; import RemoteCatalogImport from "$lib/components/feeds/RemoteCatalogImport.svelte";
import { CONTENT_LANGUAGES } from "$lib/content-languages";
import { i18n } from "$lib/i18n"; import { i18n } from "$lib/i18n";
import { onMount } from "svelte"; import { onMount } from "svelte";
import { goto } from "$app/navigation"; import { goto } from "$app/navigation";
@@ -61,7 +62,7 @@
loading = true; loading = true;
error = ""; error = "";
try { try {
const payload = await api<ListResponse<Cat>>(`/api/categories?tree=1&limit=${TREE_LIST_LIMIT}`, { const payload = await api<ListResponse<Cat>>(`/api/categories?tree=1&limit=${TREE_LIST_LIMIT}${importLanguage ? `&language=${encodeURIComponent(importLanguage)}` : ""}`, {
signal: ac.signal signal: ac.signal
}); });
if (gen !== categoriesFetchGen) return; if (gen !== categoriesFetchGen) return;
@@ -169,11 +170,14 @@
async function onImport(file: File) { async function onImport(file: File) {
const form = new FormData(); const form = new FormData();
form.append("file", file); form.append("file", file);
if (importLanguage) form.append("language", importLanguage);
await api("/api/categories/import", { method: "POST", body: form }); await api("/api/categories/import", { method: "POST", body: form });
addOpen = false; addOpen = false;
success = i18n.t("flash.categories.csvImported"); success = i18n.t("flash.categories.csvImported");
await load(); await load();
} }
let importLanguage = $state("");
</script> </script>
<PageShell title={i18n.t("categories.title")} description={i18n.t("categories.description")}> <PageShell title={i18n.t("categories.title")} description={i18n.t("categories.description")}>
@@ -186,6 +190,13 @@
<Alert message={error} /> <Alert message={error} />
<Alert tone="success" message={success} /> <Alert tone="success" message={success} />
<div class="flex flex-wrap items-center gap-3 text-sm">
<label for="catalog-import-language">Upload language</label>
<select id="catalog-import-language" class="rounded-md border border-border bg-background p-2" bind:value={importLanguage} onchange={() => void load()}>
<option value="">Company primary language</option>
{#each CONTENT_LANGUAGES as lang}<option value={lang.value}>{lang.label}</option>{/each}
</select>
</div>
{#if canAdmin}<RemoteCatalogImport kind="categories" onComplete={load}/>{/if} {#if canAdmin}<RemoteCatalogImport kind="categories" onComplete={load}/>{/if}
{#if !loading && promptCount > 0} {#if !loading && promptCount > 0}
@@ -260,7 +271,7 @@
onToggleExpand={toggleExpand} onToggleExpand={toggleExpand}
onEdit={async (cat) => { onEdit={async (cat) => {
try { try {
selected = await api<Cat>(`/api/categories/${cat.id}`); selected = await api<Cat>(`/api/categories/${cat.id}${importLanguage ? `?language=${encodeURIComponent(importLanguage)}` : ""}`);
} catch { } catch {
selected = cat; selected = cat;
} }
+24 -1
View File
@@ -1,5 +1,6 @@
<script lang="ts"> <script lang="ts">
import { i18n } from "$lib/i18n"; import { i18n } from "$lib/i18n";
import { CONTENT_LANGUAGES } from "$lib/content-languages";
import { onMount } from "svelte"; import { onMount } from "svelte";
import { goto } from "$app/navigation"; import { goto } from "$app/navigation";
import { page } from "$app/state"; import { page } from "$app/state";
@@ -160,6 +161,7 @@
let formAuthToken = $state(""); let formAuthToken = $state("");
let formAuthHeader = $state("X-API-Key"); let formAuthHeader = $state("X-API-Key");
let formType = $state("xml"); let formType = $state("xml");
let formLanguage = $state("");
let formInterval = $state("60"); let formInterval = $state("60");
let formSource = $state<"url" | "file">("url"); let formSource = $state<"url" | "file">("url");
let formFile = $state<File | null>(null); let formFile = $state<File | null>(null);
@@ -478,6 +480,7 @@ function openAdd(source: "url" | "file" = "url") {
formUrl = ""; formUrl = "";
formType = source === "file" ? "csv" : "xml"; formType = source === "file" ? "csv" : "xml";
formInterval = "60"; formInterval = "60";
formLanguage = "";
formSource = source; formSource = source;
formFile = null; formFile = null;
if (formFileInput) formFileInput.value = ""; if (formFileInput) formFileInput.value = "";
@@ -545,6 +548,7 @@ function openAdd(source: "url" | "file" = "url") {
formName = String(feed.name ?? ""); formName = String(feed.name ?? "");
formUrl = String(feed.url ?? ""); formUrl = String(feed.url ?? "");
formType = String(feed.feed_type ?? "xml"); formType = String(feed.feed_type ?? "xml");
formLanguage = String((feed.options as Record<string, unknown> | undefined)?.content_language ?? "");
formAuthToken=""; formHeaders=""; formAuthToken=""; formHeaders="";
formInterval = String(feed.sync_interval_minutes ?? 60); formInterval = String(feed.sync_interval_minutes ?? 60);
showEdit = true; showEdit = true;
@@ -568,6 +572,7 @@ function openAdd(source: "url" | "file" = "url") {
body.append("name", formName.trim()); body.append("name", formName.trim());
body.append("feed_type", formFile?.name.toLowerCase().endsWith(".json") ? "json" : formFile?.name.toLowerCase().endsWith(".xml") ? "xml" : "csv"); body.append("feed_type", formFile?.name.toLowerCase().endsWith(".json") ? "json" : formFile?.name.toLowerCase().endsWith(".xml") ? "xml" : "csv");
body.append("sync_interval_minutes", String(parseSyncIntervalMinutes(formInterval))); body.append("sync_interval_minutes", String(parseSyncIntervalMinutes(formInterval)));
body.append("content_language", formLanguage);
body.append("file", formFile); body.append("file", formFile);
created = await api<FeedRow>("/api/feeds", { method: "POST", body }); created = await api<FeedRow>("/api/feeds", { method: "POST", body });
} else { } else {
@@ -586,6 +591,7 @@ function openAdd(source: "url" | "file" = "url") {
url, url,
feed_type: inferredType, feed_type: inferredType,
sync_interval_minutes: parseSyncIntervalMinutes(formInterval), sync_interval_minutes: parseSyncIntervalMinutes(formInterval),
content_language: formLanguage,
request_headers: requestHeaders() request_headers: requestHeaders()
} }
}); });
@@ -624,7 +630,8 @@ function openAdd(source: "url" | "file" = "url") {
const body: Record<string, unknown> = { const body: Record<string, unknown> = {
name: formName.trim(), name: formName.trim(),
feed_type: nextType, feed_type: nextType,
sync_interval_minutes: parseSyncIntervalMinutes(formInterval) sync_interval_minutes: parseSyncIntervalMinutes(formInterval),
content_language: formLanguage
}; };
if (!isFileFeed(editing)) { if (!isFileFeed(editing)) {
body.url = formUrl.trim(); body.url = formUrl.trim();
@@ -1314,6 +1321,14 @@ function openAdd(source: "url" | "file" = "url") {
</TabsContent> </TabsContent>
</Tabs> </Tabs>
<div class="space-y-1.5"> <div class="space-y-1.5">
<div class="space-y-1.5">
<Label for="add-feed-language">Feed content language</Label>
<Select id="add-feed-language" bind:value={formLanguage}>
<option value="">Company primary language</option>
{#each CONTENT_LANGUAGES as lang}<option value={lang.value}>{lang.label}</option>{/each}
</Select>
<p class="text-xs text-muted-foreground">Imported names and descriptions are saved under this language. Existing translations remain separate.</p>
</div>
<Label for="add-feed-interval">{i18n.t("feeds.field.interval")}</Label> <Label for="add-feed-interval">{i18n.t("feeds.field.interval")}</Label>
<Input <Input
id="add-feed-interval" id="add-feed-interval"
@@ -1396,6 +1411,14 @@ function openAdd(source: "url" | "file" = "url") {
{/if} {/if}
</div> </div>
<div class="space-y-1.5"> <div class="space-y-1.5">
<div class="space-y-1.5">
<Label for="edit-feed-language">Feed content language</Label>
<Select id="edit-feed-language" bind:value={formLanguage}>
<option value="">Company primary language</option>
{#each CONTENT_LANGUAGES as lang}<option value={lang.value}>{lang.label}</option>{/each}
</Select>
<p class="text-xs text-muted-foreground">Imported names and descriptions are saved under this language. Existing translations remain separate.</p>
</div>
<Label for="edit-feed-interval">{i18n.t("feeds.field.interval")}</Label> <Label for="edit-feed-interval">{i18n.t("feeds.field.interval")}</Label>
<Input <Input
id="edit-feed-interval" id="edit-feed-interval"
+9
View File
@@ -0,0 +1,9 @@
# V18 — plan content credit prices
Each plan popup now edits only Titles (AI), Descriptions (AI), and SEO meta title + description (AI). Supports fractional rates to four decimal places. Blank means inherit the platform defaults: 0.10, 0.25, 0.10 respectively. Company overrides take precedence.
Migration 053 adds fixed-point fractional credit accounting **without changing the old integer columns**, so existing credit usage remains intact. New dashboard processing jobs store selected output types and debit the summed effective per-output costs (no model-token surcharge). The backend safeguards the wallet atomically and updates current billing cycle fractional spending.
The company dashboard's `GET /api/billing/processing-costs` returns effective prices to ensure on-screen estimates use the correct assigned plan/company rules. API jobs without output lists derive the default price from processing type. BYOK and hash-unchanged paths continue skipping platform inference credits.
Legacy integer credit charges for unrelated services (e.g. campaigns) remain separate; this update does not change their pricing model. Invoice amounts must still come from Stripe, not inferred from usage credits. A complete Go 1.25 build and PostgreSQL integration run are required before production deployment.
+20
View File
@@ -0,0 +1,20 @@
# V19 – Optional flat per-product processing
- Admin > Billing > Create/Edit plan > Processing mode: **Choose outputs** (default) or **Per product**.
- Per product accepts a fractional cost with at most 4 decimal places, e.g. `0.3750` credits per product. No separate title/description/SEO choices appear for customers assigned this plan.
- Customers on this plan select products, choose **Product processing**, and see their total credits before confirmation. That action submits title + description + SEO metadata in one enhance job. The actual debit uses the same flat rate.
- Plans without a `plan_processing_costs` row with `feature_name='product_ai'` retain the three independent output costs.
- Creating a new plan and selecting Per product adds the record; switching back to Choose outputs deletes it. Legacy plans are not switched automatically.
- For plans using Per product, an optional company-level `product_ai` rate takes priority over the plan rate. It does not activate Per product mode on a plan that does not opt in.
- No database migration is required; the existing processing cost tables introduced in migration 049 and numeric precision introduced in 053 are reused. Those migrations must already be applied.
- Existing completed jobs and their charges are unchanged. Future processing (including API jobs) uses the active plan's current pricing mode. If you change a plan while jobs are pending, those jobs may use the newly configured price when debited; avoid switching plans mid-batch.
- Deploy the frontend, API, and worker together.
## Acceptance test
1. Create a new test plan; default should be Choose outputs. Verify three independent options in Product Management.
2. Edit the plan, switch to Per product, price `0.375`. Reopen the popup: mode and price should persist.
3. Assign it to a test company and refresh the customer dashboard. Verify one Product processing action, with 10 items displaying 3.75 credits.
4. Run a test job and verify one `0.375` credit debit per successfully processed product. Verify title, description, and SEO result fields.
5. Switch back to Choose outputs; verify the three options reappear and the old per-output rates are preserved.
6. Test API processing under the same plan, confirming the flat rate is used without a client-side billing bypass.
@@ -0,0 +1,65 @@
# Descrybe v20 — credit reference value and import languages
## Admin — value of one credit
Open **Admin → Billing → Reference value of one credit (EUR)**.
- `GET /api/admin/credit-value-eur` (platform administrator only) returns `eur_per_credit`, `currency`, and an explanatory note.
- `PUT /api/admin/credit-value-eur` with `{ "eur_per_credit": 0.5 }` sets a reference valuation in EUR, with up to six decimal places.
- Unconfigured returns `null`, rather than inventing a platform-wide credit price.
- This is **not a Stripe product price or an invoice charge**. Credit value depends on the monthly subscription and optional purchased credit packs. Actual invoices remain Stripe's authority. The admin setting must not be used to multiply past credit charges into legally issued invoices.
Current hardcoded one-time top-up pack prices in `apps/api/internal/billing/credit_packs.go` vary from roughly **€1.16/credit (25-credit pack)** to **€0.375/credit (8,000-credit pack)**. These are reference prices from code, not verified current Stripe prices. Updating the EUR reference rate does not update them. Plan-specific processing *debits* continue to be configured in the plan popup.
## Language-selectable imports
Supported: `en fr de es it nl pt pl cs sk hu ro bg hr sl sv da fi el et lv lt mt ga ja`.
**Dashboard**
- **Feeds → Create/Edit**: choose Feed content language for XML, CSV, or JSON source data.
- **Categories → Import CSV / JSON URL**: choose Upload language / Import language.
- **Attributes → Import CSV / JSON URL**: same.
- Product feeds sync through **Feeds**, not a separate Product Management JSON importer.
**API catalog uploads**
- `POST /api/categories/import?language=sl`
- `POST /api/attributes/import?language=hr`
- `POST /api/products/import?language=de`
For `multipart/form-data`, use `file` plus `language=sl` (query parameter or multipart field).
For JSON URL import:
```json
{
"url": "https://supplier.example/products?format=json",
"format": "json",
"language": "sl",
"request_headers": {}
}
```
Import language may be omitted to use the company's primary language. Invalid language codes return HTTP 400. Only import routes accessible to an authorized company admin/API actor can be called.
**Feed create/edit API:** set `content_language` when posting to `/api/feeds` or updating `/api/feeds/{id}`. The public `POST /api/v1/feeds` API-key endpoint also accepts `content_language` for URL and multipart sources. Existing feeds without this field retain company-primary behavior. Changing feed language causes a fresh sync instead of treating old mapping hashes as unchanged.
**Data integrity**
- Category labels/descriptions are saved in `categories.localized_fields[language]`.
- Attribute names are saved in `attributes.localized_fields[language]`.
- Raw and catalog product source translations are saved in `source_localizations[language]`.
- Primary-language columns remain compatible with older consumers. When a new item first arrives only in a non-primary language, that language's title serves as the initial fallback until primary-language data is supplied.
- For categories and attributes, GET list or category detail with `?language=sl` to display that language when present, with fallback otherwise. Full `localized_fields` maps are also returned.
- Product detail APIs expose `source_localizations`. This is **supplier source data**, separate from `localized_content` containing AI-generated output.
- No translation is performed automatically by this import feature: selecting a language labels the supplied text accurately.
## Deployment
1. Commit to the canonical Git repo, do not extract ZIP files over the production checkout.
2. Apply migration `054_catalog_import_languages.sql` using `npm run migrate` (or your existing `rb` deploy).
3. Deploy API, worker, and frontend together.
4. Test one SKU and one category in two languages before enabling scheduled imports on production catalogs.
The new migration adds JSONB fields without rewriting existing supplier content. Existing imported product records are not automatically translated or relabeled.
@@ -1,98 +1,61 @@
# JAGER × Descrybe — priprava na predstavitev in ponudbo # JAGER × Descrybe – 30-minutni sestanek
**Namen:** v približno 30 minutah pokazati, ali lahko JAGER z obstoječimi funkcijami Descrybe pridobi, uredi in pripravi podatke za približno **1.000 AI-obdelanih izdelkov na mesec**. Predstavitev ni ponudba za razvoj po meri. **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.**
## 1. Predlagan potek sestanka (30 minut) ## Potek (30 minut)
| Čas | Tema | Kaj dejansko pokažemo | | Čas | Tema | Kaj naredimo |
|---|---|---| |---|---|---|
| 0–5 min | Njihove potrebe | Seznam EAN, jeziki, število **unikatnih izdelkov** in mesečnih obdelav, želeni izvoz | | **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 | Praktični demo | GROHE: že pripravljeni CSV (izdelki, kategorije, atributi). EMOS: standardni XML, ugnezdene lastnosti. Na 5–10 izbranih EAN pokažemo surove podatke, polja in uvoz | | **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 obdelava | Preverjen primer naslova, HTML opisa in SEO meta v slovenščini; razlika med uvozom in generiranjem | | **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 | Izvoz in omejitve | CSV, XML ali JSON z razpoložljivimi polji in nastavljenimi preslikavami; kaj izvirni vir vsebuje oziroma česa ne | | **20–25 min** | Rezultat | Izvoz razpoložljivih polj v CSV/XML/JSON; pokažemo, kako lahko sami urejajo vir. |
| 25–30 min | Ponudba | Demo krediti, naročnina, enkratni strošek uvajanja, naslednji koraki | | **25–30 min** | Dogovor | Povzamemo primeren paket, ceno začetne nastavitve in podatke, ki jih še potrebujemo; dogovorimo se za naslednji korak. |
**Uvodni stavek:** »Naš cilj ni, da morate ročno preurejati dobaviteljske datoteke. Pokažimo na vaših EAN-ih, kaj Descrybe prevzame iz strukturiranih virov, kaj uredi in kaj dobite nazaj za svojo trgovino.« ## Šest vprašanj, ki jih moramo dobiti odgovorjenih
## 2. Kaj Descrybe ponuja 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?
- Samostojen ali podprt uvoz **strukturiranih CSV, XML in JSON** datotek ali dostopnih URL-jev, preslikava polj in sinhronizacija. ## Kaj potrebujemo pred začetkom
- Uvoz kategorij in atributov, ko so podatki na voljo; povezovanje z izdelki v okviru funkcij aplikacije.
- AI priprava nazivov, opisov in SEO meta polj v izbranem jeziku **ob ustreznih kreditih** in kontrola rezultata.
- Upravljanje dobaviteljskih podatkov, pregled neuspelih uvozov, prilagodljiv izvoz v **CSV/XML/JSON**, kjer izvozna konfiguracija in razpoložljiva polja to omogočajo.
- Uporaba podatkov za EU energijske oznake/EPREL, **kjer so ustrezni podatki modela preverljivo na voljo**.
**Česa ne obljubimo in ne vključujemo v standardno nastavitev:** branja ali pretvarjanja PDF-katalogov; zbiranja podatkov s spletnih strani (scraping); ročnega prepisovanja artiklov; razvoja novih konektorjev; povezave z nepodprtimi ERP sistemi; pridobivanja manjkajočih fotografij, prevodov varnostnih listin, energijskih razredov ali tehničnih listov; zagotavljanja zakonodajne skladnosti; neomejenih AI obdelav. Pri manjkajočih podatkih polja ostanejo prazna ali jih naročnik dopolni sam. - 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.
## 3. Stanje njihovih dobaviteljev ## Kaj ponujamo in česa ne
| Dobavitelj | Stanje in naslednji korak | **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.
|---|---|
| **GROHE** | Pripravljene CSV datoteke za izdelke, kategorije in atribute. Na sestanku preverimo delujoč uvoz, EAN in slovenski AI rezultat. |
| **EMOS** | XML in ugnezdene lastnosti so bili preizkušeni. Potrdimo dostop do produkcijskega URL-ja in preslikavo. |
| **Sanotechnik** | Standardni JSON. Preslikamo naziv, EAN/SKU, kategorije, slike in tehnične podatke; potrdimo na njihovem viru. |
| **KOOPMAN** | Samo če dobavitelj omogoča uporaben strukturiran vir; slike, energijski razredi in dokumenti morajo biti dobavljeni oziroma preverljivi. Brez obljube samodejne pridobitve slovenskih listov. |
| **TRBOVC** | PDF in spletna stran nista del standardne ponudbe. Vključitev samo, če dobavitelj zagotovi ustrezen CSV, XML ali JSON. |
| **Groupe SEB** | Ko prejmejo ustrezen strukturiran vir, pregledamo možnost nastavitve v obstoječem uvozniku. |
**EAN filter:** od naročnika pridobimo seznam točnih EAN-ov. V predstavitvi pokažemo izbrane izdelke in AI obdelavo samo za dogovorjene izdelke. Pred prodajo preverimo, kako obstoječi uvoz oziroma izbor prepreči nepotrebno obdelavo izdelkov zunaj seznama; ne obljubljamo razvoja dodatnega EAN filtrirnega sistema. **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.
## 4. Naročnine Descrybe — predlagani cenik v EUR ## Ponudba (predlog, brez DDV)
| Paket | EUR/mesec | Največ SKU | Št. virov | AI kreditov/mesec | Podpora na ceniku | | Možnost | Enkratna cena | Kaj je vključeno |
|---|---:|---:|---:|---:|---| |---|---:|---|
| Free | 0 € | 50 | 1 | 0 | Samostojna uporaba | | **Samostojno** | **0 €** | Naročnik sam nastavi vire po navodilih; brez vključenih ur uvajanja. |
| Starter | 49 € | 100 | 2 | 100 | E-pošta | | **Prvi vir** | **199 €** | Do 1 strukturiranega vira, osnovna preslikava, test; do 30 min uvoda, približno 1–2 delovna dneva. |
| Plus | 199 € | 400 | 3 | 400 | E-pošta | | **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. |
| Growth | 299 € | 1.200 | 5 | 1.200 | E-pošta (na ceniku označena »24h«, **ne jamčimo SLA brez pogodbe**) | | **Poslovni zagon** | **1.490 €** | Do 5 standardnih virov, uskladitev izvoznega profila; do 2 h usposabljanja, približno 5–10 delovnih dni. |
| **Business** | **499 €** | **4.000** | **8** | **4.000** | Prednostna e-poštna podpora | | **Večji standardni katalog** | **2.490 €** | Do 8 podprtih virov, več preslikav, QA; do 3 h usposabljanja, približno 2–3 tedne. |
| Scale | 999 € | 12.000 | 12 | 12.000 | Prednostna podpora in Slack |
| Enterprise | Po ponudbi | Po pogodbi | Po pogodbi | Po pogodbi | Pogodbeni SLA |
**Cene so predlog zneskov v EUR, ne menjalniška pretvorba USD; brez DDV, do potrditve novih EUR Stripe cen.** Letni obračun je ločena možnost (javno prikazan 20 % popust), vendar zneske ponudimo šele po preverjanju obračuna v EUR. **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.
**Zakaj za JAGER Business?** Približno 1.000 AI-obdelanih produktov na mesec × okvirno **2 kredita za en jezik** = približno 2.000 kreditov. Growth vsebuje 1.200 (okvirno 600 obdelav enega jezika), Business 4.000 (okvirno 2.000 obdelav). Dejanska poraba je lahko drugačna pri daljših opisih, ponavljanju, dodatnih jezikih in drugih operacijah. **Število aktivnih SKU in število mesečno obdelanih izdelkov nista isto** — oboje moramo potrditi na sestanku. **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.
**Podporne ure v naročninah:** noben javni paket nima določenega fonda svetovalnih ali nastavitvenih ur. Redna tehnična podpora aplikaciji ni isto kot ročno urejanje virov ali usposabljanje. Napis »24h« ne pomeni 24 vključenih ur dela. Enterprise SLA velja samo, če je izrecno pogodbeno dogovorjen. ## Kratki odgovori in zaključek
## 5. Enkratna nastavitev in uvajanje (predlog, brez DDV) - **»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.
| Paket uvajanja | Cena | Obseg z obstoječimi funkcijami | Vključena skupna pomoč | Predvidena izvedba | **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.«
|---|---:|---|---|---|
| Samostojno | **0 €** | Registracija, vodič, samostojna nastavitev | 0 h | Po lastnem tempu |
| Pomoč pri prvem viru | **199 €** | 1 standardni vir, osnovna preslikava, testni izdelki | do 30 min usposabljanja | 1–2 delovna dneva |
| Več virov | **649 €** | do 3 strukturirani viri, kategorije/atributi, test in izvoz | do 1 h usposabljanja | 3–5 delovnih dni |
| Poslovni zagon | **1.490 €** | do 5 strukturiranih virov, sinhronizacija in izvozni profil, do 2 jezika | do 2 h usposabljanja | 5–10 delovnih dni |
| Večji standardni katalog | **2.490 €** | do 8 podprtih strukturiranih virov, več preslikav, QA in predaja | do 3 h usposabljanja | 2–3 tedne |
**Vse ure v tabeli so enkratno usposabljanje ob uvajanju, ne mesečna podpora.** Predvideni roki tečejo od prejetja popolnih podatkov in dostopov. Brez PDF uvoza, scrapinga, razvoja po meri ali ročnega popravljanja izdelkov. Naročnina in krediti se zaračunajo ločeno. Dodatno delo se ne začne brez novega dogovora. **Po sestanku zapišemo:** potrjeni dobavitelji · EAN število · število obdelav · jeziki · zahtevana izvozna polja · odgovor odgovorne osebe · dogovorjeni naslednji korak.
**Predlog posebej za JAGER:** BREZPLAČEN kratek demo na 5–10 EAN-ih s testno dodeljenimi AI krediti (npr. 20 kreditov za približno 10 enostavnih obdelav enega jezika). Po potrditvi rezultata paket **649 € enkratno za GROHE, EMOS in Sanotechnik** (če so viri dostopni in delujejo s standardnimi preslikavami), nato **Business 499 €/mesec** za pričakovanih okoli 1.000 mesečnih obdelav. KOOPMAN in TRBOVC nista vključena, dokler ni ustreznega strukturiranega vira. Če naročnik želi pet primernih virov, uporabimo paket Poslovni zagon po 1.490 €; cene ne obljubljamo brez pregleda podatkov.
## 6. Vprašanja naročnika in kratki odgovori
**»Ali lahko sami povežemo dobavitelja?«** Da, če imajo ustrezen CSV, XML ali JSON in uporabljajo obstoječe preslikave; pri prvem viru vam lahko pomagamo s plačljivim uvajanjem.
**»Zakaj ne dobimo prevoda pri GROHE?«** Uvoz podatkov še ni AI obdelava. Preverimo izbran jezik, kategorijski prompt, AI kredite in rezultate za testni EAN; obdelane izdelke je po potrebi treba ponovno zagnati.
**»Ali Demo kaj stane?«** Brezplačen prikaz na manjšem vzorcu lahko izvedemo s posebej dodeljenimi testnimi krediti. To ni plačljiv mesečni paket in ne pomeni 1.000 brezplačnih obdelav.
**»Ali morate uvoziti vse izdelke dobavitelja?«** Za AI bomo izbrali samo vaše izdelke s seznama EAN. Obseg same sinhronizacije in shranjevanja je treba preveriti glede na razpoložljive filtre in omejitev SKU.
**»Kaj pa TRBOVC iz PDF-ja?«** Naša standardna rešitev ne pretvarja PDF-jev v produktne podatke. Potrebujemo strukturiran katalog CSV/XML/JSON dobavitelja.
**»Ali izdelate slovenske energijske listine za KOOPMAN?«** Ne. Če so model in dokumenti na voljo pri dobavitelju/EPREL, jih lahko uporabimo v okviru podprtih polj. Ne ustvarjamo ali potrjujemo neobstoječih listin.
**»Ali dobimo CSV/XML/JSON za našo trgovino?«** Da, izvozne preslikave omogočajo razpoložljiva polja. Za konkreten format pred dokončno ponudbo potrdimo vzorčni izvoz.
**»Kaj če imamo več kot 1.000 artiklov v katalogu, a jih obdelamo 1.000 mesečno?«** Paket določata **obe** omejitvi: kapaciteta aktivnih SKU in količina AI kreditov; izberemo paket, ki pokrije oboje.
**»Kaj če zmanjka kreditov?«** AI obdelave zahtevajo kreditno stanje; možen je nakup dodatnih kreditov ali višji paket v skladu s cenikom. Uvoz in upravljanje podatkov sta ločena od AI obdelav.
**»Koliko ur podpore imamo mesečno?«** V standardnih paketih ni obljubljenih svetovalnih ur. Obstaja podpora za delovanje aplikacije po razredu paketa, uvodno svetovanje pa je vključeno le v enkratni paket uvajanja.
## 7. Prodajni zaključek
> »Najprej bomo na vaših dejanskih EAN-ih pokazali celoten postopek: uvoz podatkov, slovenski naziv in opis, SEO meta ter izvoz. Ko rezultat potrdite, izberemo paket glede na vaše dejansko število artiklov in okoli 1.000 mesečnih obdelav. Začetna nastavitev ima vnaprej določen obseg in ceno. Ni skritih stroškov razvoja po meri.«
**Dogovoriti se je treba:** (1) število aktivnih EAN, (2) mesečni volumen AI in jezikov, (3) dobavitelje prve faze, (4) obvezen format izvoza, (5) termin za demo s testnimi krediti, (6) potrditev cene uvajanja in naročnine v EUR. Naročnika ne obremenjujemo z internimi tehničnimi postopki.