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

No files matched your search

@@ -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) {
var total, used int
err := s.Pool.QueryRow(ctx, `
SELECT total_credits, used_credits FROM credit_balances WHERE company_id = $1`, companyID).
SELECT total_credits, (total_credits - CEIL(GREATEST(0,total_credits-used_credits-fractional_credits_used)))::integer FROM credit_balances WHERE company_id = $1`, companyID).
Scan(&total, &used)
if errors.Is(err, pgx.ErrNoRows) {
total, used = 0, 0
+38 -21
View File
@@ -36,9 +36,9 @@ const featureGatesCacheTTL = 30 * time.Second
type CreditsOverview struct {
TotalCredits int `json:"total_credits"`
UsedCredits int `json:"used_credits"`
Remaining int `json:"remaining"`
RemainingCredits int `json:"remaining_credits"`
UsedCredits float64 `json:"used_credits"`
Remaining float64 `json:"remaining"`
RemainingCredits float64 `json:"remaining_credits"`
LowCredits bool `json:"low_credits"`
LowCreditsThreshold int `json:"low_credits_threshold"`
ProductCount int `json:"product_count"`
@@ -69,9 +69,10 @@ func (s *Service) CreditsOverview(ctx context.Context, companyID uuid.UUID, lowT
lowThreshold = 100
}
var total, used int
var fractional float64
err := s.Pool.QueryRow(ctx, `
SELECT total_credits, used_credits FROM credit_balances WHERE company_id = $1`, companyID).
Scan(&total, &used)
SELECT total_credits, used_credits, fractional_credits_used::double precision FROM credit_balances WHERE company_id = $1`, companyID).
Scan(&total, &used, &fractional)
if errors.Is(err, pgx.ErrNoRows) {
_, _ = s.Pool.Exec(ctx, `INSERT INTO credit_balances (company_id) VALUES ($1) ON CONFLICT DO NOTHING`, companyID)
total, used = 0, 0
@@ -79,10 +80,13 @@ func (s *Service) CreditsOverview(ctx context.Context, companyID uuid.UUID, lowT
return CreditsOverview{}, err
}
remaining := RemainingCreditsClamped(total, used)
remaining := float64(total-used) - fractional
if remaining < 0 {
remaining = 0
}
out := CreditsOverview{
TotalCredits: total,
UsedCredits: used,
UsedCredits: float64(used) + fractional,
Remaining: remaining,
RemainingCredits: remaining,
LowCreditsThreshold: lowThreshold,
@@ -157,7 +161,7 @@ func (s *Service) CreditsOverview(ctx context.Context, companyID uuid.UUID, lowT
planName = "Free"
featuresRaw = []byte("{}")
}
ent := ComputeEntitlements(planName, monthlyVal, remaining, isTrial)
ent := ComputeEntitlements(planName, monthlyVal, int(remaining+0.9999), isTrial)
out.CanUseAI = ent.CanUseAI
out.CanUseEPREL = ent.CanUseEPREL
out.IsFreePlan = ent.IsFreePlan
@@ -214,6 +218,9 @@ func (s *Service) AIBrandApplyAllowed(ctx context.Context, companyID uuid.UUID)
type ProcessingGateOpts struct {
// RequiresAI when true enforces can_use_ai + credit wallet (AI-only job types).
RequiresAI bool
// CreditsPerProduct is the effective per-output rate for this job.
// Zero retains legacy one-credit minimum for callers without content pricing.
CreditsPerProduct float64
// RequiresEPREL when true enforces can_use_eprel (EPREL-only job types).
RequiresEPREL bool
}
@@ -239,9 +246,15 @@ func (s *Service) AssertCanStartProcessing(ctx context.Context, companyID uuid.U
if ent.RemainingCredits < 1 {
return fmt.Errorf("%w: no credits remaining — upgrade your plan to continue AI processing", ErrInsufficientCredits)
}
if ent.RemainingCredits < batchSize {
return fmt.Errorf("%w: need at least %d credits for this batch (have %d) — upgrade or select fewer products",
ErrInsufficientCredits, batchSize, ent.RemainingCredits)
needed := float64(batchSize)
if opts.CreditsPerProduct > 0 {
needed *= opts.CreditsPerProduct
}
// The wallet debit uses precise fractional values and remains authoritative.
// The coarse entitlement is rounded up, so avoid rejecting a valid sub-credit job.
if float64(ent.RemainingCredits)+0.000001 < needed {
return fmt.Errorf("%w: need about %.2f credits for this batch (up to %d whole-credit units available)",
ErrInsufficientCredits, needed, ent.RemainingCredits)
}
}
@@ -385,7 +398,7 @@ func (s *Service) applyCreditDebit(ctx context.Context, tx pgx.Tx, companyID uui
WITH upd AS (
UPDATE credit_balances
SET used_credits = used_credits + $2, updated_at = now()
WHERE company_id = $1 AND (total_credits - used_credits) >= $2
WHERE company_id = $1 AND (total_credits - used_credits - fractional_credits_used) >= $2
RETURNING company_id
),
cyc AS (
@@ -462,7 +475,7 @@ func (s *Service) lookupCost(ctx context.Context, feature string, fallback int)
var cost int
err := s.Pool.QueryRow(ctx, `
SELECT cost_per_unit FROM processing_costs
SELECT cost_per_unit::integer FROM processing_costs
WHERE feature_name = $1 AND is_active = true`, feature).Scan(&cost)
if err != nil || cost <= 0 {
return fallback
@@ -884,7 +897,7 @@ func (s *Service) AssignPlan(ctx context.Context, companyID uuid.UUID, planID in
_, err = tx.Exec(ctx, `
INSERT INTO credit_balances (company_id, total_credits, used_credits, updated_at)
VALUES ($1, $2, 0, now())
ON CONFLICT (company_id) DO UPDATE SET total_credits = EXCLUDED.total_credits, used_credits = 0, updated_at = now()`,
ON CONFLICT (company_id) DO UPDATE SET total_credits = EXCLUDED.total_credits, used_credits = 0, fractional_credits_used = 0, updated_at = now()`,
companyID, alloc)
if err != nil {
return err
@@ -931,9 +944,9 @@ type UsageDayPoint struct {
type UsageSummary struct {
CompanyID uuid.UUID `json:"company_id"`
Range string `json:"range"`
CreditsUsed int `json:"credits_used"`
CreditsUsed float64 `json:"credits_used"`
CreditsTotal int `json:"credits_total"`
CreditsRemaining int `json:"credits_remaining"`
CreditsRemaining float64 `json:"credits_remaining"`
ProductsProcessed int `json:"products_processed"`
ProductsTotal int `json:"products_total"`
Tokens int64 `json:"tokens"`
@@ -969,17 +982,21 @@ func (s *Service) UsageSummary(ctx context.Context, companyID uuid.UUID, rangeRa
}
var total, used int
var fractional float64
err := s.Pool.QueryRow(ctx, `
SELECT total_credits, used_credits FROM credit_balances WHERE company_id = $1`, companyID).
Scan(&total, &used)
SELECT total_credits, used_credits, fractional_credits_used::double precision FROM credit_balances WHERE company_id = $1`, companyID).
Scan(&total, &used, &fractional)
if errors.Is(err, pgx.ErrNoRows) {
total, used = 0, 0
} else if err != nil {
return out, err
}
out.CreditsTotal = total
out.CreditsUsed = used
out.CreditsRemaining = RemainingCreditsClamped(total, used)
out.CreditsUsed = float64(used) + fractional
out.CreditsRemaining = float64(total-used) - fractional
if out.CreditsRemaining < 0 {
out.CreditsRemaining = 0
}
out.Notes = append(out.Notes,
"Credits are the live wallet (credit_balances). Daily credit history is not ledgered yet — range filters apply to products and tokens only.")
@@ -1250,7 +1267,7 @@ func (s *Service) claimAndRollDueCompanyPlan(ctx context.Context, rowID int64) (
_, err = tx.Exec(ctx, `
INSERT INTO credit_balances (company_id, total_credits, used_credits, updated_at)
VALUES ($1, $2, 0, now())
ON CONFLICT (company_id) DO UPDATE SET total_credits = EXCLUDED.total_credits, used_credits = 0, updated_at = now()`,
ON CONFLICT (company_id) DO UPDATE SET total_credits = EXCLUDED.total_credits, used_credits = 0, fractional_credits_used = 0, updated_at = now()`,
companyID, monthly)
if err != nil {
return false, err
+45 -26
View File
@@ -124,6 +124,7 @@ func (s *Service) flushCategoryBatch(ctx context.Context, companyID uuid.UUID, b
if len(batch) == 0 {
return nil
}
lang, primary := s.importLanguage(ctx, companyID)
byUID := make(map[string]categoryCSVRow, len(batch))
order := make([]string, 0, len(batch))
@@ -184,12 +185,15 @@ func (s *Service) flushCategoryBatch(ctx context.Context, companyID uuid.UUID, b
if len(updIDs) > 0 {
_, err = tx.Exec(ctx, `
UPDATE categories AS c SET
name = v.name,
description = CASE WHEN v.description <> '' THEN v.description ELSE c.description END,
name = CASE WHEN $5 THEN v.name ELSE c.name END,
description = CASE WHEN $5 AND v.description <> '' THEN v.description ELSE c.description END,
localized_fields = jsonb_set(COALESCE(c.localized_fields, '{}'::jsonb), ARRAY[$6::text],
COALESCE(c.localized_fields -> ($6::text), '{}'::jsonb) ||
jsonb_strip_nulls(jsonb_build_object('name', NULLIF(v.name,''), 'description',NULLIF(v.description,''))), true),
updated_at = now()
FROM unnest($2::uuid[], $3::text[], $4::text[]) AS v(id, name, description)
WHERE c.id = v.id AND c.company_id = $1`,
companyID, updIDs, updNames, updDescs)
companyID, updIDs, updNames, updDescs, primary, lang)
if err != nil {
return err
}
@@ -228,12 +232,13 @@ func (s *Service) flushCategoryBatch(ctx context.Context, companyID uuid.UUID, b
}
rows, err := tx.Query(ctx, `
INSERT INTO categories (company_id, name, unique_id, parent_unique_id, description, path, level)
SELECT $1, v.name, v.unique_id, NULLIF(v.parent_unique_id, ''), NULLIF(v.description, ''), v.path, v.level
INSERT INTO categories (company_id, name, unique_id, parent_unique_id, description, path, level, localized_fields)
SELECT $1, v.name, v.unique_id, NULLIF(v.parent_unique_id, ''), NULLIF(v.description, ''), v.path, v.level,
jsonb_build_object($8::text, jsonb_strip_nulls(jsonb_build_object('name',v.name,'description',NULLIF(v.description,''))))
FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::int[])
AS v(name, unique_id, parent_unique_id, description, path, level)
RETURNING id, unique_id, COALESCE(path, ''), level`,
companyID, insNames, insUIDs, insParents, insDescs, insPaths, insLevels)
companyID, insNames, insUIDs, insParents, insDescs, insPaths, insLevels, lang)
if err != nil {
return err
}
@@ -396,6 +401,7 @@ func (s *Service) flushAttributeBatch(ctx context.Context, companyID uuid.UUID,
if len(batch) == 0 {
return nil
}
lang, primary := s.importLanguage(ctx, companyID)
byKey := make(map[string]attributeCSVRow, len(batch))
order := make([]string, 0, len(batch))
@@ -465,12 +471,14 @@ func (s *Service) flushAttributeBatch(ctx context.Context, companyID uuid.UUID,
if len(updIDs) > 0 {
_, err = tx.Exec(ctx, `
UPDATE attributes AS a SET
name = CASE WHEN v.name <> '' THEN v.name ELSE a.name END,
name = CASE WHEN $5 AND v.name <> '' THEN v.name ELSE a.name END,
value_type = CASE WHEN v.value_type <> '' THEN v.value_type ELSE a.value_type END,
localized_fields = jsonb_set(COALESCE(a.localized_fields,'{}'::jsonb), ARRAY[$6::text],
COALESCE(a.localized_fields -> ($6::text),'{}'::jsonb) || jsonb_build_object('name',v.name), true),
updated_at = now()
FROM unnest($2::uuid[], $3::text[], $4::text[]) AS v(id, name, value_type)
WHERE a.id = v.id AND a.company_id = $1`,
companyID, updIDs, updNames, updTypes)
companyID, updIDs, updNames, updTypes, primary, lang)
if err != nil {
return err
}
@@ -479,12 +487,13 @@ func (s *Service) flushAttributeBatch(ctx context.Context, companyID uuid.UUID,
if len(insKeys) > 0 {
ct, err := tx.Exec(ctx, `
INSERT INTO attributes (company_id, attribute_key, name, value_type, unit, example, parent_key)
INSERT INTO attributes (company_id, attribute_key, name, value_type, unit, example, parent_key, localized_fields)
SELECT $1, v.attribute_key, v.name, v.value_type,
NULLIF(v.unit, ''), NULLIF(v.example, ''), NULLIF(v.parent_key, '')
NULLIF(v.unit, ''), NULLIF(v.example, ''), NULLIF(v.parent_key, ''),
jsonb_build_object($8::text, jsonb_build_object('name',v.name))
FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])
AS v(attribute_key, name, value_type, unit, example, parent_key)`,
companyID, insKeys, insNames, insTypes, insUnits, insExamples, insParents)
companyID, insKeys, insNames, insTypes, insUnits, insExamples, insParents, lang)
if err != nil {
return err
}
@@ -508,6 +517,7 @@ type productCSVRow struct {
func (s *Service) ImportProductsCSV(ctx context.Context, companyID uuid.UUID, r io.Reader, fileID *uuid.UUID) (ImportResult, error) {
res := ImportResult{}
lang, primary := s.importLanguage(ctx, companyID)
merge, err := s.MergeProductsByGTIN(ctx, companyID)
if err != nil {
return res, err
@@ -566,7 +576,7 @@ func (s *Service) ImportProductsCSV(ctx context.Context, companyID uuid.UUID, r
batch = append(batch, productCSVRow{
gtin: gtin, productID: productID, name: name, category: category,
desc: desc, status: status, rawJSON: string(rawData),
mergeable: merge && !strings.HasPrefix(gtin, "nogtin-"),
mergeable: (merge || lang != primary) && !strings.HasPrefix(gtin, "nogtin-"),
})
if len(batch) >= importCSVBatchSize {
if err := s.flushProductBatch(ctx, companyID, fileID, batch, &res); err != nil {
@@ -585,6 +595,7 @@ func (s *Service) flushProductBatch(ctx context.Context, companyID uuid.UUID, fi
if len(batch) == 0 {
return nil
}
lang, primary := s.importLanguage(ctx, companyID)
// Last row wins per GTIN so a single INSERT cannot hit the same unique key twice.
byGTIN := make(map[string]productCSVRow, len(batch))
@@ -677,13 +688,15 @@ func (s *Service) flushProductBatch(ctx context.Context, companyID uuid.UUID, fi
if len(updRawIDs) > 0 {
_, err = tx.Exec(ctx, `
UPDATE raw_products AS r SET
raw_data = v.raw_data::jsonb,
mapped_data = v.raw_data::jsonb,
raw_data = CASE WHEN $6 THEN v.raw_data::jsonb ELSE r.raw_data END,
mapped_data = CASE WHEN $6 THEN v.raw_data::jsonb ELSE r.mapped_data END,
source_localizations = jsonb_set(COALESCE(r.source_localizations,'{}'::jsonb), ARRAY[$5::text],
COALESCE(r.source_localizations -> ($5::text),'{}'::jsonb) || v.raw_data::jsonb, true),
file_id = COALESCE($3, r.file_id),
updated_at = now()
FROM unnest($2::uuid[], $4::text[]) AS v(id, raw_data)
WHERE r.id = v.id AND r.company_id = $1`,
companyID, updRawIDs, fileID, updRawJSON)
companyID, updRawIDs, fileID, updRawJSON, lang, primary)
if err != nil {
return err
}
@@ -694,12 +707,13 @@ func (s *Service) flushProductBatch(ctx context.Context, companyID uuid.UUID, fi
if len(insGTINs) > 0 {
rows, err := tx.Query(ctx, `
INSERT INTO raw_products (company_id, gtin, raw_data, mapped_data, processing_status, file_id)
SELECT $1, v.gtin, v.raw_data::jsonb, v.raw_data::jsonb, 'unprocessed', $2
INSERT INTO raw_products (company_id, gtin, raw_data, mapped_data, processing_status, file_id, source_localizations)
SELECT $1, v.gtin, v.raw_data::jsonb, v.raw_data::jsonb, 'unprocessed', $2,
jsonb_build_object($5::text, v.raw_data::jsonb)
FROM unnest($3::text[], $4::text[]) AS v(gtin, raw_data)
ON CONFLICT (company_id, gtin) DO NOTHING
RETURNING id, gtin`,
companyID, fileID, insGTINs, insJSON)
companyID, fileID, insGTINs, insJSON, lang)
if err != nil {
return err
}
@@ -803,15 +817,18 @@ func (s *Service) flushProductBatch(ctx context.Context, companyID uuid.UUID, fi
_, err = tx.Exec(ctx, `
UPDATE processed_products AS p SET
product_id = COALESCE(NULLIF(v.product_id, ''), p.product_id),
name = COALESCE(NULLIF(v.name, ''), p.name),
category = COALESCE(NULLIF(v.category, ''), p.category),
description = COALESCE(NULLIF(v.description, ''), p.description),
status = COALESCE(NULLIF(v.status, ''), p.status),
name = CASE WHEN $9 THEN COALESCE(NULLIF(v.name, ''), p.name) ELSE p.name END,
category = CASE WHEN $9 THEN COALESCE(NULLIF(v.category, ''), p.category) ELSE p.category END,
description = CASE WHEN $9 THEN COALESCE(NULLIF(v.description, ''), p.description) ELSE p.description END,
status = CASE WHEN $9 THEN COALESCE(NULLIF(v.status, ''), p.status) ELSE p.status END,
source_localizations = jsonb_set(COALESCE(p.source_localizations,'{}'::jsonb), ARRAY[$8::text],
COALESCE(p.source_localizations -> ($8::text),'{}'::jsonb) || jsonb_strip_nulls(jsonb_build_object(
'name',NULLIF(v.name,''),'category',NULLIF(v.category,''),'description',NULLIF(v.description,''))),true),
updated_at = now()
FROM unnest($2::uuid[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])
AS v(id, product_id, name, category, description, status)
WHERE p.id = v.id AND p.company_id = $1`,
companyID, updProcIDs, updPIDs, updNames, updCats, updDescs, updStatuses)
companyID, updProcIDs, updPIDs, updNames, updCats, updDescs, updStatuses, lang, primary)
if err != nil {
return err
}
@@ -820,13 +837,15 @@ func (s *Service) flushProductBatch(ctx context.Context, companyID uuid.UUID, fi
if len(insRawIDs) > 0 {
_, err = tx.Exec(ctx, `
INSERT INTO processed_products (company_id, product_id, name, category, description, status, raw_product_id)
INSERT INTO processed_products (company_id, product_id, name, category, description, status, raw_product_id, source_localizations)
SELECT $1,
NULLIF(v.product_id, ''), NULLIF(v.name, ''), NULLIF(v.category, ''),
NULLIF(v.description, ''), v.status, v.raw_product_id
NULLIF(v.description, ''), v.status, v.raw_product_id,
jsonb_build_object($8::text, jsonb_strip_nulls(jsonb_build_object(
'name', NULLIF(v.name,''), 'category',NULLIF(v.category,''), 'description',NULLIF(v.description,''))))
FROM unnest($2::uuid[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])
AS v(raw_product_id, product_id, name, category, description, status)`,
companyID, insRawIDs, insPIDs, insNames, insCats, insDescs, insStatuses)
companyID, insRawIDs, insPIDs, insNames, insCats, insDescs, insStatuses, lang)
if err != nil {
return err
}
@@ -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)
rows, err := s.Pool.Query(ctx, fmt.Sprintf(`
SELECT id, name, unique_id, parent_unique_id, path, level, position, is_active, description,
title_template, description_template,
title_template, description_template, COALESCE(localized_fields,'{}'::jsonb) AS localized_fields,
(title_template IS NOT NULL AND jsonb_typeof(title_template) = 'object'
AND COALESCE(jsonb_array_length(title_template->'elements'), 0) > 0) AS has_title_formula,
(description_template IS NOT NULL AND jsonb_typeof(description_template) = 'object'
@@ -113,12 +113,13 @@ func (s *Service) ListCategories(ctx context.Context, companyID uuid.UUID, f Lis
defer rows.Close()
items, err := scanMaps(rows, []string{
"id", "name", "unique_id", "parent_unique_id", "path", "level", "position", "is_active", "description",
"title_template", "description_template", "has_title_formula", "has_description_formula", "has_prompt",
"title_template", "description_template", "localized_fields", "has_title_formula", "has_description_formula", "has_prompt",
"created_at", "updated_at",
})
if err != nil {
return nil, 0, err
}
localizeCatalogImportNames(ctx, items)
if total, ok := exactTotalFromPage(f.Offset, f.Limit, len(items)); ok {
return items, total, nil
}
@@ -186,15 +187,16 @@ func (s *Service) GetCategory(ctx context.Context, companyID, id uuid.UUID) (map
SELECT 1 FROM jsonb_each_text(COALESCE(prompt, '{}'::jsonb)) kv
WHERE length(trim(kv.value)) > 0
)) AS has_prompt,
title_template, description_template, created_at, updated_at
title_template, description_template, COALESCE(localized_fields,'{}'::jsonb), created_at, updated_at
FROM categories WHERE id = $1 AND company_id = $2`, id, companyID)
item, err := scanMap(row, []string{
"id", "name", "unique_id", "parent_unique_id", "path", "level", "position", "is_active", "description",
"prompts", "has_prompt", "title_template", "description_template", "created_at", "updated_at",
"prompts", "has_prompt", "title_template", "description_template", "localized_fields", "created_at", "updated_at",
})
if err != nil {
return nil, err
}
localizeCatalogImportNames(ctx, []map[string]any{item})
return enrichCategoryPrompts(ctx, s.Pool, companyID, item)
}
@@ -377,8 +379,8 @@ func (s *Service) ListAttributes(ctx context.Context, companyID uuid.UUID, f Lis
args := []any{companyID}
where := []string{"a.company_id = $1"}
from := "attributes a"
selectCols := "a.id, a.attribute_key, a.name, a.value_type, a.unit, a.example, a.parent_key, a.created_at, a.updated_at"
scanCols := []string{"id", "attribute_key", "name", "value_type", "unit", "example", "parent_key", "created_at", "updated_at"}
selectCols := "a.id, a.attribute_key, a.name, a.value_type, a.unit, a.example, a.parent_key, COALESCE(a.localized_fields,'{}'::jsonb), a.created_at, a.updated_at"
scanCols := []string{"id", "attribute_key", "name", "value_type", "unit", "example", "parent_key", "localized_fields", "created_at", "updated_at"}
if f.Category != "" {
from = `attributes a
INNER JOIN category_attributes ca
@@ -417,6 +419,7 @@ func (s *Service) ListAttributes(ctx context.Context, companyID uuid.UUID, f Lis
if err != nil {
return nil, 0, err
}
localizeCatalogImportNames(ctx, items)
if total, ok := exactTotalFromPage(f.Offset, f.Limit, len(items)); ok {
return items, total, nil
}
@@ -1324,6 +1327,7 @@ func (s *Service) GetProcessedProduct(ctx context.Context, companyID, id uuid.UU
`+processedHasProcessedAttributesSQL+` AS has_processed_attributes,
`+processedHasEprelSQL+` AS has_eprel,
COALESCE(p.localized_content, '{}'::jsonb) AS localized_content,
COALESCE(r.source_localizations, '{}'::jsonb) || COALESCE(p.source_localizations, '{}'::jsonb) AS source_localizations,
p.created_at, p.updated_at
FROM processed_products p
LEFT JOIN raw_products r ON r.id = p.raw_product_id
@@ -1338,7 +1342,7 @@ func (s *Service) GetProcessedProduct(ctx context.Context, companyID, id uuid.UU
"feed_id", "feed_name", "feed_last_synced_at", "raw_updated_at",
"has_processed_name", "has_processed_description", "has_attributes", "has_processed_attributes",
"has_eprel",
"localized_content",
"localized_content", "source_localizations",
"created_at", "updated_at",
})
if err != nil {
@@ -1384,6 +1388,7 @@ func (s *Service) GetRawProduct(ctx context.Context, companyID, id uuid.UUID) (m
false AS has_processed_attributes,
`+strings.ReplaceAll(processedHasEprelSQL, "r.mapped_data", "rp.mapped_data")+` AS has_eprel,
'{}'::jsonb AS localized_content,
COALESCE(rp.source_localizations, '{}'::jsonb) AS source_localizations,
rp.created_at, rp.updated_at,
(COALESCE(NULLIF(trim(rp.mapped_data->>'name'), ''), NULLIF(trim(rp.mapped_data->>'title'), ''), '') <> '') AS has_name,
(COALESCE(NULLIF(trim(rp.mapped_data->>'description'), ''), '') <> '') AS has_description,
@@ -1399,7 +1404,7 @@ func (s *Service) GetRawProduct(ctx context.Context, companyID, id uuid.UUID) (m
"feed_id", "feed_name", "feed_last_synced_at", "raw_updated_at",
"has_processed_name", "has_processed_description", "has_attributes", "has_processed_attributes",
"has_eprel",
"localized_content",
"localized_content", "source_localizations",
"created_at", "updated_at",
"has_name", "has_description", "has_category",
"is_processed", "processing_status",
+10 -2
View File
@@ -29,6 +29,7 @@ type CreateInput struct {
SyncFrequencyHours int // legacy alias; converted to minutes when SyncIntervalMinutes unset
Options map[string]any
RequestHeaders map[string]string
ContentLanguage string
}
func (s *Service) List(ctx context.Context, companyID uuid.UUID, limit, offset int, q string) ([]map[string]any, int64, int64, int64, error) {
@@ -121,6 +122,9 @@ func (s *Service) Create(ctx context.Context, companyID uuid.UUID, in CreateInpu
if opts == nil {
opts = map[string]any{}
}
if in.ContentLanguage != "" {
opts["content_language"] = in.ContentLanguage
}
if len(in.RequestHeaders) > 0 {
encrypted, err := encryptFeedHeaders(in.RequestHeaders)
if err != nil {
@@ -336,6 +340,10 @@ func (s *Service) Update(ctx context.Context, companyID, id uuid.UUID, body map[
}
}
contentLanguage := ""
if raw, ok := body["content_language"].(string); ok {
contentLanguage = strings.ToLower(strings.TrimSpace(raw))
}
var encryptedHeaders *string
if rawHeaders, exists := body["request_headers"]; exists {
headers := map[string]string{}
@@ -364,10 +372,10 @@ func (s *Service) Update(ctx context.Context, companyID, id uuid.UUID, body map[
(CASE WHEN $8 <> '' THEN COALESCE(options, '{}'::jsonb) || jsonb_build_object('item_path', to_jsonb($8::text)) ELSE COALESCE(options, '{}'::jsonb) END) - 'request_headers_encrypted'
ELSE
(CASE WHEN $8 <> '' THEN COALESCE(options, '{}'::jsonb) || jsonb_build_object('item_path', to_jsonb($8::text)) ELSE COALESCE(options, '{}'::jsonb) END) || jsonb_build_object('request_headers_encrypted', $9::text)
END,
END || CASE WHEN $10::text <> '' THEN jsonb_build_object('content_language', $10::text) ELSE '{}'::jsonb END,
updated_at = now()
WHERE id = $1 AND company_id = $2`,
id, companyID, name, url, status, feedType, interval, strings.TrimSpace(itemPath), encryptedHeaders)
id, companyID, name, url, status, feedType, interval, strings.TrimSpace(itemPath), encryptedHeaders, contentLanguage)
if err != nil {
return nil, err
}
+57 -23
View File
@@ -11,6 +11,7 @@ import (
"strconv"
"strings"
"github.com/descrybe/descrybe-v2/apps/api/internal/company"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
@@ -268,6 +269,14 @@ func (s *Service) ListSyncJobs(ctx context.Context, companyID, feedID uuid.UUID,
func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUID, feed map[string]any) (syncStats, error) {
var stats syncStats
primaryLanguage := company.LoadLanguage(ctx, s.Pool, companyID)
feedLanguage := primaryLanguage
if opts, ok := feed["options"].(map[string]any); ok {
if code, ok := opts["content_language"].(string); ok && company.IsAllowedLanguage(code) {
feedLanguage = company.NormalizeLanguage(code)
}
}
ctx = context.WithValue(ctx, syncLocaleKey{}, syncLocale{code: feedLanguage, primary: feedLanguage == primaryLanguage})
urlStr, _ := feed["url"].(string)
feedType, _ := feed["feed_type"].(string)
@@ -291,7 +300,7 @@ func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUI
if len(mappings) == 0 {
return stats, ClientMsg("no field mappings defined for feed")
}
stats.MappingHash = sha256Hex([]byte(mustJSON(mappingsRaw)))
stats.MappingHash = sha256Hex([]byte(mustJSON(mappingsRaw) + "|language=" + feedLanguage))
prev, err := s.lastSuccessfulSync(ctx, feedID)
if err != nil {
@@ -439,9 +448,16 @@ func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUI
return stats, nil
}
type syncLocaleKey struct{}
type syncLocale struct {
code string
primary bool
}
type existingProduct struct {
ID uuid.UUID
MappedData []byte
ID uuid.UUID
MappedData []byte
SourceLocalizations []byte
}
const (
@@ -450,17 +466,19 @@ const (
upsertSQLInsertSet = `
INSERT INTO raw_products (
company_id, gtin, feed_id, raw_data, mapped_data, sync_job_id,
is_processed, processing_status, updated_at
is_processed, processing_status, updated_at, source_localizations
)
SELECT $1, v.gtin, $2, v.raw_data::jsonb, v.mapped_data::jsonb, $3, false, 'unprocessed', now()
SELECT $1, v.gtin, $2, v.raw_data::jsonb, v.mapped_data::jsonb, $3, false, 'unprocessed', now(),
jsonb_build_object($7::text, v.mapped_data::jsonb)
FROM unnest($4::text[], $5::text[], $6::text[]) AS v(gtin, raw_data, mapped_data)
ON CONFLICT (company_id, gtin) DO UPDATE SET
feed_id = EXCLUDED.feed_id,
raw_data = EXCLUDED.raw_data,
mapped_data = EXCLUDED.mapped_data,
raw_data = CASE WHEN $8 THEN EXCLUDED.raw_data ELSE raw_products.raw_data END,
mapped_data = CASE WHEN $8 THEN EXCLUDED.mapped_data ELSE raw_products.mapped_data END,
source_localizations = jsonb_set(COALESCE(raw_products.source_localizations,'{}'::jsonb),ARRAY[$7::text],EXCLUDED.mapped_data,true),
sync_job_id = EXCLUDED.sync_job_id,
is_processed = false,
processing_status = 'unprocessed',
is_processed = CASE WHEN $8 THEN false ELSE raw_products.is_processed END,
processing_status = CASE WHEN $8 THEN 'unprocessed' ELSE raw_products.processing_status END,
updated_at = now()`
upsertSQLTouchSet = `
UPDATE raw_products SET sync_job_id = $3, feed_id = $4, updated_at = now()
@@ -468,11 +486,12 @@ const (
upsertSQLUpdateSet = `
UPDATE raw_products AS r SET
feed_id = $2,
raw_data = v.raw_data::jsonb,
mapped_data = v.mapped_data::jsonb,
raw_data = CASE WHEN $8 THEN v.raw_data::jsonb ELSE r.raw_data END,
mapped_data = CASE WHEN $8 THEN v.mapped_data::jsonb ELSE r.mapped_data END,
source_localizations = jsonb_set(COALESCE(r.source_localizations,'{}'::jsonb),ARRAY[$7::text],v.mapped_data::jsonb,true),
sync_job_id = $3,
is_processed = false,
processing_status = 'unprocessed',
is_processed = CASE WHEN $8 THEN false ELSE r.is_processed END,
processing_status = CASE WHEN $8 THEN 'unprocessed' ELSE r.processing_status END,
updated_at = now()
FROM unnest($4::uuid[], $5::text[], $6::text[]) AS v(id, raw_data, mapped_data)
WHERE r.id = v.id AND r.company_id = $1`
@@ -499,7 +518,7 @@ type upsertOp struct {
// can be applied with set-based UNNEST statements (≤3) in one pgx.Batch round-trip.
// Touch keeps is_processed/processing_status when mapped_data is equal (canonical JSON).
// Updates/inserts stamp mapped_data._sync_changes for seller filters (price/stock/…).
func classifyUpsertOps(chunk []pendingProduct, existing map[string]existingProduct) (ops []upsertOp, skipped int) {
func classifyUpsertOps(chunk []pendingProduct, existing map[string]existingProduct, locale ...syncLocale) (ops []upsertOp, skipped int) {
ops = make([]upsertOp, 0, len(chunk))
for _, p := range chunk {
rawJSON, err := json.Marshal(p.RawData)
@@ -523,17 +542,28 @@ func classifyUpsertOps(chunk []pendingProduct, existing map[string]existingProdu
continue
}
// Category (and similar extras) live outside feed mappings — keep them.
cleanMapped = preserveSyncedExtras(ex.MappedData, cleanMapped)
existingMapped := ex.MappedData
if len(locale) > 0 && !locale[0].primary {
var all map[string]json.RawMessage
if json.Unmarshal(ex.SourceLocalizations, &all) == nil {
if val, exists := all[locale[0].code]; exists {
existingMapped = val
} else {
existingMapped = nil
}
}
}
cleanMapped = preserveSyncedExtras(existingMapped, cleanMapped)
plainJSON, err := json.Marshal(cleanMapped)
if err != nil {
skipped++
continue
}
if bytesEqualJSON(stripSyncChangesBytes(ex.MappedData), plainJSON) {
if bytesEqualJSON(stripSyncChangesBytes(existingMapped), plainJSON) {
ops = append(ops, upsertOp{kind: upsertOpTouch, id: ex.ID})
continue
}
changes := detectMappedChanges(ex.MappedData, cleanMapped)
changes := detectMappedChanges(existingMapped, cleanMapped)
withFlags := withSyncChanges(cleanMapped, changes)
mappedJSON, err := json.Marshal(withFlags)
if err != nil {
@@ -615,7 +645,11 @@ func (s *Service) upsertChunk(ctx context.Context, companyID, feedID, jobID uuid
return 0, 0, 0, deltas, err
}
ops, skipped := classifyUpsertOps(chunk, existing)
locale, ok := ctx.Value(syncLocaleKey{}).(syncLocale)
if !ok {
locale = syncLocale{code: company.LoadLanguage(ctx, s.Pool, companyID), primary: true}
}
ops, skipped := classifyUpsertOps(chunk, existing, locale)
if len(ops) == 0 {
deltas.Skipped = skipped
return 0, 0, skipped, deltas, nil
@@ -634,7 +668,7 @@ func (s *Service) upsertChunk(ctx context.Context, companyID, feedID, jobID uuid
mappedCol[i] = string(op.mappedJSON)
deltas.addChanges(op.changes)
}
batch.Queue(upsertSQLInsertSet, companyID, feedID, jobID, gtinCol, rawCol, mappedCol)
batch.Queue(upsertSQLInsertSet, companyID, feedID, jobID, gtinCol, rawCol, mappedCol, locale.code, locale.primary)
queued++
}
if len(touches) > 0 {
@@ -655,7 +689,7 @@ func (s *Service) upsertChunk(ctx context.Context, companyID, feedID, jobID uuid
mappedCol[i] = string(op.mappedJSON)
deltas.addChanges(op.changes)
}
batch.Queue(upsertSQLUpdateSet, companyID, feedID, jobID, ids, rawCol, mappedCol)
batch.Queue(upsertSQLUpdateSet, companyID, feedID, jobID, ids, rawCol, mappedCol, locale.code, locale.primary)
queued++
}
@@ -669,7 +703,7 @@ func (s *Service) upsertChunk(ctx context.Context, companyID, feedID, jobID uuid
// Content inserts/updates stamp raw as unprocessed — drop catalog rows so
// processed_products cannot outlive that reset (matches resetRawProducts).
// Touches keep processing_status and must not invalidate catalog.
if len(inserts) > 0 || len(updates) > 0 {
if (len(inserts) > 0 || len(updates) > 0) && locale.primary {
invalidateIDs := make([]uuid.UUID, 0, len(updates))
for _, op := range updates {
invalidateIDs = append(invalidateIDs, op.id)
@@ -704,7 +738,7 @@ func (s *Service) loadExistingByGTIN(ctx context.Context, companyID uuid.UUID, g
return out, nil
}
rows, err := s.Pool.Query(ctx, `
SELECT id, gtin, mapped_data FROM raw_products
SELECT id, gtin, mapped_data, COALESCE(source_localizations,'{}'::jsonb) FROM raw_products
WHERE company_id = $1 AND gtin = ANY($2::text[])`, companyID, gtins)
if err != nil {
return nil, err
@@ -713,7 +747,7 @@ func (s *Service) loadExistingByGTIN(ctx context.Context, companyID uuid.UUID, g
for rows.Next() {
var ex existingProduct
var gtin string
if err := rows.Scan(&ex.ID, &gtin, &ex.MappedData); err != nil {
if err := rows.Scan(&ex.ID, &gtin, &ex.MappedData, &ex.SourceLocalizations); err != nil {
return nil, err
}
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
import (
"math"
"net/http"
"strconv"
"strings"
@@ -9,19 +10,19 @@ import (
)
var editableCostFeatures = map[string]bool{
"product_processing": true,
"openai_token_k": true,
"seo_meta_ai": true,
"campaign_copy": true,
"title_ai": true,
"description_ai": true,
"seo_meta_ai": true,
"product_ai": true, // presence of a plan rule enables per-product pricing
}
func (s *Server) handleAdminGetProcessingCosts(w http.ResponseWriter, r *http.Request) {
rows, err := s.Pool.Query(r.Context(), `
SELECT 'default', '', feature_name, cost_per_unit FROM processing_costs WHERE is_active = true
SELECT 'default', '', feature_name, cost_per_unit FROM processing_costs WHERE is_active = true AND feature_name IN ('title_ai','description_ai','seo_meta_ai','product_ai')
UNION ALL
SELECT 'plan', plan_id::text, feature_name, cost_per_unit FROM plan_processing_costs
SELECT 'plan', plan_id::text, feature_name, cost_per_unit FROM plan_processing_costs WHERE feature_name IN ('title_ai','description_ai','seo_meta_ai','product_ai')
UNION ALL
SELECT 'company', company_id::text, feature_name, cost_per_unit FROM company_processing_costs
SELECT 'company', company_id::text, feature_name, cost_per_unit FROM company_processing_costs WHERE feature_name IN ('title_ai','description_ai','seo_meta_ai','product_ai')
ORDER BY 1, 2, 3`)
if err != nil {
LogAndError(w, http.StatusInternalServerError, "could not load processing costs", err)
@@ -31,7 +32,7 @@ func (s *Server) handleAdminGetProcessingCosts(w http.ResponseWriter, r *http.Re
out := make([]map[string]any, 0, 16)
for rows.Next() {
var scope, id, feature string
var cost int
var cost float64
if err := rows.Scan(&scope, &id, &feature, &cost); err != nil {
LogAndError(w, http.StatusInternalServerError, "could not scan processing costs", err)
return
@@ -48,10 +49,10 @@ func (s *Server) handleAdminGetProcessingCosts(w http.ResponseWriter, r *http.Re
func (s *Server) handleAdminPutProcessingCost(w http.ResponseWriter, r *http.Request) {
var body struct {
Scope string `json:"scope"`
ID string `json:"id"`
Feature string `json:"feature"`
Cost *int `json:"cost_per_unit"` // null removes an override; cannot remove global rule
Scope string `json:"scope"`
ID string `json:"id"`
Feature string `json:"feature"`
Cost *float64 `json:"cost_per_unit"` // null removes an override; cannot remove global rule
}
if err := DecodeJSON(r, &body); err != nil {
Error(w, http.StatusBadRequest, "invalid json")
@@ -59,7 +60,7 @@ func (s *Server) handleAdminPutProcessingCost(w http.ResponseWriter, r *http.Req
}
body.Scope = strings.TrimSpace(strings.ToLower(body.Scope))
body.Feature = strings.TrimSpace(body.Feature)
if !editableCostFeatures[body.Feature] || (body.Cost != nil && (*body.Cost < 1 || *body.Cost > 1000000)) {
if !editableCostFeatures[body.Feature] || (body.Cost != nil && (math.IsNaN(*body.Cost) || math.IsInf(*body.Cost, 0) || *body.Cost < 0 || *body.Cost > 1000000 || math.Abs(*body.Cost*10000-math.Round(*body.Cost*10000)) > 0.000001)) {
Error(w, http.StatusBadRequest, "invalid feature or credit cost")
return
}
@@ -101,3 +102,78 @@ func (s *Server) handleAdminPutProcessingCost(w http.ResponseWriter, r *http.Req
w.Header().Set("Cache-Control", "private, no-store")
JSON(w, http.StatusOK, map[string]any{"status": "ok"})
}
// handleCompanyContentCosts returns effective plan/company rates to the dashboard.
// Never disclose other companies' pricing overrides.
func (s *Server) handleCompanyContentCosts(w http.ResponseWriter, r *http.Request) {
cid, ok := CompanyIDFromContext(r.Context())
if !ok || cid == uuid.Nil {
Error(w, http.StatusUnauthorized, "unauthorized")
return
}
rates, err := s.Billing.ContentRates(r.Context(), cid)
if err != nil {
LogAndError(w, http.StatusInternalServerError, "could not load credit costs", err)
return
}
out := make(map[string]float64, len(rates))
for key, units := range rates {
out[key] = float64(units) / 10000
}
mode := "outputs"
if _, ok := rates["product"]; ok {
mode = "product"
}
w.Header().Set("Cache-Control", "private, no-store")
JSON(w, http.StatusOK, map[string]any{"mode": mode, "credits": out})
}
// Monetary credit valuation is an admin reference rate. Stripe invoices, pack
// checkout prices and historic wallet ledger values are not changed by it.
const creditValueEURSetting = "billing.reference_eur_per_credit"
func (s *Server) handleAdminCreditValueEUR(w http.ResponseWriter, r *http.Request) {
if s.PlatformSettings == nil {
Error(w, http.StatusServiceUnavailable, "platform settings unavailable")
return
}
if r.Method == http.MethodGet {
saved, ok, err := s.PlatformSettings.GetKV(r.Context(), creditValueEURSetting)
if err != nil {
LogAndError(w, http.StatusInternalServerError, "unable to load credit valuation", err)
return
}
var amount any
if ok && strings.TrimSpace(saved) != "" {
parsed, err := strconv.ParseFloat(saved, 64)
if err != nil {
LogAndError(w, http.StatusInternalServerError, "invalid stored credit valuation", err)
return
}
amount = parsed
}
w.Header().Set("Cache-Control", "private, no-store")
JSON(w, http.StatusOK, map[string]any{"eur_per_credit": amount, "currency": "EUR", "note": "Reference valuation only; actual customer charges follow Stripe invoices and purchased credit pack prices."})
return
}
if r.Method != http.MethodPut {
Error(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
var body struct {
Value *float64 `json:"eur_per_credit"`
}
if err := DecodeJSON(r, &body); err != nil {
Error(w, http.StatusBadRequest, "invalid json")
return
}
if body.Value == nil || math.IsNaN(*body.Value) || math.IsInf(*body.Value, 0) || *body.Value < 0 || *body.Value > 10000 || math.Abs(*body.Value*1000000-math.Round(*body.Value*1000000)) > 0.000001 {
Error(w, http.StatusBadRequest, "EUR per credit must be between 0 and 10000 with up to six decimals")
return
}
if err := s.PlatformSettings.SetKV(r.Context(), creditValueEURSetting, strconv.FormatFloat(*body.Value, 'f', -1, 64)); err != nil {
LogAndError(w, http.StatusInternalServerError, "unable to save credit valuation", err)
return
}
JSON(w, http.StatusOK, map[string]any{"status": "ok", "eur_per_credit": *body.Value})
}
@@ -27,19 +27,19 @@ func (s *Server) handleBillingUsageExport(w http.ResponseWriter, r *http.Request
_ = out.Write([]string{"company_id", "range", "metric", "value", "notes"})
rows := []struct {
label string
value int64
value float64
notes string
}{
{"ai_calls", usage.AICalls, "Recorded provider calls in period"},
{"input_tokens", usage.InputTokens, "Includes cached input"},
{"cached_input_tokens", usage.CachedInputTokens, "Subset of input"},
{"output_tokens", usage.OutputTokens, ""},
{"products_processed", int64(usage.ProductsProcessed), "Period"},
{"credits_used_wallet", int64(usage.CreditsUsed), "All-time wallet balance, not period credits"},
{"credits_remaining", int64(usage.CreditsRemaining), "Current wallet"},
{"ai_calls", float64(usage.AICalls), "Recorded provider calls in period"},
{"input_tokens", float64(usage.InputTokens), "Includes cached input"},
{"cached_input_tokens", float64(usage.CachedInputTokens), "Subset of input"},
{"output_tokens", float64(usage.OutputTokens), ""},
{"products_processed", float64(usage.ProductsProcessed), "Period"},
{"credits_used_wallet", usage.CreditsUsed, "All-time wallet balance, not period credits"},
{"credits_remaining", usage.CreditsRemaining, "Current wallet"},
}
for _, v := range rows {
_ = out.Write([]string{cid.String(), usage.Range, v.label, strconv.FormatInt(v.value, 10), v.notes})
_ = out.Write([]string{cid.String(), usage.Range, v.label, strconv.FormatFloat(v.value, 'f', -1, 64), v.notes})
}
out.Flush()
}
+30 -3
View File
@@ -15,6 +15,15 @@ import (
func (s *Server) handleListCategories(w http.ResponseWriter, r *http.Request) {
cid, _ := CompanyIDFromContext(r.Context())
ctx := r.Context()
if lang := strings.TrimSpace(r.URL.Query().Get("language")); lang != "" {
parsed, err := company.ParseLanguage(lang, false)
if err != nil {
Error(w, http.StatusBadRequest, "unsupported language")
return
}
ctx = catalog.WithImportLanguage(ctx, parsed)
}
max := maxPageLimit
if r.URL.Query().Get("tree") == "1" {
max = maxTreePageLimit
@@ -25,7 +34,7 @@ func (s *Server) handleListCategories(w http.ResponseWriter, r *http.Request) {
Limit: limit,
Offset: offset,
}
items, total, err := s.Catalog.ListCategories(r.Context(), cid, f)
items, total, err := s.Catalog.ListCategories(ctx, cid, f)
if err != nil {
Error(w, http.StatusInternalServerError, "list failed")
return
@@ -55,12 +64,21 @@ func (s *Server) handleCreateCategory(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleGetCategory(w http.ResponseWriter, r *http.Request) {
cid, _ := CompanyIDFromContext(r.Context())
ctx := r.Context()
if lang := strings.TrimSpace(r.URL.Query().Get("language")); lang != "" {
parsed, err := company.ParseLanguage(lang, false)
if err != nil {
Error(w, http.StatusBadRequest, "unsupported language")
return
}
ctx = catalog.WithImportLanguage(ctx, parsed)
}
id, err := uuid.Parse(chi.URLParam(r, "id"))
if err != nil {
Error(w, http.StatusBadRequest, "invalid id")
return
}
item, err := s.Catalog.GetCategory(r.Context(), cid, id)
item, err := s.Catalog.GetCategory(ctx, cid, id)
if err != nil {
Error(w, http.StatusNotFound, "not found")
return
@@ -256,6 +274,15 @@ func (s *Server) handleDeleteVariable(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleListAttributes(w http.ResponseWriter, r *http.Request) {
cid, _ := CompanyIDFromContext(r.Context())
ctx := r.Context()
if lang := strings.TrimSpace(r.URL.Query().Get("language")); lang != "" {
parsed, err := company.ParseLanguage(lang, false)
if err != nil {
Error(w, http.StatusBadRequest, "unsupported language")
return
}
ctx = catalog.WithImportLanguage(ctx, parsed)
}
limit, offset := ParseLimitOffset(r)
f := catalog.ListFilter{
Query: QuerySearch(r),
@@ -264,7 +291,7 @@ func (s *Server) handleListAttributes(w http.ResponseWriter, r *http.Request) {
RootsOnly: r.URL.Query().Get("roots") == "1",
ParentKey: r.URL.Query().Get("parent_key"),
}
items, total, err := s.Catalog.ListAttributes(r.Context(), cid, f)
items, total, err := s.Catalog.ListAttributes(ctx, cid, f)
if err != nil {
Error(w, http.StatusInternalServerError, "list failed")
return
@@ -2,6 +2,7 @@ package httpapi
import (
"encoding/json"
"github.com/descrybe/descrybe-v2/apps/api/internal/company"
"github.com/descrybe/descrybe-v2/apps/api/internal/feeds"
"io"
"net/http"
@@ -200,6 +201,7 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) {
URL string `json:"url"`
RequestHeaders map[string]string `json:"request_headers"`
Format string `json:"format"`
Language string `json:"language"`
}
if err := json.NewDecoder(io.LimitReader(r.Body, 64<<10)).Decode(&req); err != nil {
Error(w, http.StatusBadRequest, "invalid JSON request")
@@ -209,6 +211,12 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) {
Error(w, http.StatusBadRequest, "url required")
return
}
lang, err := importLanguageParam(req.Language, r.URL.Query().Get("language"), company.LoadLanguage(r.Context(), s.Pool, cid))
if err != nil {
Error(w, http.StatusBadRequest, err.Error())
return
}
ctx := catalog.WithImportLanguage(r.Context(), lang)
source, err := feeds.DownloadImportSource(r.Context(), req.URL, req.RequestHeaders, catalogMaxUpload)
if err != nil {
ClientOrLog(w, http.StatusBadRequest, "could not download import URL", err, feeds.ClientError)
@@ -226,23 +234,29 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) {
var result catalog.ImportResult
switch kind {
case "categories":
result, err = s.Catalog.ImportCategoriesCSV(r.Context(), cid, data)
result, err = s.Catalog.ImportCategoriesCSV(ctx, cid, data)
case "attributes":
result, err = s.Catalog.ImportAttributesCSV(r.Context(), cid, data)
result, err = s.Catalog.ImportAttributesCSV(ctx, cid, data)
case "products":
result, err = s.Catalog.ImportProductsCSV(r.Context(), cid, data, nil)
result, err = s.Catalog.ImportProductsCSV(ctx, cid, data, nil)
}
if err != nil {
ClientOrLog(w, http.StatusBadRequest, "import failed", err, catalog.ClientError)
return
}
JSON(w, http.StatusOK, map[string]any{"kind": kind, "import": result, "source": "url"})
JSON(w, http.StatusOK, map[string]any{"kind": kind, "import": result, "source": "url", "language": lang})
return
}
if err := r.ParseMultipartForm(catalogMaxUpload); err != nil {
Error(w, http.StatusBadRequest, "invalid multipart form")
return
}
lang, langErr := importLanguageParam(r.FormValue("language"), r.URL.Query().Get("language"), company.LoadLanguage(r.Context(), s.Pool, cid))
if langErr != nil {
Error(w, http.StatusBadRequest, langErr.Error())
return
}
ctx := catalog.WithImportLanguage(r.Context(), lang)
file, header, err := r.FormFile("file")
if err != nil {
Error(w, http.StatusBadRequest, "file field required")
@@ -286,12 +300,12 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) {
}
switch kind {
case "categories":
result, err = s.Catalog.ImportCategoriesCSV(r.Context(), cid, input)
result, err = s.Catalog.ImportCategoriesCSV(ctx, cid, input)
case "attributes":
result, err = s.Catalog.ImportAttributesCSV(r.Context(), cid, input)
result, err = s.Catalog.ImportAttributesCSV(ctx, cid, input)
case "products":
fid := fileID
result, err = s.Catalog.ImportProductsCSV(r.Context(), cid, input, &fid)
result, err = s.Catalog.ImportProductsCSV(ctx, cid, input, &fid)
}
if err != nil {
public := "import failed"
@@ -317,7 +331,7 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) {
}
}
meta, _ = s.Catalog.UpdateFileStatus(r.Context(), cid, fileID, "completed", importMeta)
JSON(w, http.StatusOK, map[string]any{"file": meta, "import": result, "kind": kind})
JSON(w, http.StatusOK, map[string]any{"file": meta, "import": result, "kind": kind, "language": lang})
}
func importKindFromPath(r *http.Request) string {
@@ -341,3 +355,16 @@ func importKindFromPath(r *http.Request) string {
return ""
}
}
// importLanguageParam accepts explicit dashboard/API language, otherwise uses the
// company primary language. Never silently import to an unsupported locale.
func importLanguageParam(body, query, primary string) (string, error) {
requested := strings.TrimSpace(body)
if requested == "" {
requested = strings.TrimSpace(query)
}
if requested == "" {
requested = primary
}
return company.ParseLanguage(requested, false)
}
@@ -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"
"github.com/descrybe/descrybe-v2/apps/api/internal/catalog"
"github.com/descrybe/descrybe-v2/apps/api/internal/company"
"github.com/descrybe/descrybe-v2/apps/api/internal/feeds"
"github.com/descrybe/descrybe-v2/apps/api/internal/processing"
"github.com/go-chi/chi/v5"
@@ -53,11 +54,16 @@ func (s *Server) handleCreateFeed(w http.ResponseWriter, r *http.Request) {
FeedType string `json:"feed_type"`
SyncIntervalMinutes int `json:"sync_interval_minutes"`
RequestHeaders map[string]string `json:"request_headers"`
ContentLanguage string `json:"content_language"`
}
if err := DecodeJSON(r, &body); err != nil {
Error(w, http.StatusBadRequest, "invalid json")
return
}
if body.ContentLanguage != "" && !company.IsAllowedLanguage(body.ContentLanguage) {
Error(w, http.StatusBadRequest, "unsupported content language")
return
}
item, err := s.Feeds.Create(r.Context(), cid, feeds.CreateInput{
Name: body.Name,
URL: body.URL,
@@ -65,6 +71,7 @@ func (s *Server) handleCreateFeed(w http.ResponseWriter, r *http.Request) {
FeedType: body.FeedType,
SyncIntervalMinutes: body.SyncIntervalMinutes,
RequestHeaders: body.RequestHeaders,
ContentLanguage: company.NormalizeLanguage(body.ContentLanguage),
})
if err != nil {
ClientOrLog(w, http.StatusBadRequest, "could not create feed", err, feeds.ClientError)
@@ -84,6 +91,11 @@ func (s *Server) createFeedFromMultipart(w http.ResponseWriter, r *http.Request,
feedType := strings.TrimSpace(r.FormValue("feed_type"))
itemPath := strings.TrimSpace(r.FormValue("item_path"))
interval, _ := strconv.Atoi(strings.TrimSpace(r.FormValue("sync_interval_minutes")))
contentLanguage := strings.TrimSpace(r.FormValue("content_language"))
if contentLanguage != "" && !company.IsAllowedLanguage(contentLanguage) {
Error(w, http.StatusBadRequest, "unsupported content language")
return
}
headers := map[string]string{}
if raw := strings.TrimSpace(r.FormValue("request_headers")); raw != "" {
if err := json.Unmarshal([]byte(raw), &headers); err != nil {
@@ -147,6 +159,7 @@ func (s *Server) createFeedFromMultipart(w http.ResponseWriter, r *http.Request,
SyncIntervalMinutes: interval,
Options: options,
RequestHeaders: headers,
ContentLanguage: company.NormalizeLanguage(contentLanguage),
})
if err != nil {
ClientOrLog(w, http.StatusBadRequest, "could not create feed", err, feeds.ClientError)
@@ -186,6 +199,13 @@ func (s *Server) handleUpdateFeed(w http.ResponseWriter, r *http.Request) {
Error(w, http.StatusBadRequest, "invalid json")
return
}
if raw, exists := body["content_language"]; exists {
code, ok := raw.(string)
if !ok || (code != "" && !company.IsAllowedLanguage(code)) {
Error(w, http.StatusBadRequest, "unsupported content language")
return
}
}
item, err := s.Feeds.Update(r.Context(), cid, id, body)
if err != nil {
if feeds.IsNotFound(err) {
@@ -2,6 +2,7 @@ package httpapi
import (
"errors"
"fmt"
"net/http"
"strings"
@@ -41,14 +42,21 @@ func (s *Server) handleStartProcessingJob(w http.ResponseWriter, r *http.Request
}
ids = append(ids, id)
}
// Do not schedule jobs with unknown outputs (or create orphaned jobs).
for _, requested := range body.ProcessingTypes {
if requested != "title" && requested != "description" && requested != "seo_meta" {
Error(w, http.StatusBadRequest, fmt.Sprintf("unsupported processing output: %s", requested))
return
}
}
// The shared handler serves session dashboard jobs and /api/v1/process.
// Public API results should be directly visible in the Processed catalog tab.
var jobs []processing.Job
var err error
if strings.HasPrefix(r.URL.Path, "/api/v1/") {
jobs, err = s.Processing.StartAPIJob(r.Context(), cid, uid, ids, body.ProcessingType)
jobs, err = s.Processing.StartAPIJobWithTypes(r.Context(), cid, uid, ids, body.ProcessingType, body.ProcessingTypes)
} else {
jobs, err = s.Processing.StartJob(r.Context(), cid, uid, ids, body.ProcessingType)
jobs, err = s.Processing.StartJobWithTypes(r.Context(), cid, uid, ids, body.ProcessingType, body.ProcessingTypes)
}
if err != nil {
if writePlanGate(w, err) {
@@ -65,6 +73,7 @@ func (s *Server) handleStartProcessingJob(w http.ResponseWriter, r *http.Request
LogAndError(w, http.StatusBadRequest, "could not start processing job", err)
return
}
// Jobs already store the selected outputs transactionally, before enqueueing.
for _, job := range jobs {
if err := s.Jobs.EnqueueProcessingJob(r.Context(), job.ID); err != nil {
Error(w, http.StatusInternalServerError, "enqueue failed")
+3
View File
@@ -409,6 +409,8 @@ func (s *Server) Router() http.Handler {
r.Get("/ai-costs", s.handleAdminAICosts)
r.Get("/ai-costs/export", s.handleAdminExportAICosts)
r.Get("/billing/invoices/export", s.handleAdminExportCompanyInvoices)
r.Get("/credit-value-eur", s.handleAdminCreditValueEUR)
r.Put("/credit-value-eur", s.handleAdminCreditValueEUR)
r.Get("/processing-costs", s.handleAdminGetProcessingCosts)
r.Put("/processing-costs", s.handleAdminPutProcessingCost)
r.Get("/ai-calls/{id}", s.handleAdminGetAICall)
@@ -478,6 +480,7 @@ func (s *Server) Router() http.Handler {
r.Delete("/api-keys/{id}", s.handleRevokeAPIKey)
r.Get("/billing/credits", s.handleCreditsOverview)
r.Get("/billing/processing-costs", s.handleCompanyContentCosts)
r.Get("/billing/capabilities", s.handleGetCapabilities)
r.Get("/billing/usage", s.handleBillingUsage)
r.Get("/billing/usage/export", s.handleBillingUsageExport)
+13
View File
@@ -6,6 +6,7 @@ import (
"strings"
"github.com/descrybe/descrybe-v2/apps/api/internal/catalog"
"github.com/descrybe/descrybe-v2/apps/api/internal/company"
"github.com/descrybe/descrybe-v2/apps/api/internal/feeds"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
@@ -68,6 +69,7 @@ func (s *Server) handleV1CreateFeed(w http.ResponseWriter, r *http.Request) {
FeedType string `json:"feed_type"`
SyncIntervalMinutes int `json:"sync_interval_minutes"`
SyncFrequency int `json:"sync_frequency"` // legacy hours
ContentLanguage string `json:"content_language"`
IsActive *bool `json:"is_active"`
}
if err := DecodeJSON(r, &body); err != nil {
@@ -87,6 +89,10 @@ func (s *Server) handleV1CreateFeed(w http.ResponseWriter, r *http.Request) {
return
}
if body.ContentLanguage != "" && !company.IsAllowedLanguage(body.ContentLanguage) {
v1Err(w, http.StatusBadRequest, "validation_error", "unsupported content language")
return
}
item, err := s.Feeds.Create(r.Context(), cid, feeds.CreateInput{
Name: name,
URL: url,
@@ -94,6 +100,7 @@ func (s *Server) handleV1CreateFeed(w http.ResponseWriter, r *http.Request) {
FeedType: body.FeedType,
SyncIntervalMinutes: body.SyncIntervalMinutes,
SyncFrequencyHours: body.SyncFrequency,
ContentLanguage: company.NormalizeLanguage(body.ContentLanguage),
})
if err != nil {
if msg, ok := feeds.ClientError(err); ok {
@@ -126,6 +133,11 @@ func (s *Server) createV1FeedFromMultipart(w http.ResponseWriter, r *http.Reques
feedType := strings.TrimSpace(r.FormValue("feed_type"))
interval, _ := strconv.Atoi(strings.TrimSpace(r.FormValue("sync_interval_minutes")))
freq, _ := strconv.Atoi(strings.TrimSpace(r.FormValue("sync_frequency")))
contentLanguage := strings.TrimSpace(r.FormValue("content_language"))
if contentLanguage != "" && !company.IsAllowedLanguage(contentLanguage) {
v1Err(w, http.StatusBadRequest, "validation_error", "unsupported content language")
return
}
file, header, fileErr := r.FormFile("file")
var options map[string]any
@@ -187,6 +199,7 @@ func (s *Server) createV1FeedFromMultipart(w http.ResponseWriter, r *http.Reques
FeedType: feedType,
SyncIntervalMinutes: interval,
SyncFrequencyHours: freq,
ContentLanguage: company.NormalizeLanguage(contentLanguage),
Options: options,
})
if err != nil {
+7
View File
@@ -2136,6 +2136,12 @@ paths:
- csv
- json
description: Source format. xml, csv or json; defaults to xml when not detected.
content_language:
type: string
description: |
Optional source-language code (e.g. en, sl, hr, de). Defaults to the
company's primary content language. Affects where the synchronized
product's original supplier text is stored; it does not translate.
sync_interval_minutes:
type: integer
minimum: 1
@@ -2156,6 +2162,7 @@ paths:
item_path: channel/item
url: https://feeds.example.com/nordic/google-merchant.xml
feed_type: xml
content_language: sl
sync_interval_minutes: 60
is_active: true
responses:
@@ -411,5 +411,10 @@ func (s *Server) assertV1ProcessGates(ctx context.Context, companyID uuid.UUID,
RequiresAI: billing.ProcessingTypeRequiresAI(processingType) || billing.ProcessingTypeIsEmailCampaignAI(processingType),
RequiresEPREL: billing.ProcessingTypeRequiresEPREL(processingType),
}
if rates, err := s.Billing.ContentRates(ctx, companyID); err == nil {
if units, err := billing.ContentDebitUnits(nil, processingType, rates); err == nil {
opts.CreditsPerProduct = float64(units) / 10000
}
}
return s.Billing.AssertCanStartProcessing(ctx, companyID, batchSize, opts)
}
+48 -16
View File
@@ -135,16 +135,26 @@ type Job struct {
// of ≤maxJobProducts so ClaimNext SKIP LOCKED workers stay parallelizable.
// Absolute request cap is MaxStartProducts (100k–1M scale).
func (p *Pipeline) StartJob(ctx context.Context, companyID, userID uuid.UUID, rawIDs []uuid.UUID, processingType string) ([]Job, error) {
return p.startJobWithOrigin(ctx, companyID, userID, rawIDs, processingType, "dashboard")
return p.startJobWithOrigin(ctx, companyID, userID, rawIDs, processingType, "dashboard", nil)
}
// StartAPIJob uses the same processing pipeline and company-scoped catalog as the
// dashboard, but completed API results do not require a dashboard approval action.
func (p *Pipeline) StartAPIJob(ctx context.Context, companyID, userID uuid.UUID, rawIDs []uuid.UUID, processingType string) ([]Job, error) {
return p.startJobWithOrigin(ctx, companyID, userID, rawIDs, processingType, "api")
return p.startJobWithOrigin(ctx, companyID, userID, rawIDs, processingType, "api", nil)
}
func (p *Pipeline) startJobWithOrigin(ctx context.Context, companyID, userID uuid.UUID, rawIDs []uuid.UUID, processingType, origin string) ([]Job, error) {
// StartJobWithTypes preserves the exact outputs selected in the dashboard.
func (p *Pipeline) StartJobWithTypes(ctx context.Context, companyID, userID uuid.UUID, rawIDs []uuid.UUID, processingType string, outputs []string) ([]Job, error) {
return p.startJobWithOrigin(ctx, companyID, userID, rawIDs, processingType, "dashboard", outputs)
}
// StartAPIJobWithTypes preserves explicit output selections for public API jobs.
func (p *Pipeline) StartAPIJobWithTypes(ctx context.Context, companyID, userID uuid.UUID, rawIDs []uuid.UUID, processingType string, outputs []string) ([]Job, error) {
return p.startJobWithOrigin(ctx, companyID, userID, rawIDs, processingType, "api", outputs)
}
func (p *Pipeline) startJobWithOrigin(ctx context.Context, companyID, userID uuid.UUID, rawIDs []uuid.UUID, processingType, origin string, outputs []string) ([]Job, error) {
if processingType == "" {
processingType = "full"
}
@@ -174,7 +184,7 @@ func (p *Pipeline) startJobWithOrigin(ctx context.Context, companyID, userID uui
}
}
if p.Billing != nil {
if err := p.assertProcessingGates(ctx, companyID, processingType, len(owned)); err != nil {
if err := p.assertProcessingGates(ctx, companyID, processingType, len(owned), outputs...); err != nil {
return nil, err
}
}
@@ -189,6 +199,9 @@ func (p *Pipeline) startJobWithOrigin(ctx context.Context, companyID, userID uui
firstStep = progress[0].Step
}
if outputs == nil {
outputs = []string{}
}
chunks := chunkUUIDs(owned, perJobProductCap())
tx, err := p.Pool.Begin(ctx)
if err != nil {
@@ -201,9 +214,9 @@ func (p *Pipeline) startJobWithOrigin(ctx context.Context, companyID, userID uui
var jobID uuid.UUID
err = tx.QueryRow(ctx, `
INSERT INTO processing_jobs (
company_id, user_id, status, total_products, processing_type, current_step, step_progress, origin
) VALUES ($1, $2, 'pending', $3, $4, $5, $6::jsonb, $7) RETURNING id`,
companyID, userID, len(chunk), processingType, firstStep, progressJSON, origin).Scan(&jobID)
company_id, user_id, status, total_products, processing_type, current_step, step_progress, origin, processing_types
) VALUES ($1, $2, 'pending', $3, $4, $5, $6::jsonb, $7, $8) RETURNING id`,
companyID, userID, len(chunk), processingType, firstStep, progressJSON, origin, outputs).Scan(&jobID)
if err != nil {
return nil, err
}
@@ -229,7 +242,7 @@ func (p *Pipeline) startJobWithOrigin(ctx context.Context, companyID, userID uui
}
// assertProcessingGates enforces plan features and credit/SKU caps before starting or retrying work.
func (p *Pipeline) assertProcessingGates(ctx context.Context, companyID uuid.UUID, processingType string, batchSize int) error {
func (p *Pipeline) assertProcessingGates(ctx context.Context, companyID uuid.UUID, processingType string, batchSize int, outputs ...string) error {
if p == nil || p.Billing == nil {
return nil
}
@@ -240,6 +253,11 @@ func (p *Pipeline) assertProcessingGates(ctx context.Context, companyID uuid.UUI
RequiresAI: billing.ProcessingTypeRequiresAI(processingType) || billing.ProcessingTypeIsEmailCampaignAI(processingType),
RequiresEPREL: billing.ProcessingTypeRequiresEPREL(processingType),
}
if rates, err := p.Billing.ContentRates(ctx, companyID); err == nil {
if units, err := billing.ContentDebitUnits(outputs, processingType, rates); err == nil {
opts.CreditsPerProduct = float64(units) / 10000
}
}
return p.Billing.AssertCanStartProcessing(ctx, companyID, batchSize, opts)
}
@@ -545,7 +563,7 @@ func (p *Pipeline) RetryJob(ctx context.Context, companyID, id uuid.UUID) (Job,
if p.Limiter != nil && !p.Limiter.Allow(companyID) {
return Job{}, ErrRateLimited
}
if err := p.assertProcessingGates(ctx, companyID, job.ProcessingType, job.TotalProducts); err != nil {
if err := p.assertProcessingGates(ctx, companyID, job.ProcessingType, job.TotalProducts, selectedOutputs...); err != nil {
return Job{}, err
}
@@ -601,11 +619,12 @@ func (p *Pipeline) ProcessJob(ctx context.Context, jobID uuid.UUID) error {
var companyID uuid.UUID
var jobUserID *uuid.UUID
var status, processingType, origin string
var selectedOutputs []string
var alreadyProcessed int
err := p.Pool.QueryRow(ctx, `
SELECT company_id, user_id, status, processing_type, processed_products, origin
SELECT company_id, user_id, status, processing_type, processed_products, origin, processing_types
FROM processing_jobs WHERE id = $1`, jobID).
Scan(&companyID, &jobUserID, &status, &processingType, &alreadyProcessed, &origin)
Scan(&companyID, &jobUserID, &status, &processingType, &alreadyProcessed, &origin, &selectedOutputs)
if err != nil {
return err
}
@@ -765,7 +784,7 @@ func (p *Pipeline) ProcessJob(ctx context.Context, jobID uuid.UUID) error {
return fmt.Errorf("processing: check cancel job=%s: %w", jobID, err)
}
}
ok, tokens, result, itemErr := p.processOne(ctx, companyID, jobID, &items[i], processingType, origin, jobEngine, modeLabel, usingBYOK, &jobCache)
ok, tokens, result, itemErr := p.processOne(ctx, companyID, jobID, &items[i], processingType, selectedOutputs, origin, jobEngine, modeLabel, usingBYOK, &jobCache)
if itemErr != nil {
failed++
if _, err := p.Pool.Exec(ctx, `
@@ -1454,7 +1473,7 @@ func (p *Pipeline) reclaimOrphanedProcessingItems(ctx context.Context, jobID uui
return err
}
func (p *Pipeline) processOne(ctx context.Context, companyID, jobID uuid.UUID, it *jobItem, processingType, origin string, engine *Engine, modeLabel string, usingBYOK bool, cache *jobScopedCache) (bool, int, StepResult, error) {
func (p *Pipeline) processOne(ctx context.Context, companyID, jobID uuid.UUID, it *jobItem, processingType string, selectedOutputs []string, origin string, engine *Engine, modeLabel string, usingBYOK bool, cache *jobScopedCache) (bool, int, StepResult, error) {
if it == nil {
return false, 0, StepResult{}, fmt.Errorf("processing: nil job item")
}
@@ -1706,11 +1725,24 @@ func (p *Pipeline) processOne(ctx context.Context, companyID, jobID uuid.UUID, i
// Debit before persisting the deliverable so insufficient credits cannot yield free AI output.
// BYOK (company key): skip managed credit burn for inference.
// Hash-skip (ai_enhance_unchanged): skip flat product_processing debit — no LLM/rework.
if p.Billing != nil && shouldDebitProductProcessing(usingBYOK, result) {
if err := p.Billing.ConsumeCreditsTx(ctx, tx, companyID, result.TotalTokens, "product_processing"); err != nil {
billable := p.Billing != nil && shouldDebitProductProcessing(usingBYOK, result)
if billable && result.TotalTokens == 0 {
// Normalization-only jobs on Free cannot consume managed AI credits.
if ent, entErr := p.Billing.EntitlementsForCompany(ctx, companyID); entErr != nil {
return false, 0, result, entErr
} else if !ent.CanUseAI {
billable = false
}
}
if billable {
debit, err := p.Billing.ConsumeContentCreditsTx(ctx, tx, companyID, selectedOutputs, processingType)
if err != nil {
return false, 0, result, err
}
cache.noteCreditDebit(p.Billing.EstimateDebitForCompany(ctx, companyID, "product_processing", result.TotalTokens))
// Cache tracks whole-credit safety only; the database debit checks every fraction.
if debit >= 1 {
cache.noteCreditDebit(int(debit))
}
}
processedID, err := p.upsertProcessedProduct(ctx, tx, companyID, it.RawID, gtin, result, attrsJSON, procAttrsJSON, gptJSON, sourcesJSON, providerMode, language, origin)
@@ -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">
import { api, failureMessage } from "$lib/api";
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 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){
event.preventDefault();busy=true;error="";
try{
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(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}`);
await onComplete();
}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}>
<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" />
<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>
{#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)" />
@@ -5,6 +5,8 @@
import ConfirmationDialog from "$lib/components/categories/formula/ConfirmationDialog.svelte";
import { cn } from "$lib/utils";
import { i18n } from "$lib/i18n";
import { onMount } from "svelte";
import { api } from "$lib/api";
import { PROCESSING_OPTIONS, type ProcessingType, type ProductRow } from "./types";
let {
@@ -56,15 +58,30 @@
let pendingCredits = $state(0);
let pendingCount = $state(0);
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(
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.
const totalCredits = $derived(
PROCESSING_OPTIONS.filter((option) => selectedTypes.includes(option.type)).reduce(
(sum, option) => sum + option.credits,
// Estimated cost from the effective company/plan rates (per selected output).
const totalCredits = $derived(processingMode === "product"
? (effectiveCosts.product ?? 0.45) * selectedCount
: PROCESSING_OPTIONS.filter((option) => selectedTypes.includes(option.type)).reduce(
(sum, option) => sum + (effectiveCosts[option.type] ?? option.credits),
0
) * selectedCount
);
@@ -84,8 +101,9 @@
}
function processSelected() {
if (selectedTypes.length === 0) return;
pendingTypes = [...selectedTypes];
if (!pricingReady || (processingMode === "outputs" && selectedTypes.length === 0)) return;
if (selectedAILocked) return;
pendingTypes = processingMode === "product" ? [...processProductTypes] : [...selectedTypes];
pendingCredits = totalCredits;
pendingCount = selectedCount;
open = false;
@@ -147,12 +165,15 @@
{/if}
{#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">
<Button
variant="default"
size="sm"
mutation
disabled={selectedCount === 0 || isProcessing}
disabled={selectedCount === 0 || isProcessing || !pricingReady}
loading={isProcessing}
data-assistant-target="start-processing"
data-tour="start-processing"
@@ -187,6 +208,15 @@
</div>
</div>
{/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
type="button"
class="mb-3 flex items-center space-x-2 border-b border-border/50 pb-3"
@@ -230,12 +260,13 @@
</label>
<span class="font-mono text-xs text-muted-foreground"
>{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
>
</div>
{/each}
</div>
{/if}
</div>
<div class="my-1 h-px bg-border"></div>
<div class="space-y-2 p-2">
@@ -252,7 +283,7 @@
size="sm"
class="w-full"
mutation
disabled={selectedTypes.length === 0 || isProcessing || selectedAILocked}
disabled={!pricingReady || (processingMode === "outputs" && selectedTypes.length === 0) || isProcessing || selectedAILocked}
loading={isProcessing}
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 priceScope = $state("company");
let priceOwner = $state("");
let priceFeature = $state("product_processing");
let priceFeature = $state("title_ai");
let priceCredits = $state("2");
let pricingMessage = $state("");
let pricingSaving = $state(false);
@@ -192,8 +192,8 @@
async function saveProcessingCost() {
pricingMessage = "";
const creditCost = Number(priceCredits);
if (!priceOwner.trim() || !Number.isInteger(creditCost) || creditCost < 1 || creditCost > 1000000) {
pricingMessage = "Select a plan/company and enter a positive integer credit amount.";
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 credit amount with up to four decimal places.";
return;
}
pricingSaving = true;
@@ -399,7 +399,7 @@
{: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" />
{/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" />
<Button onclick={() => saveProcessingCost()} disabled={pricingSaving}>Save rate</Button>
{#if priceScope === "company" && priceOwner.trim()}
+91 -24
View File
@@ -74,19 +74,39 @@
type CreditRule = { scope: string; id: string; feature: string; cost_per_unit: number };
const creditFeatures = [
{ key: "product_processing", label: "AI product processing", description: "Base credits for processing a product" },
{ key: "openai_token_k", label: "AI tokens (per 1,000)", description: "Additional token-related credits where charged" },
{ key: "seo_meta_ai", label: "SEO meta generation", description: "Credits charged for SEO metadata" },
{ key: "campaign_copy", label: "Campaign copy", description: "Credits charged for campaign content" }
{ key: "title_ai", label: "Titles (AI)", description: "Credits for generating an AI product title" },
{ key: "description_ai", label: "Descriptions (AI)", description: "Credits for generating an AI product description" },
{ key: "seo_meta_ai", label: "SEO meta title & description (AI)", description: "Credits for generating both SEO meta fields" }
] as const;
type CreditFeature = (typeof creditFeatures)[number]["key"];
type CreditForm = Record<CreditFeature, string>;
type CreditForm = Record<CreditFeature | "product_ai", string>;
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 creditForm = $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() {
const result = await api<{ rules: CreditRule[] }>("/api/admin/processing-costs");
@@ -94,17 +114,21 @@
}
function planCredits(planId: number): CreditForm {
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);
if (match) next[feature.key] = String(match.cost_per_unit);
}
return next;
}
function validatePlanCredits(): void {
for (const feature of creditFeatures) {
const raw = String(creditForm[feature.key] ?? "").trim();
if (raw && (!/^\d+$/.test(raw) || Number(raw) < 1 || Number(raw) > 1000000)) {
throw new Error(`${feature.label}: enter 1–1,000,000 credits or leave blank to inherit`);
const selected: ReadonlyArray<{ key: CreditFeature | "product_ai"; label: string }> = planProcessingMode === "product"
? [{ key: "product_ai", label: "Product processing" }]
: creditFeatures;
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) {
const key = feature.key;
const next = String(creditForm[key] ?? "").trim();
if (next === creditOriginal[key]) continue;
if (next === String(creditOriginal[key] ?? "").trim()) continue;
await api("/api/admin/processing-costs", {
method: "PUT",
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 => ({
@@ -224,7 +257,7 @@
const [p, c] = await Promise.all([fetchAdminPlansList(), fetchAdminCompaniesList()]);
plans = p;
companies = c;
await loadCreditRules();
await Promise.all([loadCreditRules(), loadEuroPerCredit()]);
}
async function reload() {
@@ -235,6 +268,8 @@
planForm = emptyPlanForm();
creditForm = emptyCreditForm();
creditOriginal = emptyCreditForm();
planProcessingMode = "outputs";
perProductPrice = "0.45";
planFormOpen = true;
}
@@ -257,6 +292,8 @@
};
creditForm = planCredits(Number(plan.id));
creditOriginal = { ...creditForm };
planProcessingMode = creditForm.product_ai !== "" ? "product" : "outputs";
perProductPrice = creditForm.product_ai === "" ? "0.45" : creditForm.product_ai;
planFormOpen = true;
}
@@ -377,7 +414,22 @@
<Alert message={error} />
<Alert tone="success" message={success} />
<div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
<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">
<Card class="border-border bg-card">
<CardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle class="text-sm font-medium text-foreground">{i18n.t("admin.billing.stat.plans")}</CardTitle>
@@ -657,18 +709,33 @@
</div>
<div class="space-y-3 rounded-md border border-border p-3">
<div>
<p class="text-sm font-semibold">Processing credit costs</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-sm font-semibold">Processing pricing</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 class="grid gap-3 sm:grid-cols-2">
{#each creditFeatures as feature (feature.key)}
<div class="space-y-1">
<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" />
<p class="text-xs text-muted-foreground">{feature.description}</p>
</div>
{/each}
<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">
{#each creditFeatures as feature (feature.key)}
<div class="space-y-1">
<Label for={`plan-cost-${feature.key}`}>{feature.label}</Label>
<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>
</div>
{/each}
</div>
{/if}
</div>
<div class="flex items-start gap-3 rounded-md border border-border p-3">
<Checkbox id="plan-custom" bind:checked={planForm.is_custom} />
+13 -2
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import RemoteCatalogImport from "$lib/components/feeds/RemoteCatalogImport.svelte";
import { CONTENT_LANGUAGES } from "$lib/content-languages";
import { i18n } from "$lib/i18n";
import { onMount } from "svelte";
import { goto } from "$app/navigation";
@@ -277,7 +278,7 @@
const params = new URLSearchParams({ limit: String(limit), offset: String(offset), roots: "1" });
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);
attributes = sortItems(items);
total = unwrapTotal(payload) ?? attributes.length;
@@ -465,6 +466,7 @@
try {
const form = new FormData();
form.append("file", addFile);
if (importLanguage) form.append("language", importLanguage);
await api("/api/attributes/import", { method: "POST", body: form });
showAdd = false;
resetAddForm();
@@ -692,6 +694,8 @@
function categoryBadges(attr: Attr): string[] {
return categoryNamesByAttr[String(attr.id)] ?? [];
}
let importLanguage = $state("");
</script>
<PageShell title={i18n.t("attributes.title")} description={i18n.t("attributes.description")}>
@@ -1077,7 +1081,14 @@
{#if canAdmin}
<TabsContent value="bulk" class="mt-4">
<RemoteCatalogImport kind="attributes" onComplete={load}/>
<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}/>
<form class="space-y-4" onsubmit={bulkImport}>
<div class="grid gap-2">
<Label for="bulk-file">{i18n.t("attributes.bulk.fileLabel")}</Label>
+14 -3
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import RemoteCatalogImport from "$lib/components/feeds/RemoteCatalogImport.svelte";
import { CONTENT_LANGUAGES } from "$lib/content-languages";
import { i18n } from "$lib/i18n";
import { onMount } from "svelte";
import { goto } from "$app/navigation";
@@ -61,7 +62,7 @@
loading = true;
error = "";
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
});
if (gen !== categoriesFetchGen) return;
@@ -169,11 +170,14 @@
async function onImport(file: File) {
const form = new FormData();
form.append("file", file);
if (importLanguage) form.append("language", importLanguage);
await api("/api/categories/import", { method: "POST", body: form });
addOpen = false;
success = i18n.t("flash.categories.csvImported");
await load();
}
let importLanguage = $state("");
</script>
<PageShell title={i18n.t("categories.title")} description={i18n.t("categories.description")}>
@@ -186,7 +190,14 @@
<Alert message={error} />
<Alert tone="success" message={success} />
{#if canAdmin}<RemoteCatalogImport kind="categories" onComplete={load}/>{/if}
<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 !loading && promptCount > 0}
<p class="text-sm text-muted-foreground">
@@ -260,7 +271,7 @@
onToggleExpand={toggleExpand}
onEdit={async (cat) => {
try {
selected = await api<Cat>(`/api/categories/${cat.id}`);
selected = await api<Cat>(`/api/categories/${cat.id}${importLanguage ? `?language=${encodeURIComponent(importLanguage)}` : ""}`);
} catch {
selected = cat;
}
+26 -3
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import { i18n } from "$lib/i18n";
import { CONTENT_LANGUAGES } from "$lib/content-languages";
import { onMount } from "svelte";
import { goto } from "$app/navigation";
import { page } from "$app/state";
@@ -160,6 +161,7 @@
let formAuthToken = $state("");
let formAuthHeader = $state("X-API-Key");
let formType = $state("xml");
let formLanguage = $state("");
let formInterval = $state("60");
let formSource = $state<"url" | "file">("url");
let formFile = $state<File | null>(null);
@@ -478,6 +480,7 @@ function openAdd(source: "url" | "file" = "url") {
formUrl = "";
formType = source === "file" ? "csv" : "xml";
formInterval = "60";
formLanguage = "";
formSource = source;
formFile = null;
if (formFileInput) formFileInput.value = "";
@@ -545,6 +548,7 @@ function openAdd(source: "url" | "file" = "url") {
formName = String(feed.name ?? "");
formUrl = String(feed.url ?? "");
formType = String(feed.feed_type ?? "xml");
formLanguage = String((feed.options as Record<string, unknown> | undefined)?.content_language ?? "");
formAuthToken=""; formHeaders="";
formInterval = String(feed.sync_interval_minutes ?? 60);
showEdit = true;
@@ -568,6 +572,7 @@ function openAdd(source: "url" | "file" = "url") {
body.append("name", formName.trim());
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("content_language", formLanguage);
body.append("file", formFile);
created = await api<FeedRow>("/api/feeds", { method: "POST", body });
} else {
@@ -586,6 +591,7 @@ function openAdd(source: "url" | "file" = "url") {
url,
feed_type: inferredType,
sync_interval_minutes: parseSyncIntervalMinutes(formInterval),
content_language: formLanguage,
request_headers: requestHeaders()
}
});
@@ -624,7 +630,8 @@ function openAdd(source: "url" | "file" = "url") {
const body: Record<string, unknown> = {
name: formName.trim(),
feed_type: nextType,
sync_interval_minutes: parseSyncIntervalMinutes(formInterval)
sync_interval_minutes: parseSyncIntervalMinutes(formInterval),
content_language: formLanguage
};
if (!isFileFeed(editing)) {
body.url = formUrl.trim();
@@ -1314,7 +1321,15 @@ function openAdd(source: "url" | "file" = "url") {
</TabsContent>
</Tabs>
<div class="space-y-1.5">
<Label for="add-feed-interval">{i18n.t("feeds.field.interval")}</Label>
<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>
<Input
id="add-feed-interval"
type="number"
@@ -1396,7 +1411,15 @@ function openAdd(source: "url" | "file" = "url") {
{/if}
</div>
<div class="space-y-1.5">
<Label for="edit-feed-interval">{i18n.t("feeds.field.interval")}</Label>
<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>
<Input
id="edit-feed-interval"
type="number"