diff --git a/apps/api/internal/billing/entitlements.go b/apps/api/internal/billing/entitlements.go
index 783cd2c..b9f9665 100644
--- a/apps/api/internal/billing/entitlements.go
+++ b/apps/api/internal/billing/entitlements.go
@@ -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
diff --git a/apps/api/internal/catalog/files.go b/apps/api/internal/catalog/files.go
index 78c0ab7..4cc8a0f 100644
--- a/apps/api/internal/catalog/files.go
+++ b/apps/api/internal/catalog/files.go
@@ -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")
diff --git a/apps/api/internal/catalog/import_json.go b/apps/api/internal/catalog/import_json.go
new file mode 100644
index 0000000..df4bb28
--- /dev/null
+++ b/apps/api/internal/catalog/import_json.go
@@ -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
+}
diff --git a/apps/api/internal/catalog/v10_json_import_test.go b/apps/api/internal/catalog/v10_json_import_test.go
new file mode 100644
index 0000000..e5caa83
--- /dev/null
+++ b/apps/api/internal/catalog/v10_json_import_test.go
@@ -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)
+ }
+}
diff --git a/apps/api/internal/feeds/delete_cleanup_integration_test.go b/apps/api/internal/feeds/delete_cleanup_integration_test.go
new file mode 100644
index 0000000..691935c
--- /dev/null
+++ b/apps/api/internal/feeds/delete_cleanup_integration_test.go
@@ -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)
+ }
+}
diff --git a/apps/api/internal/feeds/download.go b/apps/api/internal/feeds/download.go
index 5e3ae93..5c79fc8 100644
--- a/apps/api/internal/feeds/download.go
+++ b/apps/api/internal/feeds/download.go
@@ -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
+}
diff --git a/apps/api/internal/feeds/export.go b/apps/api/internal/feeds/export.go
index 87aa2ec..b2f690f 100644
--- a/apps/api/internal/feeds/export.go
+++ b/apps/api/internal/feeds/export.go
@@ -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
+}
diff --git a/apps/api/internal/feeds/extract_schema.go b/apps/api/internal/feeds/extract_schema.go
index 2a74769..6cded2f 100644
--- a/apps/api/internal/feeds/extract_schema.go
+++ b/apps/api/internal/feeds/extract_schema.go
@@ -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
+}
diff --git a/apps/api/internal/feeds/headers.go b/apps/api/internal/feeds/headers.go
new file mode 100644
index 0000000..dc3bbc7
--- /dev/null
+++ b/apps/api/internal/feeds/headers.go
@@ -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)
+}
diff --git a/apps/api/internal/feeds/mapping.go b/apps/api/internal/feeds/mapping.go
index 8ef2c5d..454e408 100644
--- a/apps/api/internal/feeds/mapping.go
+++ b/apps/api/internal/feeds/mapping.go
@@ -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 {
diff --git a/apps/api/internal/feeds/parse.go b/apps/api/internal/feeds/parse.go
index 8a0e1c2..727da18 100644
--- a/apps/api/internal/feeds/parse.go
+++ b/apps/api/internal/feeds/parse.go
@@ -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).
diff --git a/apps/api/internal/feeds/parse_json.go b/apps/api/internal/feeds/parse_json.go
new file mode 100644
index 0000000..f4d7f64
--- /dev/null
+++ b/apps/api/internal/feeds/parse_json.go
@@ -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)
+}
diff --git a/apps/api/internal/feeds/present.go b/apps/api/internal/feeds/present.go
index 4b21b8d..473d4c6 100644
--- a/apps/api/internal/feeds/present.go
+++ b/apps/api/internal/feeds/present.go
@@ -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
+}
diff --git a/apps/api/internal/feeds/service.go b/apps/api/internal/feeds/service.go
index 8c5c2da..34a00bc 100644
--- a/apps/api/internal/feeds/service.go
+++ b/apps/api/internal/feeds/service.go
@@ -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 != "" {
diff --git a/apps/api/internal/feeds/source.go b/apps/api/internal/feeds/source.go
index 6cf24b9..07f7401 100644
--- a/apps/api/internal/feeds/source.go
+++ b/apps/api/internal/feeds/source.go
@@ -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,
diff --git a/apps/api/internal/feeds/specs.go b/apps/api/internal/feeds/specs.go
index 0d07514..4911979 100644
--- a/apps/api/internal/feeds/specs.go
+++ b/apps/api/internal/feeds/specs.go
@@ -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",
}
diff --git a/apps/api/internal/feeds/suggest.go b/apps/api/internal/feeds/suggest.go
index 40d5b02..3c7d8e8 100644
--- a/apps/api/internal/feeds/suggest.go
+++ b/apps/api/internal/feeds/suggest.go
@@ -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 {
diff --git a/apps/api/internal/feeds/sync.go b/apps/api/internal/feeds/sync.go
index 0e03678..904bec0 100644
--- a/apps/api/internal/feeds/sync.go
+++ b/apps/api/internal/feeds/sync.go
@@ -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)
}
diff --git a/apps/api/internal/feeds/v10_nested_xml_json_test.go b/apps/api/internal/feeds/v10_nested_xml_json_test.go
new file mode 100644
index 0000000..7d06b4a
--- /dev/null
+++ b/apps/api/internal/feeds/v10_nested_xml_json_test.go
@@ -0,0 +1,47 @@
+package feeds
+
+import (
+ "strings"
+ "testing"
+)
+
+const emos = `