From cfd31f398c8a28726484270538d19cc203edec90 Mon Sep 17 00:00:00 2001 From: GreenEclipse Date: Thu, 15 Oct 2026 21:22:43 +0200 Subject: [PATCH] Fixes --- apps/api/internal/billing/entitlements.go | 2 +- apps/api/internal/catalog/files.go | 11 +- apps/api/internal/catalog/import_json.go | 174 ++++++++++++ .../internal/catalog/v10_json_import_test.go | 43 +++ .../feeds/delete_cleanup_integration_test.go | 113 ++++++++ apps/api/internal/feeds/download.go | 52 +++- apps/api/internal/feeds/export.go | 84 ++++++ apps/api/internal/feeds/extract_schema.go | 38 ++- apps/api/internal/feeds/headers.go | 89 ++++++ apps/api/internal/feeds/mapping.go | 28 +- apps/api/internal/feeds/parse.go | 54 +++- apps/api/internal/feeds/parse_json.go | 254 ++++++++++++++++++ apps/api/internal/feeds/present.go | 13 +- apps/api/internal/feeds/service.go | 142 ++++++++-- apps/api/internal/feeds/source.go | 8 +- apps/api/internal/feeds/specs.go | 48 ++-- apps/api/internal/feeds/suggest.go | 114 ++++---- apps/api/internal/feeds/sync.go | 16 ++ .../feeds/v10_nested_xml_json_test.go | 47 ++++ .../httpapi/catalog_import_handlers.go | 62 ++++- apps/api/internal/httpapi/feeds_handlers.go | 45 +++- apps/api/internal/httpapi/server.go | 1 + .../internal/httpapi/v1_export_campaigns.go | 8 +- .../httpapi/v1_json_export_urls_test.go | 27 ++ apps/api/internal/httpapi/v1_openapi.go | 66 +++-- apps/api/internal/processing/pipeline.go | 22 ++ .../internal/processing/seo_meta_mode_test.go | 42 +++ apps/api/internal/processing/steps.go | 60 ++++- apps/api/internal/processing/v1_legacy.go | 5 +- .../categories/AddCategoryDialog.svelte | 2 +- .../feeds/RemoteCatalogImport.svelte | 27 ++ .../feeds/SchemaMappingTable.svelte | 6 +- .../lib/components/feeds/suggest-mappings.ts | 29 +- .../products/ProductProcessingActions.svelte | 45 +--- .../products/processing-options.test.ts | 24 ++ apps/web/src/lib/components/products/types.ts | 11 +- apps/web/src/lib/docs-guide/tree.ts | 8 +- apps/web/src/lib/export-presets.ts | 16 +- apps/web/src/lib/i18n/messages/de.ts | 1 + apps/web/src/lib/i18n/messages/en.ts | 3 +- apps/web/src/lib/i18n/messages/es.ts | 1 + apps/web/src/lib/i18n/messages/fr.ts | 1 + apps/web/src/lib/i18n/messages/it.ts | 1 + apps/web/src/lib/i18n/messages/ja.ts | 1 + apps/web/src/lib/i18n/messages/nl.ts | 1 + apps/web/src/lib/i18n/messages/pl.ts | 1 + apps/web/src/lib/i18n/messages/pt.ts | 1 + apps/web/src/lib/i18n/messages/sl.ts | 1 + apps/web/src/lib/public-api-base.ts | 15 +- apps/web/src/routes/attributes/+page.svelte | 4 +- apps/web/src/routes/categories/+page.svelte | 2 + apps/web/src/routes/export-feeds/+page.svelte | 7 +- apps/web/src/routes/feeds/+page.svelte | 61 ++++- .../feeds/[feedId]/mapping/+page.svelte | 12 +- apps/web/src/routes/products/+page.svelte | 32 ++- docs/API_V11_AUDIT.md | 45 ++++ docs/FEED_DELETE_CLEANUP_V12.md | 20 ++ docs/FEED_XML_JSON_V10.md | 85 ++++++ docs/V11_RELEASE_NOTES.md | 26 ++ .../sestanek-dobavitelji-onboarding-sl.md | 87 ++++++ docs/public-api-reference.md | 72 +++++ 61 files changed, 2062 insertions(+), 254 deletions(-) create mode 100644 apps/api/internal/catalog/import_json.go create mode 100644 apps/api/internal/catalog/v10_json_import_test.go create mode 100644 apps/api/internal/feeds/delete_cleanup_integration_test.go create mode 100644 apps/api/internal/feeds/headers.go create mode 100644 apps/api/internal/feeds/parse_json.go create mode 100644 apps/api/internal/feeds/v10_nested_xml_json_test.go create mode 100644 apps/api/internal/httpapi/v1_json_export_urls_test.go create mode 100644 apps/api/internal/processing/seo_meta_mode_test.go create mode 100644 apps/web/src/lib/components/feeds/RemoteCatalogImport.svelte create mode 100644 apps/web/src/lib/components/products/processing-options.test.ts create mode 100644 docs/API_V11_AUDIT.md create mode 100644 docs/FEED_DELETE_CLEANUP_V12.md create mode 100644 docs/FEED_XML_JSON_V10.md create mode 100644 docs/V11_RELEASE_NOTES.md create mode 100644 docs/client/sestanek-dobavitelji-onboarding-sl.md create mode 100644 docs/public-api-reference.md 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 = `Ročna LED svetilka 9 LED 3×AAA14400931098595025395184Svetilke|Ročne svetilkebarva: mešanica barv|napajanje: 3× AAA|svetlobni tok: 50 lm<p>Praktična LED svetilka</p>barvamešanica barv12napajanje3× AAAvir svetlobe9× LEDhttps://example.com/1.jpghttps://example.com/2.jpg` + +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) + } +} diff --git a/apps/api/internal/httpapi/catalog_import_handlers.go b/apps/api/internal/httpapi/catalog_import_handlers.go index 3d849fe..e946e6c 100644 --- a/apps/api/internal/httpapi/catalog_import_handlers.go +++ b/apps/api/internal/httpapi/catalog_import_handlers.go @@ -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" diff --git a/apps/api/internal/httpapi/feeds_handlers.go b/apps/api/internal/httpapi/feeds_handlers.go index 3f3be24..9531223 100644 --- a/apps/api/internal/httpapi/feeds_handlers.go +++ b/apps/api/internal/httpapi/feeds_handlers.go @@ -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. diff --git a/apps/api/internal/httpapi/server.go b/apps/api/internal/httpapi/server.go index a8c9c9d..fa13700 100644 --- a/apps/api/internal/httpapi/server.go +++ b/apps/api/internal/httpapi/server.go @@ -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) { diff --git a/apps/api/internal/httpapi/v1_export_campaigns.go b/apps/api/internal/httpapi/v1_export_campaigns.go index 94bcbec..b07c8d4 100644 --- a/apps/api/internal/httpapi/v1_export_campaigns.go +++ b/apps/api/internal/httpapi/v1_export_campaigns.go @@ -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) diff --git a/apps/api/internal/httpapi/v1_json_export_urls_test.go b/apps/api/internal/httpapi/v1_json_export_urls_test.go new file mode 100644 index 0000000..f3f2b19 --- /dev/null +++ b/apps/api/internal/httpapi/v1_json_export_urls_test.go @@ -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"]) + } +} diff --git a/apps/api/internal/httpapi/v1_openapi.go b/apps/api/internal/httpapi/v1_openapi.go index b2d84f5..860c79e 100644 --- a/apps/api/internal/httpapi/v1_openapi.go +++ b/apps/api/internal/httpapi/v1_openapi.go @@ -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: diff --git a/apps/api/internal/processing/pipeline.go b/apps/api/internal/processing/pipeline.go index 7c9fc39..539ed54 100644 --- a/apps/api/internal/processing/pipeline.go +++ b/apps/api/internal/processing/pipeline.go @@ -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). diff --git a/apps/api/internal/processing/seo_meta_mode_test.go b/apps/api/internal/processing/seo_meta_mode_test.go new file mode 100644 index 0000000..e1baf71 --- /dev/null +++ b/apps/api/internal/processing/seo_meta_mode_test.go @@ -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) + } +} diff --git a/apps/api/internal/processing/steps.go b/apps/api/internal/processing/steps.go index 2115697..51eed80 100644 --- a/apps/api/internal/processing/steps.go +++ b/apps/api/internal/processing/steps.go @@ -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 diff --git a/apps/api/internal/processing/v1_legacy.go b/apps/api/internal/processing/v1_legacy.go index 7b4a9c3..f31f356 100644 --- a/apps/api/internal/processing/v1_legacy.go +++ b/apps/api/internal/processing/v1_legacy.go @@ -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)) diff --git a/apps/web/src/lib/components/categories/AddCategoryDialog.svelte b/apps/web/src/lib/components/categories/AddCategoryDialog.svelte index 89fcdf5..ab75d62 100644 --- a/apps/web/src/lib/components/categories/AddCategoryDialog.svelte +++ b/apps/web/src/lib/components/categories/AddCategoryDialog.svelte @@ -169,7 +169,7 @@ {importing ? i18n.t("catalog.uploading") : i18n.t("categories.chooseCsv")} diff --git a/apps/web/src/lib/components/feeds/RemoteCatalogImport.svelte b/apps/web/src/lib/components/feeds/RemoteCatalogImport.svelte new file mode 100644 index 0000000..af86146 --- /dev/null +++ b/apps/web/src/lib/components/feeds/RemoteCatalogImport.svelte @@ -0,0 +1,27 @@ + +
+

Import {kind} from JSON URL

+ + + {#if authMode==="header"}{/if} + + + {#if error}

{error}

{/if} + +
diff --git a/apps/web/src/lib/components/feeds/SchemaMappingTable.svelte b/apps/web/src/lib/components/feeds/SchemaMappingTable.svelte index 01b0ace..6b62285 100644 --- a/apps/web/src/lib/components/feeds/SchemaMappingTable.svelte +++ b/apps/web/src/lib/components/feeds/SchemaMappingTable.svelte @@ -61,7 +61,11 @@ const filtered = $derived.by(() => { const q = filterText.trim().toLowerCase(); - return schemaFields.filter((field) => { + return [...schemaFields].sort((a,b) => { + const ar=standardFields.find((f)=>f.value===mappings[a.path])?.isRequired || standardFields.find((f)=>f.value===suggestionBySource.get(a.path)?.target)?.isRequired; + const br=standardFields.find((f)=>f.value===mappings[b.path])?.isRequired || standardFields.find((f)=>f.value===suggestionBySource.get(b.path)?.target)?.isRequired; + return Number(Boolean(br))-Number(Boolean(ar)); + }).filter((field) => { const samples = field.sample_values ?? []; const matchesText = !q || diff --git a/apps/web/src/lib/components/feeds/suggest-mappings.ts b/apps/web/src/lib/components/feeds/suggest-mappings.ts index 78623f3..c85af10 100644 --- a/apps/web/src/lib/components/feeds/suggest-mappings.ts +++ b/apps/web/src/lib/components/feeds/suggest-mappings.ts @@ -23,7 +23,14 @@ export function leafKey(path: string): string { * Matchers pick the first alias that exists in the enabled target set. */ const SOURCE_ALIASES: Record = { - gtin: ["gtin"], +gtin: ["gtin"], + productno: ["sku"], productno2: ["mpn"], + product: ["title"], descriptionbasic: ["description"], + pricevat: ["price"], priceeshopvat: ["price"], pricevoc: ["purchase_price"], + imgurl: ["image_url","main_image"], + params: ["specifications","specs"], + categoryid: ["category_id"], + ean: ["gtin"], upc: ["gtin"], barcode: ["gtin"], @@ -210,7 +217,9 @@ export function suggestMappings( schemaFields.forEach((field, order) => { const apiHint = (field.suggested_target || "").trim(); - const keys = [ + const isSpecDescription = leafKey(field.path) === "description" && (field.sample_values ?? []).some((v) => (v.match(/\|/g) ?? []).length > 2 && v.includes(":")); + const keys = [ + ...(isSpecDescription ? ["specifications"] : []), normalizeKey(field.field_name || ""), leafKey(field.path), normalizeKey(field.path) @@ -218,7 +227,13 @@ export function suggestMappings( let hit: MappingSuggestion | null = null; - if (apiHint && enabled.has(apiHint) && !usedTargets.has(apiHint)) { + if (isSpecDescription) { + const specs = resolveAlias(["specifications", "specs"], enabled); + if (specs && !usedTargets.has(specs)) { + hit = { source: field.path, target: specs, confidence: "alias", score: 1.05 }; + } + } + if (!hit && apiHint && enabled.has(apiHint) && !usedTargets.has(apiHint)) { hit = { source: field.path, target: apiHint, confidence: "alias", score: 0.98 }; } @@ -253,7 +268,11 @@ export function suggestMappings( } } - if (hit) scored.push({ ...hit, order }); + if (hit) { + if ((field.path.toLowerCase() === "params" || field.path.toLowerCase() === "attributes") && ["specifications","specs"].includes(hit.target)) hit.score = 1.15; + if (field.path.toLowerCase() === "description" && ["specifications","specs"].includes(hit.target)) hit.score = 0.92; + scored.push({ ...hit, order }); + } }); scored.sort((a, b) => b.score - a.score || a.order - b.order); @@ -327,7 +346,7 @@ export type MappingPreflightInput = { function isCsvFeedType(feedType?: string | null): boolean { const t = String(feedType ?? "").toLowerCase(); - return t === "csv" || t === "excel"; + return t === "csv" || t === "excel" || t === "json"; } /** Active source→target pairs (excludes blank / none). */ diff --git a/apps/web/src/lib/components/products/ProductProcessingActions.svelte b/apps/web/src/lib/components/products/ProductProcessingActions.svelte index a3baaa5..d04af42 100644 --- a/apps/web/src/lib/components/products/ProductProcessingActions.svelte +++ b/apps/web/src/lib/components/products/ProductProcessingActions.svelte @@ -57,30 +57,17 @@ let pendingCount = $state(0); let selectedTypes = $state([]); - const selectedData = $derived(products.filter((p) => selectedProducts.some((id) => String(id) === String(p.id)))); - const uncategorized = $derived(selectedData.filter((p) => !p.category)); - const needingCategory = ["attributes", "title", "description"] as ProcessingType[]; - const needsCategorization = $derived( - selectedTypes.some((t) => needingCategory.includes(t)) && - uncategorized.length > 0 && - !selectedTypes.includes("category") - ); const selectedAILocked = $derived( selectedTypes.some((t) => PROCESSING_OPTIONS.find((o) => o.type === t)?.requiresAI && !aiAllowedForType(t)) ); - const totalCredits = $derived.by(() => { - const selectedCredits = PROCESSING_OPTIONS.filter((o) => selectedTypes.includes(o.type)).reduce( - (sum, o) => sum + o.credits, + // Estimated cost only; actual AI usage is billed from provider tokens. + const totalCredits = $derived( + PROCESSING_OPTIONS.filter((option) => selectedTypes.includes(option.type)).reduce( + (sum, option) => sum + option.credits, 0 - ); - const n = Math.max(selectedCount, selectedData.length); - const categorized = n - uncategorized.length; - if (selectedTypes.includes("category") || !needsCategorization) { - return selectedCredits * n; - } - return categorized * selectedCredits + uncategorized.length * (selectedCredits + 0.3); - }); + ) * selectedCount + ); function toggleType(type: ProcessingType) { if (!aiAllowedForType(type) && PROCESSING_OPTIONS.find((o) => o.type === type)?.requiresAI) return; @@ -98,10 +85,7 @@ function processSelected() { if (selectedTypes.length === 0) return; - pendingTypes = - needsCategorization && !selectedTypes.includes("category") - ? (["category", ...selectedTypes] as ProcessingType[]) - : [...selectedTypes]; + pendingTypes = [...selectedTypes]; pendingCredits = totalCredits; pendingCount = selectedCount; open = false; @@ -255,21 +239,6 @@
- {#if needsCategorization && !selectedTypes.includes("category")} -
-
- {i18n.t("products.actions.autoCategorizeTitle")} -
-
- {i18n.t("products.actions.autoCategorizeBody", { - count: uncategorized.length, - types: selectedTypes - .filter((t) => needingCategory.includes(t)) - .join(", ") - })} -
-
- {/if} {#if selectedAILocked}
{i18n.t("products.actions.aiLocked")} diff --git a/apps/web/src/lib/components/products/processing-options.test.ts b/apps/web/src/lib/components/products/processing-options.test.ts new file mode 100644 index 0000000..50a98c1 --- /dev/null +++ b/apps/web/src/lib/components/products/processing-options.test.ts @@ -0,0 +1,24 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import test from 'node:test'; + +const typesFile = fileURLToPath(new URL('./types.ts', import.meta.url)); +const processingFile = fileURLToPath(new URL('./ProductProcessingActions.svelte', import.meta.url)); +const productsPage = fileURLToPath(new URL('../../../routes/products/+page.svelte', import.meta.url)); + +test('What to process lists title, description and SEO metadata only', () => { + const types = readFileSync(typesFile, 'utf8'); + const options = types.split('export const PROCESSING_OPTIONS:', 2)[1]?.split('];', 1)[0] ?? ''; + assert.match(options, /type: "title"/); + assert.match(options, /type: "description"/); + assert.match(options, /type: "seo_meta"/); + assert.doesNotMatch(options, /type: "category"|type: "attributes"/); +}); + +test('SEO Meta selected alone uses a dedicated processing mode', () => { + const code = readFileSync(productsPage, 'utf8'); + assert.match(code, /selected\.has\("seo_meta"\)\s*\?\s*"seo_meta"/); + const processing = readFileSync(processingFile, 'utf8'); + assert.doesNotMatch(processing, /pendingTypes =\s*needsCategorization/); +}); diff --git a/apps/web/src/lib/components/products/types.ts b/apps/web/src/lib/components/products/types.ts index c42e7b5..4d8ae21 100644 --- a/apps/web/src/lib/components/products/types.ts +++ b/apps/web/src/lib/components/products/types.ts @@ -43,13 +43,13 @@ export { tabToApiParams } from "../../products-search"; -export type ProcessingType = "title" | "description" | "category" | "attributes"; +export type ProcessingType = "title" | "description" | "seo_meta"; /** Options that require AI credits / paid plan (titles & descriptions). */ -export const AI_PROCESSING_TYPES: ProcessingType[] = ["title", "description"]; +export const AI_PROCESSING_TYPES: ProcessingType[] = ["title", "description", "seo_meta"]; /** Options that work on Free without AI (normalize / specs / fill). */ -export const FREE_PROCESSING_TYPES: ProcessingType[] = ["category", "attributes"]; +export const FREE_PROCESSING_TYPES: ProcessingType[] = []; export type CategoryOption = { uniqueId: string; @@ -140,10 +140,9 @@ export const PROCESSING_OPTIONS: { credits: number; requiresAI?: boolean; }[] = [ - { type: "category", labelKey: "products.option.categories", credits: 0, requiresAI: false }, - { type: "attributes", labelKey: "products.option.attributes", credits: 0, requiresAI: false }, { type: "title", labelKey: "products.option.titlesAi", credits: 0.1, requiresAI: true }, - { type: "description", labelKey: "products.option.descriptionsAi", credits: 0.25, requiresAI: true } + { type: "description", labelKey: "products.option.descriptionsAi", credits: 0.25, requiresAI: true }, + { type: "seo_meta", labelKey: "products.option.seoMetaAi", credits: 0.1, requiresAI: true } ]; /** True when product is awaiting Accept / edit / reject after enrichment. */ diff --git a/apps/web/src/lib/docs-guide/tree.ts b/apps/web/src/lib/docs-guide/tree.ts index e595865..aa23dbd 100644 --- a/apps/web/src/lib/docs-guide/tree.ts +++ b/apps/web/src/lib/docs-guide/tree.ts @@ -12,10 +12,10 @@ import { validateDocsGuideTree } from "./resolve"; */ const AUTH_NOTE = - "Company API key (prefix dk_…). Prefer Authorization: Bearer; X-API-Key also works. Create keys in Settings → API keys. On /docs when logged in, use Use my API key for RapiDoc Try-it. Do not use dashboard session cookies on /api/v1."; + "Company API key (prefix dk_…). Prefer Authorization: Bearer; X-API-Key also works. Create keys in Settings → API keys if you have the API Keys management permission. On /docs when logged in, use Use my API key for RapiDoc Try-it. Do not use dashboard session cookies on /api/v1."; const TRY_IT_TIP = - "In RapiDoc: open Authorize (/docs#auth), paste Bearer dk_… (or X-API-Key), then expand an operation and use TRY. Prefer the server that matches your environment."; + "In RapiDoc: open Authorize (/docs#auth), paste Bearer dk_… (or X-API-Key), then expand an operation and use TRY. Use the published production API server."; export const DOCS_GUIDE_TREE: DocsGuideTree = { version: 2, @@ -65,8 +65,8 @@ export const DOCS_GUIDE_TREE: DocsGuideTree = { choices: [ { id: "pipeline", - label: "Feeds → process → export", - description: "Ingest, enrich, or outbound feeds", + label: "Import → enrich → export", + description: "Connect a supplier, generate content, and download results", nextId: "q.pipeline" }, { diff --git a/apps/web/src/lib/export-presets.ts b/apps/web/src/lib/export-presets.ts index 6421f6d..a7d2b22 100644 --- a/apps/web/src/lib/export-presets.ts +++ b/apps/web/src/lib/export-presets.ts @@ -6,6 +6,7 @@ export type ExportField = { key: string; source: string }; export type ExportPresetId = | "custom_xml" | "custom_csv" + | "custom_json" | "google_shopping_csv" | "google_shopping_xml" | "meta_csv"; @@ -17,7 +18,7 @@ export type ExportPreset = { shortLabel: string; description: string; hint: string; - format: "csv" | "xml"; + format: "csv" | "xml" | "json"; root?: string; item?: string; fields: ExportField[]; @@ -110,6 +111,9 @@ export const EXPORT_PRESETS: ExportPreset[] = [ item: "product", fields: DEFAULT_CUSTOM_FIELDS }, +{ + id:"custom_json",channel:"custom",label:"Custom JSON",shortLabel:"JSON",description:"Nested JSON product catalog",hint:"Publishes a JSON URL with a products array.",format:"json",root:"products",item:"product",fields:DEFAULT_CUSTOM_FIELDS + }, { id: "custom_xml", channel: "custom", @@ -129,25 +133,25 @@ export function presetById(id: ExportPresetId | string | null | undefined): Expo } export function defaultNameForPreset(preset: ExportPreset): string { - return i18n.t(`exports.preset.${preset.id}.defaultName`); + return preset.id === "custom_json" ? "JSON product feed" : i18n.t(`exports.preset.${preset.id}.defaultName`); } export function presetLabel(preset: ExportPreset | ExportPresetId): string { const id = typeof preset === "string" ? preset : preset.id; - return i18n.t(`exports.preset.${id}.label`); + return id === "custom_json" ? "Custom JSON" : i18n.t(`exports.preset.${id}.label`); } export function presetShortLabel(preset: ExportPreset | ExportPresetId): string { const id = typeof preset === "string" ? preset : preset.id; - return i18n.t(`exports.preset.${id}.shortLabel`); + return id === "custom_json" ? "JSON" : i18n.t(`exports.preset.${id}.shortLabel`); } export function presetDescription(preset: ExportPreset | ExportPresetId): string { const id = typeof preset === "string" ? preset : preset.id; - return i18n.t(`exports.preset.${id}.description`); + return id === "custom_json" ? "Export processed products as JSON." : i18n.t(`exports.preset.${id}.description`); } export function presetHint(preset: ExportPreset | ExportPresetId): string { const id = typeof preset === "string" ? preset : preset.id; - return i18n.t(`exports.preset.${id}.hint`); + return id === "custom_json" ? "Share the JSON feed URL with a partner." : i18n.t(`exports.preset.${id}.hint`); } diff --git a/apps/web/src/lib/i18n/messages/de.ts b/apps/web/src/lib/i18n/messages/de.ts index 1974353..1ec9460 100644 --- a/apps/web/src/lib/i18n/messages/de.ts +++ b/apps/web/src/lib/i18n/messages/de.ts @@ -2766,6 +2766,7 @@ export const de: MessageDict = { "products.option.attributes": "Attribute / Spezifikationen", "products.option.titlesAi": "Titel (KI)", "products.option.descriptionsAi": "Beschreibungen (KI)", + "products.option.seoMetaAi": "SEO-Metatitel und -beschreibung (KI)", "products.enrichment.piece.name": "Bezeichnung", "products.enrichment.piece.description": "Beschreibung", "products.enrichment.piece.attributes": "Attribute", diff --git a/apps/web/src/lib/i18n/messages/en.ts b/apps/web/src/lib/i18n/messages/en.ts index eea0676..2633ffc 100644 --- a/apps/web/src/lib/i18n/messages/en.ts +++ b/apps/web/src/lib/i18n/messages/en.ts @@ -2571,7 +2571,7 @@ export const en: MessageDict = { "confirm.defaultTitle": "Confirm Deletion", "confirm.defaultDescription": "Are you sure?", "confirm.defaultConfirm": "Confirm", - "confirm.deleteFeed": "Delete feed “{name}”? This cannot be undone.", + "confirm.deleteFeed": "Delete feed “{name}” and its unprocessed products? Previously processed content and products shared with other feeds are preserved. This cannot be undone.", "confirm.deleteCampaign": "Delete campaign “{name}”? This cannot be undone.", "confirm.deleteExportFeed": "Are you sure you want to delete this export feed?", @@ -3348,6 +3348,7 @@ export const en: MessageDict = { "products.option.attributes": "Attributes / specs", "products.option.titlesAi": "Titles (AI)", "products.option.descriptionsAi": "Descriptions (AI)", + "products.option.seoMetaAi": "SEO meta title & description (AI)", "products.enrichment.piece.name": "Name", "products.enrichment.piece.description": "Description", "products.enrichment.piece.attributes": "Attributes", diff --git a/apps/web/src/lib/i18n/messages/es.ts b/apps/web/src/lib/i18n/messages/es.ts index caa72d8..f921827 100644 --- a/apps/web/src/lib/i18n/messages/es.ts +++ b/apps/web/src/lib/i18n/messages/es.ts @@ -2766,6 +2766,7 @@ export const es: MessageDict = { "products.option.attributes": "Atributos / especificaciones", "products.option.titlesAi": "Títulos (IA)", "products.option.descriptionsAi": "Descripciones (IA)", + "products.option.seoMetaAi": "Título y descripción SEO (IA)", "products.enrichment.piece.name": "Nombre", "products.enrichment.piece.description": "Descripción", "products.enrichment.piece.attributes": "Atributos", diff --git a/apps/web/src/lib/i18n/messages/fr.ts b/apps/web/src/lib/i18n/messages/fr.ts index 2e3d811..a25f19a 100644 --- a/apps/web/src/lib/i18n/messages/fr.ts +++ b/apps/web/src/lib/i18n/messages/fr.ts @@ -2766,6 +2766,7 @@ export const fr: MessageDict = { "products.option.attributes": "Attributs / spécifications", "products.option.titlesAi": "Titres (IA)", "products.option.descriptionsAi": "Descriptions (IA)", + "products.option.seoMetaAi": "Titre et description méta SEO (IA)", "products.enrichment.piece.name": "Nom", "products.enrichment.piece.description": "Description", "products.enrichment.piece.attributes": "Attributs", diff --git a/apps/web/src/lib/i18n/messages/it.ts b/apps/web/src/lib/i18n/messages/it.ts index 0f8ee9c..2ff57f4 100644 --- a/apps/web/src/lib/i18n/messages/it.ts +++ b/apps/web/src/lib/i18n/messages/it.ts @@ -2766,6 +2766,7 @@ export const it: MessageDict = { "products.option.attributes": "Attributi / specifiche", "products.option.titlesAi": "Titoli (IA)", "products.option.descriptionsAi": "Descrizioni (IA)", + "products.option.seoMetaAi": "Titolo e descrizione meta SEO (IA)", "products.enrichment.piece.name": "Nome", "products.enrichment.piece.description": "Descrizione", "products.enrichment.piece.attributes": "Attributi", diff --git a/apps/web/src/lib/i18n/messages/ja.ts b/apps/web/src/lib/i18n/messages/ja.ts index f0ffe66..84f0179 100644 --- a/apps/web/src/lib/i18n/messages/ja.ts +++ b/apps/web/src/lib/i18n/messages/ja.ts @@ -2766,6 +2766,7 @@ export const ja: MessageDict = { "products.option.attributes": "属性 / 仕様", "products.option.titlesAi": "タイトル(AI)", "products.option.descriptionsAi": "説明(AI)", + "products.option.seoMetaAi": "SEOメタタイトル・説明文(AI)", "products.enrichment.piece.name": "名前", "products.enrichment.piece.description": "説明", "products.enrichment.piece.attributes": "属性", diff --git a/apps/web/src/lib/i18n/messages/nl.ts b/apps/web/src/lib/i18n/messages/nl.ts index 1ebc0fb..561991d 100644 --- a/apps/web/src/lib/i18n/messages/nl.ts +++ b/apps/web/src/lib/i18n/messages/nl.ts @@ -2766,6 +2766,7 @@ export const nl: MessageDict = { "products.option.attributes": "Attributen / specificaties", "products.option.titlesAi": "Titels (AI)", "products.option.descriptionsAi": "Beschrijvingen (AI)", + "products.option.seoMetaAi": "SEO-metatitel en -beschrijving (AI)", "products.enrichment.piece.name": "Naam", "products.enrichment.piece.description": "Beschrijving", "products.enrichment.piece.attributes": "Attributen", diff --git a/apps/web/src/lib/i18n/messages/pl.ts b/apps/web/src/lib/i18n/messages/pl.ts index e38ece9..8573478 100644 --- a/apps/web/src/lib/i18n/messages/pl.ts +++ b/apps/web/src/lib/i18n/messages/pl.ts @@ -2766,6 +2766,7 @@ export const pl: MessageDict = { "products.option.attributes": "Atrybuty / specyfikacje", "products.option.titlesAi": "TytuÅ‚y (AI)", "products.option.descriptionsAi": "Opisy (AI)", + "products.option.seoMetaAi": "Tytuł i opis meta SEO (AI)", "products.enrichment.piece.name": "Nazwa", "products.enrichment.piece.description": "Opis", "products.enrichment.piece.attributes": "Atrybuty", diff --git a/apps/web/src/lib/i18n/messages/pt.ts b/apps/web/src/lib/i18n/messages/pt.ts index 160233b..bf49012 100644 --- a/apps/web/src/lib/i18n/messages/pt.ts +++ b/apps/web/src/lib/i18n/messages/pt.ts @@ -2766,6 +2766,7 @@ export const pt: MessageDict = { "products.option.attributes": "Atributos / especificações", "products.option.titlesAi": "Títulos (IA)", "products.option.descriptionsAi": "Descrições (IA)", + "products.option.seoMetaAi": "Título e descrição meta SEO (IA)", "products.enrichment.piece.name": "Nome", "products.enrichment.piece.description": "Descrição", "products.enrichment.piece.attributes": "Atributos", diff --git a/apps/web/src/lib/i18n/messages/sl.ts b/apps/web/src/lib/i18n/messages/sl.ts index 1a4fa0e..6063174 100644 --- a/apps/web/src/lib/i18n/messages/sl.ts +++ b/apps/web/src/lib/i18n/messages/sl.ts @@ -2,6 +2,7 @@ import type { MessageDict } from "./types.ts"; /** Slovenian (sl) UI strings for admin Fix A1 — ready pack. Not registered in UI_LOCALES yet (avoid inventing locale switcher). */ export const sl: MessageDict = { + "confirm.deleteFeed": "Izbrišem vir »{name}« in vse njegove neobdelane izdelke? Že obdelani izdelki in izdelki, povezani z drugimi viri, se ohranijo. Dejanja ni mogoče razveljaviti.", "admin.users.cloneCatalog": "Copy to my company", "admin.users.cloneCatalogAria": "Copy {name} catalog into your sandbox company", "admin.users.cloneCatalogTitle": "Copy company catalog", diff --git a/apps/web/src/lib/public-api-base.ts b/apps/web/src/lib/public-api-base.ts index 06b2d24..e864391 100644 --- a/apps/web/src/lib/public-api-base.ts +++ b/apps/web/src/lib/public-api-base.ts @@ -7,17 +7,13 @@ import { PUBLIC_API_URL } from "$env/static/public"; const API_BASE = (PUBLIC_API_URL ?? "").replace(/\/$/, ""); /** Public production API base from OpenAPI servers[0] (Descrybe-hosted; not customer self-host). */ -export const PUBLIC_DOCS_API_SERVER = "https://descrybe.io/api/v1"; +export const PUBLIC_DOCS_API_SERVER = "https://api.descrybe.io/api/v1"; /** Public OpenAPI document URL for links and fetches. */ export const OPENAPI_SPEC_URL = `${API_BASE}/api/v1/openapi.yaml`; -/** - * Absolute base for RapiDoc Try-it. - * Dev/local: PUBLIC_API_URL when set (npm run dev forces http://localhost:28471), - * else current origin so Vite proxies /api → :28471. - * Production same-origin deploy resolves to https://descrybe.io/api/v1. - * OpenAPI servers[0] stays PUBLIC_DOCS_API_SERVER for the public YAML narrative. +/** The public reference defaults to the published production API. + * A configured API origin is used only for explicitly configured deployments. */ export function docsTryItServerURL( origin = typeof window !== "undefined" ? window.location.origin : "" @@ -25,9 +21,6 @@ export function docsTryItServerURL( if (API_BASE) { return `${API_BASE}/api/v1`; } - if (origin) { - return `${origin}/api/v1`; - } return PUBLIC_DOCS_API_SERVER; } @@ -38,7 +31,7 @@ export type RapiDocTryItHost = { }; /** - * Point RapiDoc Try-it at the local/dev API. + * Point RapiDoc Try-it at the published API endpoint. * RapiDoc only selects `server-url` when it equals `default-api-server`; * otherwise Try-it uses OpenAPI servers[0] (production) even if server-url is set. */ diff --git a/apps/web/src/routes/attributes/+page.svelte b/apps/web/src/routes/attributes/+page.svelte index 2ad8d58..d6c8b2b 100644 --- a/apps/web/src/routes/attributes/+page.svelte +++ b/apps/web/src/routes/attributes/+page.svelte @@ -1,4 +1,5 @@