Fixes
This commit is contained in:
1 parent
04794aea54
commit
cfd31f398c
61 files changed
+1977
-169
No files matched your search
@@ -162,7 +162,7 @@ func (s *Service) EntitlementsForCompany(ctx context.Context, companyID uuid.UUI
|
|||||||
// (cannot be silently downgraded to normalize/specs/fill).
|
// (cannot be silently downgraded to normalize/specs/fill).
|
||||||
func ProcessingTypeRequiresAI(processingType string) bool {
|
func ProcessingTypeRequiresAI(processingType string) bool {
|
||||||
switch strings.ToLower(strings.TrimSpace(processingType)) {
|
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
|
return true
|
||||||
default:
|
default:
|
||||||
return false
|
return false
|
||||||
|
|||||||
@@ -43,13 +43,20 @@ func (s *Service) SaveUpload(ctx context.Context, companyID, userID uuid.UUID, u
|
|||||||
if uploadDir == "" {
|
if uploadDir == "" {
|
||||||
return nil, ClientMsg("upload directory not configured")
|
return nil, ClientMsg("upload directory not configured")
|
||||||
}
|
}
|
||||||
|
kind = strings.ToLower(strings.TrimSpace(kind))
|
||||||
safe := sanitizeFileName(originalName)
|
safe := sanitizeFileName(originalName)
|
||||||
lower := strings.ToLower(safe)
|
lower := strings.ToLower(safe)
|
||||||
if !strings.HasSuffix(lower, ".csv") {
|
isCSV := strings.HasSuffix(lower, ".csv") || strings.HasSuffix(lower, ".tsv")
|
||||||
return nil, ClientMsg("only .csv uploads are allowed")
|
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 != "" &&
|
if contentType != "" &&
|
||||||
!strings.Contains(strings.ToLower(contentType), "csv") &&
|
!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), "text/plain") &&
|
||||||
!strings.Contains(strings.ToLower(contentType), "octet-stream") {
|
!strings.Contains(strings.ToLower(contentType), "octet-stream") {
|
||||||
return nil, ClientMsg("invalid content type for CSV upload")
|
return nil, ClientMsg("invalid content type for CSV upload")
|
||||||
|
|||||||
@@ -0,0 +1,174 @@
|
|||||||
|
package catalog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/csv"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// JSONImportAsCSV maps JSON arrays (including wrapped nested arrays) onto the
|
||||||
|
// same validated batch import pipeline as CSV. Data must fit the catalog upload
|
||||||
|
// limit. All rows are processed by the normal company-scoped upsert routines.
|
||||||
|
func JSONImportAsCSV(r io.Reader, kind string) (io.Reader, error) {
|
||||||
|
source, err := io.ReadAll(io.LimitReader(r, (6<<20)+1))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(source) > 6<<20 {
|
||||||
|
return nil, ClientMsg("JSON catalog import exceeds 6 MiB")
|
||||||
|
}
|
||||||
|
var doc any
|
||||||
|
dec := json.NewDecoder(bytes.NewReader(source))
|
||||||
|
dec.UseNumber()
|
||||||
|
if err := dec.Decode(&doc); err != nil {
|
||||||
|
return nil, ClientMsg("invalid JSON import: " + err.Error())
|
||||||
|
}
|
||||||
|
items := findImportJSONArray(doc, kind, 0)
|
||||||
|
if len(items) == 0 {
|
||||||
|
return nil, ClientMsg("JSON must contain an array of " + kind)
|
||||||
|
}
|
||||||
|
header := []string{}
|
||||||
|
switch kind {
|
||||||
|
case "categories":
|
||||||
|
header = []string{"name", "unique_id", "parent_unique_id", "description"}
|
||||||
|
case "attributes":
|
||||||
|
header = []string{"attribute_key", "name", "value_type", "unit", "example", "parent_key", "category_id"}
|
||||||
|
case "products":
|
||||||
|
header = []string{"gtin", "product_id", "name", "category", "description", "status"}
|
||||||
|
default:
|
||||||
|
return nil, ClientMsg("invalid catalog import kind")
|
||||||
|
}
|
||||||
|
// Keep original JSON keys too; importer uses known column names (GTIN/EAN, etc).
|
||||||
|
keys := map[string]struct{}{}
|
||||||
|
for _, k := range header {
|
||||||
|
keys[k] = struct{}{}
|
||||||
|
}
|
||||||
|
for _, v := range items {
|
||||||
|
if m, ok := v.(map[string]any); ok {
|
||||||
|
for k := range m {
|
||||||
|
keys[k] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
extras := make([]string, 0, len(keys))
|
||||||
|
for k := range keys {
|
||||||
|
found := false
|
||||||
|
for _, h := range header {
|
||||||
|
if k == h {
|
||||||
|
found = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
extras = append(extras, k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Strings(extras)
|
||||||
|
header = append(header, extras...)
|
||||||
|
var buf bytes.Buffer
|
||||||
|
cw := csv.NewWriter(&buf)
|
||||||
|
if err := cw.Write(header); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for _, v := range items {
|
||||||
|
m, ok := v.(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
rec := make([]string, len(header))
|
||||||
|
for j, k := range header {
|
||||||
|
val, exists := m[k]
|
||||||
|
if !exists && (k == "gtin" || k == "product_id" || k == "name" || k == "unique_id" || k == "attribute_key") {
|
||||||
|
aliases := map[string][]string{"gtin": {"ean", "barcode", "gtin"}, "product_id": {"sku", "productno", "productno2", "id"}, "name": {"title", "product", "product_name", "productname"}, "unique_id": {"id", "category_id", "uniqueId"}, "attribute_key": {"key", "attributeKey", "id"}}
|
||||||
|
for _, alias := range aliases[k] {
|
||||||
|
for source, value := range m {
|
||||||
|
if strings.EqualFold(source, alias) && value != nil {
|
||||||
|
val = value
|
||||||
|
exists = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if exists {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !exists {
|
||||||
|
for source, value := range m {
|
||||||
|
if strings.EqualFold(source, k) {
|
||||||
|
val = value
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if val == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
switch x := val.(type) {
|
||||||
|
case string:
|
||||||
|
rec[j] = x
|
||||||
|
case json.Number:
|
||||||
|
rec[j] = string(x)
|
||||||
|
case bool:
|
||||||
|
rec[j] = fmt.Sprint(x)
|
||||||
|
default:
|
||||||
|
b, _ := json.Marshal(x)
|
||||||
|
rec[j] = string(b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := cw.Write(rec); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cw.Flush()
|
||||||
|
if err := cw.Error(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return bytes.NewReader(buf.Bytes()), nil
|
||||||
|
}
|
||||||
|
func findImportJSONArray(doc any, kind string, depth int) []any {
|
||||||
|
if depth > 6 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if items, ok := doc.([]any); ok {
|
||||||
|
if len(items) > 0 {
|
||||||
|
if _, ok := items[0].(map[string]any); ok {
|
||||||
|
return items
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
m, ok := doc.(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
keys := []string{kind, "items", "results", "data", "records", "rows"}
|
||||||
|
if kind == "products" {
|
||||||
|
keys = append([]string{"SHOPITEM", "products", "product"}, keys...)
|
||||||
|
}
|
||||||
|
if kind == "categories" {
|
||||||
|
keys = append([]string{"categories", "category"}, keys...)
|
||||||
|
}
|
||||||
|
if kind == "attributes" {
|
||||||
|
keys = append([]string{"attributes", "specifications"}, keys...)
|
||||||
|
}
|
||||||
|
for _, k := range keys {
|
||||||
|
for actual, value := range m {
|
||||||
|
if strings.EqualFold(actual, k) {
|
||||||
|
if a := findImportJSONArray(value, kind, depth+1); len(a) > 0 {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(m) == 1 {
|
||||||
|
for _, v := range m {
|
||||||
|
return findImportJSONArray(v, kind, depth+1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package catalog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/csv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestV10JsonProducts(t *testing.T) {
|
||||||
|
r, e := JSONImportAsCSV(strings.NewReader(`{"data":{"products":[{"EAN":"8595025395184","PRODUCT":"Ročna LED svetilka","PRODUCTNO":"1440093109","category":"Svetilke"}]}}`), "products")
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
cr := csv.NewReader(r)
|
||||||
|
h, _ := cr.Read()
|
||||||
|
values, e := cr.Read()
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
m := map[string]string{}
|
||||||
|
for i, k := range h {
|
||||||
|
m[k] = values[i]
|
||||||
|
}
|
||||||
|
if m["gtin"] != "8595025395184" || m["name"] != "Ročna LED svetilka" || m["product_id"] != "1440093109" {
|
||||||
|
t.Fatalf("wrong fields %v", m)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestV10JsonCategories(t *testing.T) {
|
||||||
|
r, e := JSONImportAsCSV(strings.NewReader(`{"categories":[{"name":"Svetilke","id":50}]}`), "categories")
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
cr := csv.NewReader(r)
|
||||||
|
h, _ := cr.Read()
|
||||||
|
v, _ := cr.Read()
|
||||||
|
m := map[string]string{}
|
||||||
|
for i, k := range h {
|
||||||
|
m[k] = v[i]
|
||||||
|
}
|
||||||
|
if m["unique_id"] != "50" {
|
||||||
|
t.Fatalf("unique_id: %v", m)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
package feeds
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Requires the normal migrated test PostgreSQL schema (DATABASE_URL).
|
||||||
|
func TestDeleteFeedRemovesOnlyOwnedUnprocessedProducts(t *testing.T) {
|
||||||
|
dsn := strings.TrimSpace(os.Getenv("DATABASE_URL"))
|
||||||
|
if dsn == "" {
|
||||||
|
t.Skip("DATABASE_URL is not configured")
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
pg, err := pgxpool.New(ctx, dsn)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer pg.Close()
|
||||||
|
|
||||||
|
cid, otherCID := uuid.New(), uuid.New()
|
||||||
|
for _, id := range []uuid.UUID{cid, otherCID} {
|
||||||
|
if _, err := pg.Exec(ctx, `INSERT INTO companies (id, name) VALUES ($1, $2)`, id, "delete-cleanup-"+id.String()[:8]); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
defer pg.Exec(context.Background(), `DELETE FROM companies WHERE id = ANY($1::uuid[])`, []uuid.UUID{cid, otherCID})
|
||||||
|
|
||||||
|
newFeed := func(c uuid.UUID) uuid.UUID {
|
||||||
|
t.Helper()
|
||||||
|
var id uuid.UUID
|
||||||
|
if err := pg.QueryRow(ctx, `INSERT INTO input_feeds (company_id, name) VALUES ($1, 'test-feed') RETURNING id`, c).Scan(&id); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
feed := newFeed(cid)
|
||||||
|
survivor := newFeed(cid)
|
||||||
|
otherFeed := newFeed(otherCID)
|
||||||
|
|
||||||
|
newRaw := func(c uuid.UUID, name string, fid uuid.UUID, processed bool, status string, ids any) uuid.UUID {
|
||||||
|
t.Helper()
|
||||||
|
var id uuid.UUID
|
||||||
|
err := pg.QueryRow(ctx, `
|
||||||
|
INSERT INTO raw_products (company_id, gtin, feed_id, feed_ids, is_processed, processing_status)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6) RETURNING id`, c, name, fid, ids, processed, status).Scan(&id)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
unprocessed := newRaw(cid, "delete-new", feed, false, "unprocessed", nil)
|
||||||
|
failed := newRaw(cid, "delete-failed", feed, false, "failed", nil)
|
||||||
|
processed := newRaw(cid, "keep-processed", feed, true, "processed", nil)
|
||||||
|
processing := newRaw(cid, "keep-running", feed, false, "processing", nil)
|
||||||
|
shared := newRaw(cid, "keep-shared", feed, false, "unprocessed", []string{feed.String(), survivor.String()})
|
||||||
|
secondary := newRaw(cid, "keep-secondary", survivor, false, "unprocessed", []string{feed.String(), survivor.String()})
|
||||||
|
untouchedOther := newRaw(otherCID, "keep-other-company", otherFeed, false, "unprocessed", nil)
|
||||||
|
|
||||||
|
// A processed result linked to an unprocessed raw row survives with its FK cleared.
|
||||||
|
var resultID uuid.UUID
|
||||||
|
if err := pg.QueryRow(ctx, `
|
||||||
|
INSERT INTO processed_products (company_id, raw_product_id, feed_id, name)
|
||||||
|
VALUES ($1, $2, $3, 'retained') RETURNING id`, cid, unprocessed, feed).Scan(&resultID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
svc := &Service{Pool: pg}
|
||||||
|
if _, err := svc.DeleteWithCleanup(ctx, otherCID, feed); !errors.Is(err, ErrNotFound) {
|
||||||
|
t.Fatalf("cross-tenant deletion must return not found, got %v", err)
|
||||||
|
}
|
||||||
|
count, err := svc.DeleteWithCleanup(ctx, cid, feed)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if count != 2 {
|
||||||
|
t.Fatalf("deleted raw count = %d, want 2", count)
|
||||||
|
}
|
||||||
|
|
||||||
|
var n int
|
||||||
|
if err := pg.QueryRow(ctx, `SELECT count(*) FROM raw_products WHERE id = ANY($1::uuid[])`, []uuid.UUID{unprocessed, failed}).Scan(&n); err != nil || n != 0 {
|
||||||
|
t.Fatalf("unprocessed rows still exist: count=%d err=%v", n, err)
|
||||||
|
}
|
||||||
|
for _, kept := range []uuid.UUID{processed, processing, shared, secondary, untouchedOther} {
|
||||||
|
if err := pg.QueryRow(ctx, `SELECT count(*) FROM raw_products WHERE id = $1`, kept).Scan(&n); err != nil || n != 1 {
|
||||||
|
t.Fatalf("preserved row %s count=%d err=%v", kept, n, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var newOwner uuid.UUID
|
||||||
|
if err := pg.QueryRow(ctx, `SELECT feed_id FROM raw_products WHERE id = $1`, shared).Scan(&newOwner); err != nil || newOwner != survivor {
|
||||||
|
t.Fatalf("shared row owner=%v err=%v", newOwner, err)
|
||||||
|
}
|
||||||
|
for _, kept := range []uuid.UUID{shared, secondary} {
|
||||||
|
if err := pg.QueryRow(ctx, `SELECT count(*) FROM raw_products WHERE id = $1 AND feed_ids @> jsonb_build_array($2::text)`, kept, feed).Scan(&n); err != nil || n != 0 {
|
||||||
|
t.Fatalf("stale secondary feed id in row %s: %d, %v", kept, n, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var rawLink *uuid.UUID
|
||||||
|
if err := pg.QueryRow(ctx, `SELECT raw_product_id FROM processed_products WHERE id = $1`, resultID).Scan(&rawLink); err != nil || rawLink != nil {
|
||||||
|
t.Fatalf("processed result must survive, detached from deleted raw: %v %v", rawLink, err)
|
||||||
|
}
|
||||||
|
if _, err := svc.DeleteWithCleanup(ctx, cid, feed); !errors.Is(err, ErrNotFound) {
|
||||||
|
t.Fatalf("second delete must be not found, got %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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.
|
// 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.
|
// Callers must Close the returned blob to remove the temp file.
|
||||||
func downloadFeed(ctx context.Context, rawURL string) (*feedBlob, error) {
|
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()
|
ensureAllowlist()
|
||||||
rawURL = strings.TrimSpace(rawURL)
|
rawURL = strings.TrimSpace(rawURL)
|
||||||
if 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" {
|
if req.URL.Scheme != "http" && req.URL.Scheme != "https" {
|
||||||
return errURLScheme
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
req.Header.Set("User-Agent", defaultUserAgent)
|
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)
|
res, err := client.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -402,3 +420,33 @@ func isBlockedIP(ip net.IP) bool {
|
|||||||
}
|
}
|
||||||
return false
|
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
|
||||||
|
}
|
||||||
@@ -759,6 +759,9 @@ func (s *Service) PublicExportXML(ctx context.Context, w io.Writer, token string
|
|||||||
}
|
}
|
||||||
|
|
||||||
// PublicExportCSV streams CSV for a public export token.
|
// 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 {
|
func (s *Service) PublicExportCSV(ctx context.Context, w io.Writer, token string) error {
|
||||||
return s.StreamPublicExport(ctx, w, token, "csv")
|
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 {
|
switch format {
|
||||||
case "csv":
|
case "csv":
|
||||||
return streamCSV(w, seq, tpl)
|
return streamCSV(w, seq, tpl)
|
||||||
|
case "json":
|
||||||
|
return streamJSON(w, seq, tpl)
|
||||||
default:
|
default:
|
||||||
return streamXML(w, seq, tpl, row.Name)
|
return streamXML(w, seq, tpl, row.Name)
|
||||||
}
|
}
|
||||||
@@ -966,6 +971,9 @@ func (s *Service) ExportSelectedProducts(ctx context.Context, companyID, feedID
|
|||||||
case "csv":
|
case "csv":
|
||||||
count, err = streamCSV(&buf, seq, tpl)
|
count, err = streamCSV(&buf, seq, tpl)
|
||||||
mimeType = "text/csv; charset=utf-8"
|
mimeType = "text/csv; charset=utf-8"
|
||||||
|
case "json":
|
||||||
|
count, err = streamJSON(&buf, seq, tpl)
|
||||||
|
mimeType = "application/json; charset=utf-8"
|
||||||
default:
|
default:
|
||||||
count, err = streamXML(&buf, seq, tpl, row.Name)
|
count, err = streamXML(&buf, seq, tpl, row.Name)
|
||||||
mimeType = "application/xml; charset=utf-8"
|
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) {
|
func renderExportSnippet(format string, tpl exportTemplate, products []exportProduct, feedName string) (string, int, error) {
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
switch strings.ToLower(strings.TrimSpace(format)) {
|
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":
|
case "csv":
|
||||||
cw := csv.NewWriter(&buf)
|
cw := csv.NewWriter(&buf)
|
||||||
headers := make([]string, len(tpl.Fields))
|
headers := make([]string, len(tpl.Fields))
|
||||||
@@ -1063,3 +1082,68 @@ func sanitizeExportFileName(name string) string {
|
|||||||
}
|
}
|
||||||
return out
|
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
|
||||||
|
}
|
||||||
@@ -115,6 +115,25 @@ func (s *Service) ExtractSchema(ctx context.Context, companyID, feedID uuid.UUID
|
|||||||
out.Fields = fields
|
out.Fields = fields
|
||||||
out.SampleRows = rows
|
out.SampleRows = rows
|
||||||
out.Preview = buildXMLPreview(data, local)
|
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:
|
default:
|
||||||
fields, rows, preview, err := extractCSVSchema(data)
|
fields, rows, preview, err := extractCSVSchema(data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -221,6 +240,7 @@ func guessXMLItemPath(data []byte) string {
|
|||||||
full string
|
full string
|
||||||
}
|
}
|
||||||
cands := []cand{
|
cands := []cand{
|
||||||
|
{"shopitem", "shop/shopitem"},
|
||||||
{"item", "rss/channel/item"},
|
{"item", "rss/channel/item"},
|
||||||
{"product", "products/product"},
|
{"product", "products/product"},
|
||||||
{"entry", "feed/entry"},
|
{"entry", "feed/entry"},
|
||||||
@@ -232,7 +252,6 @@ func guessXMLItemPath(data []byte) string {
|
|||||||
if path := findFirstTagPath(data, c.local); path != "" {
|
if path := findFirstTagPath(data, c.local); path != "" {
|
||||||
return path
|
return path
|
||||||
}
|
}
|
||||||
return c.full
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return "rss/channel/item"
|
return "rss/channel/item"
|
||||||
@@ -527,3 +546,20 @@ func buildXMLPreview(data []byte, itemLocal string) string {
|
|||||||
_ = itemLocal
|
_ = itemLocal
|
||||||
return strings.Join(out, "\n")
|
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
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -227,8 +227,34 @@ func isSpecificationsTarget(tgt string) bool {
|
|||||||
// CDATA HTML, or flat strings. Empty/missing yields nil.
|
// CDATA HTML, or flat strings. Empty/missing yields nil.
|
||||||
func resolveSpecifications(row map[string]string, src string) map[string]string {
|
func resolveSpecifications(row map[string]string, src string) map[string]string {
|
||||||
src = strings.Trim(strings.TrimSpace(src), "/")
|
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 {
|
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 val, ok := lookupRow(row, src); ok {
|
||||||
if pairs := ParseSpecifications(val); len(pairs) > 0 {
|
if pairs := ParseSpecifications(val); len(pairs) > 0 {
|
||||||
|
|||||||
@@ -31,18 +31,23 @@ type feedRow map[string]string
|
|||||||
|
|
||||||
func detectFeedFormat(feedType, contentType, urlHint string, sample []byte) string {
|
func detectFeedFormat(feedType, contentType, urlHint string, sample []byte) string {
|
||||||
ft := strings.ToLower(strings.TrimSpace(feedType))
|
ft := strings.ToLower(strings.TrimSpace(feedType))
|
||||||
if ft == "csv" || ft == "xml" {
|
if ft == "csv" || ft == "xml" || ft == "json" {
|
||||||
return ft
|
return ft
|
||||||
}
|
}
|
||||||
ct := strings.ToLower(contentType)
|
ct := strings.ToLower(contentType)
|
||||||
u := strings.ToLower(urlHint)
|
u := strings.ToLower(urlHint)
|
||||||
switch {
|
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"):
|
case strings.Contains(ct, "csv") || strings.HasSuffix(u, ".csv"):
|
||||||
return "csv"
|
return "csv"
|
||||||
case strings.Contains(ct, "xml") || strings.HasSuffix(u, ".xml"):
|
case strings.Contains(ct, "xml") || strings.HasSuffix(u, ".xml"):
|
||||||
return "xml"
|
return "xml"
|
||||||
}
|
}
|
||||||
trimmed := bytes.TrimSpace(sample)
|
trimmed := bytes.TrimSpace(sample)
|
||||||
|
if len(trimmed) > 0 && (trimmed[0] == '{' || trimmed[0] == '[') {
|
||||||
|
return "json"
|
||||||
|
}
|
||||||
if len(trimmed) > 0 && trimmed[0] == '<' {
|
if len(trimmed) > 0 && trimmed[0] == '<' {
|
||||||
return "xml"
|
return "xml"
|
||||||
}
|
}
|
||||||
@@ -173,7 +178,7 @@ func guessXMLItemLocal(data []byte) string {
|
|||||||
sample = sample[:xmlItemGuessBytes]
|
sample = sample[:xmlItemGuessBytes]
|
||||||
}
|
}
|
||||||
lower := strings.ToLower(sample)
|
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) {
|
if strings.Contains(lower, "<"+cand) || strings.Contains(lower, ":"+cand) {
|
||||||
return cand
|
return cand
|
||||||
}
|
}
|
||||||
@@ -193,6 +198,7 @@ func readXMLElementMap(dec *xml.Decoder, start xml.StartElement) (feedRow, error
|
|||||||
row[start.Name.Local+"/"+key] = a.Value
|
row[start.Name.Local+"/"+key] = a.Value
|
||||||
}
|
}
|
||||||
var path []string
|
var path []string
|
||||||
|
var paramName, paramValue string
|
||||||
for {
|
for {
|
||||||
tok, err := dec.Token()
|
tok, err := dec.Token()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -207,7 +213,38 @@ func readXMLElementMap(dec *xml.Decoder, start xml.StartElement) (feedRow, error
|
|||||||
row[key] = a.Value
|
row[key] = a.Value
|
||||||
}
|
}
|
||||||
case xml.EndElement:
|
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 {
|
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
|
return row, nil
|
||||||
}
|
}
|
||||||
path = path[:len(path)-1]
|
path = path[:len(path)-1]
|
||||||
@@ -217,6 +254,19 @@ func readXMLElementMap(dec *xml.Decoder, start xml.StartElement) (feedRow, error
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
leaf := path[len(path)-1]
|
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, "/")
|
full := strings.Join(path, "/")
|
||||||
// Prefer nested path as source of truth; only set bare leaf when
|
// Prefer nested path as source of truth; only set bare leaf when
|
||||||
// unique (no other nested field already owns this leaf name).
|
// unique (no other nested field already owns this leaf name).
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -61,7 +61,8 @@ func PresentFeed(feed map[string]any) map[string]any {
|
|||||||
"last_synced_at": lastSynced,
|
"last_synced_at": lastSynced,
|
||||||
"products_updated_at": productsUpdated,
|
"products_updated_at": productsUpdated,
|
||||||
"last_data_at": lastDataAt,
|
"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 {
|
if deltas, ok := opts["last_sync_deltas"].(map[string]any); ok && deltas != nil {
|
||||||
out["last_sync_deltas"] = deltas
|
out["last_sync_deltas"] = deltas
|
||||||
@@ -138,3 +139,13 @@ func formatAPITime(v any) any {
|
|||||||
return v
|
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
|
||||||
|
}
|
||||||
@@ -28,6 +28,7 @@ type CreateInput struct {
|
|||||||
SyncIntervalMinutes int
|
SyncIntervalMinutes int
|
||||||
SyncFrequencyHours int // legacy alias; converted to minutes when SyncIntervalMinutes unset
|
SyncFrequencyHours int // legacy alias; converted to minutes when SyncIntervalMinutes unset
|
||||||
Options map[string]any
|
Options map[string]any
|
||||||
|
RequestHeaders map[string]string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) List(ctx context.Context, companyID uuid.UUID, limit, offset int, q string) ([]map[string]any, int64, int64, int64, error) {
|
func (s *Service) List(ctx context.Context, companyID uuid.UUID, limit, offset int, q string) ([]map[string]any, int64, int64, int64, error) {
|
||||||
@@ -120,6 +121,13 @@ func (s *Service) Create(ctx context.Context, companyID uuid.UUID, in CreateInpu
|
|||||||
if opts == nil {
|
if opts == nil {
|
||||||
opts = map[string]any{}
|
opts = map[string]any{}
|
||||||
}
|
}
|
||||||
|
if 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)
|
itemPath := strings.TrimSpace(in.ItemPath)
|
||||||
if itemPath == "" {
|
if itemPath == "" {
|
||||||
if p, ok := opts["item_path"].(string); ok {
|
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"
|
feedType = "csv"
|
||||||
} else {
|
} else {
|
||||||
feedType = "xml"
|
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
|
interval := in.SyncIntervalMinutes
|
||||||
if interval <= 0 && in.SyncFrequencyHours > 0 {
|
if interval <= 0 && in.SyncFrequencyHours > 0 {
|
||||||
@@ -273,7 +284,7 @@ func mappingDocIncomplete(item map[string]any, mappingsRaw any, mappings []Field
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
feedType, _ := item["feed_type"].(string)
|
feedType, _ := item["feed_type"].(string)
|
||||||
if !isCSVFeedType(feedType) && feedItemPathHint(item, mappingsRaw) == "" {
|
if !isCSVFeedType(feedType) && !strings.EqualFold(feedType, "json") && feedItemPathHint(item, mappingsRaw) == "" {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
@@ -303,8 +314,8 @@ func (s *Service) Update(ctx context.Context, companyID, id uuid.UUID, body map[
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
feedType = strings.ToLower(strings.TrimSpace(feedType))
|
feedType = strings.ToLower(strings.TrimSpace(feedType))
|
||||||
if feedType != "" && feedType != "xml" && feedType != "csv" {
|
if feedType != "" && feedType != "xml" && feedType != "csv" && feedType != "json" {
|
||||||
return nil, ClientMsg("feed_type must be xml or csv")
|
return nil, ClientMsg("feed_type must be xml, csv or json")
|
||||||
}
|
}
|
||||||
interval := 0
|
interval := 0
|
||||||
switch v := body["sync_interval_minutes"].(type) {
|
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, `
|
ct, err := s.Pool.Exec(ctx, `
|
||||||
UPDATE input_feeds SET
|
UPDATE input_feeds SET
|
||||||
name = CASE WHEN $3 <> '' THEN $3 ELSE name END,
|
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,
|
status = CASE WHEN $5 <> '' THEN $5 ELSE status END,
|
||||||
feed_type = CASE WHEN $6 <> '' THEN $6 ELSE feed_type 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,
|
sync_interval_minutes = CASE WHEN $7 > 0 THEN $7 ELSE sync_interval_minutes END,
|
||||||
options = CASE
|
options = CASE WHEN $9::text IS NULL THEN
|
||||||
WHEN $8 <> '' THEN COALESCE(options, '{}'::jsonb) || jsonb_build_object('item_path', to_jsonb($8::text))
|
(CASE WHEN $8 <> '' THEN COALESCE(options, '{}'::jsonb) || jsonb_build_object('item_path', to_jsonb($8::text)) ELSE options END)
|
||||||
ELSE options
|
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,
|
END,
|
||||||
updated_at = now()
|
updated_at = now()
|
||||||
WHERE id = $1 AND company_id = $2`,
|
WHERE id = $1 AND company_id = $2`,
|
||||||
id, companyID, name, url, status, feedType, interval, strings.TrimSpace(itemPath))
|
id, companyID, name, url, status, feedType, interval, strings.TrimSpace(itemPath), encryptedHeaders)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
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)
|
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 {
|
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)
|
||||||
if err != nil {
|
|
||||||
return err
|
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 0, err
|
||||||
}
|
}
|
||||||
if ct.RowsAffected() == 0 {
|
defer tx.Rollback(ctx)
|
||||||
return ErrNotFound
|
|
||||||
|
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 nil
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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) {
|
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 == "" {
|
if format == "" {
|
||||||
format = "xml"
|
format = "xml"
|
||||||
}
|
}
|
||||||
if format != "xml" && format != "csv" {
|
if format != "xml" && format != "csv" && format != "json" {
|
||||||
return nil, ClientMsg("format must be xml or csv")
|
return nil, ClientMsg("format must be xml, csv or json")
|
||||||
}
|
}
|
||||||
var src *uuid.UUID
|
var src *uuid.UUID
|
||||||
if in.SourceFeedID != nil && *in.SourceFeedID != "" {
|
if in.SourceFeedID != nil && *in.SourceFeedID != "" {
|
||||||
|
|||||||
@@ -77,7 +77,11 @@ func (s *Service) loadFeedSource(ctx context.Context, companyID uuid.UUID, feed
|
|||||||
if urlStr == "" {
|
if urlStr == "" {
|
||||||
return nil, errSourceRequired
|
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 {
|
func sourcePathFromOptions(raw any) string {
|
||||||
@@ -121,6 +125,8 @@ func (s *Service) readLocalFeed(companyID uuid.UUID, rel string) (*feedBlob, err
|
|||||||
lower := strings.ToLower(abs)
|
lower := strings.ToLower(abs)
|
||||||
if strings.HasSuffix(lower, ".xml") {
|
if strings.HasSuffix(lower, ".xml") {
|
||||||
ct = "application/xml"
|
ct = "application/xml"
|
||||||
|
} else if strings.HasSuffix(lower, ".json") {
|
||||||
|
ct = "application/json"
|
||||||
}
|
}
|
||||||
return &feedBlob{
|
return &feedBlob{
|
||||||
path: abs,
|
path: abs,
|
||||||
|
|||||||
@@ -94,8 +94,10 @@ func isSpecFieldKey(key string) bool {
|
|||||||
leaf := strings.ToLower(leafName(key))
|
leaf := strings.ToLower(leafName(key))
|
||||||
leaf = strings.TrimPrefix(leaf, "@")
|
leaf = strings.TrimPrefix(leaf, "@")
|
||||||
switch leaf {
|
switch leaf {
|
||||||
case "specifications", "specification", "specs", "spec", "features", "feature", "attributes_raw":
|
case "specifications", "specification", "specs", "spec", "features", "feature", "attributes_raw", "params":
|
||||||
return true
|
return true
|
||||||
|
case "description":
|
||||||
|
return !strings.Contains(key, "/")
|
||||||
}
|
}
|
||||||
return strings.Contains(leaf, "specification")
|
return strings.Contains(leaf, "specification")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,12 @@ type MappingSuggestion struct {
|
|||||||
|
|
||||||
var sourceAliases = map[string][]string{
|
var sourceAliases = map[string][]string{
|
||||||
"gtin": {"gtin"},
|
"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"},
|
"ean": {"gtin"},
|
||||||
"upc": {"gtin"},
|
"upc": {"gtin"},
|
||||||
"barcode": {"gtin"},
|
"barcode": {"gtin"},
|
||||||
|
|||||||
@@ -402,7 +402,23 @@ func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUI
|
|||||||
var parseCount int
|
var parseCount int
|
||||||
switch format {
|
switch format {
|
||||||
case "xml":
|
case "xml":
|
||||||
|
if itemPath == "item" {
|
||||||
|
itemPath = ""
|
||||||
|
}
|
||||||
parseCount, err = parseXMLItems(body, itemPath, onRow)
|
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:
|
default:
|
||||||
parseCount, err = parseCSV(body, onRow)
|
parseCount, err = parseCSV(body, onRow)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package feeds
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
const emos = `<?xml version="1.0"?><SHOP><SHOPITEM><PRODUCT>Ročna LED svetilka 9 LED 3×AAA</PRODUCT><PRODUCTNO>1440093109</PRODUCTNO><EAN>8595025395184</EAN><CATEGORY>Svetilke|Ročne svetilke</CATEGORY><DESCRIPTION>barva: mešanica barv|napajanje: 3× AAA|svetlobni tok: 50 lm</DESCRIPTION><DESCRIPTION_BASIC><p>Praktična LED svetilka</p></DESCRIPTION_BASIC><PARAMS><PARAM><PARAM_NAME>barva</PARAM_NAME><VAL>mešanica barv</VAL><ORDER>12</ORDER></PARAM><PARAM><PARAM_NAME>napajanje</PARAM_NAME><VAL>3× AAA</VAL></PARAM><PARAM><PARAM_NAME>vir svetlobe</PARAM_NAME><VAL>9× LED</VAL></PARAM></PARAMS><IMGURL>https://example.com/1.jpg</IMGURL><IMGURL_ALTERNATIVE_01>https://example.com/2.jpg</IMGURL_ALTERNATIVE_01></SHOPITEM></SHOP>`
|
||||||
|
|
||||||
|
func TestV10EMOSItemAndAttrs(t *testing.T) {
|
||||||
|
var got feedRow
|
||||||
|
n, e := parseXMLItems(strings.NewReader(emos), "", func(r feedRow) error { got = r; return nil })
|
||||||
|
if e != nil || n != 1 {
|
||||||
|
t.Fatalf("parse n=%d err=%v", n, e)
|
||||||
|
}
|
||||||
|
for k, v := range map[string]string{"PRODUCT": "Ročna LED svetilka 9 LED 3×AAA", "EAN": "8595025395184", "PARAMS/barva": "mešanica barv", "PARAMS/napajanje": "3× AAA", "PARAMS/vir_svetlobe": "9× LED", "DESCRIPTION/svetlobni_tok": "50 lm", "ADDITIONAL_IMAGE_URLS": "https://example.com/2.jpg"} {
|
||||||
|
if got[k] != v {
|
||||||
|
t.Errorf("%s=%q want %q", k, got[k], v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestV10NestedJSONWrappedData(t *testing.T) {
|
||||||
|
raw := `{"data":{"products":[{"name":"Demo 1","ean":"1234567890123","attributes":[{"name":"color","value":"green"}]},{"name":"Demo 2","ean":"1234567890999"}]},"page":1}`
|
||||||
|
var rows []feedRow
|
||||||
|
n, e := parseJSONItems(strings.NewReader(raw), "", func(r feedRow) error { rows = append(rows, r); return nil })
|
||||||
|
if e != nil || n != 2 {
|
||||||
|
t.Fatalf("parse n=%d err=%v", n, e)
|
||||||
|
}
|
||||||
|
if rows[0]["attributes/color"] != "green" {
|
||||||
|
t.Errorf("nested attrs lost: %v", rows[0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestV10JSONRootAndData(t *testing.T) {
|
||||||
|
for _, raw := range []string{`[{"ean":"1"},{"ean":"2"}]`, `{"data":[{"ean":"1"},{"ean":"2"}]}`} {
|
||||||
|
n, e := parseJSONItems(strings.NewReader(raw), "", func(r feedRow) error { return nil })
|
||||||
|
if e != nil || n != 2 {
|
||||||
|
t.Fatalf("input=%s got n=%d err=%v", raw, n, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestV10PartialPreviewJSONGuess(t *testing.T) {
|
||||||
|
x := []byte(`{"data":{"products":[{"EAN":"123","sku":"demo"},`)
|
||||||
|
p := guessJSONItemPath(x)
|
||||||
|
if p != "products" {
|
||||||
|
t.Fatalf("guess=%q", p)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,8 +1,12 @@
|
|||||||
package httpapi
|
package httpapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"github.com/descrybe/descrybe-v2/apps/api/internal/feeds"
|
||||||
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/descrybe/descrybe-v2/apps/api/internal/catalog"
|
"github.com/descrybe/descrybe-v2/apps/api/internal/catalog"
|
||||||
@@ -191,6 +195,50 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
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 {
|
if err := r.ParseMultipartForm(catalogMaxUpload); err != nil {
|
||||||
Error(w, http.StatusBadRequest, "invalid multipart form")
|
Error(w, http.StatusBadRequest, "invalid multipart form")
|
||||||
return
|
return
|
||||||
@@ -228,14 +276,22 @@ func (s *Server) handleImportCSV(w http.ResponseWriter, r *http.Request) {
|
|||||||
defer f.Close()
|
defer f.Close()
|
||||||
|
|
||||||
var result any
|
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 {
|
switch kind {
|
||||||
case "categories":
|
case "categories":
|
||||||
result, err = s.Catalog.ImportCategoriesCSV(r.Context(), cid, f)
|
result, err = s.Catalog.ImportCategoriesCSV(r.Context(), cid, input)
|
||||||
case "attributes":
|
case "attributes":
|
||||||
result, err = s.Catalog.ImportAttributesCSV(r.Context(), cid, f)
|
result, err = s.Catalog.ImportAttributesCSV(r.Context(), cid, input)
|
||||||
case "products":
|
case "products":
|
||||||
fid := fileID
|
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 {
|
if err != nil {
|
||||||
public := "import failed"
|
public := "import failed"
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package httpapi
|
package httpapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -51,6 +52,7 @@ func (s *Server) handleCreateFeed(w http.ResponseWriter, r *http.Request) {
|
|||||||
ItemPath string `json:"item_path"`
|
ItemPath string `json:"item_path"`
|
||||||
FeedType string `json:"feed_type"`
|
FeedType string `json:"feed_type"`
|
||||||
SyncIntervalMinutes int `json:"sync_interval_minutes"`
|
SyncIntervalMinutes int `json:"sync_interval_minutes"`
|
||||||
|
RequestHeaders map[string]string `json:"request_headers"`
|
||||||
}
|
}
|
||||||
if err := DecodeJSON(r, &body); err != nil {
|
if err := DecodeJSON(r, &body); err != nil {
|
||||||
Error(w, http.StatusBadRequest, "invalid json")
|
Error(w, http.StatusBadRequest, "invalid json")
|
||||||
@@ -62,6 +64,7 @@ func (s *Server) handleCreateFeed(w http.ResponseWriter, r *http.Request) {
|
|||||||
ItemPath: body.ItemPath,
|
ItemPath: body.ItemPath,
|
||||||
FeedType: body.FeedType,
|
FeedType: body.FeedType,
|
||||||
SyncIntervalMinutes: body.SyncIntervalMinutes,
|
SyncIntervalMinutes: body.SyncIntervalMinutes,
|
||||||
|
RequestHeaders: body.RequestHeaders,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ClientOrLog(w, http.StatusBadRequest, "could not create feed", err, feeds.ClientError)
|
ClientOrLog(w, http.StatusBadRequest, "could not create feed", err, feeds.ClientError)
|
||||||
@@ -81,6 +84,13 @@ func (s *Server) createFeedFromMultipart(w http.ResponseWriter, r *http.Request,
|
|||||||
feedType := strings.TrimSpace(r.FormValue("feed_type"))
|
feedType := strings.TrimSpace(r.FormValue("feed_type"))
|
||||||
itemPath := strings.TrimSpace(r.FormValue("item_path"))
|
itemPath := strings.TrimSpace(r.FormValue("item_path"))
|
||||||
interval, _ := strconv.Atoi(strings.TrimSpace(r.FormValue("sync_interval_minutes")))
|
interval, _ := strconv.Atoi(strings.TrimSpace(r.FormValue("sync_interval_minutes")))
|
||||||
|
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")
|
file, header, fileErr := r.FormFile("file")
|
||||||
var options map[string]any
|
var options map[string]any
|
||||||
@@ -107,10 +117,15 @@ func (s *Server) createFeedFromMultipart(w http.ResponseWriter, r *http.Request,
|
|||||||
"source_path": pathStr,
|
"source_path": pathStr,
|
||||||
"source_file_id": fileID,
|
"source_file_id": fileID,
|
||||||
"source_filename": fileName,
|
"source_filename": fileName,
|
||||||
"source_kind": "csv",
|
"source_kind": feedType,
|
||||||
}
|
}
|
||||||
if feedType == "" {
|
if feedType == "" {
|
||||||
feedType = "csv"
|
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 {
|
if fid, err := uuid.Parse(fileID); err == nil {
|
||||||
_, _ = s.Catalog.UpdateFileStatus(r.Context(), cid, fid, "uploaded", map[string]any{
|
_, _ = 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,
|
FeedType: feedType,
|
||||||
SyncIntervalMinutes: interval,
|
SyncIntervalMinutes: interval,
|
||||||
Options: options,
|
Options: options,
|
||||||
|
RequestHeaders: headers,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ClientOrLog(w, http.StatusBadRequest, "could not create feed", err, feeds.ClientError)
|
ClientOrLog(w, http.StatusBadRequest, "could not create feed", err, feeds.ClientError)
|
||||||
@@ -192,7 +208,8 @@ func (s *Server) handleDeleteFeed(w http.ResponseWriter, r *http.Request) {
|
|||||||
Error(w, http.StatusBadRequest, "invalid id")
|
Error(w, http.StatusBadRequest, "invalid id")
|
||||||
return
|
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) {
|
if feeds.IsNotFound(err) {
|
||||||
Error(w, http.StatusNotFound, "not found")
|
Error(w, http.StatusNotFound, "not found")
|
||||||
return
|
return
|
||||||
@@ -200,7 +217,10 @@ func (s *Server) handleDeleteFeed(w http.ResponseWriter, r *http.Request) {
|
|||||||
Error(w, http.StatusInternalServerError, "delete failed")
|
Error(w, http.StatusInternalServerError, "delete failed")
|
||||||
return
|
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) {
|
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) {
|
func writePublicExportError(w http.ResponseWriter, err error) {
|
||||||
// Format mismatch must look identical to unknown tokens so probing .xml/.csv
|
// Format mismatch must look identical to unknown tokens so probing .xml/.csv
|
||||||
// cannot confirm whether a guessed public_token exists.
|
// cannot confirm whether a guessed public_token exists.
|
||||||
|
|||||||
@@ -301,6 +301,7 @@ func (s *Server) Router() http.Handler {
|
|||||||
r.Get("/support-kb/{filename}", s.handlePublicKBImage)
|
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}.xml", s.handlePublicExportXML)
|
||||||
r.With(s.RateLimitPublicExport).Get("/export-feeds/{token}.csv", s.handlePublicExportCSV)
|
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.Get("/unsubscribe", s.handlePublicUnsubscribeGet)
|
||||||
r.Post("/unsubscribe", s.handlePublicUnsubscribePost)
|
r.Post("/unsubscribe", s.handlePublicUnsubscribePost)
|
||||||
r.NotFound(func(w http.ResponseWriter, _ *http.Request) {
|
r.NotFound(func(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
|||||||
@@ -43,8 +43,8 @@ func presentV1ExportFeed(item map[string]any) map[string]any {
|
|||||||
if token, _ := item["public_token"].(string); token != "" {
|
if token, _ := item["public_token"].(string); token != "" {
|
||||||
format := strings.ToLower(strings.TrimSpace(fmt.Sprint(item["format"])))
|
format := strings.ToLower(strings.TrimSpace(fmt.Sprint(item["format"])))
|
||||||
ext := "xml"
|
ext := "xml"
|
||||||
if format == "csv" {
|
if format == "csv" || format == "json" {
|
||||||
ext = "csv"
|
ext = format
|
||||||
}
|
}
|
||||||
path := "/api/public/export-feeds/" + token + "." + ext
|
path := "/api/public/export-feeds/" + token + "." + ext
|
||||||
// Only advertise the matching extension — wrong-format URLs 404 and must not
|
// 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"])))
|
format = strings.ToLower(strings.TrimSpace(fmt.Sprint(result["format"])))
|
||||||
}
|
}
|
||||||
ext := "xml"
|
ext := "xml"
|
||||||
if format == "csv" {
|
if format == "csv" || format == "json" {
|
||||||
ext = "csv"
|
ext = format
|
||||||
}
|
}
|
||||||
token, _ := feed["public_token"].(string)
|
token, _ := feed["public_token"].(string)
|
||||||
downloadURL := fmt.Sprintf("/api/export-feeds/%s/%s", id.String(), ext)
|
downloadURL := fmt.Sprintf("/api/export-feeds/%s/%s", id.String(), ext)
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPublicJSONExportOnlyAdvertisesJSON(t *testing.T) {
|
||||||
|
item := presentV1ExportFeed(map[string]any{
|
||||||
|
"id": "00000000-0000-0000-0000-000000000001",
|
||||||
|
"name": "JSON catalog", "format": "json", "public_token": "exampleToken",
|
||||||
|
})
|
||||||
|
urls, ok := item["public_urls"].(map[string]string)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("public_urls missing: %#v", item)
|
||||||
|
}
|
||||||
|
got := urls["json"]
|
||||||
|
if got != "/api/public/export-feeds/exampleToken.json" {
|
||||||
|
t.Fatalf("json URL = %q", got)
|
||||||
|
}
|
||||||
|
if _, exists := urls["xml"]; exists {
|
||||||
|
t.Fatal("JSON export must not advertise XML URL")
|
||||||
|
}
|
||||||
|
if !strings.HasSuffix(urls["token"], ".json") {
|
||||||
|
t.Fatalf("token URL = %q", urls["token"])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,8 +17,10 @@ info:
|
|||||||
|
|
||||||
## Authentication
|
## Authentication
|
||||||
|
|
||||||
All /api/v1 operations require a company API key (Bearer or X-API-Key) except
|
Public /api/v1 operations require a company API key (Bearer or X-API-Key)
|
||||||
GET /health and GET /openapi.yaml.
|
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).
|
Document-level security is BearerAuth OR ApiKeyAuth (same key value).
|
||||||
Do not send dashboard session cookies or CSRF tokens to /api/v1.
|
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
|
1. Sign in at https://api.descrybe.io
|
||||||
2. Open Settings -> API keys (/settings?tab=api-keys)
|
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
|
(session cookie + CSRF; not this public OpenAPI surface). The secret is
|
||||||
shown once and starts with dk_.
|
shown once and starts with dk_.
|
||||||
4. Store it securely. Later list/revoke shows only key_prefix (first 10
|
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
|
items[].description on the start body is optional source text the model may
|
||||||
rewrite. Poll GET /products/process/{id} for the generated HTML.
|
rewrite. Poll GET /products/process/{id} for the generated HTML.
|
||||||
meta_title / meta_description are separate short SEO fields and may be
|
meta_title / meta_description are separate short SEO fields. The SEO-only
|
||||||
omitted depending on company configuration.
|
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
|
Note: Dashboard JSON under /api/* uses session cookies + CSRF and is separate
|
||||||
from this public API-key surface. Other path aliases
|
from this public API-key surface. Other path aliases
|
||||||
@@ -2136,7 +2141,7 @@ paths:
|
|||||||
application/json:
|
application/json:
|
||||||
schema:
|
schema:
|
||||||
type: object
|
type: object
|
||||||
required: [name, item_path]
|
required: [name]
|
||||||
properties:
|
properties:
|
||||||
name:
|
name:
|
||||||
type: string
|
type: string
|
||||||
@@ -2144,7 +2149,9 @@ paths:
|
|||||||
item_path:
|
item_path:
|
||||||
type: string
|
type: string
|
||||||
description: |
|
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:
|
url:
|
||||||
type: string
|
type: string
|
||||||
format: uri
|
format: uri
|
||||||
@@ -2156,7 +2163,8 @@ paths:
|
|||||||
enum:
|
enum:
|
||||||
- xml
|
- xml
|
||||||
- csv
|
- 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:
|
sync_interval_minutes:
|
||||||
type: integer
|
type: integer
|
||||||
minimum: 1
|
minimum: 1
|
||||||
@@ -2366,13 +2374,14 @@ paths:
|
|||||||
description: Remote feed URL, or null to clear
|
description: Remote feed URL, or null to clear
|
||||||
item_path:
|
item_path:
|
||||||
type: string
|
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:
|
feed_type:
|
||||||
type: string
|
type: string
|
||||||
enum:
|
enum:
|
||||||
- xml
|
- xml
|
||||||
- csv
|
- csv
|
||||||
description: Source format. xml or csv.
|
- json
|
||||||
|
description: Source format. xml, csv or json.
|
||||||
status:
|
status:
|
||||||
type: string
|
type: string
|
||||||
description: |
|
description: |
|
||||||
@@ -2472,7 +2481,12 @@ paths:
|
|||||||
tags:
|
tags:
|
||||||
- Feeds
|
- Feeds
|
||||||
summary: Delete feed
|
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:
|
responses:
|
||||||
'200':
|
'200':
|
||||||
description: Feed deleted. Flat FeedDeleted when handleDeleteFeed succeeds. Requires company-admin
|
description: Feed deleted. Flat FeedDeleted when handleDeleteFeed succeeds. Requires company-admin
|
||||||
@@ -2484,6 +2498,7 @@ paths:
|
|||||||
example:
|
example:
|
||||||
id: 22222222-2222-2222-2222-222222222222
|
id: 22222222-2222-2222-2222-222222222222
|
||||||
deleted: true
|
deleted: true
|
||||||
|
deleted_unprocessed_products: 18
|
||||||
'400':
|
'400':
|
||||||
description: Invalid feed UUID.
|
description: Invalid feed UUID.
|
||||||
content:
|
content:
|
||||||
@@ -2866,7 +2881,7 @@ paths:
|
|||||||
properties:
|
properties:
|
||||||
item_path:
|
item_path:
|
||||||
type: string
|
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:
|
example:
|
||||||
item_path: channel/item
|
item_path: channel/item
|
||||||
responses:
|
responses:
|
||||||
@@ -3165,7 +3180,8 @@ paths:
|
|||||||
enum:
|
enum:
|
||||||
- xml
|
- xml
|
||||||
- csv
|
- csv
|
||||||
description: Output format. xml or csv (required).
|
- json
|
||||||
|
description: Output format. xml, csv or json (required).
|
||||||
source_feed_id:
|
source_feed_id:
|
||||||
type: string
|
type: string
|
||||||
format: uuid
|
format: uuid
|
||||||
@@ -3660,7 +3676,7 @@ paths:
|
|||||||
- Export feeds
|
- Export feeds
|
||||||
summary: Rotate public export URL token
|
summary: Rotate public export URL token
|
||||||
description: |
|
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).
|
URL stops working immediately. Requires company admin (or platform staff).
|
||||||
Response is a flat ExportFeedDetail including the new public_token.
|
Response is a flat ExportFeedDetail including the new public_token.
|
||||||
parameters:
|
parameters:
|
||||||
@@ -5228,11 +5244,13 @@ components:
|
|||||||
description: |
|
description: |
|
||||||
full (default) runs the whole pipeline including AI enhance, which
|
full (default) runs the whole pipeline including AI enhance, which
|
||||||
writes formula-driven HTML descriptions (not a one- or two-sentence
|
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
|
array of those steps); dual-mode also accepts v2 dashboard types such as
|
||||||
normalize_only, enhance_only, attributes_only, eprel_only, categorize_only
|
normalize_only, enhance_only, attributes_only, eprel_only, categorize_only
|
||||||
(ParseV1ProcessingType). Alias processingType accepted when values match.
|
(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:
|
oneOf:
|
||||||
- type: string
|
- type: string
|
||||||
enum:
|
enum:
|
||||||
@@ -5241,6 +5259,7 @@ components:
|
|||||||
- title
|
- title
|
||||||
- description
|
- description
|
||||||
- attributes
|
- attributes
|
||||||
|
- seo_meta
|
||||||
- normalize_only
|
- normalize_only
|
||||||
- enhance
|
- enhance
|
||||||
- enhance_only
|
- enhance_only
|
||||||
@@ -5261,6 +5280,7 @@ components:
|
|||||||
- title
|
- title
|
||||||
- description
|
- description
|
||||||
- attributes
|
- attributes
|
||||||
|
- seo_meta
|
||||||
processingType:
|
processingType:
|
||||||
description: CamelCase alias of processing_type (must match if both set)
|
description: CamelCase alias of processing_type (must match if both set)
|
||||||
oneOf:
|
oneOf:
|
||||||
@@ -5272,7 +5292,7 @@ components:
|
|||||||
type: array
|
type: array
|
||||||
items:
|
items:
|
||||||
type: string
|
type: string
|
||||||
description: Dashboard fine-grained steps; used when processing_type omitted
|
description: Informational dashboard selection; execution uses processing_type.
|
||||||
examples:
|
examples:
|
||||||
by_ean:
|
by_ean:
|
||||||
summary: "items[].ean (preferred)"
|
summary: "items[].ean (preferred)"
|
||||||
@@ -5318,15 +5338,15 @@ components:
|
|||||||
processing_type:
|
processing_type:
|
||||||
type: string
|
type: string
|
||||||
description: |
|
description: |
|
||||||
full (default) or a named dashboard step (category, title, description,
|
full (default) or a named processing mode (title, description, seo_meta,
|
||||||
attributes, normalize_only, enhance_only, …).
|
seo_meta, attributes, normalize_only, enhance_only, …).
|
||||||
default: full
|
default: full
|
||||||
example: full
|
example: full
|
||||||
processing_types:
|
processing_types:
|
||||||
type: array
|
type: array
|
||||||
items:
|
items:
|
||||||
type: string
|
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:
|
example:
|
||||||
raw_product_ids:
|
raw_product_ids:
|
||||||
- 2c5ea4c0-4067-4e44-8c5a-9a8b7c6d5e4f
|
- 2c5ea4c0-4067-4e44-8c5a-9a8b7c6d5e4f
|
||||||
@@ -6064,12 +6084,18 @@ components:
|
|||||||
required:
|
required:
|
||||||
- id
|
- id
|
||||||
- deleted
|
- deleted
|
||||||
|
- deleted_unprocessed_products
|
||||||
properties:
|
properties:
|
||||||
id:
|
id:
|
||||||
type: string
|
type: string
|
||||||
format: uuid
|
format: uuid
|
||||||
deleted:
|
deleted:
|
||||||
type: boolean
|
type: boolean
|
||||||
|
deleted_unprocessed_products:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
minimum: 0
|
||||||
|
description: Number of unprocessed/failed raw products deleted with this feed.
|
||||||
PreparedCampaign:
|
PreparedCampaign:
|
||||||
type: object
|
type: object
|
||||||
properties:
|
properties:
|
||||||
|
|||||||
@@ -1587,6 +1587,28 @@ func (p *Pipeline) processOne(ctx context.Context, companyID, jobID uuid.UUID, i
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return false, 0, StepResult{}, err
|
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.
|
// Persist mapped unique_id only when it exists in the company taxonomy.
|
||||||
// Coerce display names (feed/vector) → unique_id before filtering so A1-style
|
// Coerce display names (feed/vector) → unique_id before filtering so A1-style
|
||||||
// name tokens are not wiped. Empty taxonomy set skips filtering (unit tests).
|
// name tokens are not wiped. Empty taxonomy set skips filtering (unit tests).
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package processing
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSEOMetaOnlySelectsEnrichmentPrerequisites(t *testing.T) {
|
||||||
|
steps := resolveSteps("seo_meta")
|
||||||
|
want := []string{StepNormalize, StepParseSpecs, StepFillFields, StepCategorize, StepAIEnhance}
|
||||||
|
if !reflect.DeepEqual(steps, want) {
|
||||||
|
t.Fatalf("seo_meta steps = %v, want %v", steps, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSEOMetaAcceptedByPublicProcess(t *testing.T) {
|
||||||
|
storage, response, err := ParseV1ProcessingType("seo_meta")
|
||||||
|
if err != nil || storage != "seo_meta" || response != "seo_meta" {
|
||||||
|
t.Fatalf("ParseV1ProcessingType(seo_meta) = %q, %v, %v", storage, response, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSEOMetaPartialResultIncludesMetaNotCopy(t *testing.T) {
|
||||||
|
input := []V1ProcessJobItem{{
|
||||||
|
"ean": "1234567890123", "name": "Existing name", "description": "Existing description",
|
||||||
|
"meta_title": "SEO title", "meta_description": "SEO description", "status": "completed",
|
||||||
|
}}
|
||||||
|
result := ProjectV1ProcessJobItems("seo_meta", input)
|
||||||
|
if len(result) != 1 {
|
||||||
|
t.Fatalf("items = %d", len(result))
|
||||||
|
}
|
||||||
|
item := result[0]
|
||||||
|
if item["meta_title"] != "SEO title" || item["meta_description"] != "SEO description" {
|
||||||
|
t.Fatalf("missing SEO metadata: %#v", item)
|
||||||
|
}
|
||||||
|
if _, found := item["name"]; found {
|
||||||
|
t.Fatalf("SEO-only response must not project title: %#v", item)
|
||||||
|
}
|
||||||
|
if _, found := item["description"]; found {
|
||||||
|
t.Fatalf("SEO-only response must not project description: %#v", item)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -314,10 +314,22 @@ func (e *Engine) RunSteps(ctx context.Context, companyID string, in ProductInput
|
|||||||
priorDesc = in.PriorProcessedDescription
|
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{
|
name, desc, tokens, raw, err := e.enhance(ctx, ProductInput{
|
||||||
GTIN: in.GTIN,
|
GTIN: in.GTIN,
|
||||||
Name: out.Name,
|
Name: promptName,
|
||||||
Description: out.Description,
|
Description: promptDesc,
|
||||||
Mapped: normalized,
|
Mapped: normalized,
|
||||||
BrandPrompt: in.BrandPrompt,
|
BrandPrompt: in.BrandPrompt,
|
||||||
Language: lang,
|
Language: lang,
|
||||||
@@ -405,6 +417,14 @@ func (e *Engine) RunSteps(ctx context.Context, companyID string, in ProductInput
|
|||||||
allUnchanged = false
|
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{
|
localized[lang] = company.LocalizedFields{
|
||||||
ProcessedName: name,
|
ProcessedName: name,
|
||||||
ProcessedDescription: desc,
|
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).
|
// Merge LLM attrs onto pipeline attrs (validated against category keys).
|
||||||
// Attrs are independent of title/description soft-fail (synthesized/refused).
|
// 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 {
|
if merged := mergeEnhanceAttrsInto(attrs, enhanceAttrsFromRaw(raw), enhanceAllowedAttrKeys(in, out.Category)); len(merged) > 0 {
|
||||||
attrs = merged
|
attrs = merged
|
||||||
enhanceAttrs = AttrsForEnhance(attrs, enhanceAllowedAttrKeys(in, out.Category))
|
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.
|
// repair short prose / title echo that ignored A1 description_template.
|
||||||
finalDescTpl := effectiveDescriptionTemplateFor(in, out)
|
finalDescTpl := effectiveDescriptionTemplateFor(in, out)
|
||||||
finalRepaired := false
|
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 != "" {
|
if synth := synthesizeProductDescription(out.ProcessedName, displayCat, in.Language, out.Attributes, finalDescTpl); synth != "" {
|
||||||
out.ProcessedDescription = synth
|
out.ProcessedDescription = synth
|
||||||
finalRepaired = true
|
finalRepaired = true
|
||||||
@@ -605,6 +625,36 @@ func (e *Engine) RunSteps(ctx context.Context, companyID string, in ProductInput
|
|||||||
out.LocalizedContent[lang] = lf
|
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 {
|
if out.Attributes == nil {
|
||||||
out.Attributes = map[string]any{}
|
out.Attributes = map[string]any{}
|
||||||
}
|
}
|
||||||
@@ -708,7 +758,7 @@ func noteMissingCategory(out *StepResult, policy StepPolicy, vectorEnabled bool)
|
|||||||
|
|
||||||
func resolveSteps(processingType string) []string {
|
func resolveSteps(processingType string) []string {
|
||||||
switch strings.ToLower(strings.TrimSpace(processingType)) {
|
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
|
// parse_specs/fill_fields/categorize feed ai_enhance — they never rewrite
|
||||||
// title/description themselves. Without them enhance ran with empty Attrs
|
// title/description themselves. Without them enhance ran with empty Attrs
|
||||||
// and (for feeds without a mapped category) no category, so the category
|
// and (for feeds without a mapped category) no category, so the category
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ import (
|
|||||||
"github.com/jackc/pgx/v5/pgxpool"
|
"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
|
const v1MetaDescriptionMaxChars = 155
|
||||||
|
|
||||||
@@ -791,6 +791,9 @@ func ProjectV1ProcessJobItems(storedType string, items []V1ProcessJobItem) []V1P
|
|||||||
}
|
}
|
||||||
case "attributes":
|
case "attributes":
|
||||||
projected["attributes"] = item["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))
|
out = append(out, withAlwaysIncluded(projected, main, more, eprel))
|
||||||
|
|||||||
@@ -169,7 +169,7 @@
|
|||||||
{importing ? i18n.t("catalog.uploading") : i18n.t("categories.chooseCsv")}
|
{importing ? i18n.t("catalog.uploading") : i18n.t("categories.chooseCsv")}
|
||||||
<input
|
<input
|
||||||
type="file"
|
type="file"
|
||||||
accept=".csv,.tsv,text/csv,text/tab-separated-values"
|
accept=".csv,.tsv,.json,text/csv,text/tab-separated-values,application/json"
|
||||||
class="absolute inset-0 cursor-pointer opacity-0"
|
class="absolute inset-0 cursor-pointer opacity-0"
|
||||||
onchange={handleFile}
|
onchange={handleFile}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { api, failureMessage } from "$lib/api";
|
||||||
|
import { notifySuccess } from "$lib/notify";
|
||||||
|
let {kind,onComplete}:{kind:"categories"|"attributes"|"products";onComplete:()=>void|Promise<void>}=$props();
|
||||||
|
let url=$state(""); let token=$state(""); let authMode=$state("bearer"); let headerName=$state("X-API-Key");let extra=$state("");let busy=$state(false);let error=$state("");
|
||||||
|
async function submit(event:SubmitEvent){
|
||||||
|
event.preventDefault();busy=true;error="";
|
||||||
|
try{
|
||||||
|
const headers:Record<string,string>=extra.trim()?JSON.parse(extra):{};
|
||||||
|
if (!headers||Array.isArray(headers)||typeof headers!=="object"||Object.values(headers).some(v=>typeof v!=="string"))throw new Error("Headers must be a JSON object of strings");
|
||||||
|
if(token.trim())headers[authMode==="bearer"?"Authorization":headerName.trim()||"X-API-Key"]=authMode==="bearer"?`Bearer ${token.trim()}`:token.trim();
|
||||||
|
const result=await api<{import?:{created?:number;updated?:number;skipped?:number}}>(`/api/${kind}/import`,{method:"POST",body:{url:url.trim(),format:"json",request_headers:headers}});
|
||||||
|
notifySuccess(`Imported ${result.import?.created??0} new and ${result.import?.updated??0} updated ${kind}`);
|
||||||
|
await onComplete();
|
||||||
|
}catch(e){error=failureMessage(e,"JSON import failed")}finally{busy=false}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
<form class="space-y-2 rounded-md border border-border p-3" onsubmit={submit}>
|
||||||
|
<p class="text-sm font-medium">Import {kind} from JSON URL</p>
|
||||||
|
<input class="w-full rounded-md border bg-background p-2 text-sm" type="url" required bind:value={url} placeholder="https://supplier.example/api/products?format=json" />
|
||||||
|
<select class="w-full rounded-md border bg-background p-2 text-sm" bind:value={authMode}><option value="bearer">Bearer token (optional)</option><option value="header">Custom API key header</option></select>
|
||||||
|
{#if authMode==="header"}<input class="w-full rounded-md border bg-background p-2 text-sm" bind:value={headerName} placeholder="X-API-Key" />{/if}
|
||||||
|
<input class="w-full rounded-md border bg-background p-2 text-sm" type="password" autocomplete="off" bind:value={token} placeholder="API key / token (optional)" />
|
||||||
|
<textarea class="w-full rounded-md border bg-background p-2 font-mono text-xs" rows="2" bind:value={extra} placeholder='Additional headers JSON, e.g. {"X-Tenant":"my-store"}'></textarea>
|
||||||
|
{#if error}<p class="text-sm text-destructive">{error}</p>{/if}
|
||||||
|
<button class="rounded-md bg-primary px-3 py-2 text-sm font-medium text-primary-foreground disabled:opacity-50" disabled={busy}>{busy?"Importing...":"Import JSON"}</button>
|
||||||
|
</form>
|
||||||
@@ -61,7 +61,11 @@
|
|||||||
|
|
||||||
const filtered = $derived.by(() => {
|
const filtered = $derived.by(() => {
|
||||||
const q = filterText.trim().toLowerCase();
|
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 samples = field.sample_values ?? [];
|
||||||
const matchesText =
|
const matchesText =
|
||||||
!q ||
|
!q ||
|
||||||
|
|||||||
@@ -23,7 +23,14 @@ export function leafKey(path: string): string {
|
|||||||
* Matchers pick the first alias that exists in the enabled target set.
|
* Matchers pick the first alias that exists in the enabled target set.
|
||||||
*/
|
*/
|
||||||
const SOURCE_ALIASES: Record<string, string[]> = {
|
const SOURCE_ALIASES: Record<string, string[]> = {
|
||||||
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"],
|
ean: ["gtin"],
|
||||||
upc: ["gtin"],
|
upc: ["gtin"],
|
||||||
barcode: ["gtin"],
|
barcode: ["gtin"],
|
||||||
@@ -210,7 +217,9 @@ export function suggestMappings(
|
|||||||
|
|
||||||
schemaFields.forEach((field, order) => {
|
schemaFields.forEach((field, order) => {
|
||||||
const apiHint = (field.suggested_target || "").trim();
|
const apiHint = (field.suggested_target || "").trim();
|
||||||
|
const isSpecDescription = leafKey(field.path) === "description" && (field.sample_values ?? []).some((v) => (v.match(/\|/g) ?? []).length > 2 && v.includes(":"));
|
||||||
const keys = [
|
const keys = [
|
||||||
|
...(isSpecDescription ? ["specifications"] : []),
|
||||||
normalizeKey(field.field_name || ""),
|
normalizeKey(field.field_name || ""),
|
||||||
leafKey(field.path),
|
leafKey(field.path),
|
||||||
normalizeKey(field.path)
|
normalizeKey(field.path)
|
||||||
@@ -218,7 +227,13 @@ export function suggestMappings(
|
|||||||
|
|
||||||
let hit: MappingSuggestion | null = null;
|
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 };
|
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);
|
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 {
|
function isCsvFeedType(feedType?: string | null): boolean {
|
||||||
const t = String(feedType ?? "").toLowerCase();
|
const t = String(feedType ?? "").toLowerCase();
|
||||||
return t === "csv" || t === "excel";
|
return t === "csv" || t === "excel" || t === "json";
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Active source→target pairs (excludes blank / none). */
|
/** Active source→target pairs (excludes blank / none). */
|
||||||
|
|||||||
@@ -57,30 +57,17 @@
|
|||||||
let pendingCount = $state(0);
|
let pendingCount = $state(0);
|
||||||
let selectedTypes = $state<ProcessingType[]>([]);
|
let selectedTypes = $state<ProcessingType[]>([]);
|
||||||
|
|
||||||
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(
|
const selectedAILocked = $derived(
|
||||||
selectedTypes.some((t) => PROCESSING_OPTIONS.find((o) => o.type === t)?.requiresAI && !aiAllowedForType(t))
|
selectedTypes.some((t) => PROCESSING_OPTIONS.find((o) => o.type === t)?.requiresAI && !aiAllowedForType(t))
|
||||||
);
|
);
|
||||||
|
|
||||||
const totalCredits = $derived.by(() => {
|
// Estimated cost only; actual AI usage is billed from provider tokens.
|
||||||
const selectedCredits = PROCESSING_OPTIONS.filter((o) => selectedTypes.includes(o.type)).reduce(
|
const totalCredits = $derived(
|
||||||
(sum, o) => sum + o.credits,
|
PROCESSING_OPTIONS.filter((option) => selectedTypes.includes(option.type)).reduce(
|
||||||
|
(sum, option) => sum + option.credits,
|
||||||
0
|
0
|
||||||
|
) * selectedCount
|
||||||
);
|
);
|
||||||
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);
|
|
||||||
});
|
|
||||||
|
|
||||||
function toggleType(type: ProcessingType) {
|
function toggleType(type: ProcessingType) {
|
||||||
if (!aiAllowedForType(type) && PROCESSING_OPTIONS.find((o) => o.type === type)?.requiresAI) return;
|
if (!aiAllowedForType(type) && PROCESSING_OPTIONS.find((o) => o.type === type)?.requiresAI) return;
|
||||||
@@ -98,10 +85,7 @@
|
|||||||
|
|
||||||
function processSelected() {
|
function processSelected() {
|
||||||
if (selectedTypes.length === 0) return;
|
if (selectedTypes.length === 0) return;
|
||||||
pendingTypes =
|
pendingTypes = [...selectedTypes];
|
||||||
needsCategorization && !selectedTypes.includes("category")
|
|
||||||
? (["category", ...selectedTypes] as ProcessingType[])
|
|
||||||
: [...selectedTypes];
|
|
||||||
pendingCredits = totalCredits;
|
pendingCredits = totalCredits;
|
||||||
pendingCount = selectedCount;
|
pendingCount = selectedCount;
|
||||||
open = false;
|
open = false;
|
||||||
@@ -255,21 +239,6 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="my-1 h-px bg-border"></div>
|
<div class="my-1 h-px bg-border"></div>
|
||||||
<div class="space-y-2 p-2">
|
<div class="space-y-2 p-2">
|
||||||
{#if needsCategorization && !selectedTypes.includes("category")}
|
|
||||||
<div class="mb-2 rounded border border-primary/20 bg-primary/5 p-2 text-xs">
|
|
||||||
<div class="font-medium text-foreground">
|
|
||||||
{i18n.t("products.actions.autoCategorizeTitle")}
|
|
||||||
</div>
|
|
||||||
<div class="text-muted-foreground">
|
|
||||||
{i18n.t("products.actions.autoCategorizeBody", {
|
|
||||||
count: uncategorized.length,
|
|
||||||
types: selectedTypes
|
|
||||||
.filter((t) => needingCategory.includes(t))
|
|
||||||
.join(", ")
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
{#if selectedAILocked}
|
{#if selectedAILocked}
|
||||||
<div class="mb-2 rounded border border-destructive/30 bg-destructive/5 p-2 text-xs text-muted-foreground">
|
<div class="mb-2 rounded border border-destructive/30 bg-destructive/5 p-2 text-xs text-muted-foreground">
|
||||||
{i18n.t("products.actions.aiLocked")}
|
{i18n.t("products.actions.aiLocked")}
|
||||||
|
|||||||
@@ -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/);
|
||||||
|
});
|
||||||
@@ -43,13 +43,13 @@ export {
|
|||||||
tabToApiParams
|
tabToApiParams
|
||||||
} from "../../products-search";
|
} 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). */
|
/** 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). */
|
/** 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 = {
|
export type CategoryOption = {
|
||||||
uniqueId: string;
|
uniqueId: string;
|
||||||
@@ -140,10 +140,9 @@ export const PROCESSING_OPTIONS: {
|
|||||||
credits: number;
|
credits: number;
|
||||||
requiresAI?: boolean;
|
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: "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. */
|
/** True when product is awaiting Accept / edit / reject after enrichment. */
|
||||||
|
|||||||
@@ -12,10 +12,10 @@ import { validateDocsGuideTree } from "./resolve";
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
const AUTH_NOTE =
|
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 =
|
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 = {
|
export const DOCS_GUIDE_TREE: DocsGuideTree = {
|
||||||
version: 2,
|
version: 2,
|
||||||
@@ -65,8 +65,8 @@ export const DOCS_GUIDE_TREE: DocsGuideTree = {
|
|||||||
choices: [
|
choices: [
|
||||||
{
|
{
|
||||||
id: "pipeline",
|
id: "pipeline",
|
||||||
label: "Feeds → process → export",
|
label: "Import → enrich → export",
|
||||||
description: "Ingest, enrich, or outbound feeds",
|
description: "Connect a supplier, generate content, and download results",
|
||||||
nextId: "q.pipeline"
|
nextId: "q.pipeline"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ export type ExportField = { key: string; source: string };
|
|||||||
export type ExportPresetId =
|
export type ExportPresetId =
|
||||||
| "custom_xml"
|
| "custom_xml"
|
||||||
| "custom_csv"
|
| "custom_csv"
|
||||||
|
| "custom_json"
|
||||||
| "google_shopping_csv"
|
| "google_shopping_csv"
|
||||||
| "google_shopping_xml"
|
| "google_shopping_xml"
|
||||||
| "meta_csv";
|
| "meta_csv";
|
||||||
@@ -17,7 +18,7 @@ export type ExportPreset = {
|
|||||||
shortLabel: string;
|
shortLabel: string;
|
||||||
description: string;
|
description: string;
|
||||||
hint: string;
|
hint: string;
|
||||||
format: "csv" | "xml";
|
format: "csv" | "xml" | "json";
|
||||||
root?: string;
|
root?: string;
|
||||||
item?: string;
|
item?: string;
|
||||||
fields: ExportField[];
|
fields: ExportField[];
|
||||||
@@ -110,6 +111,9 @@ export const EXPORT_PRESETS: ExportPreset[] = [
|
|||||||
item: "product",
|
item: "product",
|
||||||
fields: DEFAULT_CUSTOM_FIELDS
|
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",
|
id: "custom_xml",
|
||||||
channel: "custom",
|
channel: "custom",
|
||||||
@@ -129,25 +133,25 @@ export function presetById(id: ExportPresetId | string | null | undefined): Expo
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function defaultNameForPreset(preset: ExportPreset): string {
|
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 {
|
export function presetLabel(preset: ExportPreset | ExportPresetId): string {
|
||||||
const id = typeof preset === "string" ? preset : preset.id;
|
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 {
|
export function presetShortLabel(preset: ExportPreset | ExportPresetId): string {
|
||||||
const id = typeof preset === "string" ? preset : preset.id;
|
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 {
|
export function presetDescription(preset: ExportPreset | ExportPresetId): string {
|
||||||
const id = typeof preset === "string" ? preset : preset.id;
|
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 {
|
export function presetHint(preset: ExportPreset | ExportPresetId): string {
|
||||||
const id = typeof preset === "string" ? preset : preset.id;
|
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`);
|
||||||
}
|
}
|
||||||
@@ -2766,6 +2766,7 @@ export const de: MessageDict = {
|
|||||||
"products.option.attributes": "Attribute / Spezifikationen",
|
"products.option.attributes": "Attribute / Spezifikationen",
|
||||||
"products.option.titlesAi": "Titel (KI)",
|
"products.option.titlesAi": "Titel (KI)",
|
||||||
"products.option.descriptionsAi": "Beschreibungen (KI)",
|
"products.option.descriptionsAi": "Beschreibungen (KI)",
|
||||||
|
"products.option.seoMetaAi": "SEO-Metatitel und -beschreibung (KI)",
|
||||||
"products.enrichment.piece.name": "Bezeichnung",
|
"products.enrichment.piece.name": "Bezeichnung",
|
||||||
"products.enrichment.piece.description": "Beschreibung",
|
"products.enrichment.piece.description": "Beschreibung",
|
||||||
"products.enrichment.piece.attributes": "Attribute",
|
"products.enrichment.piece.attributes": "Attribute",
|
||||||
|
|||||||
@@ -2571,7 +2571,7 @@ export const en: MessageDict = {
|
|||||||
"confirm.defaultTitle": "Confirm Deletion",
|
"confirm.defaultTitle": "Confirm Deletion",
|
||||||
"confirm.defaultDescription": "Are you sure?",
|
"confirm.defaultDescription": "Are you sure?",
|
||||||
"confirm.defaultConfirm": "Confirm",
|
"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.deleteCampaign": "Delete campaign “{name}”? This cannot be undone.",
|
||||||
"confirm.deleteExportFeed":
|
"confirm.deleteExportFeed":
|
||||||
"Are you sure you want to delete this export feed?",
|
"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.attributes": "Attributes / specs",
|
||||||
"products.option.titlesAi": "Titles (AI)",
|
"products.option.titlesAi": "Titles (AI)",
|
||||||
"products.option.descriptionsAi": "Descriptions (AI)",
|
"products.option.descriptionsAi": "Descriptions (AI)",
|
||||||
|
"products.option.seoMetaAi": "SEO meta title & description (AI)",
|
||||||
"products.enrichment.piece.name": "Name",
|
"products.enrichment.piece.name": "Name",
|
||||||
"products.enrichment.piece.description": "Description",
|
"products.enrichment.piece.description": "Description",
|
||||||
"products.enrichment.piece.attributes": "Attributes",
|
"products.enrichment.piece.attributes": "Attributes",
|
||||||
|
|||||||
@@ -2766,6 +2766,7 @@ export const es: MessageDict = {
|
|||||||
"products.option.attributes": "Atributos / especificaciones",
|
"products.option.attributes": "Atributos / especificaciones",
|
||||||
"products.option.titlesAi": "TÃÂÂtulos (IA)",
|
"products.option.titlesAi": "TÃÂÂtulos (IA)",
|
||||||
"products.option.descriptionsAi": "Descripciones (IA)",
|
"products.option.descriptionsAi": "Descripciones (IA)",
|
||||||
|
"products.option.seoMetaAi": "Título y descripción SEO (IA)",
|
||||||
"products.enrichment.piece.name": "Nombre",
|
"products.enrichment.piece.name": "Nombre",
|
||||||
"products.enrichment.piece.description": "Descripción",
|
"products.enrichment.piece.description": "Descripción",
|
||||||
"products.enrichment.piece.attributes": "Atributos",
|
"products.enrichment.piece.attributes": "Atributos",
|
||||||
|
|||||||
@@ -2766,6 +2766,7 @@ export const fr: MessageDict = {
|
|||||||
"products.option.attributes": "Attributs / spécifications",
|
"products.option.attributes": "Attributs / spécifications",
|
||||||
"products.option.titlesAi": "Titres (IA)",
|
"products.option.titlesAi": "Titres (IA)",
|
||||||
"products.option.descriptionsAi": "Descriptions (IA)",
|
"products.option.descriptionsAi": "Descriptions (IA)",
|
||||||
|
"products.option.seoMetaAi": "Titre et description méta SEO (IA)",
|
||||||
"products.enrichment.piece.name": "Nom",
|
"products.enrichment.piece.name": "Nom",
|
||||||
"products.enrichment.piece.description": "Description",
|
"products.enrichment.piece.description": "Description",
|
||||||
"products.enrichment.piece.attributes": "Attributs",
|
"products.enrichment.piece.attributes": "Attributs",
|
||||||
|
|||||||
@@ -2766,6 +2766,7 @@ export const it: MessageDict = {
|
|||||||
"products.option.attributes": "Attributi / specifiche",
|
"products.option.attributes": "Attributi / specifiche",
|
||||||
"products.option.titlesAi": "Titoli (IA)",
|
"products.option.titlesAi": "Titoli (IA)",
|
||||||
"products.option.descriptionsAi": "Descrizioni (IA)",
|
"products.option.descriptionsAi": "Descrizioni (IA)",
|
||||||
|
"products.option.seoMetaAi": "Titolo e descrizione meta SEO (IA)",
|
||||||
"products.enrichment.piece.name": "Nome",
|
"products.enrichment.piece.name": "Nome",
|
||||||
"products.enrichment.piece.description": "Descrizione",
|
"products.enrichment.piece.description": "Descrizione",
|
||||||
"products.enrichment.piece.attributes": "Attributi",
|
"products.enrichment.piece.attributes": "Attributi",
|
||||||
|
|||||||
@@ -2766,6 +2766,7 @@ export const ja: MessageDict = {
|
|||||||
"products.option.attributes": "属性 / 仕様",
|
"products.option.attributes": "属性 / 仕様",
|
||||||
"products.option.titlesAi": "タイトル(AI)",
|
"products.option.titlesAi": "タイトル(AI)",
|
||||||
"products.option.descriptionsAi": "説明(AI)",
|
"products.option.descriptionsAi": "説明(AI)",
|
||||||
|
"products.option.seoMetaAi": "SEOメタタイトル・説明文(AI)",
|
||||||
"products.enrichment.piece.name": "Ã¥ÂÂÂÂå‰ÂÂ",
|
"products.enrichment.piece.name": "Ã¥ÂÂÂÂå‰ÂÂ",
|
||||||
"products.enrichment.piece.description": "説明",
|
"products.enrichment.piece.description": "説明",
|
||||||
"products.enrichment.piece.attributes": "属性",
|
"products.enrichment.piece.attributes": "属性",
|
||||||
|
|||||||
@@ -2766,6 +2766,7 @@ export const nl: MessageDict = {
|
|||||||
"products.option.attributes": "Attributen / specificaties",
|
"products.option.attributes": "Attributen / specificaties",
|
||||||
"products.option.titlesAi": "Titels (AI)",
|
"products.option.titlesAi": "Titels (AI)",
|
||||||
"products.option.descriptionsAi": "Beschrijvingen (AI)",
|
"products.option.descriptionsAi": "Beschrijvingen (AI)",
|
||||||
|
"products.option.seoMetaAi": "SEO-metatitel en -beschrijving (AI)",
|
||||||
"products.enrichment.piece.name": "Naam",
|
"products.enrichment.piece.name": "Naam",
|
||||||
"products.enrichment.piece.description": "Beschrijving",
|
"products.enrichment.piece.description": "Beschrijving",
|
||||||
"products.enrichment.piece.attributes": "Attributen",
|
"products.enrichment.piece.attributes": "Attributen",
|
||||||
|
|||||||
@@ -2766,6 +2766,7 @@ export const pl: MessageDict = {
|
|||||||
"products.option.attributes": "Atrybuty / specyfikacje",
|
"products.option.attributes": "Atrybuty / specyfikacje",
|
||||||
"products.option.titlesAi": "Tytuły (AI)",
|
"products.option.titlesAi": "Tytuły (AI)",
|
||||||
"products.option.descriptionsAi": "Opisy (AI)",
|
"products.option.descriptionsAi": "Opisy (AI)",
|
||||||
|
"products.option.seoMetaAi": "Tytuł i opis meta SEO (AI)",
|
||||||
"products.enrichment.piece.name": "Nazwa",
|
"products.enrichment.piece.name": "Nazwa",
|
||||||
"products.enrichment.piece.description": "Opis",
|
"products.enrichment.piece.description": "Opis",
|
||||||
"products.enrichment.piece.attributes": "Atrybuty",
|
"products.enrichment.piece.attributes": "Atrybuty",
|
||||||
|
|||||||
@@ -2766,6 +2766,7 @@ export const pt: MessageDict = {
|
|||||||
"products.option.attributes": "Atributos / especificações",
|
"products.option.attributes": "Atributos / especificações",
|
||||||
"products.option.titlesAi": "TÃÂÂtulos (IA)",
|
"products.option.titlesAi": "TÃÂÂtulos (IA)",
|
||||||
"products.option.descriptionsAi": "Descrições (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.name": "Nome",
|
||||||
"products.enrichment.piece.description": "Descrição",
|
"products.enrichment.piece.description": "Descrição",
|
||||||
"products.enrichment.piece.attributes": "Atributos",
|
"products.enrichment.piece.attributes": "Atributos",
|
||||||
|
|||||||
@@ -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). */
|
/** Slovenian (sl) UI strings for admin Fix A1  ready pack. Not registered in UI_LOCALES yet (avoid inventing locale switcher). */
|
||||||
export const sl: MessageDict = {
|
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.cloneCatalog": "Copy to my company",
|
||||||
"admin.users.cloneCatalogAria": "Copy {name} catalog into your sandbox company",
|
"admin.users.cloneCatalogAria": "Copy {name} catalog into your sandbox company",
|
||||||
"admin.users.cloneCatalogTitle": "Copy company catalog",
|
"admin.users.cloneCatalogTitle": "Copy company catalog",
|
||||||
|
|||||||
@@ -7,17 +7,13 @@ import { PUBLIC_API_URL } from "$env/static/public";
|
|||||||
const API_BASE = (PUBLIC_API_URL ?? "").replace(/\/$/, "");
|
const API_BASE = (PUBLIC_API_URL ?? "").replace(/\/$/, "");
|
||||||
|
|
||||||
/** Public production API base from OpenAPI servers[0] (Descrybe-hosted; not customer self-host). */
|
/** 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. */
|
/** Public OpenAPI document URL for links and fetches. */
|
||||||
export const OPENAPI_SPEC_URL = `${API_BASE}/api/v1/openapi.yaml`;
|
export const OPENAPI_SPEC_URL = `${API_BASE}/api/v1/openapi.yaml`;
|
||||||
|
|
||||||
/**
|
/** The public reference defaults to the published production API.
|
||||||
* Absolute base for RapiDoc Try-it.
|
* A configured API origin is used only for explicitly configured deployments.
|
||||||
* 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.
|
|
||||||
*/
|
*/
|
||||||
export function docsTryItServerURL(
|
export function docsTryItServerURL(
|
||||||
origin = typeof window !== "undefined" ? window.location.origin : ""
|
origin = typeof window !== "undefined" ? window.location.origin : ""
|
||||||
@@ -25,9 +21,6 @@ export function docsTryItServerURL(
|
|||||||
if (API_BASE) {
|
if (API_BASE) {
|
||||||
return `${API_BASE}/api/v1`;
|
return `${API_BASE}/api/v1`;
|
||||||
}
|
}
|
||||||
if (origin) {
|
|
||||||
return `${origin}/api/v1`;
|
|
||||||
}
|
|
||||||
return PUBLIC_DOCS_API_SERVER;
|
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`;
|
* 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.
|
* otherwise Try-it uses OpenAPI servers[0] (production) even if server-url is set.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import RemoteCatalogImport from "$lib/components/feeds/RemoteCatalogImport.svelte";
|
||||||
import { i18n } from "$lib/i18n";
|
import { i18n } from "$lib/i18n";
|
||||||
import { onMount } from "svelte";
|
import { onMount } from "svelte";
|
||||||
import { goto } from "$app/navigation";
|
import { goto } from "$app/navigation";
|
||||||
@@ -1076,6 +1077,7 @@
|
|||||||
|
|
||||||
{#if canAdmin}
|
{#if canAdmin}
|
||||||
<TabsContent value="bulk" class="mt-4">
|
<TabsContent value="bulk" class="mt-4">
|
||||||
|
<RemoteCatalogImport kind="attributes" onComplete={load}/>
|
||||||
<form class="space-y-4" onsubmit={bulkImport}>
|
<form class="space-y-4" onsubmit={bulkImport}>
|
||||||
<div class="grid gap-2">
|
<div class="grid gap-2">
|
||||||
<Label for="bulk-file">{i18n.t("attributes.bulk.fileLabel")}</Label>
|
<Label for="bulk-file">{i18n.t("attributes.bulk.fileLabel")}</Label>
|
||||||
@@ -1093,7 +1095,7 @@
|
|||||||
<Input
|
<Input
|
||||||
id="bulk-file"
|
id="bulk-file"
|
||||||
type="file"
|
type="file"
|
||||||
accept=".csv,.tsv,text/csv,text/tab-separated-values"
|
accept=".csv,.tsv,.json,text/csv,text/tab-separated-values,application/json"
|
||||||
onchange={(e) => {
|
onchange={(e) => {
|
||||||
const input = e.currentTarget as HTMLInputElement;
|
const input = e.currentTarget as HTMLInputElement;
|
||||||
addFile = input.files?.[0] ?? null;
|
addFile = input.files?.[0] ?? null;
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import RemoteCatalogImport from "$lib/components/feeds/RemoteCatalogImport.svelte";
|
||||||
import { i18n } from "$lib/i18n";
|
import { i18n } from "$lib/i18n";
|
||||||
import { onMount } from "svelte";
|
import { onMount } from "svelte";
|
||||||
import { goto } from "$app/navigation";
|
import { goto } from "$app/navigation";
|
||||||
@@ -185,6 +186,7 @@
|
|||||||
|
|
||||||
<Alert message={error} />
|
<Alert message={error} />
|
||||||
<Alert tone="success" message={success} />
|
<Alert tone="success" message={success} />
|
||||||
|
{#if canAdmin}<RemoteCatalogImport kind="categories" onComplete={load}/>{/if}
|
||||||
|
|
||||||
{#if !loading && promptCount > 0}
|
{#if !loading && promptCount > 0}
|
||||||
<p class="text-sm text-muted-foreground">
|
<p class="text-sm text-muted-foreground">
|
||||||
|
|||||||
@@ -197,7 +197,7 @@
|
|||||||
|
|
||||||
function publicPath(feed: ExportRow): string {
|
function publicPath(feed: ExportRow): string {
|
||||||
const token = String(feed.public_token ?? "");
|
const token = String(feed.public_token ?? "");
|
||||||
const ext = String(feed.format ?? "xml").toLowerCase() === "csv" ? "csv" : "xml";
|
const ext = ["csv","json"].includes(String(feed.format ?? "xml").toLowerCase()) ? String(feed.format).toLowerCase() : "xml";
|
||||||
return `/api/public/export-feeds/${token}.${ext}`;
|
return `/api/public/export-feeds/${token}.${ext}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -234,11 +234,12 @@
|
|||||||
|
|
||||||
function inferPresetId(format: string, template: ExportRow["template"]): ExportPresetId {
|
function inferPresetId(format: string, template: ExportRow["template"]): ExportPresetId {
|
||||||
const channel = String(template?.channel ?? "").toLowerCase();
|
const channel = String(template?.channel ?? "").toLowerCase();
|
||||||
const fmt = format === "csv" ? "csv" : "xml";
|
const fmt = format === "json" ? "json" : format === "csv" ? "csv" : "xml";
|
||||||
if (channel === "google_shopping") {
|
if (channel === "google_shopping") {
|
||||||
return fmt === "csv" ? "google_shopping_csv" : "google_shopping_xml";
|
return fmt === "csv" ? "google_shopping_csv" : "google_shopping_xml";
|
||||||
}
|
}
|
||||||
if (channel === "meta") return "meta_csv";
|
if (channel === "meta") return "meta_csv";
|
||||||
|
if (fmt === "json") return "custom_json";
|
||||||
return fmt === "csv" ? "custom_csv" : "custom_xml";
|
return fmt === "csv" ? "custom_csv" : "custom_xml";
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -271,7 +272,7 @@
|
|||||||
const full = await api<ExportRow>(`/api/export-feeds/${feed.id}`);
|
const full = await api<ExportRow>(`/api/export-feeds/${feed.id}`);
|
||||||
editingId = String(full.id);
|
editingId = String(full.id);
|
||||||
formName = String(full.name ?? i18n.t("exports.fallbackName"));
|
formName = String(full.name ?? i18n.t("exports.fallbackName"));
|
||||||
formFormat = String(full.format ?? "xml").toLowerCase() === "csv" ? "csv" : "xml";
|
formFormat = ["csv","json"].includes(String(full.format ?? "xml").toLowerCase()) ? String(full.format).toLowerCase() : "xml";
|
||||||
formRoot = String(full.template?.root ?? "products");
|
formRoot = String(full.template?.root ?? "products");
|
||||||
formItem = String(full.template?.item ?? "product");
|
formItem = String(full.template?.item ?? "product");
|
||||||
formSourceFeedId = full.source_feed_id ? String(full.source_feed_id) : "";
|
formSourceFeedId = full.source_feed_id ? String(full.source_feed_id) : "";
|
||||||
|
|||||||
@@ -155,6 +155,10 @@
|
|||||||
|
|
||||||
let formName = $state("");
|
let formName = $state("");
|
||||||
let formUrl = $state("");
|
let formUrl = $state("");
|
||||||
|
let formHeaders = $state("");
|
||||||
|
let formAuthType = $state("bearer");
|
||||||
|
let formAuthToken = $state("");
|
||||||
|
let formAuthHeader = $state("X-API-Key");
|
||||||
let formType = $state("xml");
|
let formType = $state("xml");
|
||||||
let formInterval = $state("60");
|
let formInterval = $state("60");
|
||||||
let formSource = $state<"url" | "file">("url");
|
let formSource = $state<"url" | "file">("url");
|
||||||
@@ -458,8 +462,19 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function openAdd(source: "url" | "file" = "url") {
|
function requestHeaders(): Record<string,string> {
|
||||||
|
const headers:Record<string,string>={};
|
||||||
|
if (formHeaders.trim()) {
|
||||||
|
const parsed=JSON.parse(formHeaders);
|
||||||
|
if (!parsed || Array.isArray(parsed) || typeof parsed!=="object") throw new Error("HTTP headers must be a JSON object");
|
||||||
|
for (const [k,v] of Object.entries(parsed)) {if(typeof v!=="string")throw new Error("Header values must be strings");headers[k]=v}
|
||||||
|
}
|
||||||
|
if (formAuthToken.trim()) headers[formAuthType==="bearer"?"Authorization":formAuthHeader.trim()||"X-API-Key"] = formAuthType==="bearer"?`Bearer ${formAuthToken.trim()}`:formAuthToken.trim();
|
||||||
|
return headers;
|
||||||
|
}
|
||||||
|
function openAdd(source: "url" | "file" = "url") {
|
||||||
formName = "";
|
formName = "";
|
||||||
|
formHeaders="";formAuthToken="";formAuthType="bearer";formAuthHeader="X-API-Key";
|
||||||
formUrl = "";
|
formUrl = "";
|
||||||
formType = source === "file" ? "csv" : "xml";
|
formType = source === "file" ? "csv" : "xml";
|
||||||
formInterval = "60";
|
formInterval = "60";
|
||||||
@@ -512,7 +527,7 @@
|
|||||||
function onCsvSelected(event: Event) {
|
function onCsvSelected(event: Event) {
|
||||||
const input = event.currentTarget as HTMLInputElement;
|
const input = event.currentTarget as HTMLInputElement;
|
||||||
const file = input.files?.[0] ?? null;
|
const file = input.files?.[0] ?? null;
|
||||||
if (file && !file.name.toLowerCase().endsWith(".csv")) {
|
if (file && !/\.(csv|json|xml)$/i.test(file.name)) {
|
||||||
formFile = null;
|
formFile = null;
|
||||||
input.value = "";
|
input.value = "";
|
||||||
error = i18n.t("flash.feed.csvRequired");
|
error = i18n.t("flash.feed.csvRequired");
|
||||||
@@ -530,6 +545,7 @@
|
|||||||
formName = String(feed.name ?? "");
|
formName = String(feed.name ?? "");
|
||||||
formUrl = String(feed.url ?? "");
|
formUrl = String(feed.url ?? "");
|
||||||
formType = String(feed.feed_type ?? "xml");
|
formType = String(feed.feed_type ?? "xml");
|
||||||
|
formAuthToken=""; formHeaders="";
|
||||||
formInterval = String(feed.sync_interval_minutes ?? 60);
|
formInterval = String(feed.sync_interval_minutes ?? 60);
|
||||||
showEdit = true;
|
showEdit = true;
|
||||||
clearFormFeedback();
|
clearFormFeedback();
|
||||||
@@ -550,12 +566,13 @@
|
|||||||
}
|
}
|
||||||
const body = new FormData();
|
const body = new FormData();
|
||||||
body.append("name", formName.trim());
|
body.append("name", formName.trim());
|
||||||
body.append("feed_type", "csv");
|
body.append("feed_type", formFile?.name.toLowerCase().endsWith(".json") ? "json" : formFile?.name.toLowerCase().endsWith(".xml") ? "xml" : "csv");
|
||||||
body.append("sync_interval_minutes", String(parseSyncIntervalMinutes(formInterval)));
|
body.append("sync_interval_minutes", String(parseSyncIntervalMinutes(formInterval)));
|
||||||
body.append("file", formFile);
|
body.append("file", formFile);
|
||||||
created = await api<FeedRow>("/api/feeds", { method: "POST", body });
|
created = await api<FeedRow>("/api/feeds", { method: "POST", body });
|
||||||
} else {
|
} else {
|
||||||
const url = formUrl.trim();
|
const url = formUrl.trim();
|
||||||
|
const inferredType = formType === "xml" && /(?:\.json(?:$|[?#])|[?&]format=json(?:&|$))/i.test(url) ? "json" : formType;
|
||||||
if (!url) {
|
if (!url) {
|
||||||
error = i18n.t("flash.feed.urlRequired");
|
error = i18n.t("flash.feed.urlRequired");
|
||||||
fieldErrors = { url: error };
|
fieldErrors = { url: error };
|
||||||
@@ -567,8 +584,9 @@
|
|||||||
body: {
|
body: {
|
||||||
name: formName.trim(),
|
name: formName.trim(),
|
||||||
url,
|
url,
|
||||||
feed_type: formType,
|
feed_type: inferredType,
|
||||||
sync_interval_minutes: parseSyncIntervalMinutes(formInterval)
|
sync_interval_minutes: parseSyncIntervalMinutes(formInterval),
|
||||||
|
request_headers: requestHeaders()
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -602,14 +620,16 @@
|
|||||||
saving = true;
|
saving = true;
|
||||||
clearFormFeedback();
|
clearFormFeedback();
|
||||||
try {
|
try {
|
||||||
const nextType = isFileFeed(editing) ? "csv" : formType;
|
const nextType = isFileFeed(editing) ? String(editing.feed_type ?? "csv") : formType;
|
||||||
const body: Record<string, string | number> = {
|
const body: Record<string, unknown> = {
|
||||||
name: formName.trim(),
|
name: formName.trim(),
|
||||||
feed_type: nextType,
|
feed_type: nextType,
|
||||||
sync_interval_minutes: parseSyncIntervalMinutes(formInterval)
|
sync_interval_minutes: parseSyncIntervalMinutes(formInterval)
|
||||||
};
|
};
|
||||||
if (!isFileFeed(editing)) {
|
if (!isFileFeed(editing)) {
|
||||||
body.url = formUrl.trim();
|
body.url = formUrl.trim();
|
||||||
|
// An empty form preserves existing encrypted credentials.
|
||||||
|
if (formAuthToken.trim() || formHeaders.trim()) body.request_headers = requestHeaders();
|
||||||
}
|
}
|
||||||
await api(`/api/feeds/${editing.id}`, {
|
await api(`/api/feeds/${editing.id}`, {
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
@@ -1254,9 +1274,20 @@
|
|||||||
<Select id="add-feed-type" bind:value={formType}>
|
<Select id="add-feed-type" bind:value={formType}>
|
||||||
<option value="xml">XML</option>
|
<option value="xml">XML</option>
|
||||||
<option value="csv">CSV</option>
|
<option value="csv">CSV</option>
|
||||||
|
<option value="json">JSON</option>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
<FeedFormatHelp format={formType === "csv" ? "csv" : "xml"} />
|
{#if formType === "json"}<p class="text-xs text-muted-foreground">JSON arrays and nested products/results/items are supported. Map a record path if needed.</p>{:else}
|
||||||
|
<FeedFormatHelp format={formType === "csv" ? "csv" : "xml"} />{/if}
|
||||||
|
<div class="space-y-2 rounded-md border p-3">
|
||||||
|
<p class="text-sm font-medium">Optional HTTP authentication</p>
|
||||||
|
<Select bind:value={formAuthType}><option value="bearer">Bearer token</option><option value="header">API key / custom header</option></Select>
|
||||||
|
{#if formAuthType === "header"}<Input placeholder="Header name (X-API-Key)" bind:value={formAuthHeader} />{/if}
|
||||||
|
<Input type="password" autocomplete="off" placeholder="Token / API key (optional)" bind:value={formAuthToken}/>
|
||||||
|
<Label for="feed-headers">Other headers (JSON object, optional)</Label>
|
||||||
|
<textarea id="feed-headers" class="w-full rounded-md border bg-background p-2 font-mono text-xs" rows="2" bind:value={formHeaders} placeholder='{"X-Store-ID":"store-1"}'></textarea>
|
||||||
|
<p class="text-xs text-muted-foreground">Credentials are encrypted. Existing keys are not shown when editing.</p>
|
||||||
|
</div>
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
<TabsContent value="file" class="mt-4 space-y-4">
|
<TabsContent value="file" class="mt-4 space-y-4">
|
||||||
<div class="space-y-1.5">
|
<div class="space-y-1.5">
|
||||||
@@ -1265,7 +1296,7 @@
|
|||||||
id="add-feed-file"
|
id="add-feed-file"
|
||||||
bind:this={formFileInput}
|
bind:this={formFileInput}
|
||||||
type="file"
|
type="file"
|
||||||
accept=".csv,text/csv"
|
accept=".csv,.xml,.json,text/csv,application/xml,application/json"
|
||||||
class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm file:mr-3 file:rounded-md file:border-0 file:bg-muted file:px-3 file:py-1.5 file:text-sm file:font-medium"
|
class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm file:mr-3 file:rounded-md file:border-0 file:bg-muted file:px-3 file:py-1.5 file:text-sm file:font-medium"
|
||||||
onchange={onCsvSelected}
|
onchange={onCsvSelected}
|
||||||
required={formSource === "file"}
|
required={formSource === "file"}
|
||||||
@@ -1343,12 +1374,22 @@
|
|||||||
aria-describedby={fieldDescribedBy(fieldErrors, "url", FEEDS_FORM_ERROR_ID)}
|
aria-describedby={fieldDescribedBy(fieldErrors, "url", FEEDS_FORM_ERROR_ID)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="space-y-2 rounded-md border p-3">
|
||||||
|
<p class="text-sm font-medium">Update HTTP credentials (optional)</p>
|
||||||
|
<p class="text-xs text-muted-foreground">Leave blank to keep existing encrypted credentials. Enter a new token or headers to replace them.</p>
|
||||||
|
<Select bind:value={formAuthType}><option value="bearer">Bearer token</option><option value="header">API key / custom header</option></Select>
|
||||||
|
{#if formAuthType === "header"}<Input placeholder="Header name" bind:value={formAuthHeader} />{/if}
|
||||||
|
<Input type="password" autocomplete="off" placeholder="New token / API key" bind:value={formAuthToken} />
|
||||||
|
<Label for="edit-feed-headers">Other headers (JSON object)</Label>
|
||||||
|
<textarea id="edit-feed-headers" class="w-full rounded-md border bg-background p-2 font-mono text-xs" rows="2" bind:value={formHeaders} placeholder='{"X-Store-ID":"store-1"}'></textarea>
|
||||||
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
<div class="space-y-1.5">
|
<div class="space-y-1.5">
|
||||||
<Label for="edit-feed-type">{i18n.t("feeds.field.type")}</Label>
|
<Label for="edit-feed-type">{i18n.t("feeds.field.type")}</Label>
|
||||||
<Select id="edit-feed-type" bind:value={formType} disabled={editing != null && isFileFeed(editing)}>
|
<Select id="edit-feed-type" bind:value={formType} disabled={editing != null && isFileFeed(editing)}>
|
||||||
<option value="xml">XML</option>
|
<option value="xml">XML</option>
|
||||||
<option value="csv">CSV</option>
|
<option value="csv">CSV</option>
|
||||||
|
<option value="json">JSON</option>
|
||||||
</Select>
|
</Select>
|
||||||
{#if editing && isFileFeed(editing)}
|
{#if editing && isFileFeed(editing)}
|
||||||
<p class="text-xs text-muted-foreground">{i18n.t("feeds.csvTypeLocked")}</p>
|
<p class="text-xs text-muted-foreground">{i18n.t("feeds.csvTypeLocked")}</p>
|
||||||
|
|||||||
@@ -199,7 +199,7 @@
|
|||||||
itemPath = normalized.itemPath;
|
itemPath = normalized.itemPath;
|
||||||
rows =
|
rows =
|
||||||
normalized.rows.length > 0
|
normalized.rows.length > 0
|
||||||
? normalized.rows
|
? requiredFirst(normalized.rows,enabledFields)
|
||||||
: [{ source: "", target: "none" }];
|
: [{ source: "", target: "none" }];
|
||||||
if (itemPath || isCsv) activeTab = "fields";
|
if (itemPath || isCsv) activeTab = "fields";
|
||||||
dirty = false;
|
dirty = false;
|
||||||
@@ -219,7 +219,7 @@
|
|||||||
const keys = enabledFields.map((f) => f.value);
|
const keys = enabledFields.map((f) => f.value);
|
||||||
const again = normalizeMappingRows(mapRes.mappings, keys);
|
const again = normalizeMappingRows(mapRes.mappings, keys);
|
||||||
itemPath = again.itemPath || itemPath;
|
itemPath = again.itemPath || itemPath;
|
||||||
if (again.rows.length > 0) rows = again.rows;
|
if (again.rows.length > 0) rows = requiredFirst(again.rows,enabledFields);
|
||||||
})
|
})
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
}
|
}
|
||||||
@@ -260,7 +260,11 @@
|
|||||||
})();
|
})();
|
||||||
});
|
});
|
||||||
|
|
||||||
function markDirty() {
|
function requiredFirst(items: FieldMappingRow[], fields: TargetField[]): FieldMappingRow[] {
|
||||||
|
const required = new Set(fields.filter(f => f.isRequired).map(f => f.value));
|
||||||
|
return [...items].sort((a,b)=>Number(required.has(b.target))-Number(required.has(a.target)));
|
||||||
|
}
|
||||||
|
function markDirty() {
|
||||||
dirty = true;
|
dirty = true;
|
||||||
success = "";
|
success = "";
|
||||||
showPostMapCta = false;
|
showPostMapCta = false;
|
||||||
@@ -454,7 +458,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function addRow() {
|
function addRow() {
|
||||||
rows = [...rows, { source: "", target: "none" }];
|
rows = [{ source: "", target: "none" }, ...rows.filter(r => r.source.trim() || r.target !== "none")];
|
||||||
markDirty();
|
markDirty();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -39,6 +39,7 @@
|
|||||||
import UpgradeBanner from "$lib/components/UpgradeBanner.svelte";
|
import UpgradeBanner from "$lib/components/UpgradeBanner.svelte";
|
||||||
import { Button, Card, CardHeader } from "$lib/components/ui";
|
import { Button, Card, CardHeader } from "$lib/components/ui";
|
||||||
import ProductTabs from "$lib/components/products/ProductTabs.svelte";
|
import ProductTabs from "$lib/components/products/ProductTabs.svelte";
|
||||||
|
import RemoteCatalogImport from "$lib/components/feeds/RemoteCatalogImport.svelte";
|
||||||
import ProductSearchFilters from "$lib/components/products/ProductSearchFilters.svelte";
|
import ProductSearchFilters from "$lib/components/products/ProductSearchFilters.svelte";
|
||||||
import ProductTable from "$lib/components/products/ProductTable.svelte";
|
import ProductTable from "$lib/components/products/ProductTable.svelte";
|
||||||
import ProductEmptyState from "$lib/components/products/ProductEmptyState.svelte";
|
import ProductEmptyState from "$lib/components/products/ProductEmptyState.svelte";
|
||||||
@@ -629,23 +630,12 @@
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const wantsAI = types.some((t) => t === "title" || t === "description");
|
const selected = new Set(types);
|
||||||
const wantsAttrs = types.includes("attributes") || types.includes("category");
|
// The worker accepts a single execution mode; SEO-only preserves existing
|
||||||
let processingType = "full";
|
// product copy, while selecting multiple outputs runs the AI enhancement pass.
|
||||||
if (types.length === 1 && types[0] === "title") {
|
const processingType = selected.size === 1
|
||||||
processingType = "title";
|
? selected.has("seo_meta") ? "seo_meta" : selected.has("title") ? "title" : "description"
|
||||||
} else if (types.length === 1 && types[0] === "description") {
|
: "enhance";
|
||||||
processingType = "description";
|
|
||||||
} else if (types.length === 1 && types[0] === "category") {
|
|
||||||
// Vector categorize runs inside fill_fields (attributes pipeline), not normalize_only.
|
|
||||||
processingType = "attributes";
|
|
||||||
} else if (types.length === 1 && types[0] === "attributes") {
|
|
||||||
processingType = "attributes";
|
|
||||||
} else if (wantsAI && !wantsAttrs) {
|
|
||||||
processingType = "enhance";
|
|
||||||
} else if (!wantsAI && wantsAttrs) {
|
|
||||||
processingType = "attributes";
|
|
||||||
}
|
|
||||||
|
|
||||||
const job = await api<{
|
const job = await api<{
|
||||||
id: string;
|
id: string;
|
||||||
@@ -1309,6 +1299,14 @@
|
|||||||
/>
|
/>
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
|
{#if canAdmin}
|
||||||
|
<details class="mb-4 rounded-md border border-border bg-card p-3">
|
||||||
|
<summary class="cursor-pointer text-sm font-medium">Import products from a JSON URL</summary>
|
||||||
|
<div class="mt-3">
|
||||||
|
<RemoteCatalogImport kind="products" onComplete={async () => { await loadProducts(); }} />
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
{/if}
|
||||||
<Card
|
<Card
|
||||||
class={`min-w-0 overflow-x-auto border-border shadow-sm transition-all duration-300 ${fetching ? "bg-background/20 backdrop-blur-sm" : ""}`}
|
class={`min-w-0 overflow-x-auto border-border shadow-sm transition-all duration-300 ${fetching ? "bg-background/20 backdrop-blur-sm" : ""}`}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# Public API / processing audit (v11)
|
||||||
|
|
||||||
|
## Customer-facing API contract
|
||||||
|
|
||||||
|
- **Public API base**: `https://api.descrybe.io/api/v1`
|
||||||
|
- **Interactive reference**: `https://descrybe.io/docs`
|
||||||
|
- **Spec**: `https://api.descrybe.io/api/v1/openapi.yaml`
|
||||||
|
- **Authentication**: Company API key in `Authorization: Bearer dk_...` or `X-API-Key: dk_...`, except public health/spec operations.
|
||||||
|
- **Dashboard operations**: Team and platform-admin controls are not available via an API key. They require a signed-in dashboard session and CSRF where applicable.
|
||||||
|
|
||||||
|
Source comparison: `apps/api/internal/httpapi/v1.go` vs `apps/api/internal/httpapi/v1_openapi.go`. The router registers **35 public paths and 49 method/path operations**; all 49 are covered by the OpenAPI definition. The OpenAPI document also includes two intentionally separate session-only paths (`/team/{userID}`, `/admin/emails/set-password`).
|
||||||
|
|
||||||
|
## Processing modes
|
||||||
|
|
||||||
|
The **What to process** menu now includes only these content deliverables:
|
||||||
|
|
||||||
|
| Choice | Execution mode | What happens |
|
||||||
|
|---|---|---|
|
||||||
|
| AI Title | `title` | Runs the enrichment pipeline to generate product copy |
|
||||||
|
| AI Description | `description` | Runs the enrichment pipeline to generate product copy |
|
||||||
|
| SEO Meta | `seo_meta` | Generates `meta_title` / `meta_description`, preserving existing product name and description |
|
||||||
|
| Any combination | `enhance` | Runs the combined enrichment pass; the backend is not yet a fully independent field-by-field AI generator |
|
||||||
|
|
||||||
|
Category resolution and attribute parsing are internal prerequisites and are not checkboxes. The backend uses `processing_type` to select execution; `processing_types` is an informational selection list, not an execution instruction.
|
||||||
|
|
||||||
|
For the public API, `POST /products/process` accepts products by EAN; `POST /process` uses raw-product UUIDs. The payloads, status codes, and response wrappers differ. See [public-api-reference.md](public-api-reference.md) and the interactive OpenAPI spec.
|
||||||
|
|
||||||
|
## Feed and export formats
|
||||||
|
|
||||||
|
- Feed ingestion: XML (including `SHOPITEM` and nested `PARAMS`), CSV, JSON.
|
||||||
|
- Feed create: `name` plus `url` or `item_path`. Remote feeds can generally infer an item path. Explicit JSON array paths are also supported.
|
||||||
|
- Secret-bearing feed headers are configured through the logged-in dashboard; the public `POST /feeds` body does not accept arbitrary headers.
|
||||||
|
- Export-feed create supports `xml`, `csv`, and `json`; public token URLs have the corresponding extension. JSON token download is registered at `/api/public/export-feeds/{token}.json`.
|
||||||
|
|
||||||
|
## Deployment
|
||||||
|
|
||||||
|
Deploy the **web, API, and worker** from the same ZIP. This update does not require a database migration. After deployment, check the production `/docs` page, the three processing checkboxes, a SEO-only job, and a JSON export URL.
|
||||||
|
|
||||||
|
## Checks and limitations
|
||||||
|
|
||||||
|
- OpenAPI YAML parses; all references resolve; all 49 public route/method registrations appear in the document.
|
||||||
|
- Two frontend processing selection tests pass.
|
||||||
|
- The modified frontend TypeScript blocks parse.
|
||||||
|
- All 664 Go source/test files parse with standard `go/parser`.
|
||||||
|
- A complete Go 1.25 API/worker compilation, Svelte build, database-integrated processing, and live endpoint E2E were **not** available here, so production runtime compatibility still requires your deployment checks.
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# Feed removal – unprocessed raw product cleanup (v12)
|
||||||
|
|
||||||
|
`DELETE /api/feeds/{id}` (dashboard) and `DELETE /api/v1/feeds/{id}` (public API, where authorized) now use the same service transaction:
|
||||||
|
|
||||||
|
1. Lock the company-owned feed (`SELECT … FOR UPDATE`). Cross-company IDs return 404.
|
||||||
|
2. Transfer raw products still associated with another existing feed (legacy `feed_ids`) to that surviving feed.
|
||||||
|
3. Delete raw products owned only by the removed feed when `is_processed = false` and `processing_status IN ('unprocessed', 'failed')`.
|
||||||
|
4. Remove deleted-feed references from the `feed_ids` arrays of retained raw products.
|
||||||
|
5. Delete the input-feed row and let normal foreign keys remove its mappings/sync history while setting feed IDs to NULL on preserved products.
|
||||||
|
6. Commit all actions together. If any statement fails, nothing is deleted.
|
||||||
|
|
||||||
|
**Never deleted:** already processed products; actively processing raw products; products owned by another feed; users' other companies' data. When a processed output points to a raw product that is removed, PostgreSQL detaches its `raw_product_id` reference; the processed output stays.
|
||||||
|
|
||||||
|
**Response:** `{ "id": "...", "deleted": true, "deleted_unprocessed_products": 42 }`.
|
||||||
|
|
||||||
|
**Caveat:** a raw product in `processing` status is not deleted because a worker may be generating content; deleting the source feed detaches it instead. The worker should be deployed with the matching API release so feed synchronization writes respect the deleted feed's FK.
|
||||||
|
|
||||||
|
**Checks:** `go test ./internal/feeds -run TestDeleteFeedRemovesOnlyOwnedUnprocessedProducts -count=1` from `apps/api`, with migrated test PostgreSQL and `DATABASE_URL`. This verifies two deleted rows, processed/processing preservation, multi-source reassignment, tenant boundaries, and repeat deletion. A full Go 1.25 build and DB integration test must run on the deployment/test environment.
|
||||||
|
|
||||||
|
No database migration is necessary.
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
# Descrybe feed import/export — XML and JSON v10
|
||||||
|
|
||||||
|
## XML: supplier SHOPITEM records and nested attributes
|
||||||
|
|
||||||
|
Feeds with `<SHOP><SHOPITEM>…</SHOPITEM></SHOP>` are supported. Record path is detected as `SHOP/SHOPITEM`, and the sync parser recognizes `SHOPITEM` even if the UI has not saved a record path. `PRODUCT` inside `SHOPITEM` is treated as the product name, not an item wrapper.
|
||||||
|
|
||||||
|
Recommended EMOS mapping (auto-suggestions select available standard fields):
|
||||||
|
|
||||||
|
| Source | Target |
|
||||||
|
| --- | --- |
|
||||||
|
| `EAN` | `gtin` (required) |
|
||||||
|
| `PRODUCT` | `title` |
|
||||||
|
| `PRODUCTNO` | `sku` |
|
||||||
|
| `PRODUCTNO2` | `mpn` |
|
||||||
|
| `MANUFACTURER` | `brand` |
|
||||||
|
| `CATEGORY` | `category` (hierarchical supplier path retained) |
|
||||||
|
| `DESCRIPTION_BASIC` | `description` (the supplier's HTML) |
|
||||||
|
| `PARAMS` | `specifications` (nested named values) |
|
||||||
|
| `DESCRIPTION` | `specifications` (pipe-separated `label: value` fallback when `PARAMS` is unavailable) |
|
||||||
|
| `IMGURL` | `image_url` |
|
||||||
|
| `ADDITIONAL_IMAGE_URLS` | `additional_image_urls` |
|
||||||
|
| `PRICE_VAT` | `price` |
|
||||||
|
| `PRICE_VOC` | `purchase_price` |
|
||||||
|
| `AVAILABILITY` | `availability` |
|
||||||
|
| `URL` | `product_url` |
|
||||||
|
|
||||||
|
Every `PARAMS/PARAM` entry becomes its own `PARAMS/<normalized-name>` key, with its corresponding `VAL` and no value from any other `PARAM`. `ORDER` only affects the supplier's display order and is not imported as a technical attribute. Additional `IMGURL_ALTERNATIVE_XX` URLs are collected into `ADDITIONAL_IMAGE_URLS`.
|
||||||
|
|
||||||
|
For auto-mapping: open the feed's **Map fields** screen, extract schema, review suggested mappings, and apply. Required mappings appear first; newly added mapping rows are inserted at the top of the editable section. Approve proposed aliases when supplier semantics are ambiguous.
|
||||||
|
|
||||||
|
## JSON product feed (URL or file)
|
||||||
|
|
||||||
|
Create a feed using JSON and supply an HTTP URL or a local `.json` file. Supported shapes include:
|
||||||
|
|
||||||
|
```json
|
||||||
|
[{"ean":"8595025395184","name":"Lamp"}]
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"data":{"products":[{"ean":"8595025395184","name":"Lamp","attributes":[{"name":"color","value":"white"}]}]}}
|
||||||
|
```
|
||||||
|
|
||||||
|
Also recognizes arrays named `products`, `items`, `results`, `records`, `shopitem`, `offers`, `entries`, and `data`. For unusual shapes, set the JSON product record path (e.g., `data/products`) on the mapping screen. Scalar fields use slash-separated nested paths, and repeated `[{name,value}]` attribute pairs become named specification children.
|
||||||
|
|
||||||
|
For the Sanotechnik example, use `https://datacore.sanotechnik.com/datacore/sanotechnik-products/?format=json`. The exact response shape could not be verified from the external endpoint; extract the schema and confirm the suggested item path and mappings before syncing the full feed.
|
||||||
|
|
||||||
|
## Authentication and headers
|
||||||
|
|
||||||
|
Feed creation/editing supports Bearer tokens, a named API-key header, and additional string-valued HTTP headers. Credentials are encrypted in existing `input_feeds.options`, not returned in feed DTOs. When editing a feed, leave header inputs blank to retain existing credentials. A redirect to another hostname strips all custom headers. HTTP and DNS targets are subject to the existing SSRF protections.
|
||||||
|
|
||||||
|
JSON URL catalog import for **products, categories, or attributes** is available in the respective catalog pages. These are bounded one-time imports using existing company-scoped CSV upserts and a **6 MiB** catalog upload limit. For large product catalogs, use an automatically synced JSON feed instead (existing max **256 MiB** download and **1,000,000** row guard).
|
||||||
|
|
||||||
|
Example one-time catalog request (requires a user session or supported authentication):
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api/categories/import
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{"url":"https://supplier.example/catalog/categories?format=json","format":"json","request_headers":{"X-API-Key":"YOUR_KEY"}}
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `/api/attributes/import` or `/api/products/import` for those catalog types. Direct one-time product imports use the existing product catalog's core-field importer; nested specifications should be imported with a mapped JSON feed.
|
||||||
|
|
||||||
|
## JSON export
|
||||||
|
|
||||||
|
Select **Custom JSON** when creating an export feed. Generated JSON contains a configurable array root (default `products`); fields are mapped from Descrybe product data. JSON public feeds have paths:
|
||||||
|
|
||||||
|
```text
|
||||||
|
/api/public/export-feeds/<token>.json
|
||||||
|
```
|
||||||
|
|
||||||
|
The export stream writes records incrementally; the format choice is also honored for on-demand and selected-product exports. Do not share the public export URL as a secret credential: the URL token is the access mechanism, as with existing CSV/XML public exports.
|
||||||
|
|
||||||
|
## Deployment and verification
|
||||||
|
|
||||||
|
No SQL migration is needed for these features because feed type, export format, and encrypted source settings reuse existing TEXT/JSONB columns.
|
||||||
|
|
||||||
|
1. Deploy updated **API, worker and frontend** together.
|
||||||
|
2. Rebuild using **Go 1.25** (required by the project).
|
||||||
|
3. Create an XML `SHOPITEM` feed and verify named attributes survive sync; map EAN as GTIN.
|
||||||
|
4. Create a JSON feed and extract its schema; check the detected array path.
|
||||||
|
5. Create a Custom JSON export and fetch the generated `.json` URL.
|
||||||
|
6. Run the new Go parser/catalog regression tests and your normal integration suite.
|
||||||
|
|
||||||
|
Focused tests were run under an isolated Go 1.23 standard-library harness for parser and JSON-to-CSV helper files. Changed frontend scripts passed TypeScript syntax transpilation. The complete Go 1.25 application build, Svelte compiler build, and live Sanotechnik request were not verified in this environment.
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# Descrybe v11 – Processing and public API documentation
|
||||||
|
|
||||||
|
**Source baseline:** Descrybe v10 XML/JSON feed imports and exports.
|
||||||
|
|
||||||
|
## Updated
|
||||||
|
|
||||||
|
- The product bulk **What to process** menu offers AI Title, AI Description, and SEO Meta only.
|
||||||
|
- SEO-only processing uses `processing_type: seo_meta`. The AI is called for metadata, but saved title/description fields are kept instead of accepting unrelated rewrites.
|
||||||
|
- SEO Meta is gated like other paid AI processing modes.
|
||||||
|
- The in-app documentation and RapiDoc target the production API endpoint by default.
|
||||||
|
- OpenAPI is corrected for JSON feed/import/export formats, optional feed record paths, actual processing-mode behavior, permissions, and SEO metadata.
|
||||||
|
- JSON public export links now use `.json` rather than defaulting to `.xml`.
|
||||||
|
- The public API guide includes all router-registered paths and real production authentication examples.
|
||||||
|
|
||||||
|
## Deploy
|
||||||
|
|
||||||
|
Update **frontend, API, and worker together**. No new database migration is required. The production API reference is at `https://descrybe.io/docs`.
|
||||||
|
|
||||||
|
## Check
|
||||||
|
|
||||||
|
1. Bulk-select some products and open **What to process**. Only AI Title / AI Description / SEO Meta should appear.
|
||||||
|
2. Run only **SEO Meta**. The existing product name and description should remain unchanged; generated `meta_title` and `meta_description` should be available in processed product data when company policy allows SEO metadata and AI generation succeeds.
|
||||||
|
3. Create a JSON export feed; its returned URL should end in `.json`.
|
||||||
|
4. Open `/docs`, authorize using a company API key, and verify the production server and the documented paths.
|
||||||
|
|
||||||
|
See [API_V11_AUDIT.md](API_V11_AUDIT.md) for contract checks and limitations.
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
# Descrybe – sestanek z naročnikom: dobavitelji in pilot
|
||||||
|
|
||||||
|
**Trajanje:** 30 minut · **Cilj:** na dejanskih EAN-ih preveriti uvoz, kakovost podatkov, slovenski AI opis ter izvozne podatke; dogovoriti se za odgovornosti in stroške.
|
||||||
|
|
||||||
|
## 1. Kratek uvod (3 min)
|
||||||
|
|
||||||
|
»Descrybe je platforma za zbiranje, urejanje in dopolnjevanje podatkov o izdelkih. Iz dobaviteljskih virov uvozimo izdelke, preslikamo polja, kategorije in tehnične lastnosti, po potrebi pripravimo AI naslove, opise in SEO meta podatke ter izvozimo podatke za vašo trgovino. Cilj je, da po prvi nastavitvi lahko večino rednega dela upravljate sami.«
|
||||||
|
|
||||||
|
### Kaj je že pripravljeno
|
||||||
|
|
||||||
|
- **GROHE:** iz prejetega CSV so bili pripravljeni ločeni uvozi kategorij, atributov in izdelkov. Potreben je še pregled pravilnosti ter preizkus generiranja slovenskih vsebin.
|
||||||
|
- **EMOS:** XML format in ugnezdene lastnosti so bile preizkušene. Na produkcijskem viru je treba potrditi dostopnost, EAN preslikavo in periodično sinhronizacijo.
|
||||||
|
- **Sanotechnik:** dobavitelj nudi JSON; preslikavo njegovih polj in EAN omejitev je treba potrditi na dejanskem dostopnem viru.
|
||||||
|
- **KOOPMAN in TRBOVC:** obseg je treba najprej preveriti, ker podatki niso nujno v enotnem strukturiranem viru.
|
||||||
|
- **Groupe SEB:** ločena ocena po prejemu specifikacije.
|
||||||
|
|
||||||
|
## 2. Praktični pilot (10 min)
|
||||||
|
|
||||||
|
1. Naročnik predloži TXT z EAN-i. Za sestanek izberemo **5–10 izdelkov**, med njimi vsaj enega iz GROHE in enega iz EMOS. Pred uvozom preverimo, ali lahko izbor EAN izvajamo z obstoječim filtrom; po potrebi ga vključimo v izvedbeni obseg.
|
||||||
|
2. Prikažemo razliko med **surovim uvozom** in **AI obdelavo**: EAN, naziv, znamka, opis, kategorija, tehnične lastnosti, slike, dokumenti.
|
||||||
|
3. Za 1–2 izdelka izberemo slovenski jezik, pregledamo AI naziv, HTML opis in SEO meta podatke. Ustreznost preveri naročnik; prevod se ne ustvari že s samim uvozom dobaviteljeve datoteke.
|
||||||
|
4. Pokažemo **izvoz v CSV, XML ali JSON** glede na preslikavo in dejansko razpoložljive podatke. Pred končno obljubo preverimo konkreten izvozni profil trgovine.
|
||||||
|
5. Zabeležimo manjkajoče podatke in odločitve (npr. energetske nalepke, PDF dokumenti, barve, kategorije).
|
||||||
|
|
||||||
|
**Opomba o preizkusu:** paket Free in prikazani Demo z 0 AI krediti ne omogočata dokazovanja AI generiranja. Za tak preizkus mora imeti testni račun dodeljene AI kredite oziroma ustrezno plačljivo naročnino.
|
||||||
|
|
||||||
|
## 3. Kaj vključuje Descrybe in kaj ni zajeto
|
||||||
|
|
||||||
|
| Zajeto v osnovnem izdelku, v okviru paketa | Izven standardnega priklopa / dodatno po ponudbi |
|
||||||
|
|---|---|
|
||||||
|
| Uvoz dobaviteljskih CSV, XML in JSON virov ter preslikava polj | Razvoj posebnih konektorjev, avtomatizacija neprilagojenih PDF-jev, kompleksno zajemanje spletnih strani |
|
||||||
|
| Uvoz in urejanje kategorij ter atributov, če so podatki na voljo | Ročno dopolnjevanje podatkov, ki jih dobavitelj ne zagotavlja |
|
||||||
|
| AI naslovi, opisi, meta podatki in izbrani jeziki ob ustreznem dobroimetju | Neomejeni AI prevodi ali zagotovilo, da AI vsebina nikoli ne potrebuje pregleda |
|
||||||
|
| Izvoz glede na podprta polja in nastavljen profil | Integracija z ERP/spletno trgovino, za katero je treba razviti nov namenski modul |
|
||||||
|
| Prikaz uvoženih podatkov in razpoložljivih podatkov za energijske oznake | Jamstvo zakonodajne skladnosti, pridobitev manjkajočih izjav in specifikacij od proizvajalcev |
|
||||||
|
|
||||||
|
**KOOPMAN lučke:** za izdelke, za katere veljajo pravila energijskega označevanja, so potrebni pravilni energijski razred, elektronska nalepka in podatkovni list, ki morajo biti ustrezno predstavljeni kupcem. Pred priklopom določimo, katere izdelke pravila zajemajo, ali so modeli v EPREL in ali so dokumenti/slovenske informacije razpoložljivi. Ne smemo obljubiti ustvarjanja energijskih nalepk ali razredov iz nič. Končno pravilnost objave potrdi trgovec. Vir: https://energy-efficient-products.ec.europa.eu/product-list/light-sources_en in https://energy-efficient-products.ec.europa.eu/dealers_en
|
||||||
|
|
||||||
|
## 4. Pet načinov vključitve (enkratno, brez DDV)
|
||||||
|
|
||||||
|
| Scenarij | Cena | Vključeno | Tipičen rok |
|
||||||
|
|---|---:|---|---|
|
||||||
|
| **Samostojni začetek** | **0 €** | Registracija, navodila, samostojna preslikava enega vira, samostojen preizkus | Samostojno |
|
||||||
|
| **Pomoč pri začetku** | **199 €** | 1 običajen strukturiran vir, osnovna preslikava, preverjanje manjšega vzorca, 1 kratek prikaz | 1–2 delovna dneva |
|
||||||
|
| **Katalog iz več virov** | **649 €** | Do 3 običajni strukturirani viri, kategorije, atributi, osnovna pravila, kontrolni vzorec in predaja | 3–5 delovnih dni |
|
||||||
|
| **Poslovni zagon** | **1.490 €** | Do 3 standardni viri, razpored sinhronizacije, do 2 jezika, izvoz/API povezava na obstoječe zmožnosti in usposabljanje | 1–2 tedna |
|
||||||
|
| **Integracija po meri** | **od 3.500 €** | ERP/PIM, zahtevni PDF viri, posebne integracije, večje migracije in QA po dogovoru | Po oceni |
|
||||||
|
|
||||||
|
Cene veljajo za dogovorjen obseg dela. Velikost kataloga ni sama po sebi obljuba ročne priprave vseh artiklov. Za dodatne posege predhodno potrdimo ceno (orientacijsko 65–85 €/h). **Naročnina in AI krediti niso vključeni.**
|
||||||
|
|
||||||
|
## 5. Okvirna cena za posameznega dobavitelja
|
||||||
|
|
||||||
|
| Dobavitelj | Ocena priklopa | Pogoj |
|
||||||
|
|---|---:|---|
|
||||||
|
| **GROHE** | **0–99 €** | Če se uporabi že pripravljena CSV preslikava, le končna validacija in kratek prikaz. |
|
||||||
|
| **EMOS** | **149–249 €** | Dostopen XML, EAN, slike, lastnosti, brez razvoja posebnega konektorja. |
|
||||||
|
| **Sanotechnik** | **199–299 €** | Delujoč JSON endpoint in ustrezna preslikava kategorij/slik/polja SKU/EAN. |
|
||||||
|
| **KOOPMAN** | **350–650 €** | Če je dostop do ustreznih produktnih podatkov, slik, modelov ter energetskih dokumentov; dodatno delo lahko ceno spremeni. |
|
||||||
|
| **TRBOVC** | **450–950 €** | Splet + PDF: po pregledu strukture, dovoljene uporabe in možnosti samodejne ekstrakcije; drugače po uri ali novi ponudbi. |
|
||||||
|
| **Groupe SEB** | **Po ogledu vira** | Najprej brezplačna kratka tehnična ocena, nato fiksna ponudba za dogovorjen obseg. |
|
||||||
|
|
||||||
|
**Predlog za to stranko:** najprej **brezplačni 30-minutni prikaz** in omejeni pilot. Nato **649 € za do tri standardne vire** (npr. že pripravljeni GROHE + EMOS + Sanotechnik, če so dostopni in preslikava zadostuje). KOOPMAN ter TRBOVC se ocenita posebej, če vključujeta neurejene dokumente, dodatno preverjanje ali spletno zajemanje. To ni avtomatska zaveza za kompletno obdelavo vseh dobaviteljev.
|
||||||
|
|
||||||
|
## 6. Redna naročnina – pomembna omejitev
|
||||||
|
|
||||||
|
**Po naročnikovem ceniku** so naročnine v USD, enkratna nastavitev pa je tu predlagana v EUR brez DDV.
|
||||||
|
|
||||||
|
- **Free:** $0/mesec; 50 SKU; 1 vir; **0 AI kreditov**.
|
||||||
|
- **Starter:** $49/mesec; 100 SKU; 2 vira; 100 kreditov.
|
||||||
|
- **Plus:** $199/mesec; 400 SKU; 3 viri; 400 kreditov.
|
||||||
|
- **Growth:** $299/mesec; 1.200 SKU; 5 virov; 1.200 kreditov.
|
||||||
|
- **Business:** $499/mesec; 4.000 SKU; 8 virov; 4.000 kreditov.
|
||||||
|
- **Scale:** $999/mesec; 12.000 SKU; 12 virov; 12.000 kreditov.
|
||||||
|
- **Enterprise:** ponudba po meri; veljajo pogodbeno dogovorjeni pogoji.
|
||||||
|
|
||||||
|
Če ostane vseh **pet virov** (GROHE, EMOS, Sanotechnik, KOOPMAN, TRBOVC), je Growth najnižji od prikazanih paketov z dovolj velikim številom virov **pod pogojem, da je izbranih največ 1.200 SKU**. Z Groupe SEB bi bilo virov šest, zato bi bil med prikazanimi standardnimi paketi potreben najmanj Business (in največ 4.000 SKU). Končni paket določimo šele po prejemu seznama EAN. Letni način obračuna je ločen od mesečnega; pred ponudbo potrdimo aktualen cenik.
|
||||||
|
|
||||||
|
## 7. Vprašanja in dogovor ob koncu (5 min)
|
||||||
|
|
||||||
|
- Koliko **unikatnih EAN-ov** je na seznamu in koliko izdelkov je dejansko v prodaji?
|
||||||
|
- Kateri dobavitelji morajo v prvi fazi delovati in kako pogosto je potrebna sinhronizacija?
|
||||||
|
- Kateri jeziki so obvezni in ali želi naročnik AI besedila ali samo prenos obstoječih podatkov?
|
||||||
|
- Katera polja mora trgovina prejeti v izvozu (EAN, naziv, opis HTML, specifikacije, slike, meta naslov/opis, oznake)?
|
||||||
|
- Ali so na voljo potrebna dovoljenja za pridobivanje podatkov, dostopi in energetske listine?
|
||||||
|
- Dogovor: priprava pilota na 5–10 EAN-ih, potrditev izvoznega vzorca, nato pisna ponudba in rok za izbrane dobavitelje.
|
||||||
|
|
||||||
|
**Zaključni stavek:** »Predlagamo, da najprej skupaj preizkusimo nekaj vaših izdelkov od uvoza do končnega izvoza. Tako boste videli rezultat in ceno dejanske nastavitve še pred odločitvijo za večji projekt.«
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
# Descrybe public API
|
||||||
|
|
||||||
|
Production API: `https://api.descrybe.io/api/v1`
|
||||||
|
Interactive reference: `https://descrybe.io/docs`
|
||||||
|
OpenAPI YAML: `https://api.descrybe.io/api/v1/openapi.yaml`
|
||||||
|
|
||||||
|
## Authentication
|
||||||
|
|
||||||
|
Use a company API key from Settings → API keys. Team members with API Keys management permission can create keys. Send `Authorization: Bearer dk_...` (preferred) or `X-API-Key: dk_...`. Treat the secret as confidential; the full key is shown only when created. These are company-scoped public API endpoints, not dashboard session endpoints.
|
||||||
|
|
||||||
|
## Example requests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -H 'Authorization: Bearer dk_YOUR_KEY' 'https://api.descrybe.io/api/v1/products?page=1&limit=25'
|
||||||
|
curl -H 'Authorization: Bearer dk_YOUR_KEY' 'https://api.descrybe.io/api/v1/feeds'
|
||||||
|
curl -X POST 'https://api.descrybe.io/api/v1/process' -H 'Authorization: Bearer dk_YOUR_KEY' -H 'Content-Type: application/json' -d '{"raw_product_ids":["YOUR_RAW_UUID"],"processing_type":"seo_meta"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
For `POST /products/process`, supply `items[].ean` and expect HTTP 200 with a `data` envelope. For `POST /process`, supply existing `raw_product_ids` and expect HTTP 202 with flat processing job details. `processing_types` is informational; **`processing_type` controls the execution mode**. `seo_meta` processes SEO metadata while keeping existing enhanced titles/descriptions. Multiple selected content outputs use the `enhance` mode.
|
||||||
|
|
||||||
|
## URL feeds
|
||||||
|
|
||||||
|
Feeds support XML, CSV, and JSON. For a public create call use `POST /feeds` with `name`, `url`, `feed_type`, and optional `item_path`. JSON object wrappers and XML record names can usually be detected during schema extraction; specify an item path if automatic detection does not find the right array. For protected URL sources or custom authorization headers, use the authenticated company dashboard feed configuration, which securely saves the secrets. The public feed-create JSON contract does not accept arbitrary secret headers.
|
||||||
|
|
||||||
|
Export feeds support XML, CSV and JSON, with a URL extension matching the saved format. For exports, create a template with `POST /export-feeds` and generate with `POST /export-feeds/{id}/generate`. The public download token must be handled like a secret.
|
||||||
|
|
||||||
|
## Registered endpoints
|
||||||
|
|
||||||
|
All paths below are relative to `/api/v1`, and are checked against the API router.
|
||||||
|
|
||||||
|
- `GET, POST /attributes`
|
||||||
|
- `POST /attributes/create`
|
||||||
|
- `PATCH, DELETE /attributes/{id}`
|
||||||
|
- `GET /campaigns`
|
||||||
|
- `POST /campaigns/prepare`
|
||||||
|
- `GET, POST /categories`
|
||||||
|
- `POST /categories/create`
|
||||||
|
- `GET, PATCH, DELETE /categories/{id}`
|
||||||
|
- `GET, POST /export-feeds`
|
||||||
|
- `GET, PATCH, DELETE /export-feeds/{id}`
|
||||||
|
- `POST /export-feeds/{id}/export-products`
|
||||||
|
- `POST /export-feeds/{id}/generate`
|
||||||
|
- `POST /export-feeds/{id}/rotate-token`
|
||||||
|
- `PUT /export-feeds/{id}/template`
|
||||||
|
- `GET, POST /feeds`
|
||||||
|
- `GET, PATCH, DELETE /feeds/{id}`
|
||||||
|
- `POST /feeds/{id}/extract-schema`
|
||||||
|
- `GET, PUT /feeds/{id}/mappings`
|
||||||
|
- `POST /feeds/{id}/sync`
|
||||||
|
- `POST /feeds/{id}/sync-process-sample`
|
||||||
|
- `GET /health`
|
||||||
|
- `GET /marketing/calendar`
|
||||||
|
- `POST /marketing/calendar/prepare`
|
||||||
|
- `GET /openapi.yaml`
|
||||||
|
- `POST, GET /process`
|
||||||
|
- `GET /process/{id}`
|
||||||
|
- `POST /process/{id}/cancel`
|
||||||
|
- `POST /process/{id}/retry`
|
||||||
|
- `POST /process/{id}/terminate`
|
||||||
|
- `GET /products`
|
||||||
|
- `POST /products/process`
|
||||||
|
- `GET /products/process/{id}`
|
||||||
|
- `GET /products/quality`
|
||||||
|
- `POST /products/reset`
|
||||||
|
- `GET, PATCH /products/{id}`
|
||||||
|
|
||||||
|
## Response handling
|
||||||
|
|
||||||
|
Public catalog and feed list/create routes generally use `data` (and `meta` for paginated lists). Processing jobs under `/process` use a flat job response instead. Do not interchange processed product `id` and `raw_product_id` for job starts. Handle 401 for invalid/revoked keys, 402 for plan/credit gates, 429 with `Retry-After` for throttled operations, and validation errors as documented per operation.
|
||||||
|
|
||||||
|
The dashboard has additional `/api/*` endpoints requiring a signed-in session and CSRF token. Two dashboard-only Team/Admin operations are included in the OpenAPI document for operator reference; **API keys cannot call them**.
|
||||||
|
|
||||||
Reference in new issue
Block a user