This commit is contained in:
greeneclipse committed 2026-10-15 21:22:43 +02:00
1 parent 04794aea54
commit cfd31f398c
61 files changed
+2062 -254

No files matched your search

+1 -1
View File
@@ -162,7 +162,7 @@ func (s *Service) EntitlementsForCompany(ctx context.Context, companyID uuid.UUI
// (cannot be silently downgraded to normalize/specs/fill).
func ProcessingTypeRequiresAI(processingType string) bool {
switch strings.ToLower(strings.TrimSpace(processingType)) {
case "enhance", "enhance_only", "enhance-only", "title", "description", "seo", "seo_ai":
case "enhance", "enhance_only", "enhance-only", "title", "description", "seo", "seo_ai", "seo_meta":
return true
default:
return false
+9 -2
View File
@@ -43,13 +43,20 @@ func (s *Service) SaveUpload(ctx context.Context, companyID, userID uuid.UUID, u
if uploadDir == "" {
return nil, ClientMsg("upload directory not configured")
}
kind = strings.ToLower(strings.TrimSpace(kind))
safe := sanitizeFileName(originalName)
lower := strings.ToLower(safe)
if !strings.HasSuffix(lower, ".csv") {
return nil, ClientMsg("only .csv uploads are allowed")
isCSV := strings.HasSuffix(lower, ".csv") || strings.HasSuffix(lower, ".tsv")
isXML := strings.HasSuffix(lower, ".xml") && kind == "feed"
isJSON := strings.HasSuffix(lower, ".json")
if !isCSV && !isXML && !isJSON {
return nil, ClientMsg("only CSV, JSON or XML feed uploads are allowed")
}
if contentType != "" &&
!strings.Contains(strings.ToLower(contentType), "csv") &&
!strings.Contains(strings.ToLower(contentType), "json") &&
!strings.Contains(strings.ToLower(contentType), "xml") &&
!strings.Contains(strings.ToLower(contentType), "tab-separated") &&
!strings.Contains(strings.ToLower(contentType), "text/plain") &&
!strings.Contains(strings.ToLower(contentType), "octet-stream") {
return nil, ClientMsg("invalid content type for CSV upload")
+174
View File
@@ -0,0 +1,174 @@
package catalog
import (
"bytes"
"encoding/csv"
"encoding/json"
"fmt"
"io"
"sort"
"strings"
)
// JSONImportAsCSV maps JSON arrays (including wrapped nested arrays) onto the
// same validated batch import pipeline as CSV. Data must fit the catalog upload
// limit. All rows are processed by the normal company-scoped upsert routines.
func JSONImportAsCSV(r io.Reader, kind string) (io.Reader, error) {
source, err := io.ReadAll(io.LimitReader(r, (6<<20)+1))
if err != nil {
return nil, err
}
if len(source) > 6<<20 {
return nil, ClientMsg("JSON catalog import exceeds 6 MiB")
}
var doc any
dec := json.NewDecoder(bytes.NewReader(source))
dec.UseNumber()
if err := dec.Decode(&doc); err != nil {
return nil, ClientMsg("invalid JSON import: " + err.Error())
}
items := findImportJSONArray(doc, kind, 0)
if len(items) == 0 {
return nil, ClientMsg("JSON must contain an array of " + kind)
}
header := []string{}
switch kind {
case "categories":
header = []string{"name", "unique_id", "parent_unique_id", "description"}
case "attributes":
header = []string{"attribute_key", "name", "value_type", "unit", "example", "parent_key", "category_id"}
case "products":
header = []string{"gtin", "product_id", "name", "category", "description", "status"}
default:
return nil, ClientMsg("invalid catalog import kind")
}
// Keep original JSON keys too; importer uses known column names (GTIN/EAN, etc).
keys := map[string]struct{}{}
for _, k := range header {
keys[k] = struct{}{}
}
for _, v := range items {
if m, ok := v.(map[string]any); ok {
for k := range m {
keys[k] = struct{}{}
}
}
}
extras := make([]string, 0, len(keys))
for k := range keys {
found := false
for _, h := range header {
if k == h {
found = true
break
}
}
if !found {
extras = append(extras, k)
}
}
sort.Strings(extras)
header = append(header, extras...)
var buf bytes.Buffer
cw := csv.NewWriter(&buf)
if err := cw.Write(header); err != nil {
return nil, err
}
for _, v := range items {
m, ok := v.(map[string]any)
if !ok {
continue
}
rec := make([]string, len(header))
for j, k := range header {
val, exists := m[k]
if !exists && (k == "gtin" || k == "product_id" || k == "name" || k == "unique_id" || k == "attribute_key") {
aliases := map[string][]string{"gtin": {"ean", "barcode", "gtin"}, "product_id": {"sku", "productno", "productno2", "id"}, "name": {"title", "product", "product_name", "productname"}, "unique_id": {"id", "category_id", "uniqueId"}, "attribute_key": {"key", "attributeKey", "id"}}
for _, alias := range aliases[k] {
for source, value := range m {
if strings.EqualFold(source, alias) && value != nil {
val = value
exists = true
break
}
}
if exists {
break
}
}
}
if !exists {
for source, value := range m {
if strings.EqualFold(source, k) {
val = value
break
}
}
}
if val == nil {
continue
}
switch x := val.(type) {
case string:
rec[j] = x
case json.Number:
rec[j] = string(x)
case bool:
rec[j] = fmt.Sprint(x)
default:
b, _ := json.Marshal(x)
rec[j] = string(b)
}
}
if err := cw.Write(rec); err != nil {
return nil, err
}
}
cw.Flush()
if err := cw.Error(); err != nil {
return nil, err
}
return bytes.NewReader(buf.Bytes()), nil
}
func findImportJSONArray(doc any, kind string, depth int) []any {
if depth > 6 {
return nil
}
if items, ok := doc.([]any); ok {
if len(items) > 0 {
if _, ok := items[0].(map[string]any); ok {
return items
}
}
return nil
}
m, ok := doc.(map[string]any)
if !ok {
return nil
}
keys := []string{kind, "items", "results", "data", "records", "rows"}
if kind == "products" {
keys = append([]string{"SHOPITEM", "products", "product"}, keys...)
}
if kind == "categories" {
keys = append([]string{"categories", "category"}, keys...)
}
if kind == "attributes" {
keys = append([]string{"attributes", "specifications"}, keys...)
}
for _, k := range keys {
for actual, value := range m {
if strings.EqualFold(actual, k) {
if a := findImportJSONArray(value, kind, depth+1); len(a) > 0 {
return a
}
}
}
}
if len(m) == 1 {
for _, v := range m {
return findImportJSONArray(v, kind, depth+1)
}
}
return nil
}
@@ -0,0 +1,43 @@
package catalog
import (
"encoding/csv"
"strings"
"testing"
)
func TestV10JsonProducts(t *testing.T) {
r, e := JSONImportAsCSV(strings.NewReader(`{"data":{"products":[{"EAN":"8595025395184","PRODUCT":"Ročna LED svetilka","PRODUCTNO":"1440093109","category":"Svetilke"}]}}`), "products")
if e != nil {
t.Fatal(e)
}
cr := csv.NewReader(r)
h, _ := cr.Read()
values, e := cr.Read()
if e != nil {
t.Fatal(e)
}
m := map[string]string{}
for i, k := range h {
m[k] = values[i]
}
if m["gtin"] != "8595025395184" || m["name"] != "Ročna LED svetilka" || m["product_id"] != "1440093109" {
t.Fatalf("wrong fields %v", m)
}
}
func TestV10JsonCategories(t *testing.T) {
r, e := JSONImportAsCSV(strings.NewReader(`{"categories":[{"name":"Svetilke","id":50}]}`), "categories")
if e != nil {
t.Fatal(e)
}
cr := csv.NewReader(r)
h, _ := cr.Read()
v, _ := cr.Read()
m := map[string]string{}
for i, k := range h {
m[k] = v[i]
}
if m["unique_id"] != "50" {
t.Fatalf("unique_id: %v", m)
}
}
@@ -0,0 +1,113 @@
package feeds
import (
"context"
"errors"
"os"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
)
// Requires the normal migrated test PostgreSQL schema (DATABASE_URL).
func TestDeleteFeedRemovesOnlyOwnedUnprocessedProducts(t *testing.T) {
dsn := strings.TrimSpace(os.Getenv("DATABASE_URL"))
if dsn == "" {
t.Skip("DATABASE_URL is not configured")
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
pg, err := pgxpool.New(ctx, dsn)
if err != nil {
t.Fatal(err)
}
defer pg.Close()
cid, otherCID := uuid.New(), uuid.New()
for _, id := range []uuid.UUID{cid, otherCID} {
if _, err := pg.Exec(ctx, `INSERT INTO companies (id, name) VALUES ($1, $2)`, id, "delete-cleanup-"+id.String()[:8]); err != nil {
t.Fatal(err)
}
}
defer pg.Exec(context.Background(), `DELETE FROM companies WHERE id = ANY($1::uuid[])`, []uuid.UUID{cid, otherCID})
newFeed := func(c uuid.UUID) uuid.UUID {
t.Helper()
var id uuid.UUID
if err := pg.QueryRow(ctx, `INSERT INTO input_feeds (company_id, name) VALUES ($1, 'test-feed') RETURNING id`, c).Scan(&id); err != nil {
t.Fatal(err)
}
return id
}
feed := newFeed(cid)
survivor := newFeed(cid)
otherFeed := newFeed(otherCID)
newRaw := func(c uuid.UUID, name string, fid uuid.UUID, processed bool, status string, ids any) uuid.UUID {
t.Helper()
var id uuid.UUID
err := pg.QueryRow(ctx, `
INSERT INTO raw_products (company_id, gtin, feed_id, feed_ids, is_processed, processing_status)
VALUES ($1, $2, $3, $4, $5, $6) RETURNING id`, c, name, fid, ids, processed, status).Scan(&id)
if err != nil {
t.Fatal(err)
}
return id
}
unprocessed := newRaw(cid, "delete-new", feed, false, "unprocessed", nil)
failed := newRaw(cid, "delete-failed", feed, false, "failed", nil)
processed := newRaw(cid, "keep-processed", feed, true, "processed", nil)
processing := newRaw(cid, "keep-running", feed, false, "processing", nil)
shared := newRaw(cid, "keep-shared", feed, false, "unprocessed", []string{feed.String(), survivor.String()})
secondary := newRaw(cid, "keep-secondary", survivor, false, "unprocessed", []string{feed.String(), survivor.String()})
untouchedOther := newRaw(otherCID, "keep-other-company", otherFeed, false, "unprocessed", nil)
// A processed result linked to an unprocessed raw row survives with its FK cleared.
var resultID uuid.UUID
if err := pg.QueryRow(ctx, `
INSERT INTO processed_products (company_id, raw_product_id, feed_id, name)
VALUES ($1, $2, $3, 'retained') RETURNING id`, cid, unprocessed, feed).Scan(&resultID); err != nil {
t.Fatal(err)
}
svc := &Service{Pool: pg}
if _, err := svc.DeleteWithCleanup(ctx, otherCID, feed); !errors.Is(err, ErrNotFound) {
t.Fatalf("cross-tenant deletion must return not found, got %v", err)
}
count, err := svc.DeleteWithCleanup(ctx, cid, feed)
if err != nil {
t.Fatal(err)
}
if count != 2 {
t.Fatalf("deleted raw count = %d, want 2", count)
}
var n int
if err := pg.QueryRow(ctx, `SELECT count(*) FROM raw_products WHERE id = ANY($1::uuid[])`, []uuid.UUID{unprocessed, failed}).Scan(&n); err != nil || n != 0 {
t.Fatalf("unprocessed rows still exist: count=%d err=%v", n, err)
}
for _, kept := range []uuid.UUID{processed, processing, shared, secondary, untouchedOther} {
if err := pg.QueryRow(ctx, `SELECT count(*) FROM raw_products WHERE id = $1`, kept).Scan(&n); err != nil || n != 1 {
t.Fatalf("preserved row %s count=%d err=%v", kept, n, err)
}
}
var newOwner uuid.UUID
if err := pg.QueryRow(ctx, `SELECT feed_id FROM raw_products WHERE id = $1`, shared).Scan(&newOwner); err != nil || newOwner != survivor {
t.Fatalf("shared row owner=%v err=%v", newOwner, err)
}
for _, kept := range []uuid.UUID{shared, secondary} {
if err := pg.QueryRow(ctx, `SELECT count(*) FROM raw_products WHERE id = $1 AND feed_ids @> jsonb_build_array($2::text)`, kept, feed).Scan(&n); err != nil || n != 0 {
t.Fatalf("stale secondary feed id in row %s: %d, %v", kept, n, err)
}
}
var rawLink *uuid.UUID
if err := pg.QueryRow(ctx, `SELECT raw_product_id FROM processed_products WHERE id = $1`, resultID).Scan(&rawLink); err != nil || rawLink != nil {
t.Fatalf("processed result must survive, detached from deleted raw: %v %v", rawLink, err)
}
if _, err := svc.DeleteWithCleanup(ctx, cid, feed); !errors.Is(err, ErrNotFound) {
t.Fatalf("second delete must be not found, got %v", err)
}
}
+50 -2
View File
@@ -172,6 +172,13 @@ func ValidateFeedURL(ctx context.Context, rawURL string) error {
// downloadFeed streams an http(s) feed to a temp file with SSRF controls and a hard size cap.
// Callers must Close the returned blob to remove the temp file.
func downloadFeed(ctx context.Context, rawURL string) (*feedBlob, error) {
return downloadFeedWithHeaders(ctx, rawURL, nil)
}
func downloadFeedWithHeaders(ctx context.Context, rawURL string, extra map[string]string) (*feedBlob, error) {
extra, err := validatedFeedHeaders(extra)
if err != nil {
return nil, err
}
ensureAllowlist()
rawURL = strings.TrimSpace(rawURL)
if rawURL == "" {
@@ -203,7 +210,15 @@ func downloadFeed(ctx context.Context, rawURL string) (*feedBlob, error) {
if req.URL.Scheme != "http" && req.URL.Scheme != "https" {
return errURLScheme
}
return assertPublicHost(req.Context(), req.URL.Hostname())
if err := assertPublicHost(req.Context(), req.URL.Hostname()); err != nil {
return err
}
if len(via) > 0 && !strings.EqualFold(req.URL.Hostname(), via[0].URL.Hostname()) {
for name := range extra {
req.Header.Del(name)
}
}
return nil
},
}
@@ -212,7 +227,10 @@ func downloadFeed(ctx context.Context, rawURL string) (*feedBlob, error) {
return nil, err
}
req.Header.Set("User-Agent", defaultUserAgent)
req.Header.Set("Accept", "text/csv,application/csv,application/xml,text/xml,application/atom+xml,*/*")
req.Header.Set("Accept", "application/json,text/csv,application/csv,application/xml,text/xml,application/atom+xml,*/*")
for name, value := range extra {
req.Header.Set(name, value)
}
res, err := client.Do(req)
if err != nil {
@@ -402,3 +420,33 @@ func isBlockedIP(ip net.IP) bool {
}
return false
}
// DownloadImportSource safely fetches a one-time catalog import URL with optional headers.
// The caller must close the returned reader, which removes the temporary file.
func DownloadImportSource(ctx context.Context, rawURL string, headers map[string]string, maxSize int64) (io.ReadCloser, error) {
b, err := downloadFeedWithHeaders(ctx, rawURL, headers)
if err != nil {
return nil, err
}
if b.size > maxSize {
b.Close()
return nil, ClientMsg("catalog import exceeds size limit")
}
f, err := b.Open()
if err != nil {
b.Close()
return nil, err
}
return &cleanupImportReader{ReadCloser: f, blob: b}, nil
}
type cleanupImportReader struct {
io.ReadCloser
blob *feedBlob
}
func (r *cleanupImportReader) Close() error {
err := r.ReadCloser.Close()
_ = r.blob.Close()
return err
}
+84
View File
@@ -759,6 +759,9 @@ func (s *Service) PublicExportXML(ctx context.Context, w io.Writer, token string
}
// PublicExportCSV streams CSV for a public export token.
func (s *Service) PublicExportJSON(ctx context.Context, w io.Writer, token string) error {
return s.StreamPublicExport(ctx, w, token, "json")
}
func (s *Service) PublicExportCSV(ctx context.Context, w io.Writer, token string) error {
return s.StreamPublicExport(ctx, w, token, "csv")
}
@@ -805,6 +808,8 @@ func (s *Service) streamExport(ctx context.Context, w io.Writer, row exportFeedR
switch format {
case "csv":
return streamCSV(w, seq, tpl)
case "json":
return streamJSON(w, seq, tpl)
default:
return streamXML(w, seq, tpl, row.Name)
}
@@ -966,6 +971,9 @@ func (s *Service) ExportSelectedProducts(ctx context.Context, companyID, feedID
case "csv":
count, err = streamCSV(&buf, seq, tpl)
mimeType = "text/csv; charset=utf-8"
case "json":
count, err = streamJSON(&buf, seq, tpl)
mimeType = "application/json; charset=utf-8"
default:
count, err = streamXML(&buf, seq, tpl, row.Name)
mimeType = "application/xml; charset=utf-8"
@@ -1002,6 +1010,17 @@ func (s *Service) queryExportProductsByIDs(ctx context.Context, companyID uuid.U
func renderExportSnippet(format string, tpl exportTemplate, products []exportProduct, feedName string) (string, int, error) {
var buf bytes.Buffer
switch strings.ToLower(strings.TrimSpace(format)) {
case "json":
seq := exportProductSeq(func(yield func(exportProduct) error) error {
for _, p := range products {
if err := yield(p); err != nil {
return err
}
}
return nil
})
n, err := streamJSON(&buf, seq, tpl)
return buf.String(), n, err
case "csv":
cw := csv.NewWriter(&buf)
headers := make([]string, len(tpl.Fields))
@@ -1063,3 +1082,68 @@ func sanitizeExportFileName(name string) string {
}
return out
}
// streamJSON emits valid JSON objects one at a time with no catalog-wide buffering.
// The outer key follows the configured template root (products by default).
func streamJSON(w io.Writer, seq exportProductSeq, tpl exportTemplate) (int, error) {
root := strings.TrimSpace(tpl.Root)
if root == "" {
root = "products"
}
key, err := json.Marshal(root)
if err != nil {
return 0, err
}
if _, err := fmt.Fprintf(w, "{%s:[", key); err != nil {
return 0, err
}
count := 0
err = seq(func(p exportProduct) error {
row := make(map[string]any, len(tpl.Fields))
for _, field := range tpl.Fields {
name := strings.TrimSpace(field.Key)
if name == "" {
name = field.Source
}
if isSpecExpandSource(field.Source) {
specs := map[string]string{}
for _, spec := range expandSpecFields(p) {
if val := productFieldValue(p, spec.Source); val != "" {
specs[spec.Key] = val
}
}
if len(specs) > 0 {
row[name] = specs
}
continue
}
if name != "" {
row[name] = productFieldValue(p, field.Source)
}
}
encoded, err := json.Marshal(row)
if err != nil {
return err
}
if count > 0 {
if _, err := io.WriteString(w, ","); err != nil {
return err
}
}
if _, err := w.Write(encoded); err != nil {
return err
}
count++
if count%exportChunkHint == 0 {
if f, ok := w.(interface{ Flush() }); ok {
f.Flush()
}
}
return nil
})
if err != nil {
return count, err
}
_, err = io.WriteString(w, "]}\n")
return count, err
}
+37 -1
View File
@@ -115,6 +115,25 @@ func (s *Service) ExtractSchema(ctx context.Context, companyID, feedID uuid.UUID
out.Fields = fields
out.SampleRows = rows
out.Preview = buildXMLPreview(data, local)
case "json":
suggested := guessJSONItemPath(data)
out.SuggestedPath = suggested
path := itemPathHint
if path == "" {
path = suggested
out.ItemPath = path
}
fields, rows, err := extractJSONSchema(data, path)
if err != nil && !(truncated && rows > 0 && (errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, io.EOF) || strings.Contains(strings.ToLower(err.Error()), "unexpected eof"))) {
return nil, fmt.Errorf("JSON preview: %w; check the item path and response format", err)
}
out.Fields = fields
out.SampleRows = rows
preview := data
if len(preview) > 4096 {
preview = preview[:4096]
}
out.Preview = string(preview)
default:
fields, rows, preview, err := extractCSVSchema(data)
if err != nil {
@@ -221,6 +240,7 @@ func guessXMLItemPath(data []byte) string {
full string
}
cands := []cand{
{"shopitem", "shop/shopitem"},
{"item", "rss/channel/item"},
{"product", "products/product"},
{"entry", "feed/entry"},
@@ -232,7 +252,6 @@ func guessXMLItemPath(data []byte) string {
if path := findFirstTagPath(data, c.local); path != "" {
return path
}
return c.full
}
}
return "rss/channel/item"
@@ -527,3 +546,20 @@ func buildXMLPreview(data []byte, itemLocal string) string {
_ = itemLocal
return strings.Join(out, "\n")
}
func extractJSONSchema(data []byte, itemPath string) ([]SchemaField, int, error) {
acc := map[string]*fieldAcc{}
rows := 0
_, err := parseJSONItems(bytes.NewReader(data), itemPath, func(row feedRow) error {
rows++
if rows > schemaMaxRows {
return errStopSchema
}
accumulateRowFields(acc, row)
return nil
})
if err != nil && !errors.Is(err, errStopSchema) {
return nil, rows, err
}
return finalizeSchema(acc), rows, nil
}
+89
View File
@@ -0,0 +1,89 @@
package feeds
import (
"encoding/json"
"errors"
"net/http"
"os"
"strings"
"github.com/descrybe/descrybe-v2/apps/api/internal/platformsettings"
)
// Custom remote source headers are stored only as encrypted options; never in response DTOs.
func validatedFeedHeaders(input map[string]string) (map[string]string, error) {
if len(input) > 20 {
return nil, ClientMsg("at most 20 HTTP headers")
}
clean := make(map[string]string, len(input))
for name, value := range input {
name = http.CanonicalHeaderKey(strings.TrimSpace(name))
value = strings.TrimSpace(value)
if !httpValidHeaderName(name) || strings.ContainsAny(value, "\r\n") || len(value) > 4096 {
return nil, ClientMsg("invalid feed HTTP header")
}
switch strings.ToLower(name) {
case "host", "connection", "content-length", "transfer-encoding", "cookie", "proxy-authorization", "proxy-connection", "upgrade":
return nil, ClientMsg("unsafe feed HTTP header")
}
if value != "" {
clean[name] = value
}
}
return clean, nil
}
func httpValidHeaderName(name string) bool {
if name == "" || len(name) > 100 {
return false
}
for _, r := range name {
if !(r >= 'A' && r <= 'Z' || r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || strings.ContainsRune("!#$%&'*+-.^_`|~", r)) {
return false
}
}
return true
}
func secretEncryptionKey() []byte {
material := os.Getenv("APP_ENCRYPTION_KEY")
if material == "" {
material = os.Getenv("CREDENTIALS_ENCRYPTION_KEY")
}
return platformsettings.DeriveKey(material, os.Getenv("TOKEN_SIGNING_SECRET"))
}
func encryptFeedHeaders(headers map[string]string) (string, error) {
clean, err := validatedFeedHeaders(headers)
if err != nil {
return "", err
}
if len(clean) == 0 {
return "", nil
}
key := secretEncryptionKey()
if len(key) != 32 {
return "", errors.New("APP_ENCRYPTION_KEY is required for authenticated feed URLs")
}
b, err := json.Marshal(clean)
if err != nil {
return "", err
}
return platformsettings.EncryptSecret(key, string(b))
}
func decryptFeedHeaders(options any) (map[string]string, error) {
opt, ok := options.(map[string]any)
if !ok {
return nil, nil
}
encrypted, _ := opt["request_headers_encrypted"].(string)
if encrypted == "" {
return nil, nil
}
plain, err := platformsettings.DecryptSecret(secretEncryptionKey(), encrypted)
if err != nil {
return nil, errors.New("cannot decrypt feed credentials; ensure same APP_ENCRYPTION_KEY on API and worker")
}
out := map[string]string{}
if err := json.Unmarshal([]byte(plain), &out); err != nil {
return nil, err
}
return validatedFeedHeaders(out)
}
+27 -1
View File
@@ -227,8 +227,34 @@ func isSpecificationsTarget(tgt string) bool {
// CDATA HTML, or flat strings. Empty/missing yields nil.
func resolveSpecifications(row map[string]string, src string) map[string]string {
src = strings.Trim(strings.TrimSpace(src), "/")
if strings.EqualFold(leafName(src), "PARAMS") {
specs := map[string]string{}
for k, v := range row {
if !strings.HasPrefix(strings.ToLower(k), strings.ToLower(src)+"/") {
continue
}
rel := k[len(src)+1:]
if strings.Contains(rel, "/") || strings.EqualFold(rel, "PARAM") {
continue
}
if strings.TrimSpace(v) != "" {
specs[rel] = v
}
}
if len(specs) > 0 {
return normalizeSpecKeys(specs)
}
}
if children := collectPrefixed(row, src); len(children) > 0 {
return normalizeSpecKeys(children)
clean := map[string]string{}
for k, v := range children {
if !strings.Contains(k, "/") {
clean[k] = v
}
}
if len(clean) > 0 {
return normalizeSpecKeys(clean)
}
}
if val, ok := lookupRow(row, src); ok {
if pairs := ParseSpecifications(val); len(pairs) > 0 {
+52 -2
View File
@@ -31,18 +31,23 @@ type feedRow map[string]string
func detectFeedFormat(feedType, contentType, urlHint string, sample []byte) string {
ft := strings.ToLower(strings.TrimSpace(feedType))
if ft == "csv" || ft == "xml" {
if ft == "csv" || ft == "xml" || ft == "json" {
return ft
}
ct := strings.ToLower(contentType)
u := strings.ToLower(urlHint)
switch {
case strings.Contains(ct, "json") || strings.Contains(u, ".json") || strings.Contains(u, "format=json"):
return "json"
case strings.Contains(ct, "csv") || strings.HasSuffix(u, ".csv"):
return "csv"
case strings.Contains(ct, "xml") || strings.HasSuffix(u, ".xml"):
return "xml"
}
trimmed := bytes.TrimSpace(sample)
if len(trimmed) > 0 && (trimmed[0] == '{' || trimmed[0] == '[') {
return "json"
}
if len(trimmed) > 0 && trimmed[0] == '<' {
return "xml"
}
@@ -173,7 +178,7 @@ func guessXMLItemLocal(data []byte) string {
sample = sample[:xmlItemGuessBytes]
}
lower := strings.ToLower(sample)
for _, cand := range []string{"item", "product", "entry", "offer", "row"} {
for _, cand := range []string{"shopitem", "item", "entry", "offer", "row", "product"} {
if strings.Contains(lower, "<"+cand) || strings.Contains(lower, ":"+cand) {
return cand
}
@@ -193,6 +198,7 @@ func readXMLElementMap(dec *xml.Decoder, start xml.StartElement) (feedRow, error
row[start.Name.Local+"/"+key] = a.Value
}
var path []string
var paramName, paramValue string
for {
tok, err := dec.Token()
if err != nil {
@@ -207,7 +213,38 @@ func readXMLElementMap(dec *xml.Decoder, start xml.StartElement) (feedRow, error
row[key] = a.Value
}
case xml.EndElement:
if strings.EqualFold(t.Name.Local, "PARAM") && len(path) >= 2 && strings.EqualFold(path[len(path)-2], "PARAMS") {
name := strings.TrimSpace(paramName)
value := strings.TrimSpace(paramValue)
if name != "" && value != "" {
key := "PARAMS/" + sanitizePathSegment(name)
if key != "PARAMS/" {
row[key] = value
}
}
paramName, paramValue = "", ""
}
if len(path) == 0 {
count := 0
for k := range row {
if strings.HasPrefix(k, "PARAMS/") && !strings.Contains(strings.TrimPrefix(k, "PARAMS/"), "/") {
count++
}
}
if count > 0 {
row["PARAMS"] = fmt.Sprintf("%d named attributes", count)
}
// Supplier feeds often publish additional images as numbered siblings.
images := make([]string, 0, 12)
for i := 1; i <= 50; i++ {
name := fmt.Sprintf("IMGURL_ALTERNATIVE_%02d", i)
if v := strings.TrimSpace(row[name]); v != "" {
images = append(images, v)
}
}
if len(images) > 0 {
row["ADDITIONAL_IMAGE_URLS"] = strings.Join(images, ",")
}
return row, nil
}
path = path[:len(path)-1]
@@ -217,6 +254,19 @@ func readXMLElementMap(dec *xml.Decoder, start xml.StartElement) (feedRow, error
continue
}
leaf := path[len(path)-1]
if len(path) >= 3 && strings.EqualFold(path[len(path)-3], "PARAMS") && strings.EqualFold(path[len(path)-2], "PARAM") {
if strings.EqualFold(leaf, "PARAM_NAME") {
paramName += text
continue
}
if strings.EqualFold(leaf, "VAL") {
paramValue += text
continue
}
if strings.EqualFold(leaf, "ORDER") {
continue
}
}
full := strings.Join(path, "/")
// Prefer nested path as source of truth; only set bare leaf when
// unique (no other nested field already owns this leaf name).
+254
View File
@@ -0,0 +1,254 @@
package feeds
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"regexp"
"sort"
"strconv"
"strings"
)
// parseJSONItems consumes one object at a time from a root array or a nested array
// (data.products, results, items, SHOPITEM, etc). It does not buffer the catalog.
func parseJSONItems(r io.Reader, itemPath string, onRow func(feedRow) error) (int, error) {
dec := json.NewDecoder(bufio.NewReader(r))
dec.UseNumber()
first, err := dec.Token()
if err != nil {
return 0, fmt.Errorf("json: %w", err)
}
count := 0
var visit func(any, []string) error
visit = func(token any, path []string) error {
delim, ok := token.(json.Delim)
if !ok {
return nil
}
switch delim {
case '[':
if jsonItemPathMatches(itemPath, path) || (itemPath == "" && isLikelyJSONItemArray(path)) {
for dec.More() {
var raw json.RawMessage
if err := dec.Decode(&raw); err != nil {
return err
}
var obj any
d := json.NewDecoder(bytes.NewReader(raw))
d.UseNumber()
if err := d.Decode(&obj); err != nil {
return err
}
if _, ok := obj.(map[string]any); !ok {
continue
}
row := feedRow{}
flattenJSONValue(row, "", obj, 0)
expandSpecificationFields(row)
count++
if count > maxParseRows {
return parseTooManyRows()
}
if err := onRow(row); err != nil {
return err
}
}
} else {
for dec.More() {
next, e := dec.Token()
if e != nil {
return e
}
if err := visit(next, path); err != nil {
return err
}
}
}
case '{':
for dec.More() {
k, e := dec.Token()
if e != nil {
return e
}
key, _ := k.(string)
next, e := dec.Token()
if e != nil {
return e
}
if err := visit(next, append(append([]string(nil), path...), key)); err != nil {
return err
}
}
default:
return fmt.Errorf("invalid JSON document")
}
_, err := dec.Token()
return err
}
if err := visit(first, nil); err != nil {
return count, fmt.Errorf("json: %w", err)
}
if count == 0 {
return 0, errors.New("JSON contained no product records; check item path (for example products or data/products)")
}
return count, nil
}
func jsonItemPathMatches(hint string, path []string) bool {
hint = strings.Trim(strings.ToLower(strings.TrimSpace(hint)), "/.")
if hint == "" {
return false
}
hint = strings.ReplaceAll(hint, ".", "/")
actual := strings.ToLower(strings.Join(path, "/"))
return actual == hint || strings.HasSuffix(actual, "/"+hint)
}
func isLikelyJSONItemArray(path []string) bool {
if len(path) == 0 {
return true
}
name := strings.ToLower(path[len(path)-1])
switch name {
case "products", "product", "items", "shopitem", "results", "entries", "offers", "rows", "records", "data":
return true
}
return false
}
func flattenJSONValue(row feedRow, prefix string, v any, depth int) {
if depth > 12 || len(row) > 4000 {
return
}
switch x := v.(type) {
case map[string]any:
keys := make([]string, 0, len(x))
for k := range x {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
path := k
if prefix != "" {
path = prefix + "/" + k
}
flattenJSONValue(row, path, x[k], depth+1)
}
case []any:
if len(x) == 0 {
return
}
// Attribute arrays [{name: ..., value: ...}] become named specification children.
for i, v := range x {
if i >= 250 {
return
}
if m, ok := v.(map[string]any); ok {
name := jsonString(m["name"])
if name == "" {
name = jsonString(m["PARAM_NAME"])
}
value := jsonString(m["value"])
if value == "" {
value = jsonString(m["VAL"])
}
if name != "" && value != "" {
row[prefix] = "Nested attributes"
row[prefix+"/"+sanitizePathSegment(name)] = value
continue
}
}
if s := jsonString(v); s != "" {
if _, ok := v.(map[string]any); !ok {
row[prefix+"/"+strconv.Itoa(i)] = s
continue
}
}
flattenJSONValue(row, prefix+"/"+strconv.Itoa(i), v, depth+1)
}
// For image galleries, keep the first URL in the parent path.
if _, ok := row[prefix]; !ok {
if first := jsonString(x[0]); first != "" {
row[prefix] = first
}
}
case nil:
return
default:
value := jsonString(v)
if value == "" {
return
}
row[prefix] = value
leaf := leafName(prefix)
if _, ok := row[leaf]; !ok && leaf != "" {
row[leaf] = value
}
}
}
func jsonString(v any) string {
switch x := v.(type) {
case string:
return x
case json.Number:
return string(x)
case bool:
return strconv.FormatBool(x)
case float64:
return strconv.FormatFloat(x, 'f', -1, 64)
}
return ""
}
// guessJSONItemPath picks a recognized list field in the preview; callers can override.
func guessJSONItemPath(data []byte) string {
var node any
dec := json.NewDecoder(bytes.NewReader(data))
dec.UseNumber()
if dec.Decode(&node) != nil {
// Schema previews intentionally stop at 512 KiB, often halfway through
// large JSON documents. Recognize the first array property in the prefix.
re := regexp.MustCompile(`(?i)"([^"\\]+)"\s*:\s*\[\s*\{`)
if parts := re.FindSubmatch(data); len(parts) > 1 {
return string(parts[1])
}
return ""
}
var find func(any, []string, int) string
find = func(v any, path []string, depth int) string {
if depth > 5 {
return ""
}
switch x := v.(type) {
case []any:
if len(x) > 0 {
if _, ok := x[0].(map[string]any); ok {
return strings.Join(path, "/")
}
}
case map[string]any:
for _, key := range []string{"products", "items", "SHOPITEM", "results", "data", "records", "product", "entries", "offers", "rows"} {
if n, ok := x[key]; ok {
if p := find(n, append(path, key), depth+1); p != "" || len(path) == 0 && key == "products" {
return p
}
}
}
keys := make([]string, 0, len(x))
for k := range x {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
if p := find(x[k], append(path, k), depth+1); p != "" {
return p
}
}
}
return ""
}
return find(node, nil, 0)
}
+12 -1
View File
@@ -61,7 +61,8 @@ func PresentFeed(feed map[string]any) map[string]any {
"last_synced_at": lastSynced,
"products_updated_at": productsUpdated,
"last_data_at": lastDataAt,
"options": opts,
"options": publicFeedOptions(opts),
"has_auth_headers": opts["request_headers_encrypted"] != nil && opts["request_headers_encrypted"] != "",
}
if deltas, ok := opts["last_sync_deltas"].(map[string]any); ok && deltas != nil {
out["last_sync_deltas"] = deltas
@@ -138,3 +139,13 @@ func formatAPITime(v any) any {
return v
}
}
func publicFeedOptions(opts map[string]any) map[string]any {
safe := make(map[string]any, len(opts))
for k, v := range opts {
if k != "request_headers_encrypted" && k != "request_headers" {
safe[k] = v
}
}
return safe
}
+125 -17
View File
@@ -28,6 +28,7 @@ type CreateInput struct {
SyncIntervalMinutes int
SyncFrequencyHours int // legacy alias; converted to minutes when SyncIntervalMinutes unset
Options map[string]any
RequestHeaders map[string]string
}
func (s *Service) List(ctx context.Context, companyID uuid.UUID, limit, offset int, q string) ([]map[string]any, int64, int64, int64, error) {
@@ -120,6 +121,13 @@ func (s *Service) Create(ctx context.Context, companyID uuid.UUID, in CreateInpu
if opts == nil {
opts = map[string]any{}
}
if len(in.RequestHeaders) > 0 {
encrypted, err := encryptFeedHeaders(in.RequestHeaders)
if err != nil {
return nil, err
}
opts["request_headers_encrypted"] = encrypted
}
itemPath := strings.TrimSpace(in.ItemPath)
if itemPath == "" {
if p, ok := opts["item_path"].(string); ok {
@@ -140,10 +148,13 @@ func (s *Service) Create(ctx context.Context, companyID uuid.UUID, in CreateInpu
feedType = "csv"
} else {
feedType = "xml"
if strings.Contains(strings.ToLower(url), ".json") || strings.Contains(strings.ToLower(url), "format=json") {
feedType = "json"
}
}
}
if feedType != "xml" && feedType != "csv" {
return nil, ClientMsg("feed_type must be xml or csv")
if feedType != "xml" && feedType != "csv" && feedType != "json" {
return nil, ClientMsg("feed_type must be xml, csv or json")
}
interval := in.SyncIntervalMinutes
if interval <= 0 && in.SyncFrequencyHours > 0 {
@@ -273,7 +284,7 @@ func mappingDocIncomplete(item map[string]any, mappingsRaw any, mappings []Field
return true
}
feedType, _ := item["feed_type"].(string)
if !isCSVFeedType(feedType) && feedItemPathHint(item, mappingsRaw) == "" {
if !isCSVFeedType(feedType) && !strings.EqualFold(feedType, "json") && feedItemPathHint(item, mappingsRaw) == "" {
return true
}
return false
@@ -303,8 +314,8 @@ func (s *Service) Update(ctx context.Context, companyID, id uuid.UUID, body map[
return nil, err
}
feedType = strings.ToLower(strings.TrimSpace(feedType))
if feedType != "" && feedType != "xml" && feedType != "csv" {
return nil, ClientMsg("feed_type must be xml or csv")
if feedType != "" && feedType != "xml" && feedType != "csv" && feedType != "json" {
return nil, ClientMsg("feed_type must be xml, csv or json")
}
interval := 0
switch v := body["sync_interval_minutes"].(type) {
@@ -325,6 +336,21 @@ func (s *Service) Update(ctx context.Context, companyID, id uuid.UUID, body map[
}
}
var encryptedHeaders *string
if rawHeaders, exists := body["request_headers"]; exists {
headers := map[string]string{}
if rawHeaders != nil {
b, _ := json.Marshal(rawHeaders)
if err := json.Unmarshal(b, &headers); err != nil {
return nil, ClientMsg("invalid HTTP headers")
}
}
encrypted, err := encryptFeedHeaders(headers)
if err != nil {
return nil, err
}
encryptedHeaders = &encrypted
}
ct, err := s.Pool.Exec(ctx, `
UPDATE input_feeds SET
name = CASE WHEN $3 <> '' THEN $3 ELSE name END,
@@ -332,13 +358,16 @@ func (s *Service) Update(ctx context.Context, companyID, id uuid.UUID, body map[
status = CASE WHEN $5 <> '' THEN $5 ELSE status END,
feed_type = CASE WHEN $6 <> '' THEN $6 ELSE feed_type END,
sync_interval_minutes = CASE WHEN $7 > 0 THEN $7 ELSE sync_interval_minutes END,
options = CASE
WHEN $8 <> '' THEN COALESCE(options, '{}'::jsonb) || jsonb_build_object('item_path', to_jsonb($8::text))
ELSE options
END,
options = CASE WHEN $9::text IS NULL THEN
(CASE WHEN $8 <> '' THEN COALESCE(options, '{}'::jsonb) || jsonb_build_object('item_path', to_jsonb($8::text)) ELSE options END)
WHEN $9::text = '' THEN
(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,
updated_at = now()
WHERE id = $1 AND company_id = $2`,
id, companyID, name, url, status, feedType, interval, strings.TrimSpace(itemPath))
id, companyID, name, url, status, feedType, interval, strings.TrimSpace(itemPath), encryptedHeaders)
if err != nil {
return nil, err
}
@@ -348,15 +377,94 @@ func (s *Service) Update(ctx context.Context, companyID, id uuid.UUID, body map[
return s.Get(ctx, companyID, id)
}
// Delete removes a feed and its unprocessed raw catalog rows. Processed catalog
// entries are retained, and rows shared with another existing feed are reassigned.
func (s *Service) Delete(ctx context.Context, companyID, id uuid.UUID) error {
ct, err := s.Pool.Exec(ctx, `DELETE FROM input_feeds WHERE id = $1 AND company_id = $2`, id, companyID)
_, err := s.DeleteWithCleanup(ctx, companyID, id)
return err
}
// DeleteWithCleanup executes the feed removal and raw-product cleanup atomically.
// It holds a row lock on the feed, which also serializes FK-checked sync writes
// against deletion; a concurrent worker cannot recreate rows for the deleted feed.
// The returned count includes only deleted raw products, never processed results.
func (s *Service) DeleteWithCleanup(ctx context.Context, companyID, id uuid.UUID) (int64, error) {
tx, err := s.Pool.Begin(ctx)
if err != nil {
return err
return 0, err
}
if ct.RowsAffected() == 0 {
return ErrNotFound
defer tx.Rollback(ctx)
var lockedID uuid.UUID
if err := tx.QueryRow(ctx, `
SELECT id FROM input_feeds
WHERE id = $1 AND company_id = $2
FOR UPDATE`, id, companyID).Scan(&lockedID); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return 0, ErrNotFound
}
return 0, err
}
return nil
// Legacy catalogs can associate one product with multiple feed IDs.
// Preserve any shared unprocessed row, but make a surviving feed its owner.
_, err = tx.Exec(ctx, `
WITH shared AS (
SELECT r.id AS raw_id, MIN(f.id::text)::uuid AS replacement
FROM raw_products r
JOIN LATERAL jsonb_array_elements_text(
CASE WHEN jsonb_typeof(r.feed_ids) = 'array' THEN r.feed_ids ELSE '[]'::jsonb END
) AS ids(value) ON true
JOIN input_feeds f ON f.id::text = ids.value
AND f.company_id = $1 AND f.id <> $2
WHERE r.company_id = $1 AND r.feed_id = $2
AND r.is_processed = false
AND r.processing_status IN ('unprocessed', 'failed')
GROUP BY r.id
)
UPDATE raw_products r SET feed_id = shared.replacement, updated_at = now()
FROM shared WHERE r.id = shared.raw_id AND r.company_id = $1`, companyID, id)
if err != nil {
return 0, err
}
// Only truly unprocessed/failed rows owned by this feed are removed.
// 'processing' rows are intentionally retained to avoid racing active AI jobs.
deleted, err := tx.Exec(ctx, `
DELETE FROM raw_products
WHERE company_id = $1 AND feed_id = $2
AND is_processed = false
AND processing_status IN ('unprocessed', 'failed')`, companyID, id)
if err != nil {
return 0, err
}
// Remove references from secondary feed lists on retained products, too.
_, err = tx.Exec(ctx, `
UPDATE raw_products r SET feed_ids = COALESCE((
SELECT jsonb_agg(ids.value ORDER BY ids.ordinality)
FROM jsonb_array_elements_text(r.feed_ids) WITH ORDINALITY AS ids(value, ordinality)
WHERE ids.value <> $2::text
), '[]'::jsonb), updated_at = now()
WHERE r.company_id = $1 AND jsonb_typeof(r.feed_ids) = 'array'
AND r.feed_ids @> jsonb_build_array($2::text)`, companyID, id)
if err != nil {
return 0, err
}
// FK ON DELETE SET NULL preserves processed products, processing rows and
// export feed definitions; dependent mappings / sync jobs cascade as before.
ct, err := tx.Exec(ctx, `DELETE FROM input_feeds WHERE id = $1 AND company_id = $2`, id, companyID)
if err != nil {
return 0, err
}
if ct.RowsAffected() != 1 {
return 0, ErrNotFound
}
if err := tx.Commit(ctx); err != nil {
return 0, err
}
return deleted.RowsAffected(), nil
}
func (s *Service) GetMappings(ctx context.Context, companyID, feedID uuid.UUID) (map[string]any, error) {
@@ -508,8 +616,8 @@ func (s *Service) CreateExportFeed(ctx context.Context, companyID uuid.UUID, in
if format == "" {
format = "xml"
}
if format != "xml" && format != "csv" {
return nil, ClientMsg("format must be xml or csv")
if format != "xml" && format != "csv" && format != "json" {
return nil, ClientMsg("format must be xml, csv or json")
}
var src *uuid.UUID
if in.SourceFeedID != nil && *in.SourceFeedID != "" {
+7 -1
View File
@@ -77,7 +77,11 @@ func (s *Service) loadFeedSource(ctx context.Context, companyID uuid.UUID, feed
if urlStr == "" {
return nil, errSourceRequired
}
return downloadFeed(ctx, urlStr)
headers, err := decryptFeedHeaders(feed["options"])
if err != nil {
return nil, err
}
return downloadFeedWithHeaders(ctx, urlStr, headers)
}
func sourcePathFromOptions(raw any) string {
@@ -121,6 +125,8 @@ func (s *Service) readLocalFeed(companyID uuid.UUID, rel string) (*feedBlob, err
lower := strings.ToLower(abs)
if strings.HasSuffix(lower, ".xml") {
ct = "application/xml"
} else if strings.HasSuffix(lower, ".json") {
ct = "application/json"
}
return &feedBlob{
path: abs,
+25 -23
View File
@@ -8,10 +8,10 @@ import (
)
const (
maxSpecPairs = 200
maxSpecRawBytes = 64 << 10 // 64 KiB per specifications blob
maxSpecLabelRunes = 120
maxSpecValueRunes = 2000
maxSpecPairs = 200
maxSpecRawBytes = 64 << 10 // 64 KiB per specifications blob
maxSpecLabelRunes = 120
maxSpecValueRunes = 2000
)
var (
@@ -94,8 +94,10 @@ func isSpecFieldKey(key string) bool {
leaf := strings.ToLower(leafName(key))
leaf = strings.TrimPrefix(leaf, "@")
switch leaf {
case "specifications", "specification", "specs", "spec", "features", "feature", "attributes_raw":
case "specifications", "specification", "specs", "spec", "features", "feature", "attributes_raw", "params":
return true
case "description":
return !strings.Contains(key, "/")
}
return strings.Contains(leaf, "specification")
}
@@ -407,24 +409,24 @@ func compactAttributeKey(key string) string {
// Known supplier / locale labels → Descrybe standard field keys (snake_case).
// Freeform specs keep kebab-case from AttributeKeyFromLabel.
var attributeKeyAliases = map[string]string{
"visina": "net_height",
"height": "net_height",
"netheight": "net_height",
"sirina": "net_width",
"width": "net_width",
"netwidth": "net_width",
"globina": "net_depth",
"depth": "net_depth",
"netdepth": "net_depth",
"netmass": "net_mass",
"mass": "net_mass",
"weight": "net_mass",
"teza": "net_mass",
"productmodel": "product_model",
"model": "product_model",
"eprelid": "eprel_id",
"eprel": "eprel_id",
"energyclass": "energy_class",
"visina": "net_height",
"height": "net_height",
"netheight": "net_height",
"sirina": "net_width",
"width": "net_width",
"netwidth": "net_width",
"globina": "net_depth",
"depth": "net_depth",
"netdepth": "net_depth",
"netmass": "net_mass",
"mass": "net_mass",
"weight": "net_mass",
"teza": "net_mass",
"productmodel": "product_model",
"model": "product_model",
"eprelid": "eprel_id",
"eprel": "eprel_id",
"energyclass": "energy_class",
"energijskirazred": "energy_class",
}
+60 -54
View File
@@ -11,60 +11,66 @@ type MappingSuggestion struct {
}
var sourceAliases = map[string][]string{
"gtin": {"gtin"},
"ean": {"gtin"},
"upc": {"gtin"},
"barcode": {"gtin"},
"title": {"title"},
"name": {"title"},
"productname": {"title"},
"brand": {"brand"},
"manufacturer": {"brand"},
"description": {"description"},
"desc": {"description"},
"price": {"price"},
"regularprice": {"price"},
"saleprice": {"sale_price", "price"},
"currency": {"currency"},
"image": {"image_url", "main_image", "image"},
"imageurl": {"image_url", "main_image", "image"},
"imagelink": {"image_url", "main_image", "image"},
"mainimage": {"image_url", "main_image", "image"},
"mainimageurl": {"image_url", "main_image", "image"},
"link": {"product_url"},
"url": {"product_url"},
"producturl": {"product_url"},
"sku": {"sku"},
"mpn": {"mpn"},
"category": {"category"},
"availability": {"availability"},
"stockstatus": {"availability", "stock_status"},
"stock": {"stock"},
"quantity": {"stock"},
"qty": {"stock"},
"color": {"color"},
"size": {"size"},
"material": {"material"},
"weight": {"weight"},
"netmass": {"weight"},
"purchaseprice": {"purchase_price", "price"},
"buyprice": {"purchase_price"},
"cost": {"purchase_price"},
"costprice": {"purchase_price"},
"officiallink": {"official_link"},
"warranty": {"warranty"},
"garancija": {"warranty"},
"service": {"service"},
"servis": {"service"},
"productmodel": {"product_model"},
"model": {"product_model"},
"modelnumber": {"product_model"},
"eprelid": {"eprel_id"},
"eprel": {"eprel_id"},
"specifications": {"specs", "specifications"},
"specs": {"specs", "specifications"},
"specification": {"specs", "specifications"},
"techspecs": {"specs", "specifications"},
"gtin": {"gtin"},
"productno": {"sku"}, "productno2": {"mpn"},
"product": {"title"}, "descriptionbasic": {"description"},
"pricevat": {"price"}, "priceeshopvat": {"price"},
"pricevoc": {"purchase_price"},
"imgurl": {"image_url"}, "params": {"specifications"},
"categoryid": {"category_id"},
"ean": {"gtin"},
"upc": {"gtin"},
"barcode": {"gtin"},
"title": {"title"},
"name": {"title"},
"productname": {"title"},
"brand": {"brand"},
"manufacturer": {"brand"},
"description": {"description"},
"desc": {"description"},
"price": {"price"},
"regularprice": {"price"},
"saleprice": {"sale_price", "price"},
"currency": {"currency"},
"image": {"image_url", "main_image", "image"},
"imageurl": {"image_url", "main_image", "image"},
"imagelink": {"image_url", "main_image", "image"},
"mainimage": {"image_url", "main_image", "image"},
"mainimageurl": {"image_url", "main_image", "image"},
"link": {"product_url"},
"url": {"product_url"},
"producturl": {"product_url"},
"sku": {"sku"},
"mpn": {"mpn"},
"category": {"category"},
"availability": {"availability"},
"stockstatus": {"availability", "stock_status"},
"stock": {"stock"},
"quantity": {"stock"},
"qty": {"stock"},
"color": {"color"},
"size": {"size"},
"material": {"material"},
"weight": {"weight"},
"netmass": {"weight"},
"purchaseprice": {"purchase_price", "price"},
"buyprice": {"purchase_price"},
"cost": {"purchase_price"},
"costprice": {"purchase_price"},
"officiallink": {"official_link"},
"warranty": {"warranty"},
"garancija": {"warranty"},
"service": {"service"},
"servis": {"service"},
"productmodel": {"product_model"},
"model": {"product_model"},
"modelnumber": {"product_model"},
"eprelid": {"eprel_id"},
"eprel": {"eprel_id"},
"specifications": {"specs", "specifications"},
"specs": {"specs", "specifications"},
"specification": {"specs", "specifications"},
"techspecs": {"specs", "specifications"},
}
func normalizeSuggestKey(raw string) string {
+16
View File
@@ -402,7 +402,23 @@ func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUI
var parseCount int
switch format {
case "xml":
if itemPath == "item" {
itemPath = ""
}
parseCount, err = parseXMLItems(body, itemPath, onRow)
case "json":
jsonPath := itemPath
if jsonPath == "item" {
jsonPath = ""
}
if v := itemPathFromMappings(mappingsRaw); v != "" {
jsonPath = v
} else if opts, ok := feed["options"].(map[string]any); ok {
if v, ok := opts["item_path"].(string); ok {
jsonPath = v
}
}
parseCount, err = parseJSONItems(body, jsonPath, onRow)
default:
parseCount, err = parseCSV(body, onRow)
}
@@ -0,0 +1,47 @@
package feeds
import (
"strings"
"testing"
)
const emos = `<?xml version="1.0"?><SHOP><SHOPITEM><PRODUCT>Ročna LED svetilka 9 LED 3×AAA</PRODUCT><PRODUCTNO>1440093109</PRODUCTNO><EAN>8595025395184</EAN><CATEGORY>Svetilke|Ročne svetilke</CATEGORY><DESCRIPTION>barva: mešanica barv|napajanje: 3× AAA|svetlobni tok: 50 lm</DESCRIPTION><DESCRIPTION_BASIC>&lt;p&gt;Praktična LED svetilka&lt;/p&gt;</DESCRIPTION_BASIC><PARAMS><PARAM><PARAM_NAME>barva</PARAM_NAME><VAL>mešanica barv</VAL><ORDER>12</ORDER></PARAM><PARAM><PARAM_NAME>napajanje</PARAM_NAME><VAL>3× AAA</VAL></PARAM><PARAM><PARAM_NAME>vir svetlobe</PARAM_NAME><VAL>9× LED</VAL></PARAM></PARAMS><IMGURL>https://example.com/1.jpg</IMGURL><IMGURL_ALTERNATIVE_01>https://example.com/2.jpg</IMGURL_ALTERNATIVE_01></SHOPITEM></SHOP>`
func TestV10EMOSItemAndAttrs(t *testing.T) {
var got feedRow
n, e := parseXMLItems(strings.NewReader(emos), "", func(r feedRow) error { got = r; return nil })
if e != nil || n != 1 {
t.Fatalf("parse n=%d err=%v", n, e)
}
for k, v := range map[string]string{"PRODUCT": "Ročna LED svetilka 9 LED 3×AAA", "EAN": "8595025395184", "PARAMS/barva": "mešanica barv", "PARAMS/napajanje": "3× AAA", "PARAMS/vir_svetlobe": "9× LED", "DESCRIPTION/svetlobni_tok": "50 lm", "ADDITIONAL_IMAGE_URLS": "https://example.com/2.jpg"} {
if got[k] != v {
t.Errorf("%s=%q want %q", k, got[k], v)
}
}
}
func TestV10NestedJSONWrappedData(t *testing.T) {
raw := `{"data":{"products":[{"name":"Demo 1","ean":"1234567890123","attributes":[{"name":"color","value":"green"}]},{"name":"Demo 2","ean":"1234567890999"}]},"page":1}`
var rows []feedRow
n, e := parseJSONItems(strings.NewReader(raw), "", func(r feedRow) error { rows = append(rows, r); return nil })
if e != nil || n != 2 {
t.Fatalf("parse n=%d err=%v", n, e)
}
if rows[0]["attributes/color"] != "green" {
t.Errorf("nested attrs lost: %v", rows[0])
}
}
func TestV10JSONRootAndData(t *testing.T) {
for _, raw := range []string{`[{"ean":"1"},{"ean":"2"}]`, `{"data":[{"ean":"1"},{"ean":"2"}]}`} {
n, e := parseJSONItems(strings.NewReader(raw), "", func(r feedRow) error { return nil })
if e != nil || n != 2 {
t.Fatalf("input=%s got n=%d err=%v", raw, n, e)
}
}
}
func TestV10PartialPreviewJSONGuess(t *testing.T) {
x := []byte(`{"data":{"products":[{"EAN":"123","sku":"demo"},`)
p := guessJSONItemPath(x)
if p != "products" {
t.Fatalf("guess=%q", p)
}
}
@@ -1,8 +1,12 @@
package httpapi
import (
"encoding/json"
"github.com/descrybe/descrybe-v2/apps/api/internal/feeds"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/descrybe/descrybe-v2/apps/api/internal/catalog"
@@ -191,6 +195,50 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) {
return
}
if strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "application/json") {
var req struct {
URL string `json:"url"`
RequestHeaders map[string]string `json:"request_headers"`
Format string `json:"format"`
}
if err := json.NewDecoder(io.LimitReader(r.Body, 64<<10)).Decode(&req); err != nil {
Error(w, http.StatusBadRequest, "invalid JSON request")
return
}
if strings.TrimSpace(req.URL) == "" {
Error(w, http.StatusBadRequest, "url required")
return
}
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)
return
}
defer source.Close()
var data io.Reader = source
if strings.EqualFold(req.Format, "json") || strings.Contains(strings.ToLower(req.URL), "json") {
data, err = catalog.JSONImportAsCSV(source, kind)
if err != nil {
ClientOrLog(w, http.StatusBadRequest, "invalid JSON import", err, catalog.ClientError)
return
}
}
var result catalog.ImportResult
switch kind {
case "categories":
result, err = s.Catalog.ImportCategoriesCSV(r.Context(), cid, data)
case "attributes":
result, err = s.Catalog.ImportAttributesCSV(r.Context(), cid, data)
case "products":
result, err = s.Catalog.ImportProductsCSV(r.Context(), 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"})
return
}
if err := r.ParseMultipartForm(catalogMaxUpload); err != nil {
Error(w, http.StatusBadRequest, "invalid multipart form")
return
@@ -228,14 +276,22 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) {
defer f.Close()
var result any
var input io.Reader = f
if strings.EqualFold(filepath.Ext(header.Filename), ".json") || strings.Contains(strings.ToLower(header.Header.Get("Content-Type")), "application/json") {
input, err = catalog.JSONImportAsCSV(f, kind)
if err != nil {
Error(w, http.StatusBadRequest, err.Error())
return
}
}
switch kind {
case "categories":
result, err = s.Catalog.ImportCategoriesCSV(r.Context(), cid, f)
result, err = s.Catalog.ImportCategoriesCSV(r.Context(), cid, input)
case "attributes":
result, err = s.Catalog.ImportAttributesCSV(r.Context(), cid, f)
result, err = s.Catalog.ImportAttributesCSV(r.Context(), cid, input)
case "products":
fid := fileID
result, err = s.Catalog.ImportProductsCSV(r.Context(), cid, f, &fid)
result, err = s.Catalog.ImportProductsCSV(r.Context(), cid, input, &fid)
}
if err != nil {
public := "import failed"
+37 -8
View File
@@ -1,6 +1,7 @@
package httpapi
import (
"encoding/json"
"errors"
"fmt"
"net/http"
@@ -46,11 +47,12 @@ func (s *Server) handleCreateFeed(w http.ResponseWriter, r *http.Request) {
}
var body struct {
Name string `json:"name"`
URL string `json:"url"`
ItemPath string `json:"item_path"`
FeedType string `json:"feed_type"`
SyncIntervalMinutes int `json:"sync_interval_minutes"`
Name string `json:"name"`
URL string `json:"url"`
ItemPath string `json:"item_path"`
FeedType string `json:"feed_type"`
SyncIntervalMinutes int `json:"sync_interval_minutes"`
RequestHeaders map[string]string `json:"request_headers"`
}
if err := DecodeJSON(r, &body); err != nil {
Error(w, http.StatusBadRequest, "invalid json")
@@ -62,6 +64,7 @@ func (s *Server) handleCreateFeed(w http.ResponseWriter, r *http.Request) {
ItemPath: body.ItemPath,
FeedType: body.FeedType,
SyncIntervalMinutes: body.SyncIntervalMinutes,
RequestHeaders: body.RequestHeaders,
})
if err != nil {
ClientOrLog(w, http.StatusBadRequest, "could not create feed", err, feeds.ClientError)
@@ -81,6 +84,13 @@ 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")))
headers := map[string]string{}
if raw := strings.TrimSpace(r.FormValue("request_headers")); raw != "" {
if err := json.Unmarshal([]byte(raw), &headers); err != nil {
Error(w, http.StatusBadRequest, "invalid request_headers JSON")
return
}
}
file, header, fileErr := r.FormFile("file")
var options map[string]any
@@ -107,10 +117,15 @@ func (s *Server) createFeedFromMultipart(w http.ResponseWriter, r *http.Request,
"source_path": pathStr,
"source_file_id": fileID,
"source_filename": fileName,
"source_kind": "csv",
"source_kind": feedType,
}
if feedType == "" {
feedType = "csv"
if strings.HasSuffix(strings.ToLower(header.Filename), ".xml") {
feedType = "xml"
} else if strings.HasSuffix(strings.ToLower(header.Filename), ".json") {
feedType = "json"
}
}
if fid, err := uuid.Parse(fileID); err == nil {
_, _ = s.Catalog.UpdateFileStatus(r.Context(), cid, fid, "uploaded", map[string]any{
@@ -131,6 +146,7 @@ func (s *Server) createFeedFromMultipart(w http.ResponseWriter, r *http.Request,
FeedType: feedType,
SyncIntervalMinutes: interval,
Options: options,
RequestHeaders: headers,
})
if err != nil {
ClientOrLog(w, http.StatusBadRequest, "could not create feed", err, feeds.ClientError)
@@ -192,7 +208,8 @@ func (s *Server) handleDeleteFeed(w http.ResponseWriter, r *http.Request) {
Error(w, http.StatusBadRequest, "invalid id")
return
}
if err := s.Feeds.Delete(r.Context(), cid, id); err != nil {
deletedUnprocessed, err := s.Feeds.DeleteWithCleanup(r.Context(), cid, id)
if err != nil {
if feeds.IsNotFound(err) {
Error(w, http.StatusNotFound, "not found")
return
@@ -200,7 +217,10 @@ func (s *Server) handleDeleteFeed(w http.ResponseWriter, r *http.Request) {
Error(w, http.StatusInternalServerError, "delete failed")
return
}
JSON(w, http.StatusOK, map[string]any{"id": id.String(), "deleted": true})
JSON(w, http.StatusOK, map[string]any{
"id": id.String(), "deleted": true,
"deleted_unprocessed_products": deletedUnprocessed,
})
}
func (s *Server) handleSyncFeed(w http.ResponseWriter, r *http.Request) {
@@ -584,6 +604,15 @@ func (s *Server) handlePublicExportCSV(w http.ResponseWriter, r *http.Request) {
}
}
func (s *Server) handlePublicExportJSON(w http.ResponseWriter, r *http.Request) {
token := chi.URLParam(r, "token")
lw := &lazyHeaderWriter{ResponseWriter: w, contentType: "application/json; charset=utf-8"}
if err := s.Feeds.PublicExportJSON(r.Context(), lw, token); err != nil {
if !lw.wrote {
writePublicExportError(w, err)
}
}
}
func writePublicExportError(w http.ResponseWriter, err error) {
// Format mismatch must look identical to unknown tokens so probing .xml/.csv
// cannot confirm whether a guessed public_token exists.
+1
View File
@@ -301,6 +301,7 @@ func (s *Server) Router() http.Handler {
r.Get("/support-kb/{filename}", s.handlePublicKBImage)
r.With(s.RateLimitPublicExport).Get("/export-feeds/{token}.xml", s.handlePublicExportXML)
r.With(s.RateLimitPublicExport).Get("/export-feeds/{token}.csv", s.handlePublicExportCSV)
r.With(s.RateLimitPublicExport).Get("/export-feeds/{token}.json", s.handlePublicExportJSON)
r.Get("/unsubscribe", s.handlePublicUnsubscribeGet)
r.Post("/unsubscribe", s.handlePublicUnsubscribePost)
r.NotFound(func(w http.ResponseWriter, _ *http.Request) {
@@ -43,8 +43,8 @@ func presentV1ExportFeed(item map[string]any) map[string]any {
if token, _ := item["public_token"].(string); token != "" {
format := strings.ToLower(strings.TrimSpace(fmt.Sprint(item["format"])))
ext := "xml"
if format == "csv" {
ext = "csv"
if format == "csv" || format == "json" {
ext = format
}
path := "/api/public/export-feeds/" + token + "." + ext
// Only advertise the matching extension — wrong-format URLs 404 and must not
@@ -157,8 +157,8 @@ func (s *Server) handleV1GenerateExportFeed(w http.ResponseWriter, r *http.Reque
format = strings.ToLower(strings.TrimSpace(fmt.Sprint(result["format"])))
}
ext := "xml"
if format == "csv" {
ext = "csv"
if format == "csv" || format == "json" {
ext = format
}
token, _ := feed["public_token"].(string)
downloadURL := fmt.Sprintf("/api/export-feeds/%s/%s", id.String(), ext)
@@ -0,0 +1,27 @@
package httpapi
import (
"strings"
"testing"
)
func TestPublicJSONExportOnlyAdvertisesJSON(t *testing.T) {
item := presentV1ExportFeed(map[string]any{
"id": "00000000-0000-0000-0000-000000000001",
"name": "JSON catalog", "format": "json", "public_token": "exampleToken",
})
urls, ok := item["public_urls"].(map[string]string)
if !ok {
t.Fatalf("public_urls missing: %#v", item)
}
got := urls["json"]
if got != "/api/public/export-feeds/exampleToken.json" {
t.Fatalf("json URL = %q", got)
}
if _, exists := urls["xml"]; exists {
t.Fatal("JSON export must not advertise XML URL")
}
if !strings.HasSuffix(urls["token"], ".json") {
t.Fatalf("token URL = %q", urls["token"])
}
}
+46 -20
View File
@@ -17,8 +17,10 @@ info:
## Authentication
All /api/v1 operations require a company API key (Bearer or X-API-Key) except
GET /health and GET /openapi.yaml.
Public /api/v1 operations require a company API key (Bearer or X-API-Key)
except GET /health and GET /openapi.yaml. Dashboard-only Team/Admin
operations described separately use a signed-in session and CSRF header;
they are not executable with a company API key.
Document-level security is BearerAuth OR ApiKeyAuth (same key value).
Do not send dashboard session cookies or CSRF tokens to /api/v1.
@@ -36,7 +38,8 @@ info:
1. Sign in at https://api.descrybe.io
2. Open Settings -> API keys (/settings?tab=api-keys)
3. Company admins create a key via dashboard POST /api/api-keys
3. Company admins or teammates granted API Keys management permission create
a key via dashboard POST /api/api-keys
(session cookie + CSRF; not this public OpenAPI surface). The secret is
shown once and starts with dk_.
4. Store it securely. Later list/revoke shows only key_prefix (first 10
@@ -134,8 +137,10 @@ info:
items[].description on the start body is optional source text the model may
rewrite. Poll GET /products/process/{id} for the generated HTML.
meta_title / meta_description are separate short SEO fields and may be
omitted depending on company configuration.
meta_title / meta_description are separate short SEO fields. The SEO-only
processing_type seo_meta generates these fields without replacing saved
product titles or descriptions. Company feature policies may still suppress
metadata output.
Note: Dashboard JSON under /api/* uses session cookies + CSRF and is separate
from this public API-key surface. Other path aliases
@@ -2136,7 +2141,7 @@ paths:
application/json:
schema:
type: object
required: [name, item_path]
required: [name]
properties:
name:
type: string
@@ -2144,7 +2149,9 @@ paths:
item_path:
type: string
description: |
XML item xpath / path stored in options.item_path (e.g. channel/item). Required.
Optional XML record path stored in options.item_path (e.g. SHOPITEM).
Auto-detection is available for typical feeds. For JSON use the item
array path (e.g. results or data.products) when needed.
url:
type: string
format: uri
@@ -2156,7 +2163,8 @@ paths:
enum:
- xml
- csv
description: Source format. xml (default) or csv.
- json
description: Source format. xml, csv or json; defaults to xml when not detected.
sync_interval_minutes:
type: integer
minimum: 1
@@ -2366,13 +2374,14 @@ paths:
description: Remote feed URL, or null to clear
item_path:
type: string
description: XML item xpath / path (stored in options.item_path)
description: Optional XML record path or JSON array path (stored in options.item_path)
feed_type:
type: string
enum:
- xml
- csv
description: Source format. xml or csv.
- json
description: Source format. xml, csv or json.
status:
type: string
description: |
@@ -2472,7 +2481,12 @@ paths:
tags:
- Feeds
summary: Delete feed
description: "Company-admin only. Flat { id, deleted: true } (not a message envelope)."
description: >-
Company-admin only. Atomically removes the input feed and its exclusively
owned, unprocessed or failed raw products. Previously processed products
are retained; active processing rows are not deleted, and products shared
with another existing feed are reassigned to that feed. Flat response
with id, deleted, and deleted_unprocessed_products (no message envelope).
responses:
'200':
description: Feed deleted. Flat FeedDeleted when handleDeleteFeed succeeds. Requires company-admin
@@ -2484,6 +2498,7 @@ paths:
example:
id: 22222222-2222-2222-2222-222222222222
deleted: true
deleted_unprocessed_products: 18
'400':
description: Invalid feed UUID.
content:
@@ -2866,7 +2881,7 @@ paths:
properties:
item_path:
type: string
description: Optional XML item path hint; inferred when omitted
description: Optional XML record path or JSON array path hint; inferred when omitted
example:
item_path: channel/item
responses:
@@ -3165,7 +3180,8 @@ paths:
enum:
- xml
- csv
description: Output format. xml or csv (required).
- json
description: Output format. xml, csv or json (required).
source_feed_id:
type: string
format: uuid
@@ -3660,7 +3676,7 @@ paths:
- Export feeds
summary: Rotate public export URL token
description: |
Replaces public_token so the previous /api/public/export-feeds/{token}.{xml|csv}
Replaces public_token so the previous /api/public/export-feeds/{token}.{xml|csv|json}
URL stops working immediately. Requires company admin (or platform staff).
Response is a flat ExportFeedDetail including the new public_token.
parameters:
@@ -5228,11 +5244,13 @@ components:
description: |
full (default) runs the whole pipeline including AI enhance, which
writes formula-driven HTML descriptions (not a one- or two-sentence
blurb). Named steps category|title|description|attributes (string or
blurb). Named steps category|title|description|attributes|seo_meta (string or
array of those steps); dual-mode also accepts v2 dashboard types such as
normalize_only, enhance_only, attributes_only, eprel_only, categorize_only
(ParseV1ProcessingType). Alias processingType accepted when values match.
The description step still emits the category formula HTML body.
The description step emits the category formula HTML body.
seo_meta generates meta_title and meta_description, preserving
existing product titles and descriptions.
oneOf:
- type: string
enum:
@@ -5241,6 +5259,7 @@ components:
- title
- description
- attributes
- seo_meta
- normalize_only
- enhance
- enhance_only
@@ -5261,6 +5280,7 @@ components:
- title
- description
- attributes
- seo_meta
processingType:
description: CamelCase alias of processing_type (must match if both set)
oneOf:
@@ -5272,7 +5292,7 @@ components:
type: array
items:
type: string
description: Dashboard fine-grained steps; used when processing_type omitted
description: Informational dashboard selection; execution uses processing_type.
examples:
by_ean:
summary: "items[].ean (preferred)"
@@ -5318,15 +5338,15 @@ components:
processing_type:
type: string
description: |
full (default) or a named dashboard step (category, title, description,
attributes, normalize_only, enhance_only, …).
full (default) or a named processing mode (title, description, seo_meta,
seo_meta, attributes, normalize_only, enhance_only, …).
default: full
example: full
processing_types:
type: array
items:
type: string
description: Optional fine-grained steps (dashboard); StartJob uses processing_type
description: Informational dashboard selection; execution uses processing_type. For seo_meta alone set processing_type to seo_meta.
example:
raw_product_ids:
- 2c5ea4c0-4067-4e44-8c5a-9a8b7c6d5e4f
@@ -6064,12 +6084,18 @@ components:
required:
- id
- deleted
- deleted_unprocessed_products
properties:
id:
type: string
format: uuid
deleted:
type: boolean
deleted_unprocessed_products:
type: integer
format: int64
minimum: 0
description: Number of unprocessed/failed raw products deleted with this feed.
PreparedCampaign:
type: object
properties:
+22
View File
@@ -1587,6 +1587,28 @@ func (p *Pipeline) processOne(ctx context.Context, companyID, jobID uuid.UUID, i
if err != nil {
return false, 0, StepResult{}, err
}
if strings.EqualFold(strings.TrimSpace(processingType), "seo_meta") {
// SEO metadata processing must not rewrite product display content.
if in.PriorProcessedName != "" {
result.ProcessedName = in.PriorProcessedName
}
if in.PriorProcessedDescription != "" {
result.ProcessedDescription = in.PriorProcessedDescription
}
if in.PriorCategory != "" {
result.Category = in.PriorCategory
}
for lang, fields := range result.LocalizedContent {
previous := company.FieldsForLanguage(in.PriorLocalized, lang)
if previous.ProcessedName != "" {
fields.ProcessedName = previous.ProcessedName
}
if previous.ProcessedDescription != "" {
fields.ProcessedDescription = previous.ProcessedDescription
}
result.LocalizedContent[lang] = fields
}
}
// Persist mapped unique_id only when it exists in the company taxonomy.
// Coerce display names (feed/vector) → unique_id before filtering so A1-style
// name tokens are not wiped. Empty taxonomy set skips filtering (unit tests).
@@ -0,0 +1,42 @@
package processing
import (
"reflect"
"testing"
)
func TestSEOMetaOnlySelectsEnrichmentPrerequisites(t *testing.T) {
steps := resolveSteps("seo_meta")
want := []string{StepNormalize, StepParseSpecs, StepFillFields, StepCategorize, StepAIEnhance}
if !reflect.DeepEqual(steps, want) {
t.Fatalf("seo_meta steps = %v, want %v", steps, want)
}
}
func TestSEOMetaAcceptedByPublicProcess(t *testing.T) {
storage, response, err := ParseV1ProcessingType("seo_meta")
if err != nil || storage != "seo_meta" || response != "seo_meta" {
t.Fatalf("ParseV1ProcessingType(seo_meta) = %q, %v, %v", storage, response, err)
}
}
func TestSEOMetaPartialResultIncludesMetaNotCopy(t *testing.T) {
input := []V1ProcessJobItem{{
"ean": "1234567890123", "name": "Existing name", "description": "Existing description",
"meta_title": "SEO title", "meta_description": "SEO description", "status": "completed",
}}
result := ProjectV1ProcessJobItems("seo_meta", input)
if len(result) != 1 {
t.Fatalf("items = %d", len(result))
}
item := result[0]
if item["meta_title"] != "SEO title" || item["meta_description"] != "SEO description" {
t.Fatalf("missing SEO metadata: %#v", item)
}
if _, found := item["name"]; found {
t.Fatalf("SEO-only response must not project title: %#v", item)
}
if _, found := item["description"]; found {
t.Fatalf("SEO-only response must not project description: %#v", item)
}
}
+55 -5
View File
@@ -314,10 +314,22 @@ func (e *Engine) RunSteps(ctx context.Context, companyID string, in ProductInput
priorDesc = in.PriorProcessedDescription
}
}
metaOnly := strings.EqualFold(strings.TrimSpace(processingType), "seo_meta")
promptName, promptDesc := out.Name, out.Description
if metaOnly {
if priorName != "" {
promptName = priorName
}
if priorDesc != "" {
promptDesc = priorDesc
}
// Bypass unrelated description/title hash caching for a metadata refresh.
priorHash = ""
}
name, desc, tokens, raw, err := e.enhance(ctx, ProductInput{
GTIN: in.GTIN,
Name: out.Name,
Description: out.Description,
Name: promptName,
Description: promptDesc,
Mapped: normalized,
BrandPrompt: in.BrandPrompt,
Language: lang,
@@ -405,6 +417,14 @@ func (e *Engine) RunSteps(ctx context.Context, companyID string, in ProductInput
allUnchanged = false
}
}
if metaOnly {
// Do not persist unrelated AI rewrites on SEO-only jobs.
name, desc = promptName, promptDesc
persistHash = company.FieldsForLanguage(in.PriorLocalized, lang).EnhanceInputHash
if lang == primary && persistHash == "" {
persistHash = in.PriorEnhanceHash
}
}
localized[lang] = company.LocalizedFields{
ProcessedName: name,
ProcessedDescription: desc,
@@ -444,7 +464,7 @@ func (e *Engine) RunSteps(ctx context.Context, companyID string, in ProductInput
}
// Merge LLM attrs onto pipeline attrs (validated against category keys).
// Attrs are independent of title/description soft-fail (synthesized/refused).
if err == nil && status != "failed" && status != "parse_failed" {
if !metaOnly && err == nil && status != "failed" && status != "parse_failed" {
if merged := mergeEnhanceAttrsInto(attrs, enhanceAttrsFromRaw(raw), enhanceAllowedAttrKeys(in, out.Category)); len(merged) > 0 {
attrs = merged
enhanceAttrs = AttrsForEnhance(attrs, enhanceAllowedAttrKeys(in, out.Category))
@@ -576,7 +596,7 @@ func (e *Engine) RunSteps(ctx context.Context, companyID string, in ProductInput
// repair short prose / title echo that ignored A1 description_template.
finalDescTpl := effectiveDescriptionTemplateFor(in, out)
finalRepaired := false
if descriptionNeedsEnhanceRepair(out.ProcessedDescription, finalDescTpl, out.ProcessedName, out.Name) {
if !strings.EqualFold(strings.TrimSpace(processingType), "seo_meta") && descriptionNeedsEnhanceRepair(out.ProcessedDescription, finalDescTpl, out.ProcessedName, out.Name) {
if synth := synthesizeProductDescription(out.ProcessedName, displayCat, in.Language, out.Attributes, finalDescTpl); synth != "" {
out.ProcessedDescription = synth
finalRepaired = true
@@ -605,6 +625,36 @@ func (e *Engine) RunSteps(ctx context.Context, companyID string, in ProductInput
out.LocalizedContent[lang] = lf
}
}
if strings.EqualFold(strings.TrimSpace(processingType), "seo_meta") {
// Preserve existing product copy even if enhancement attempted title/description
// repair internally while building SEO metadata.
if in.PriorProcessedName != "" {
out.ProcessedName = in.PriorProcessedName
} else {
out.ProcessedName = out.Name
}
if in.PriorProcessedDescription != "" {
out.ProcessedDescription = in.PriorProcessedDescription
} else {
out.ProcessedDescription = out.Description
}
for lang, fields := range out.LocalizedContent {
old := company.FieldsForLanguage(in.PriorLocalized, lang)
if old.ProcessedName != "" {
fields.ProcessedName = old.ProcessedName
} else {
fields.ProcessedName = out.Name
}
if old.ProcessedDescription != "" {
fields.ProcessedDescription = old.ProcessedDescription
} else {
fields.ProcessedDescription = out.Description
}
out.LocalizedContent[lang] = fields
}
delete(out.FieldSources, "name")
delete(out.FieldSources, "description")
}
if out.Attributes == nil {
out.Attributes = map[string]any{}
}
@@ -708,7 +758,7 @@ func noteMissingCategory(out *StepResult, policy StepPolicy, vectorEnabled bool)
func resolveSteps(processingType string) []string {
switch strings.ToLower(strings.TrimSpace(processingType)) {
case "enhance", "enhance_only", "enhance-only", "title", "description":
case "enhance", "enhance_only", "enhance-only", "title", "description", "seo_meta":
// parse_specs/fill_fields/categorize feed ai_enhance — they never rewrite
// title/description themselves. Without them enhance ran with empty Attrs
// and (for feeds without a mapped category) no category, so the category
+4 -1
View File
@@ -15,7 +15,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool"
)
var v1PartialSteps = []string{"category", "title", "description", "attributes"}
var v1PartialSteps = []string{"category", "title", "description", "attributes", "seo_meta"}
const v1MetaDescriptionMaxChars = 155
@@ -791,6 +791,9 @@ func ProjectV1ProcessJobItems(storedType string, items []V1ProcessJobItem) []V1P
}
case "attributes":
projected["attributes"] = item["attributes"]
case "seo_meta":
projected["meta_title"] = item["meta_title"]
projected["meta_description"] = item["meta_description"]
}
}
out = append(out, withAlwaysIncluded(projected, main, more, eprel))