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

No files matched your search

@@ -0,0 +1,113 @@
package feeds
import (
"context"
"errors"
"os"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
)
// Requires the normal migrated test PostgreSQL schema (DATABASE_URL).
func TestDeleteFeedRemovesOnlyOwnedUnprocessedProducts(t *testing.T) {
dsn := strings.TrimSpace(os.Getenv("DATABASE_URL"))
if dsn == "" {
t.Skip("DATABASE_URL is not configured")
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
pg, err := pgxpool.New(ctx, dsn)
if err != nil {
t.Fatal(err)
}
defer pg.Close()
cid, otherCID := uuid.New(), uuid.New()
for _, id := range []uuid.UUID{cid, otherCID} {
if _, err := pg.Exec(ctx, `INSERT INTO companies (id, name) VALUES ($1, $2)`, id, "delete-cleanup-"+id.String()[:8]); err != nil {
t.Fatal(err)
}
}
defer pg.Exec(context.Background(), `DELETE FROM companies WHERE id = ANY($1::uuid[])`, []uuid.UUID{cid, otherCID})
newFeed := func(c uuid.UUID) uuid.UUID {
t.Helper()
var id uuid.UUID
if err := pg.QueryRow(ctx, `INSERT INTO input_feeds (company_id, name) VALUES ($1, 'test-feed') RETURNING id`, c).Scan(&id); err != nil {
t.Fatal(err)
}
return id
}
feed := newFeed(cid)
survivor := newFeed(cid)
otherFeed := newFeed(otherCID)
newRaw := func(c uuid.UUID, name string, fid uuid.UUID, processed bool, status string, ids any) uuid.UUID {
t.Helper()
var id uuid.UUID
err := pg.QueryRow(ctx, `
INSERT INTO raw_products (company_id, gtin, feed_id, feed_ids, is_processed, processing_status)
VALUES ($1, $2, $3, $4, $5, $6) RETURNING id`, c, name, fid, ids, processed, status).Scan(&id)
if err != nil {
t.Fatal(err)
}
return id
}
unprocessed := newRaw(cid, "delete-new", feed, false, "unprocessed", nil)
failed := newRaw(cid, "delete-failed", feed, false, "failed", nil)
processed := newRaw(cid, "keep-processed", feed, true, "processed", nil)
processing := newRaw(cid, "keep-running", feed, false, "processing", nil)
shared := newRaw(cid, "keep-shared", feed, false, "unprocessed", []string{feed.String(), survivor.String()})
secondary := newRaw(cid, "keep-secondary", survivor, false, "unprocessed", []string{feed.String(), survivor.String()})
untouchedOther := newRaw(otherCID, "keep-other-company", otherFeed, false, "unprocessed", nil)
// A processed result linked to an unprocessed raw row survives with its FK cleared.
var resultID uuid.UUID
if err := pg.QueryRow(ctx, `
INSERT INTO processed_products (company_id, raw_product_id, feed_id, name)
VALUES ($1, $2, $3, 'retained') RETURNING id`, cid, unprocessed, feed).Scan(&resultID); err != nil {
t.Fatal(err)
}
svc := &Service{Pool: pg}
if _, err := svc.DeleteWithCleanup(ctx, otherCID, feed); !errors.Is(err, ErrNotFound) {
t.Fatalf("cross-tenant deletion must return not found, got %v", err)
}
count, err := svc.DeleteWithCleanup(ctx, cid, feed)
if err != nil {
t.Fatal(err)
}
if count != 2 {
t.Fatalf("deleted raw count = %d, want 2", count)
}
var n int
if err := pg.QueryRow(ctx, `SELECT count(*) FROM raw_products WHERE id = ANY($1::uuid[])`, []uuid.UUID{unprocessed, failed}).Scan(&n); err != nil || n != 0 {
t.Fatalf("unprocessed rows still exist: count=%d err=%v", n, err)
}
for _, kept := range []uuid.UUID{processed, processing, shared, secondary, untouchedOther} {
if err := pg.QueryRow(ctx, `SELECT count(*) FROM raw_products WHERE id = $1`, kept).Scan(&n); err != nil || n != 1 {
t.Fatalf("preserved row %s count=%d err=%v", kept, n, err)
}
}
var newOwner uuid.UUID
if err := pg.QueryRow(ctx, `SELECT feed_id FROM raw_products WHERE id = $1`, shared).Scan(&newOwner); err != nil || newOwner != survivor {
t.Fatalf("shared row owner=%v err=%v", newOwner, err)
}
for _, kept := range []uuid.UUID{shared, secondary} {
if err := pg.QueryRow(ctx, `SELECT count(*) FROM raw_products WHERE id = $1 AND feed_ids @> jsonb_build_array($2::text)`, kept, feed).Scan(&n); err != nil || n != 0 {
t.Fatalf("stale secondary feed id in row %s: %d, %v", kept, n, err)
}
}
var rawLink *uuid.UUID
if err := pg.QueryRow(ctx, `SELECT raw_product_id FROM processed_products WHERE id = $1`, resultID).Scan(&rawLink); err != nil || rawLink != nil {
t.Fatalf("processed result must survive, detached from deleted raw: %v %v", rawLink, err)
}
if _, err := svc.DeleteWithCleanup(ctx, cid, feed); !errors.Is(err, ErrNotFound) {
t.Fatalf("second delete must be not found, got %v", err)
}
}
+50 -2
View File
@@ -172,6 +172,13 @@ func ValidateFeedURL(ctx context.Context, rawURL string) error {
// downloadFeed streams an http(s) feed to a temp file with SSRF controls and a hard size cap.
// Callers must Close the returned blob to remove the temp file.
func downloadFeed(ctx context.Context, rawURL string) (*feedBlob, error) {
return downloadFeedWithHeaders(ctx, rawURL, nil)
}
func downloadFeedWithHeaders(ctx context.Context, rawURL string, extra map[string]string) (*feedBlob, error) {
extra, err := validatedFeedHeaders(extra)
if err != nil {
return nil, err
}
ensureAllowlist()
rawURL = strings.TrimSpace(rawURL)
if rawURL == "" {
@@ -203,7 +210,15 @@ func downloadFeed(ctx context.Context, rawURL string) (*feedBlob, error) {
if req.URL.Scheme != "http" && req.URL.Scheme != "https" {
return errURLScheme
}
return assertPublicHost(req.Context(), req.URL.Hostname())
if err := assertPublicHost(req.Context(), req.URL.Hostname()); err != nil {
return err
}
if len(via) > 0 && !strings.EqualFold(req.URL.Hostname(), via[0].URL.Hostname()) {
for name := range extra {
req.Header.Del(name)
}
}
return nil
},
}
@@ -212,7 +227,10 @@ func downloadFeed(ctx context.Context, rawURL string) (*feedBlob, error) {
return nil, err
}
req.Header.Set("User-Agent", defaultUserAgent)
req.Header.Set("Accept", "text/csv,application/csv,application/xml,text/xml,application/atom+xml,*/*")
req.Header.Set("Accept", "application/json,text/csv,application/csv,application/xml,text/xml,application/atom+xml,*/*")
for name, value := range extra {
req.Header.Set(name, value)
}
res, err := client.Do(req)
if err != nil {
@@ -402,3 +420,33 @@ func isBlockedIP(ip net.IP) bool {
}
return false
}
// DownloadImportSource safely fetches a one-time catalog import URL with optional headers.
// The caller must close the returned reader, which removes the temporary file.
func DownloadImportSource(ctx context.Context, rawURL string, headers map[string]string, maxSize int64) (io.ReadCloser, error) {
b, err := downloadFeedWithHeaders(ctx, rawURL, headers)
if err != nil {
return nil, err
}
if b.size > maxSize {
b.Close()
return nil, ClientMsg("catalog import exceeds size limit")
}
f, err := b.Open()
if err != nil {
b.Close()
return nil, err
}
return &cleanupImportReader{ReadCloser: f, blob: b}, nil
}
type cleanupImportReader struct {
io.ReadCloser
blob *feedBlob
}
func (r *cleanupImportReader) Close() error {
err := r.ReadCloser.Close()
_ = r.blob.Close()
return err
}
+84
View File
@@ -759,6 +759,9 @@ func (s *Service) PublicExportXML(ctx context.Context, w io.Writer, token string
}
// PublicExportCSV streams CSV for a public export token.
func (s *Service) PublicExportJSON(ctx context.Context, w io.Writer, token string) error {
return s.StreamPublicExport(ctx, w, token, "json")
}
func (s *Service) PublicExportCSV(ctx context.Context, w io.Writer, token string) error {
return s.StreamPublicExport(ctx, w, token, "csv")
}
@@ -805,6 +808,8 @@ func (s *Service) streamExport(ctx context.Context, w io.Writer, row exportFeedR
switch format {
case "csv":
return streamCSV(w, seq, tpl)
case "json":
return streamJSON(w, seq, tpl)
default:
return streamXML(w, seq, tpl, row.Name)
}
@@ -966,6 +971,9 @@ func (s *Service) ExportSelectedProducts(ctx context.Context, companyID, feedID
case "csv":
count, err = streamCSV(&buf, seq, tpl)
mimeType = "text/csv; charset=utf-8"
case "json":
count, err = streamJSON(&buf, seq, tpl)
mimeType = "application/json; charset=utf-8"
default:
count, err = streamXML(&buf, seq, tpl, row.Name)
mimeType = "application/xml; charset=utf-8"
@@ -1002,6 +1010,17 @@ func (s *Service) queryExportProductsByIDs(ctx context.Context, companyID uuid.U
func renderExportSnippet(format string, tpl exportTemplate, products []exportProduct, feedName string) (string, int, error) {
var buf bytes.Buffer
switch strings.ToLower(strings.TrimSpace(format)) {
case "json":
seq := exportProductSeq(func(yield func(exportProduct) error) error {
for _, p := range products {
if err := yield(p); err != nil {
return err
}
}
return nil
})
n, err := streamJSON(&buf, seq, tpl)
return buf.String(), n, err
case "csv":
cw := csv.NewWriter(&buf)
headers := make([]string, len(tpl.Fields))
@@ -1063,3 +1082,68 @@ func sanitizeExportFileName(name string) string {
}
return out
}
// streamJSON emits valid JSON objects one at a time with no catalog-wide buffering.
// The outer key follows the configured template root (products by default).
func streamJSON(w io.Writer, seq exportProductSeq, tpl exportTemplate) (int, error) {
root := strings.TrimSpace(tpl.Root)
if root == "" {
root = "products"
}
key, err := json.Marshal(root)
if err != nil {
return 0, err
}
if _, err := fmt.Fprintf(w, "{%s:[", key); err != nil {
return 0, err
}
count := 0
err = seq(func(p exportProduct) error {
row := make(map[string]any, len(tpl.Fields))
for _, field := range tpl.Fields {
name := strings.TrimSpace(field.Key)
if name == "" {
name = field.Source
}
if isSpecExpandSource(field.Source) {
specs := map[string]string{}
for _, spec := range expandSpecFields(p) {
if val := productFieldValue(p, spec.Source); val != "" {
specs[spec.Key] = val
}
}
if len(specs) > 0 {
row[name] = specs
}
continue
}
if name != "" {
row[name] = productFieldValue(p, field.Source)
}
}
encoded, err := json.Marshal(row)
if err != nil {
return err
}
if count > 0 {
if _, err := io.WriteString(w, ","); err != nil {
return err
}
}
if _, err := w.Write(encoded); err != nil {
return err
}
count++
if count%exportChunkHint == 0 {
if f, ok := w.(interface{ Flush() }); ok {
f.Flush()
}
}
return nil
})
if err != nil {
return count, err
}
_, err = io.WriteString(w, "]}\n")
return count, err
}
+37 -1
View File
@@ -115,6 +115,25 @@ func (s *Service) ExtractSchema(ctx context.Context, companyID, feedID uuid.UUID
out.Fields = fields
out.SampleRows = rows
out.Preview = buildXMLPreview(data, local)
case "json":
suggested := guessJSONItemPath(data)
out.SuggestedPath = suggested
path := itemPathHint
if path == "" {
path = suggested
out.ItemPath = path
}
fields, rows, err := extractJSONSchema(data, path)
if err != nil && !(truncated && rows > 0 && (errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, io.EOF) || strings.Contains(strings.ToLower(err.Error()), "unexpected eof"))) {
return nil, fmt.Errorf("JSON preview: %w; check the item path and response format", err)
}
out.Fields = fields
out.SampleRows = rows
preview := data
if len(preview) > 4096 {
preview = preview[:4096]
}
out.Preview = string(preview)
default:
fields, rows, preview, err := extractCSVSchema(data)
if err != nil {
@@ -221,6 +240,7 @@ func guessXMLItemPath(data []byte) string {
full string
}
cands := []cand{
{"shopitem", "shop/shopitem"},
{"item", "rss/channel/item"},
{"product", "products/product"},
{"entry", "feed/entry"},
@@ -232,7 +252,6 @@ func guessXMLItemPath(data []byte) string {
if path := findFirstTagPath(data, c.local); path != "" {
return path
}
return c.full
}
}
return "rss/channel/item"
@@ -527,3 +546,20 @@ func buildXMLPreview(data []byte, itemLocal string) string {
_ = itemLocal
return strings.Join(out, "\n")
}
func extractJSONSchema(data []byte, itemPath string) ([]SchemaField, int, error) {
acc := map[string]*fieldAcc{}
rows := 0
_, err := parseJSONItems(bytes.NewReader(data), itemPath, func(row feedRow) error {
rows++
if rows > schemaMaxRows {
return errStopSchema
}
accumulateRowFields(acc, row)
return nil
})
if err != nil && !errors.Is(err, errStopSchema) {
return nil, rows, err
}
return finalizeSchema(acc), rows, nil
}
+89
View File
@@ -0,0 +1,89 @@
package feeds
import (
"encoding/json"
"errors"
"net/http"
"os"
"strings"
"github.com/descrybe/descrybe-v2/apps/api/internal/platformsettings"
)
// Custom remote source headers are stored only as encrypted options; never in response DTOs.
func validatedFeedHeaders(input map[string]string) (map[string]string, error) {
if len(input) > 20 {
return nil, ClientMsg("at most 20 HTTP headers")
}
clean := make(map[string]string, len(input))
for name, value := range input {
name = http.CanonicalHeaderKey(strings.TrimSpace(name))
value = strings.TrimSpace(value)
if !httpValidHeaderName(name) || strings.ContainsAny(value, "\r\n") || len(value) > 4096 {
return nil, ClientMsg("invalid feed HTTP header")
}
switch strings.ToLower(name) {
case "host", "connection", "content-length", "transfer-encoding", "cookie", "proxy-authorization", "proxy-connection", "upgrade":
return nil, ClientMsg("unsafe feed HTTP header")
}
if value != "" {
clean[name] = value
}
}
return clean, nil
}
func httpValidHeaderName(name string) bool {
if name == "" || len(name) > 100 {
return false
}
for _, r := range name {
if !(r >= 'A' && r <= 'Z' || r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || strings.ContainsRune("!#$%&'*+-.^_`|~", r)) {
return false
}
}
return true
}
func secretEncryptionKey() []byte {
material := os.Getenv("APP_ENCRYPTION_KEY")
if material == "" {
material = os.Getenv("CREDENTIALS_ENCRYPTION_KEY")
}
return platformsettings.DeriveKey(material, os.Getenv("TOKEN_SIGNING_SECRET"))
}
func encryptFeedHeaders(headers map[string]string) (string, error) {
clean, err := validatedFeedHeaders(headers)
if err != nil {
return "", err
}
if len(clean) == 0 {
return "", nil
}
key := secretEncryptionKey()
if len(key) != 32 {
return "", errors.New("APP_ENCRYPTION_KEY is required for authenticated feed URLs")
}
b, err := json.Marshal(clean)
if err != nil {
return "", err
}
return platformsettings.EncryptSecret(key, string(b))
}
func decryptFeedHeaders(options any) (map[string]string, error) {
opt, ok := options.(map[string]any)
if !ok {
return nil, nil
}
encrypted, _ := opt["request_headers_encrypted"].(string)
if encrypted == "" {
return nil, nil
}
plain, err := platformsettings.DecryptSecret(secretEncryptionKey(), encrypted)
if err != nil {
return nil, errors.New("cannot decrypt feed credentials; ensure same APP_ENCRYPTION_KEY on API and worker")
}
out := map[string]string{}
if err := json.Unmarshal([]byte(plain), &out); err != nil {
return nil, err
}
return validatedFeedHeaders(out)
}
+27 -1
View File
@@ -227,8 +227,34 @@ func isSpecificationsTarget(tgt string) bool {
// CDATA HTML, or flat strings. Empty/missing yields nil.
func resolveSpecifications(row map[string]string, src string) map[string]string {
src = strings.Trim(strings.TrimSpace(src), "/")
if strings.EqualFold(leafName(src), "PARAMS") {
specs := map[string]string{}
for k, v := range row {
if !strings.HasPrefix(strings.ToLower(k), strings.ToLower(src)+"/") {
continue
}
rel := k[len(src)+1:]
if strings.Contains(rel, "/") || strings.EqualFold(rel, "PARAM") {
continue
}
if strings.TrimSpace(v) != "" {
specs[rel] = v
}
}
if len(specs) > 0 {
return normalizeSpecKeys(specs)
}
}
if children := collectPrefixed(row, src); len(children) > 0 {
return normalizeSpecKeys(children)
clean := map[string]string{}
for k, v := range children {
if !strings.Contains(k, "/") {
clean[k] = v
}
}
if len(clean) > 0 {
return normalizeSpecKeys(clean)
}
}
if val, ok := lookupRow(row, src); ok {
if pairs := ParseSpecifications(val); len(pairs) > 0 {
+52 -2
View File
@@ -31,18 +31,23 @@ type feedRow map[string]string
func detectFeedFormat(feedType, contentType, urlHint string, sample []byte) string {
ft := strings.ToLower(strings.TrimSpace(feedType))
if ft == "csv" || ft == "xml" {
if ft == "csv" || ft == "xml" || ft == "json" {
return ft
}
ct := strings.ToLower(contentType)
u := strings.ToLower(urlHint)
switch {
case strings.Contains(ct, "json") || strings.Contains(u, ".json") || strings.Contains(u, "format=json"):
return "json"
case strings.Contains(ct, "csv") || strings.HasSuffix(u, ".csv"):
return "csv"
case strings.Contains(ct, "xml") || strings.HasSuffix(u, ".xml"):
return "xml"
}
trimmed := bytes.TrimSpace(sample)
if len(trimmed) > 0 && (trimmed[0] == '{' || trimmed[0] == '[') {
return "json"
}
if len(trimmed) > 0 && trimmed[0] == '<' {
return "xml"
}
@@ -173,7 +178,7 @@ func guessXMLItemLocal(data []byte) string {
sample = sample[:xmlItemGuessBytes]
}
lower := strings.ToLower(sample)
for _, cand := range []string{"item", "product", "entry", "offer", "row"} {
for _, cand := range []string{"shopitem", "item", "entry", "offer", "row", "product"} {
if strings.Contains(lower, "<"+cand) || strings.Contains(lower, ":"+cand) {
return cand
}
@@ -193,6 +198,7 @@ func readXMLElementMap(dec *xml.Decoder, start xml.StartElement) (feedRow, error
row[start.Name.Local+"/"+key] = a.Value
}
var path []string
var paramName, paramValue string
for {
tok, err := dec.Token()
if err != nil {
@@ -207,7 +213,38 @@ func readXMLElementMap(dec *xml.Decoder, start xml.StartElement) (feedRow, error
row[key] = a.Value
}
case xml.EndElement:
if strings.EqualFold(t.Name.Local, "PARAM") && len(path) >= 2 && strings.EqualFold(path[len(path)-2], "PARAMS") {
name := strings.TrimSpace(paramName)
value := strings.TrimSpace(paramValue)
if name != "" && value != "" {
key := "PARAMS/" + sanitizePathSegment(name)
if key != "PARAMS/" {
row[key] = value
}
}
paramName, paramValue = "", ""
}
if len(path) == 0 {
count := 0
for k := range row {
if strings.HasPrefix(k, "PARAMS/") && !strings.Contains(strings.TrimPrefix(k, "PARAMS/"), "/") {
count++
}
}
if count > 0 {
row["PARAMS"] = fmt.Sprintf("%d named attributes", count)
}
// Supplier feeds often publish additional images as numbered siblings.
images := make([]string, 0, 12)
for i := 1; i <= 50; i++ {
name := fmt.Sprintf("IMGURL_ALTERNATIVE_%02d", i)
if v := strings.TrimSpace(row[name]); v != "" {
images = append(images, v)
}
}
if len(images) > 0 {
row["ADDITIONAL_IMAGE_URLS"] = strings.Join(images, ",")
}
return row, nil
}
path = path[:len(path)-1]
@@ -217,6 +254,19 @@ func readXMLElementMap(dec *xml.Decoder, start xml.StartElement) (feedRow, error
continue
}
leaf := path[len(path)-1]
if len(path) >= 3 && strings.EqualFold(path[len(path)-3], "PARAMS") && strings.EqualFold(path[len(path)-2], "PARAM") {
if strings.EqualFold(leaf, "PARAM_NAME") {
paramName += text
continue
}
if strings.EqualFold(leaf, "VAL") {
paramValue += text
continue
}
if strings.EqualFold(leaf, "ORDER") {
continue
}
}
full := strings.Join(path, "/")
// Prefer nested path as source of truth; only set bare leaf when
// unique (no other nested field already owns this leaf name).
+254
View File
@@ -0,0 +1,254 @@
package feeds
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"regexp"
"sort"
"strconv"
"strings"
)
// parseJSONItems consumes one object at a time from a root array or a nested array
// (data.products, results, items, SHOPITEM, etc). It does not buffer the catalog.
func parseJSONItems(r io.Reader, itemPath string, onRow func(feedRow) error) (int, error) {
dec := json.NewDecoder(bufio.NewReader(r))
dec.UseNumber()
first, err := dec.Token()
if err != nil {
return 0, fmt.Errorf("json: %w", err)
}
count := 0
var visit func(any, []string) error
visit = func(token any, path []string) error {
delim, ok := token.(json.Delim)
if !ok {
return nil
}
switch delim {
case '[':
if jsonItemPathMatches(itemPath, path) || (itemPath == "" && isLikelyJSONItemArray(path)) {
for dec.More() {
var raw json.RawMessage
if err := dec.Decode(&raw); err != nil {
return err
}
var obj any
d := json.NewDecoder(bytes.NewReader(raw))
d.UseNumber()
if err := d.Decode(&obj); err != nil {
return err
}
if _, ok := obj.(map[string]any); !ok {
continue
}
row := feedRow{}
flattenJSONValue(row, "", obj, 0)
expandSpecificationFields(row)
count++
if count > maxParseRows {
return parseTooManyRows()
}
if err := onRow(row); err != nil {
return err
}
}
} else {
for dec.More() {
next, e := dec.Token()
if e != nil {
return e
}
if err := visit(next, path); err != nil {
return err
}
}
}
case '{':
for dec.More() {
k, e := dec.Token()
if e != nil {
return e
}
key, _ := k.(string)
next, e := dec.Token()
if e != nil {
return e
}
if err := visit(next, append(append([]string(nil), path...), key)); err != nil {
return err
}
}
default:
return fmt.Errorf("invalid JSON document")
}
_, err := dec.Token()
return err
}
if err := visit(first, nil); err != nil {
return count, fmt.Errorf("json: %w", err)
}
if count == 0 {
return 0, errors.New("JSON contained no product records; check item path (for example products or data/products)")
}
return count, nil
}
func jsonItemPathMatches(hint string, path []string) bool {
hint = strings.Trim(strings.ToLower(strings.TrimSpace(hint)), "/.")
if hint == "" {
return false
}
hint = strings.ReplaceAll(hint, ".", "/")
actual := strings.ToLower(strings.Join(path, "/"))
return actual == hint || strings.HasSuffix(actual, "/"+hint)
}
func isLikelyJSONItemArray(path []string) bool {
if len(path) == 0 {
return true
}
name := strings.ToLower(path[len(path)-1])
switch name {
case "products", "product", "items", "shopitem", "results", "entries", "offers", "rows", "records", "data":
return true
}
return false
}
func flattenJSONValue(row feedRow, prefix string, v any, depth int) {
if depth > 12 || len(row) > 4000 {
return
}
switch x := v.(type) {
case map[string]any:
keys := make([]string, 0, len(x))
for k := range x {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
path := k
if prefix != "" {
path = prefix + "/" + k
}
flattenJSONValue(row, path, x[k], depth+1)
}
case []any:
if len(x) == 0 {
return
}
// Attribute arrays [{name: ..., value: ...}] become named specification children.
for i, v := range x {
if i >= 250 {
return
}
if m, ok := v.(map[string]any); ok {
name := jsonString(m["name"])
if name == "" {
name = jsonString(m["PARAM_NAME"])
}
value := jsonString(m["value"])
if value == "" {
value = jsonString(m["VAL"])
}
if name != "" && value != "" {
row[prefix] = "Nested attributes"
row[prefix+"/"+sanitizePathSegment(name)] = value
continue
}
}
if s := jsonString(v); s != "" {
if _, ok := v.(map[string]any); !ok {
row[prefix+"/"+strconv.Itoa(i)] = s
continue
}
}
flattenJSONValue(row, prefix+"/"+strconv.Itoa(i), v, depth+1)
}
// For image galleries, keep the first URL in the parent path.
if _, ok := row[prefix]; !ok {
if first := jsonString(x[0]); first != "" {
row[prefix] = first
}
}
case nil:
return
default:
value := jsonString(v)
if value == "" {
return
}
row[prefix] = value
leaf := leafName(prefix)
if _, ok := row[leaf]; !ok && leaf != "" {
row[leaf] = value
}
}
}
func jsonString(v any) string {
switch x := v.(type) {
case string:
return x
case json.Number:
return string(x)
case bool:
return strconv.FormatBool(x)
case float64:
return strconv.FormatFloat(x, 'f', -1, 64)
}
return ""
}
// guessJSONItemPath picks a recognized list field in the preview; callers can override.
func guessJSONItemPath(data []byte) string {
var node any
dec := json.NewDecoder(bytes.NewReader(data))
dec.UseNumber()
if dec.Decode(&node) != nil {
// Schema previews intentionally stop at 512 KiB, often halfway through
// large JSON documents. Recognize the first array property in the prefix.
re := regexp.MustCompile(`(?i)"([^"\\]+)"\s*:\s*\[\s*\{`)
if parts := re.FindSubmatch(data); len(parts) > 1 {
return string(parts[1])
}
return ""
}
var find func(any, []string, int) string
find = func(v any, path []string, depth int) string {
if depth > 5 {
return ""
}
switch x := v.(type) {
case []any:
if len(x) > 0 {
if _, ok := x[0].(map[string]any); ok {
return strings.Join(path, "/")
}
}
case map[string]any:
for _, key := range []string{"products", "items", "SHOPITEM", "results", "data", "records", "product", "entries", "offers", "rows"} {
if n, ok := x[key]; ok {
if p := find(n, append(path, key), depth+1); p != "" || len(path) == 0 && key == "products" {
return p
}
}
}
keys := make([]string, 0, len(x))
for k := range x {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
if p := find(x[k], append(path, k), depth+1); p != "" {
return p
}
}
}
return ""
}
return find(node, nil, 0)
}
+12 -1
View File
@@ -61,7 +61,8 @@ func PresentFeed(feed map[string]any) map[string]any {
"last_synced_at": lastSynced,
"products_updated_at": productsUpdated,
"last_data_at": lastDataAt,
"options": opts,
"options": publicFeedOptions(opts),
"has_auth_headers": opts["request_headers_encrypted"] != nil && opts["request_headers_encrypted"] != "",
}
if deltas, ok := opts["last_sync_deltas"].(map[string]any); ok && deltas != nil {
out["last_sync_deltas"] = deltas
@@ -138,3 +139,13 @@ func formatAPITime(v any) any {
return v
}
}
func publicFeedOptions(opts map[string]any) map[string]any {
safe := make(map[string]any, len(opts))
for k, v := range opts {
if k != "request_headers_encrypted" && k != "request_headers" {
safe[k] = v
}
}
return safe
}
+125 -17
View File
@@ -28,6 +28,7 @@ type CreateInput struct {
SyncIntervalMinutes int
SyncFrequencyHours int // legacy alias; converted to minutes when SyncIntervalMinutes unset
Options map[string]any
RequestHeaders map[string]string
}
func (s *Service) List(ctx context.Context, companyID uuid.UUID, limit, offset int, q string) ([]map[string]any, int64, int64, int64, error) {
@@ -120,6 +121,13 @@ func (s *Service) Create(ctx context.Context, companyID uuid.UUID, in CreateInpu
if opts == nil {
opts = map[string]any{}
}
if len(in.RequestHeaders) > 0 {
encrypted, err := encryptFeedHeaders(in.RequestHeaders)
if err != nil {
return nil, err
}
opts["request_headers_encrypted"] = encrypted
}
itemPath := strings.TrimSpace(in.ItemPath)
if itemPath == "" {
if p, ok := opts["item_path"].(string); ok {
@@ -140,10 +148,13 @@ func (s *Service) Create(ctx context.Context, companyID uuid.UUID, in CreateInpu
feedType = "csv"
} else {
feedType = "xml"
if strings.Contains(strings.ToLower(url), ".json") || strings.Contains(strings.ToLower(url), "format=json") {
feedType = "json"
}
}
}
if feedType != "xml" && feedType != "csv" {
return nil, ClientMsg("feed_type must be xml or csv")
if feedType != "xml" && feedType != "csv" && feedType != "json" {
return nil, ClientMsg("feed_type must be xml, csv or json")
}
interval := in.SyncIntervalMinutes
if interval <= 0 && in.SyncFrequencyHours > 0 {
@@ -273,7 +284,7 @@ func mappingDocIncomplete(item map[string]any, mappingsRaw any, mappings []Field
return true
}
feedType, _ := item["feed_type"].(string)
if !isCSVFeedType(feedType) && feedItemPathHint(item, mappingsRaw) == "" {
if !isCSVFeedType(feedType) && !strings.EqualFold(feedType, "json") && feedItemPathHint(item, mappingsRaw) == "" {
return true
}
return false
@@ -303,8 +314,8 @@ func (s *Service) Update(ctx context.Context, companyID, id uuid.UUID, body map[
return nil, err
}
feedType = strings.ToLower(strings.TrimSpace(feedType))
if feedType != "" && feedType != "xml" && feedType != "csv" {
return nil, ClientMsg("feed_type must be xml or csv")
if feedType != "" && feedType != "xml" && feedType != "csv" && feedType != "json" {
return nil, ClientMsg("feed_type must be xml, csv or json")
}
interval := 0
switch v := body["sync_interval_minutes"].(type) {
@@ -325,6 +336,21 @@ func (s *Service) Update(ctx context.Context, companyID, id uuid.UUID, body map[
}
}
var encryptedHeaders *string
if rawHeaders, exists := body["request_headers"]; exists {
headers := map[string]string{}
if rawHeaders != nil {
b, _ := json.Marshal(rawHeaders)
if err := json.Unmarshal(b, &headers); err != nil {
return nil, ClientMsg("invalid HTTP headers")
}
}
encrypted, err := encryptFeedHeaders(headers)
if err != nil {
return nil, err
}
encryptedHeaders = &encrypted
}
ct, err := s.Pool.Exec(ctx, `
UPDATE input_feeds SET
name = CASE WHEN $3 <> '' THEN $3 ELSE name END,
@@ -332,13 +358,16 @@ func (s *Service) Update(ctx context.Context, companyID, id uuid.UUID, body map[
status = CASE WHEN $5 <> '' THEN $5 ELSE status END,
feed_type = CASE WHEN $6 <> '' THEN $6 ELSE feed_type END,
sync_interval_minutes = CASE WHEN $7 > 0 THEN $7 ELSE sync_interval_minutes END,
options = CASE
WHEN $8 <> '' THEN COALESCE(options, '{}'::jsonb) || jsonb_build_object('item_path', to_jsonb($8::text))
ELSE options
END,
options = CASE WHEN $9::text IS NULL THEN
(CASE WHEN $8 <> '' THEN COALESCE(options, '{}'::jsonb) || jsonb_build_object('item_path', to_jsonb($8::text)) ELSE options END)
WHEN $9::text = '' THEN
(CASE WHEN $8 <> '' THEN COALESCE(options, '{}'::jsonb) || jsonb_build_object('item_path', to_jsonb($8::text)) ELSE COALESCE(options, '{}'::jsonb) END) - 'request_headers_encrypted'
ELSE
(CASE WHEN $8 <> '' THEN COALESCE(options, '{}'::jsonb) || jsonb_build_object('item_path', to_jsonb($8::text)) ELSE COALESCE(options, '{}'::jsonb) END) || jsonb_build_object('request_headers_encrypted', $9::text)
END,
updated_at = now()
WHERE id = $1 AND company_id = $2`,
id, companyID, name, url, status, feedType, interval, strings.TrimSpace(itemPath))
id, companyID, name, url, status, feedType, interval, strings.TrimSpace(itemPath), encryptedHeaders)
if err != nil {
return nil, err
}
@@ -348,15 +377,94 @@ func (s *Service) Update(ctx context.Context, companyID, id uuid.UUID, body map[
return s.Get(ctx, companyID, id)
}
// Delete removes a feed and its unprocessed raw catalog rows. Processed catalog
// entries are retained, and rows shared with another existing feed are reassigned.
func (s *Service) Delete(ctx context.Context, companyID, id uuid.UUID) error {
ct, err := s.Pool.Exec(ctx, `DELETE FROM input_feeds WHERE id = $1 AND company_id = $2`, id, companyID)
_, err := s.DeleteWithCleanup(ctx, companyID, id)
return err
}
// DeleteWithCleanup executes the feed removal and raw-product cleanup atomically.
// It holds a row lock on the feed, which also serializes FK-checked sync writes
// against deletion; a concurrent worker cannot recreate rows for the deleted feed.
// The returned count includes only deleted raw products, never processed results.
func (s *Service) DeleteWithCleanup(ctx context.Context, companyID, id uuid.UUID) (int64, error) {
tx, err := s.Pool.Begin(ctx)
if err != nil {
return err
return 0, err
}
if ct.RowsAffected() == 0 {
return ErrNotFound
defer tx.Rollback(ctx)
var lockedID uuid.UUID
if err := tx.QueryRow(ctx, `
SELECT id FROM input_feeds
WHERE id = $1 AND company_id = $2
FOR UPDATE`, id, companyID).Scan(&lockedID); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return 0, ErrNotFound
}
return 0, err
}
return nil
// Legacy catalogs can associate one product with multiple feed IDs.
// Preserve any shared unprocessed row, but make a surviving feed its owner.
_, err = tx.Exec(ctx, `
WITH shared AS (
SELECT r.id AS raw_id, MIN(f.id::text)::uuid AS replacement
FROM raw_products r
JOIN LATERAL jsonb_array_elements_text(
CASE WHEN jsonb_typeof(r.feed_ids) = 'array' THEN r.feed_ids ELSE '[]'::jsonb END
) AS ids(value) ON true
JOIN input_feeds f ON f.id::text = ids.value
AND f.company_id = $1 AND f.id <> $2
WHERE r.company_id = $1 AND r.feed_id = $2
AND r.is_processed = false
AND r.processing_status IN ('unprocessed', 'failed')
GROUP BY r.id
)
UPDATE raw_products r SET feed_id = shared.replacement, updated_at = now()
FROM shared WHERE r.id = shared.raw_id AND r.company_id = $1`, companyID, id)
if err != nil {
return 0, err
}
// Only truly unprocessed/failed rows owned by this feed are removed.
// 'processing' rows are intentionally retained to avoid racing active AI jobs.
deleted, err := tx.Exec(ctx, `
DELETE FROM raw_products
WHERE company_id = $1 AND feed_id = $2
AND is_processed = false
AND processing_status IN ('unprocessed', 'failed')`, companyID, id)
if err != nil {
return 0, err
}
// Remove references from secondary feed lists on retained products, too.
_, err = tx.Exec(ctx, `
UPDATE raw_products r SET feed_ids = COALESCE((
SELECT jsonb_agg(ids.value ORDER BY ids.ordinality)
FROM jsonb_array_elements_text(r.feed_ids) WITH ORDINALITY AS ids(value, ordinality)
WHERE ids.value <> $2::text
), '[]'::jsonb), updated_at = now()
WHERE r.company_id = $1 AND jsonb_typeof(r.feed_ids) = 'array'
AND r.feed_ids @> jsonb_build_array($2::text)`, companyID, id)
if err != nil {
return 0, err
}
// FK ON DELETE SET NULL preserves processed products, processing rows and
// export feed definitions; dependent mappings / sync jobs cascade as before.
ct, err := tx.Exec(ctx, `DELETE FROM input_feeds WHERE id = $1 AND company_id = $2`, id, companyID)
if err != nil {
return 0, err
}
if ct.RowsAffected() != 1 {
return 0, ErrNotFound
}
if err := tx.Commit(ctx); err != nil {
return 0, err
}
return deleted.RowsAffected(), nil
}
func (s *Service) GetMappings(ctx context.Context, companyID, feedID uuid.UUID) (map[string]any, error) {
@@ -508,8 +616,8 @@ func (s *Service) CreateExportFeed(ctx context.Context, companyID uuid.UUID, in
if format == "" {
format = "xml"
}
if format != "xml" && format != "csv" {
return nil, ClientMsg("format must be xml or csv")
if format != "xml" && format != "csv" && format != "json" {
return nil, ClientMsg("format must be xml, csv or json")
}
var src *uuid.UUID
if in.SourceFeedID != nil && *in.SourceFeedID != "" {
+7 -1
View File
@@ -77,7 +77,11 @@ func (s *Service) loadFeedSource(ctx context.Context, companyID uuid.UUID, feed
if urlStr == "" {
return nil, errSourceRequired
}
return downloadFeed(ctx, urlStr)
headers, err := decryptFeedHeaders(feed["options"])
if err != nil {
return nil, err
}
return downloadFeedWithHeaders(ctx, urlStr, headers)
}
func sourcePathFromOptions(raw any) string {
@@ -121,6 +125,8 @@ func (s *Service) readLocalFeed(companyID uuid.UUID, rel string) (*feedBlob, err
lower := strings.ToLower(abs)
if strings.HasSuffix(lower, ".xml") {
ct = "application/xml"
} else if strings.HasSuffix(lower, ".json") {
ct = "application/json"
}
return &feedBlob{
path: abs,
+25 -23
View File
@@ -8,10 +8,10 @@ import (
)
const (
maxSpecPairs = 200
maxSpecRawBytes = 64 << 10 // 64 KiB per specifications blob
maxSpecLabelRunes = 120
maxSpecValueRunes = 2000
maxSpecPairs = 200
maxSpecRawBytes = 64 << 10 // 64 KiB per specifications blob
maxSpecLabelRunes = 120
maxSpecValueRunes = 2000
)
var (
@@ -94,8 +94,10 @@ func isSpecFieldKey(key string) bool {
leaf := strings.ToLower(leafName(key))
leaf = strings.TrimPrefix(leaf, "@")
switch leaf {
case "specifications", "specification", "specs", "spec", "features", "feature", "attributes_raw":
case "specifications", "specification", "specs", "spec", "features", "feature", "attributes_raw", "params":
return true
case "description":
return !strings.Contains(key, "/")
}
return strings.Contains(leaf, "specification")
}
@@ -407,24 +409,24 @@ func compactAttributeKey(key string) string {
// Known supplier / locale labels → Descrybe standard field keys (snake_case).
// Freeform specs keep kebab-case from AttributeKeyFromLabel.
var attributeKeyAliases = map[string]string{
"visina": "net_height",
"height": "net_height",
"netheight": "net_height",
"sirina": "net_width",
"width": "net_width",
"netwidth": "net_width",
"globina": "net_depth",
"depth": "net_depth",
"netdepth": "net_depth",
"netmass": "net_mass",
"mass": "net_mass",
"weight": "net_mass",
"teza": "net_mass",
"productmodel": "product_model",
"model": "product_model",
"eprelid": "eprel_id",
"eprel": "eprel_id",
"energyclass": "energy_class",
"visina": "net_height",
"height": "net_height",
"netheight": "net_height",
"sirina": "net_width",
"width": "net_width",
"netwidth": "net_width",
"globina": "net_depth",
"depth": "net_depth",
"netdepth": "net_depth",
"netmass": "net_mass",
"mass": "net_mass",
"weight": "net_mass",
"teza": "net_mass",
"productmodel": "product_model",
"model": "product_model",
"eprelid": "eprel_id",
"eprel": "eprel_id",
"energyclass": "energy_class",
"energijskirazred": "energy_class",
}
+60 -54
View File
@@ -11,60 +11,66 @@ type MappingSuggestion struct {
}
var sourceAliases = map[string][]string{
"gtin": {"gtin"},
"ean": {"gtin"},
"upc": {"gtin"},
"barcode": {"gtin"},
"title": {"title"},
"name": {"title"},
"productname": {"title"},
"brand": {"brand"},
"manufacturer": {"brand"},
"description": {"description"},
"desc": {"description"},
"price": {"price"},
"regularprice": {"price"},
"saleprice": {"sale_price", "price"},
"currency": {"currency"},
"image": {"image_url", "main_image", "image"},
"imageurl": {"image_url", "main_image", "image"},
"imagelink": {"image_url", "main_image", "image"},
"mainimage": {"image_url", "main_image", "image"},
"mainimageurl": {"image_url", "main_image", "image"},
"link": {"product_url"},
"url": {"product_url"},
"producturl": {"product_url"},
"sku": {"sku"},
"mpn": {"mpn"},
"category": {"category"},
"availability": {"availability"},
"stockstatus": {"availability", "stock_status"},
"stock": {"stock"},
"quantity": {"stock"},
"qty": {"stock"},
"color": {"color"},
"size": {"size"},
"material": {"material"},
"weight": {"weight"},
"netmass": {"weight"},
"purchaseprice": {"purchase_price", "price"},
"buyprice": {"purchase_price"},
"cost": {"purchase_price"},
"costprice": {"purchase_price"},
"officiallink": {"official_link"},
"warranty": {"warranty"},
"garancija": {"warranty"},
"service": {"service"},
"servis": {"service"},
"productmodel": {"product_model"},
"model": {"product_model"},
"modelnumber": {"product_model"},
"eprelid": {"eprel_id"},
"eprel": {"eprel_id"},
"specifications": {"specs", "specifications"},
"specs": {"specs", "specifications"},
"specification": {"specs", "specifications"},
"techspecs": {"specs", "specifications"},
"gtin": {"gtin"},
"productno": {"sku"}, "productno2": {"mpn"},
"product": {"title"}, "descriptionbasic": {"description"},
"pricevat": {"price"}, "priceeshopvat": {"price"},
"pricevoc": {"purchase_price"},
"imgurl": {"image_url"}, "params": {"specifications"},
"categoryid": {"category_id"},
"ean": {"gtin"},
"upc": {"gtin"},
"barcode": {"gtin"},
"title": {"title"},
"name": {"title"},
"productname": {"title"},
"brand": {"brand"},
"manufacturer": {"brand"},
"description": {"description"},
"desc": {"description"},
"price": {"price"},
"regularprice": {"price"},
"saleprice": {"sale_price", "price"},
"currency": {"currency"},
"image": {"image_url", "main_image", "image"},
"imageurl": {"image_url", "main_image", "image"},
"imagelink": {"image_url", "main_image", "image"},
"mainimage": {"image_url", "main_image", "image"},
"mainimageurl": {"image_url", "main_image", "image"},
"link": {"product_url"},
"url": {"product_url"},
"producturl": {"product_url"},
"sku": {"sku"},
"mpn": {"mpn"},
"category": {"category"},
"availability": {"availability"},
"stockstatus": {"availability", "stock_status"},
"stock": {"stock"},
"quantity": {"stock"},
"qty": {"stock"},
"color": {"color"},
"size": {"size"},
"material": {"material"},
"weight": {"weight"},
"netmass": {"weight"},
"purchaseprice": {"purchase_price", "price"},
"buyprice": {"purchase_price"},
"cost": {"purchase_price"},
"costprice": {"purchase_price"},
"officiallink": {"official_link"},
"warranty": {"warranty"},
"garancija": {"warranty"},
"service": {"service"},
"servis": {"service"},
"productmodel": {"product_model"},
"model": {"product_model"},
"modelnumber": {"product_model"},
"eprelid": {"eprel_id"},
"eprel": {"eprel_id"},
"specifications": {"specs", "specifications"},
"specs": {"specs", "specifications"},
"specification": {"specs", "specifications"},
"techspecs": {"specs", "specifications"},
}
func normalizeSuggestKey(raw string) string {
+16
View File
@@ -402,7 +402,23 @@ func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUI
var parseCount int
switch format {
case "xml":
if itemPath == "item" {
itemPath = ""
}
parseCount, err = parseXMLItems(body, itemPath, onRow)
case "json":
jsonPath := itemPath
if jsonPath == "item" {
jsonPath = ""
}
if v := itemPathFromMappings(mappingsRaw); v != "" {
jsonPath = v
} else if opts, ok := feed["options"].(map[string]any); ok {
if v, ok := opts["item_path"].(string); ok {
jsonPath = v
}
}
parseCount, err = parseJSONItems(body, jsonPath, onRow)
default:
parseCount, err = parseCSV(body, onRow)
}
@@ -0,0 +1,47 @@
package feeds
import (
"strings"
"testing"
)
const emos = `<?xml version="1.0"?><SHOP><SHOPITEM><PRODUCT>Ročna LED svetilka 9 LED 3×AAA</PRODUCT><PRODUCTNO>1440093109</PRODUCTNO><EAN>8595025395184</EAN><CATEGORY>Svetilke|Ročne svetilke</CATEGORY><DESCRIPTION>barva: mešanica barv|napajanje: 3× AAA|svetlobni tok: 50 lm</DESCRIPTION><DESCRIPTION_BASIC>&lt;p&gt;Praktična LED svetilka&lt;/p&gt;</DESCRIPTION_BASIC><PARAMS><PARAM><PARAM_NAME>barva</PARAM_NAME><VAL>mešanica barv</VAL><ORDER>12</ORDER></PARAM><PARAM><PARAM_NAME>napajanje</PARAM_NAME><VAL>3× AAA</VAL></PARAM><PARAM><PARAM_NAME>vir svetlobe</PARAM_NAME><VAL>9× LED</VAL></PARAM></PARAMS><IMGURL>https://example.com/1.jpg</IMGURL><IMGURL_ALTERNATIVE_01>https://example.com/2.jpg</IMGURL_ALTERNATIVE_01></SHOPITEM></SHOP>`
func TestV10EMOSItemAndAttrs(t *testing.T) {
var got feedRow
n, e := parseXMLItems(strings.NewReader(emos), "", func(r feedRow) error { got = r; return nil })
if e != nil || n != 1 {
t.Fatalf("parse n=%d err=%v", n, e)
}
for k, v := range map[string]string{"PRODUCT": "Ročna LED svetilka 9 LED 3×AAA", "EAN": "8595025395184", "PARAMS/barva": "mešanica barv", "PARAMS/napajanje": "3× AAA", "PARAMS/vir_svetlobe": "9× LED", "DESCRIPTION/svetlobni_tok": "50 lm", "ADDITIONAL_IMAGE_URLS": "https://example.com/2.jpg"} {
if got[k] != v {
t.Errorf("%s=%q want %q", k, got[k], v)
}
}
}
func TestV10NestedJSONWrappedData(t *testing.T) {
raw := `{"data":{"products":[{"name":"Demo 1","ean":"1234567890123","attributes":[{"name":"color","value":"green"}]},{"name":"Demo 2","ean":"1234567890999"}]},"page":1}`
var rows []feedRow
n, e := parseJSONItems(strings.NewReader(raw), "", func(r feedRow) error { rows = append(rows, r); return nil })
if e != nil || n != 2 {
t.Fatalf("parse n=%d err=%v", n, e)
}
if rows[0]["attributes/color"] != "green" {
t.Errorf("nested attrs lost: %v", rows[0])
}
}
func TestV10JSONRootAndData(t *testing.T) {
for _, raw := range []string{`[{"ean":"1"},{"ean":"2"}]`, `{"data":[{"ean":"1"},{"ean":"2"}]}`} {
n, e := parseJSONItems(strings.NewReader(raw), "", func(r feedRow) error { return nil })
if e != nil || n != 2 {
t.Fatalf("input=%s got n=%d err=%v", raw, n, e)
}
}
}
func TestV10PartialPreviewJSONGuess(t *testing.T) {
x := []byte(`{"data":{"products":[{"EAN":"123","sku":"demo"},`)
p := guessJSONItemPath(x)
if p != "products" {
t.Fatalf("guess=%q", p)
}
}