This commit is contained in:
greeneclipse committed 2026-11-15 10:04:44 +01:00
1 parent 41f1a7dbe4
commit e7964c58c8
13 files changed
+1215 -24

No files matched your search

@@ -0,0 +1,96 @@
package catalog
import (
"context"
"os"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
)
// The product detail payload must carry feed_field_sources so the product page can
// show which feed supplied each field.
func TestProductDetailsExposeFeedFieldSources(t *testing.T) {
dsn := strings.TrimSpace(os.Getenv("DATABASE_URL"))
if dsn == "" {
t.Skip("DATABASE_URL not set")
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
pg, err := pgxpool.New(ctx, dsn)
if err != nil {
t.Fatal(err)
}
defer pg.Close()
companyID := uuid.New()
if _, err := pg.Exec(ctx, `INSERT INTO companies (id, name) VALUES ($1, $2)`, companyID, "ffs-"+companyID.String()[:8]); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = pg.Exec(context.Background(), `DELETE FROM companies WHERE id = $1`, companyID) })
var feedA, feedB uuid.UUID
for name, dst := range map[string]*uuid.UUID{"Vendor A": &feedA, "Vendor B": &feedB} {
if err := pg.QueryRow(ctx, `
INSERT INTO input_feeds (company_id, name, url, feed_type, status, sync_interval_minutes, options)
VALUES ($1, $2, 'https://example.com/f.csv', 'csv', 'active', 60, '{}'::jsonb) RETURNING id`,
companyID, name).Scan(dst); err != nil {
t.Fatal(err)
}
}
sources := `{"primary":{"feed_id":"` + feedA.String() + `","feed_name":"Vendor A"},
"feeds":[{"feed_id":"` + feedA.String() + `","feed_name":"Vendor A"},{"feed_id":"` + feedB.String() + `","feed_name":"Vendor B"}],
"fields":{"description":{"feed_id":"` + feedB.String() + `","feed_name":"Vendor B","conflict":true,"also":[{"feed_id":"` + feedA.String() + `","feed_name":"Vendor A"}]},
"brand":{"feed_id":"` + feedA.String() + `","feed_name":"Vendor A"}}}`
var rawID, procID uuid.UUID
if err := pg.QueryRow(ctx, `
INSERT INTO raw_products (company_id, gtin, feed_id, mapped_data, feed_field_sources)
VALUES ($1, '4548736180307', $2, '{"name":"TV","brand":"Sony"}'::jsonb, $3::jsonb) RETURNING id`,
companyID, feedA, sources).Scan(&rawID); err != nil {
t.Fatal(err)
}
if err := pg.QueryRow(ctx, `
INSERT INTO processed_products (company_id, raw_product_id, product_id, name)
VALUES ($1, $2, '4548736180307', 'TV') RETURNING id`, companyID, rawID).Scan(&procID); err != nil {
t.Fatal(err)
}
svc := &Service{Pool: pg}
for name, load := range map[string]func() (map[string]any, error){
"processed": func() (map[string]any, error) { return svc.GetProcessedProduct(ctx, companyID, procID) },
"raw": func() (map[string]any, error) { return svc.GetRawProduct(ctx, companyID, rawID) },
} {
item, err := load()
if err != nil {
t.Fatalf("%s: %v", name, err)
}
ffs, ok := item["feed_field_sources"].(map[string]any)
if !ok {
t.Fatalf("%s: feed_field_sources missing or wrong type: %#v", name, item["feed_field_sources"])
}
fields, _ := ffs["fields"].(map[string]any)
desc, _ := fields["description"].(map[string]any)
if desc["feed_name"] != "Vendor B" || desc["conflict"] != true {
t.Errorf("%s: description source = %#v", name, desc)
}
if feeds, _ := ffs["feeds"].([]any); len(feeds) != 2 {
t.Errorf("%s: feeds = %#v", name, ffs["feeds"])
}
}
// A product synced before merging existed has no sources: the key is present but empty.
if _, err := pg.Exec(ctx, `UPDATE raw_products SET feed_field_sources = NULL WHERE id = $1`, rawID); err != nil {
t.Fatal(err)
}
item, err := svc.GetRawProduct(ctx, companyID, rawID)
if err != nil {
t.Fatal(err)
}
if v := item["feed_field_sources"]; v != nil {
t.Errorf("NULL sources should surface as nil, got %#v", v)
}
}
+4
View File
@@ -1317,6 +1317,7 @@ func (s *Service) GetProcessedProduct(ctx context.Context, companyID, id uuid.UU
COALESCE(p.meta_title, '') AS meta_title,
COALESCE(p.meta_description, '') AS meta_description,
p.status, p.processing_origin, p.attributes, p.processed_attributes, r.gtin, r.mapped_data,
r.feed_field_sources,
COALESCE(p.feed_id, r.feed_id) AS feed_id,
f.name AS feed_name,
f.last_synced_at AS feed_last_synced_at,
@@ -1339,6 +1340,7 @@ func (s *Service) GetProcessedProduct(ctx context.Context, companyID, id uuid.UU
"description", "original_description", "processed_name", "processed_description",
"meta_title", "meta_description",
"status", "processing_origin", "attributes", "processed_attributes", "gtin", "mapped_data",
"feed_field_sources",
"feed_id", "feed_name", "feed_last_synced_at", "raw_updated_at",
"has_processed_name", "has_processed_description", "has_attributes", "has_processed_attributes",
"has_eprel",
@@ -1378,6 +1380,7 @@ func (s *Service) GetRawProduct(ctx context.Context, companyID, id uuid.UUID) (m
'{}'::jsonb AS processed_attributes,
rp.gtin,
rp.mapped_data,
rp.feed_field_sources,
rp.feed_id,
f.name AS feed_name,
f.last_synced_at AS feed_last_synced_at,
@@ -1401,6 +1404,7 @@ func (s *Service) GetRawProduct(ctx context.Context, companyID, id uuid.UUID) (m
"id", "product_id", "name", "category", "category_name", "category_unique_id",
"description", "processed_name", "processed_description",
"status", "attributes", "processed_attributes", "gtin", "mapped_data",
"feed_field_sources",
"feed_id", "feed_name", "feed_last_synced_at", "raw_updated_at",
"has_processed_name", "has_processed_description", "has_attributes", "has_processed_attributes",
"has_eprel",
+356
View File
@@ -0,0 +1,356 @@
package feeds
import (
"encoding/json"
"fmt"
"html"
"regexp"
"sort"
"strings"
"github.com/google/uuid"
)
// Cross-feed merge.
//
// A product (company + EAN) can appear in several vendor feeds, each with partial data.
// Every feed keeps its own row (raw_product_feed_rows); raw_products.mapped_data is the
// merge of all of them and raw_products.feed_field_sources records which feed supplied
// each field.
//
// Rules:
// - A field that only one feed has is taken as is.
// - description / long_description: the feed with the most text wins.
// - image lists (more_images, …): union of every feed, duplicates removed.
// - specifications: union of the keys of every feed.
// - Any other field present in several feeds with different values is a conflict;
// the richest feed (most filled fields) wins and the others are listed as "also".
// feedRowInput is one feed's mapped data for a single EAN.
type feedRowInput struct {
FeedID uuid.UUID
FeedName string
Mapped map[string]any
}
// sourceRef identifies a feed in the field-source map.
type sourceRef struct {
FeedID string `json:"feed_id"`
FeedName string `json:"feed_name"`
}
// fieldSource says where one merged field came from.
type fieldSource struct {
FeedID string `json:"feed_id"`
FeedName string `json:"feed_name"`
Conflict bool `json:"conflict,omitempty"`
Also []sourceRef `json:"also,omitempty"` // other feeds that had a different value
MergedBy []sourceRef `json:"merged_from,omitempty"` // lists/specs: every contributing feed
Keys map[string]string `json:"keys,omitempty"` // specifications: key -> feed name
}
// feedFieldSources is stored in raw_products.feed_field_sources.
type feedFieldSources struct {
Primary sourceRef `json:"primary"` // richest feed; becomes raw_products.feed_id
Feeds []sourceRef `json:"feeds"`
Fields map[string]fieldSource `json:"fields"`
}
var (
listFieldKeys = map[string]bool{
"more_images": true, "moreimages": true, "images": true,
"additional_image_urls": true, "additional_image_link": true,
}
descriptionFieldKeys = map[string]bool{"description": true, "long_description": true}
htmlTagRe = regexp.MustCompile(`(?s)<[^>]*>`)
spaceRe = regexp.MustCompile(`\s+`)
listSplitRe = regexp.MustCompile(`[,;\n\r|]+`)
)
func filledValue(v any) bool {
switch t := v.(type) {
case nil:
return false
case string:
s := strings.TrimSpace(t)
return s != "" && s != "<nil>"
case map[string]any:
return len(t) > 0
case map[string]string:
return len(t) > 0
case []any:
return len(t) > 0
default:
return true
}
}
func normalizedValue(v any) string {
switch t := v.(type) {
case string:
return strings.ToLower(spaceRe.ReplaceAllString(strings.TrimSpace(t), " "))
default:
b, err := json.Marshal(t)
if err != nil {
return fmt.Sprint(t)
}
return strings.ToLower(string(b))
}
}
// plainTextLen measures description richness without HTML markup.
func plainTextLen(v any) int {
s, ok := v.(string)
if !ok {
return 0
}
s = htmlTagRe.ReplaceAllString(s, " ")
s = html.UnescapeString(s)
return len([]rune(strings.TrimSpace(spaceRe.ReplaceAllString(s, " "))))
}
func asStringMap(v any) (map[string]any, bool) {
switch t := v.(type) {
case map[string]any:
return t, true
case map[string]string:
out := make(map[string]any, len(t))
for k, val := range t {
out[k] = val
}
return out, true
}
return nil, false
}
func rowFilledCount(m map[string]any) int {
n := 0
for k, v := range m {
if k == syncChangesMappedKey {
continue
}
if specs, ok := asStringMap(v); ok && k == "specifications" {
n += len(specs)
continue
}
if filledValue(v) {
n++
}
}
return n
}
func descriptionLen(m map[string]any) int {
best := 0
for k := range descriptionFieldKeys {
if n := plainTextLen(m[k]); n > best {
best = n
}
}
return best
}
func splitList(v any) []string {
s, ok := v.(string)
if !ok {
return nil
}
var out []string
for _, part := range listSplitRe.Split(s, -1) {
if p := strings.TrimSpace(part); p != "" {
out = append(out, p)
}
}
return out
}
// mergeFeedRows merges the per-feed mapped data of one EAN. The result never mutates
// its inputs. With a single row it returns a copy plus a source map naming that feed.
func mergeFeedRows(rows []feedRowInput) (map[string]any, feedFieldSources) {
merged := map[string]any{}
src := feedFieldSources{Feeds: []sourceRef{}, Fields: map[string]fieldSource{}}
if len(rows) == 0 {
return merged, src
}
// Richest feed first: most filled fields, then longest description, then a stable
// tiebreak so repeated syncs always produce the same result.
ordered := append([]feedRowInput(nil), rows...)
sort.SliceStable(ordered, func(i, j int) bool {
a, b := ordered[i], ordered[j]
if ca, cb := rowFilledCount(a.Mapped), rowFilledCount(b.Mapped); ca != cb {
return ca > cb
}
if da, db := descriptionLen(a.Mapped), descriptionLen(b.Mapped); da != db {
return da > db
}
return a.FeedID.String() < b.FeedID.String()
})
ref := func(r feedRowInput) sourceRef {
return sourceRef{FeedID: r.FeedID.String(), FeedName: r.FeedName}
}
src.Primary = ref(ordered[0])
keySet := map[string]struct{}{}
for _, r := range ordered {
for k := range r.Mapped {
if k != syncChangesMappedKey {
keySet[k] = struct{}{}
}
}
}
keys := make([]string, 0, len(keySet))
for k := range keySet {
keys = append(keys, k)
}
sort.Strings(keys)
contributed := map[string]bool{}
for _, key := range keys {
lk := strings.ToLower(key)
var holders []feedRowInput
for _, r := range ordered {
if filledValue(r.Mapped[key]) {
holders = append(holders, r)
}
}
if len(holders) == 0 {
continue
}
winner := holders[0]
switch {
case lk == "specifications":
specs := map[string]any{}
keyFeed := map[string]string{}
var contributors []sourceRef
seenFeed := map[string]bool{}
var rawBlob feedRowInput
var haveBlob bool
for _, r := range holders {
m, ok := asStringMap(r.Mapped[key])
if !ok {
if !haveBlob {
rawBlob, haveBlob = r, true
}
continue
}
for sk, sv := range m {
if !filledValue(sv) {
continue
}
if _, exists := specs[sk]; exists {
continue
}
specs[sk] = sv
keyFeed[sk] = r.FeedName
if !seenFeed[r.FeedID.String()] {
seenFeed[r.FeedID.String()] = true
contributors = append(contributors, ref(r))
}
}
}
if len(specs) == 0 && haveBlob {
merged[key] = rawBlob.Mapped[key]
src.Fields[key] = fieldSource{FeedID: ref(rawBlob).FeedID, FeedName: rawBlob.FeedName}
contributed[rawBlob.FeedID.String()] = true
continue
}
merged[key] = specs
first := contributors[0]
fs := fieldSource{FeedID: first.FeedID, FeedName: first.FeedName, Keys: keyFeed}
if len(contributors) > 1 {
fs.MergedBy = contributors
}
src.Fields[key] = fs
for _, c := range contributors {
contributed[c.FeedID] = true
}
case listFieldKeys[lk] && len(holders) == 1:
// Only one feed has the list: keep it byte-for-byte so single-feed
// products are never rewritten (and reprocessed) by the merge.
merged[key] = winner.Mapped[key]
src.Fields[key] = fieldSource{FeedID: ref(winner).FeedID, FeedName: winner.FeedName}
contributed[winner.FeedID.String()] = true
case listFieldKeys[lk]:
seen := map[string]bool{}
var list []string
var contributors []sourceRef
seenFeed := map[string]bool{}
for _, r := range holders {
for _, item := range splitList(r.Mapped[key]) {
norm := strings.ToLower(item)
if seen[norm] {
continue
}
seen[norm] = true
list = append(list, item)
if !seenFeed[r.FeedID.String()] {
seenFeed[r.FeedID.String()] = true
contributors = append(contributors, ref(r))
}
}
}
if len(list) == 0 {
continue
}
merged[key] = strings.Join(list, ",")
fs := fieldSource{FeedID: contributors[0].FeedID, FeedName: contributors[0].FeedName}
if len(contributors) > 1 {
fs.MergedBy = contributors
}
src.Fields[key] = fs
for _, c := range contributors {
contributed[c.FeedID] = true
}
default:
if descriptionFieldKeys[lk] {
// Most text wins; the richest-feed order breaks ties.
for _, r := range holders[1:] {
if plainTextLen(r.Mapped[key]) > plainTextLen(winner.Mapped[key]) {
winner = r
}
}
}
merged[key] = winner.Mapped[key]
fs := fieldSource{FeedID: ref(winner).FeedID, FeedName: winner.FeedName}
winNorm := normalizedValue(winner.Mapped[key])
for _, r := range holders {
if r.FeedID == winner.FeedID {
continue
}
if normalizedValue(r.Mapped[key]) != winNorm {
fs.Conflict = true
fs.Also = append(fs.Also, ref(r))
}
}
src.Fields[key] = fs
contributed[winner.FeedID.String()] = true
}
}
for _, r := range ordered {
if contributed[r.FeedID.String()] || len(ordered) == 1 {
src.Feeds = append(src.Feeds, ref(r))
}
}
return merged, src
}
// feedIDsOf lists the feeds that have a row for the EAN, for raw_products.feed_ids.
func feedIDsOf(rows []feedRowInput) []string {
ids := make([]string, 0, len(rows))
seen := map[string]bool{}
for _, r := range rows {
id := r.FeedID.String()
if !seen[id] {
seen[id] = true
ids = append(ids, id)
}
}
sort.Strings(ids)
return ids
}
@@ -0,0 +1,281 @@
package feeds
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
)
type mergeFixture struct {
ctx context.Context
pg *pgxpool.Pool
svc *Service
companyID uuid.UUID
dir string
}
func newMergeFixture(t *testing.T) *mergeFixture {
t.Helper()
dsn := strings.TrimSpace(os.Getenv("DATABASE_URL"))
if dsn == "" {
t.Skip("DATABASE_URL not set")
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
t.Cleanup(cancel)
pg, err := pgxpool.New(ctx, dsn)
if err != nil {
t.Fatal(err)
}
t.Cleanup(pg.Close)
companyID := uuid.New()
if _, err := pg.Exec(ctx, `INSERT INTO companies (id, name) VALUES ($1, $2)`, companyID, "merge-"+companyID.String()[:8]); err != nil {
t.Fatalf("seed company: %v", err)
}
t.Cleanup(func() { _, _ = pg.Exec(context.Background(), `DELETE FROM companies WHERE id = $1`, companyID) })
dir := t.TempDir()
if err := os.MkdirAll(filepath.Join(dir, companyID.String()), 0o755); err != nil {
t.Fatal(err)
}
return &mergeFixture{ctx: ctx, pg: pg, svc: &Service{Pool: pg, UploadDir: dir}, companyID: companyID, dir: dir}
}
// addFeed creates a CSV feed whose columns are mapped to the given canonical fields.
func (f *mergeFixture) addFeed(t *testing.T, name string, columns map[string]string) uuid.UUID {
t.Helper()
rel := f.companyID.String() + "/" + strings.ReplaceAll(strings.ToLower(name), " ", "-") + ".csv"
opts, _ := json.Marshal(map[string]any{"source_path": rel})
var feedID uuid.UUID
if err := f.pg.QueryRow(f.ctx, `
INSERT INTO input_feeds (company_id, name, url, feed_type, status, sync_interval_minutes, options)
VALUES ($1, $2, '', 'csv', 'active', 60, $3::jsonb) RETURNING id`, f.companyID, name, string(opts)).Scan(&feedID); err != nil {
t.Fatalf("seed feed: %v", err)
}
var mappings []map[string]string
for src, tgt := range columns {
mappings = append(mappings, map[string]string{"source": src, "target": tgt})
}
mb, _ := json.Marshal(mappings)
if _, err := f.pg.Exec(f.ctx, `INSERT INTO feed_mappings (feed_id, company_id, mappings) VALUES ($1, $2, $3::jsonb)`,
feedID, f.companyID, string(mb)); err != nil {
t.Fatalf("seed mapping: %v", err)
}
return feedID
}
func (f *mergeFixture) writeCSV(t *testing.T, name string, lines ...string) {
t.Helper()
p := filepath.Join(f.dir, f.companyID.String(), strings.ReplaceAll(strings.ToLower(name), " ", "-")+".csv")
if err := os.WriteFile(p, []byte(strings.Join(lines, "\n")+"\n"), 0o644); err != nil {
t.Fatal(err)
}
}
type rawState struct {
Mapped map[string]any
FeedID uuid.UUID
FeedIDs []string
Sources feedFieldSources
Status string
}
func (f *mergeFixture) raw(t *testing.T, gtin string) rawState {
t.Helper()
var st rawState
var mapped, ids, src []byte
if err := f.pg.QueryRow(f.ctx, `
SELECT mapped_data, feed_id, COALESCE(feed_ids, '[]'::jsonb), COALESCE(feed_field_sources, '{}'::jsonb), processing_status
FROM raw_products WHERE company_id = $1 AND gtin = $2`, f.companyID, gtin).Scan(&mapped, &st.FeedID, &ids, &src, &st.Status); err != nil {
t.Fatalf("load raw %s: %v", gtin, err)
}
_ = json.Unmarshal(mapped, &st.Mapped)
_ = json.Unmarshal(ids, &st.FeedIDs)
_ = json.Unmarshal(src, &st.Sources)
return st
}
func (f *mergeFixture) sync(t *testing.T, feedID uuid.UUID) time.Duration {
t.Helper()
start := time.Now()
if _, err := f.svc.Sync(f.ctx, f.companyID, feedID); err != nil {
t.Fatalf("sync: %v", err)
}
return time.Since(start)
}
func TestSyncMergesSameEANAcrossFeeds(t *testing.T) {
f := newMergeFixture(t)
const ean = "4548736180307"
longDesc := strings.Repeat("Sony Bravia 4K z Google TV in HDR10 z 20 W zvokom. ", 12)
vendorA := f.addFeed(t, "Vendor A", map[string]string{
"EAN": "gtin", "Name": "name", "Brand": "brand", "Desc": "description", "Price": "price",
})
vendorB := f.addFeed(t, "Vendor B", map[string]string{
"EAN": "gtin", "Title": "name", "Description": "description", "Image": "main_image",
"More": "more_images", "EPREL": "eprel_id",
})
// 1) Vendor A alone: thin data.
f.writeCSV(t, "Vendor A", "EAN,Name,Brand,Desc,Price", ean+",Sony TV 65,Sony,Kratek opis.,560")
f.sync(t, vendorA)
st := f.raw(t, ean)
if st.FeedID != vendorA || st.Mapped["description"] != "Kratek opis." {
t.Fatalf("after A: feed=%v mapped=%v", st.FeedID, st.Mapped)
}
// Pretend the product was already processed, to prove a content change resets it.
if _, err := f.pg.Exec(f.ctx, `UPDATE raw_products SET is_processed = true, processing_status = 'processed' WHERE company_id = $1 AND gtin = $2`, f.companyID, ean); err != nil {
t.Fatal(err)
}
if _, err := f.pg.Exec(f.ctx, `INSERT INTO processed_products (company_id, raw_product_id, product_id, name) SELECT company_id, id, gtin, 'x' FROM raw_products WHERE company_id = $1 AND gtin = $2`, f.companyID, ean); err != nil {
t.Fatal(err)
}
// 2) Vendor B brings the description, images and EPREL id.
f.writeCSV(t, "Vendor B",
"EAN,Title,Description,Image,More,EPREL",
ean+",TV SONY K65,"+longDesc+",https://img/main.jpg,https://img/1.jpg;https://img/2.jpg,2651553")
f.sync(t, vendorB)
st = f.raw(t, ean)
if got := st.Mapped["description"]; !strings.Contains(fmt.Sprint(got), "Google TV") {
t.Fatalf("richest description did not win: %v", got)
}
for k, want := range map[string]string{
"brand": "Sony", "price": "560", "main_image": "https://img/main.jpg", "eprel_id": "2651553",
"name": "TV SONY K65", // Vendor B has more filled fields (5 vs 4), so it wins the conflicting name
} {
if st.Mapped[k] != want {
t.Errorf("merged %s = %v, want %q", k, st.Mapped[k], want)
}
}
if len(st.FeedIDs) != 2 {
t.Errorf("feed_ids = %v, want both feeds", st.FeedIDs)
}
if st.FeedID != vendorB {
t.Errorf("owner feed = %v, want richest feed B", st.FeedID)
}
if st.Sources.Primary.FeedName != "Vendor B" || st.Sources.Fields["name"].FeedName != "Vendor B" ||
len(st.Sources.Fields["name"].Also) != 1 || st.Sources.Fields["name"].Also[0].FeedName != "Vendor A" {
t.Errorf("name conflict not recorded: primary=%+v name=%+v", st.Sources.Primary, st.Sources.Fields["name"])
}
if st.Sources.Fields["description"].FeedName != "Vendor B" || !st.Sources.Fields["description"].Conflict {
t.Errorf("description source = %+v", st.Sources.Fields["description"])
}
if st.Sources.Fields["eprel_id"].FeedName != "Vendor B" || st.Sources.Fields["brand"].FeedName != "Vendor A" {
t.Errorf("sources = %+v", st.Sources.Fields)
}
if n := f.count(t, `SELECT count(*) FROM raw_product_feed_rows WHERE company_id = $1 AND gtin = $2`, ean); n != 2 {
t.Errorf("feed rows = %d, want 2", n)
}
if st.Status != "unprocessed" {
t.Errorf("changed content must reset processing, got %q", st.Status)
}
if n := f.count(t, `SELECT count(*) FROM processed_products WHERE company_id = $1`, ""); n != 0 {
t.Errorf("stale processed_products row survived: %d", n)
}
// 3) The regression the old code had: Vendor A re-syncs with a new price and must
// NOT wipe what Vendor B contributed.
f.writeCSV(t, "Vendor A", "EAN,Name,Brand,Desc,Price", ean+",Sony TV 65,Sony,Kratek opis.,499")
f.sync(t, vendorA)
st = f.raw(t, ean)
if st.Mapped["price"] != "499" {
t.Errorf("price update from A lost: %v", st.Mapped["price"])
}
if st.Mapped["eprel_id"] != "2651553" || st.Mapped["main_image"] != "https://img/main.jpg" ||
!strings.Contains(fmt.Sprint(st.Mapped["description"]), "Google TV") {
t.Errorf("Vendor B data lost after Vendor A re-sync: %v", st.Mapped)
}
// 4) Re-syncing unchanged data is stable (no flip-flopping between feeds).
f.writeCSV(t, "Vendor B",
"EAN,Title,Description,Image,More,EPREL",
ean+",TV SONY K65,"+longDesc+",https://img/main.jpg,https://img/1.jpg;https://img/2.jpg,2651553 ")
f.sync(t, vendorB)
again := f.raw(t, ean)
if again.FeedID != vendorB || fmt.Sprint(again.Mapped) != fmt.Sprint(st.Mapped) {
t.Errorf("unchanged re-sync altered product:\nbefore=%v\nafter=%v", st.Mapped, again.Mapped)
}
// A product only one feed carries is untouched by the merge.
f.writeCSV(t, "Vendor A", "EAN,Name,Brand,Desc,Price",
ean+",Sony TV 65,Sony,Kratek opis.,499", "9999999999994,Solo,Acme,Samo A,1")
f.sync(t, vendorA)
solo := f.raw(t, "9999999999994")
if solo.Mapped["name"] != "Solo" || len(solo.FeedIDs) != 1 || solo.FeedID != vendorA {
t.Errorf("single-feed product wrong: %+v", solo)
}
}
func (f *mergeFixture) count(t *testing.T, q, gtin string) int {
t.Helper()
var n int
var err error
if gtin == "" {
err = f.pg.QueryRow(f.ctx, q, f.companyID).Scan(&n)
} else {
err = f.pg.QueryRow(f.ctx, q, f.companyID, gtin).Scan(&n)
}
if err != nil {
t.Fatal(err)
}
return n
}
// TestSyncMergeTiming measures how long a resync takes with merging. Run with
// MERGE_TIMING_N=20000 for a bigger catalog; defaults to 5000 EANs per feed.
func TestSyncMergeTiming(t *testing.T) {
if os.Getenv("MERGE_TIMING") == "" {
t.Skip("set MERGE_TIMING=1 to run")
}
f := newMergeFixture(t)
n := 5000
if v, err := strconv.Atoi(os.Getenv("MERGE_TIMING_N")); err == nil && v > 0 {
n = v
}
a := f.addFeed(t, "Vendor A", map[string]string{"EAN": "gtin", "Name": "name", "Brand": "brand", "Desc": "description"})
b := f.addFeed(t, "Vendor B", map[string]string{"EAN": "gtin", "Title": "name", "Description": "description", "Image": "main_image", "EPREL": "eprel_id"})
var la, lb []string
la = append(la, "EAN,Name,Brand,Desc")
lb = append(lb, "EAN,Title,Description,Image,EPREL")
for i := 0; i < n; i++ {
ean := fmt.Sprintf("%013d", 4000000000000+i)
la = append(la, fmt.Sprintf("%s,Product %d,Brand,Short %d", ean, i, i))
if i%2 == 0 { // half of the catalog is carried by both vendors
lb = append(lb, fmt.Sprintf("%s,Product %d full,%s,https://img/%d.jpg,%d", ean, i,
strings.Repeat("Long enriched description. ", 20), i, 1000000+i))
}
}
f.writeCSV(t, "Vendor A", la...)
f.writeCSV(t, "Vendor B", lb...)
d1 := f.sync(t, a)
d2 := f.sync(t, b)
// Change every price/name so the resync is a full content update, not a hash skip.
for i := range la[1:] {
la[i+1] += "!"
}
f.writeCSV(t, "Vendor A", la...)
d3 := f.sync(t, a)
d4 := f.sync(t, a) // identical file: content-hash skip
t.Logf("EANs per feed: A=%d B=%d (overlap=%d)", n, len(lb)-1, len(lb)-1)
t.Logf("first sync A: %v (%.0f rows/s)", d1, float64(n)/d1.Seconds())
t.Logf("first sync B (merge): %v (%.0f rows/s)", d2, float64(len(lb)-1)/d2.Seconds())
t.Logf("changed resync A: %v (%.0f rows/s)", d3, float64(n)/d3.Seconds())
t.Logf("unchanged resync A: %v", d4)
merged := f.count(t, `SELECT count(*) FROM raw_products WHERE company_id = $1 AND jsonb_array_length(COALESCE(feed_ids,'[]'::jsonb)) = 2`, "")
if merged != len(lb)-1 {
t.Fatalf("merged products = %d, want %d", merged, len(lb)-1)
}
}
+101
View File
@@ -0,0 +1,101 @@
package feeds
import (
"context"
"encoding/json"
"github.com/google/uuid"
)
const upsertFeedRowsSQL = `
INSERT INTO raw_product_feed_rows (company_id, gtin, feed_id, raw_data, mapped_data, content_hash)
SELECT $1, v.gtin, $2, v.raw_data::jsonb, v.mapped_data::jsonb, v.content_hash
FROM unnest($3::text[], $4::text[], $5::text[], $6::text[]) AS v(gtin, raw_data, mapped_data, content_hash)
ON CONFLICT (company_id, gtin, feed_id) DO UPDATE SET
raw_data = EXCLUDED.raw_data,
mapped_data = EXCLUDED.mapped_data,
content_hash = EXCLUDED.content_hash,
updated_at = now()
WHERE raw_product_feed_rows.content_hash IS DISTINCT FROM EXCLUDED.content_hash`
// mergeChunkAcrossFeeds stores this feed's row for every EAN in the chunk, loads the
// rows other feeds hold for the same EANs, and rewrites each pending product's
// MappedData with the merge of all of them. It also fills the field-source metadata
// that upsertChunk writes to raw_products. A product only this feed carries is left
// exactly as the feed produced it.
func (s *Service) mergeChunkAcrossFeeds(ctx context.Context, companyID, feedID uuid.UUID, chunk []pendingProduct) error {
if len(chunk) == 0 {
return nil
}
gtins := make([]string, len(chunk))
rawCol := make([]string, len(chunk))
mappedCol := make([]string, len(chunk))
hashCol := make([]string, len(chunk))
for i, p := range chunk {
gtins[i] = p.GTIN
rb, err := json.Marshal(p.RawData)
if err != nil {
return err
}
mb, err := json.Marshal(stripSyncChanges(p.MappedData))
if err != nil {
return err
}
rawCol[i], mappedCol[i], hashCol[i] = string(rb), string(mb), p.ContentHash
}
if _, err := s.Pool.Exec(ctx, upsertFeedRowsSQL, companyID, feedID, gtins, rawCol, mappedCol, hashCol); err != nil {
return err
}
// Rows other feeds hold for these EANs.
rows, err := s.Pool.Query(ctx, `
SELECT r.gtin, r.feed_id, COALESCE(f.name, ''), r.mapped_data
FROM raw_product_feed_rows r
JOIN input_feeds f ON f.id = r.feed_id AND f.company_id = r.company_id
WHERE r.company_id = $1 AND r.gtin = ANY($2::text[]) AND r.feed_id <> $3`, companyID, gtins, feedID)
if err != nil {
return err
}
defer rows.Close()
others := map[string][]feedRowInput{}
for rows.Next() {
var gtin, name string
var fid uuid.UUID
var raw []byte
if err := rows.Scan(&gtin, &fid, &name, &raw); err != nil {
return err
}
var mapped map[string]any
if err := json.Unmarshal(raw, &mapped); err != nil || mapped == nil {
continue
}
others[gtin] = append(others[gtin], feedRowInput{FeedID: fid, FeedName: name, Mapped: mapped})
}
if err := rows.Err(); err != nil {
return err
}
var thisFeedName string
if err := s.Pool.QueryRow(ctx, `SELECT COALESCE(name, '') FROM input_feeds WHERE id = $1 AND company_id = $2`,
feedID, companyID).Scan(&thisFeedName); err != nil {
return err
}
for i := range chunk {
p := &chunk[i]
all := append([]feedRowInput{{FeedID: feedID, FeedName: thisFeedName, Mapped: p.MappedData}}, others[p.GTIN]...)
merged, sources := mergeFeedRows(all)
if len(all) > 1 {
merged["gtin"] = p.GTIN
p.MappedData = merged
}
if sb, err := json.Marshal(sources); err == nil {
p.Sources = string(sb)
}
if ib, err := json.Marshal(feedIDsOf(all)); err == nil {
p.FeedIDsJSON = string(ib)
}
p.PrimaryFeed = sources.Primary.FeedID
}
return nil
}
+186
View File
@@ -0,0 +1,186 @@
package feeds
import (
"strings"
"testing"
"github.com/google/uuid"
)
var (
feedA = uuid.MustParse("00000000-0000-0000-0000-00000000000a")
feedB = uuid.MustParse("00000000-0000-0000-0000-00000000000b")
feedC = uuid.MustParse("00000000-0000-0000-0000-00000000000c")
)
func TestMergeFeedRows_nonConflictingFieldsAreCombined(t *testing.T) {
a := feedRowInput{FeedID: feedA, FeedName: "Vendor A", Mapped: map[string]any{
"gtin": "4548736180307", "name": "Sony TV 65", "brand": "Sony",
}}
b := feedRowInput{FeedID: feedB, FeedName: "Vendor B", Mapped: map[string]any{
"gtin": "4548736180307", "main_image": "https://img/x.jpg", "eprel_id": "2651553",
}}
got, src := mergeFeedRows([]feedRowInput{a, b})
for k, want := range map[string]string{
"name": "Sony TV 65", "brand": "Sony", "main_image": "https://img/x.jpg", "eprel_id": "2651553",
} {
if got[k] != want {
t.Errorf("%s = %v, want %q", k, got[k], want)
}
}
if src.Fields["eprel_id"].FeedName != "Vendor B" || src.Fields["brand"].FeedName != "Vendor A" {
t.Errorf("wrong sources: %+v", src.Fields)
}
if src.Fields["name"].Conflict {
t.Error("a field only one feed has must not be a conflict")
}
if len(src.Feeds) != 2 {
t.Errorf("feeds = %v, want both feeds", src.Feeds)
}
}
func TestMergeFeedRows_longestDescriptionWins(t *testing.T) {
short := feedRowInput{FeedID: feedA, FeedName: "A", Mapped: map[string]any{
"name": "TV", "brand": "Sony", "stock": "5", "price": "9", "description": "Short.",
}}
long := feedRowInput{FeedID: feedB, FeedName: "B", Mapped: map[string]any{
"name": "TV", "description": "<p>" + strings.Repeat("Ostra 4K slika z Google TV in HDR. ", 20) + "</p>",
}}
got, src := mergeFeedRows([]feedRowInput{short, long})
if !strings.Contains(got["description"].(string), "Google TV") {
t.Fatalf("richer description lost: %v", got["description"])
}
if src.Fields["description"].FeedName != "B" || !src.Fields["description"].Conflict {
t.Errorf("description source = %+v", src.Fields["description"])
}
// Feed A has more fields overall, so it stays primary for ordinary fields.
if src.Primary.FeedName != "A" {
t.Errorf("primary = %v, want A", src.Primary)
}
}
func TestMergeFeedRows_htmlMarkupDoesNotCountAsRichness(t *testing.T) {
markup := feedRowInput{FeedID: feedA, FeedName: "A", Mapped: map[string]any{
"description": "<div><p><span><b>Hi</b></span></p></div>" + strings.Repeat("<br/>", 50),
}}
text := feedRowInput{FeedID: feedB, FeedName: "B", Mapped: map[string]any{
"description": "A genuinely longer plain sentence about the product.",
}}
got, _ := mergeFeedRows([]feedRowInput{markup, text})
if got["description"] != text.Mapped["description"] {
t.Errorf("markup-heavy but text-poor description won: %v", got["description"])
}
}
func TestMergeFeedRows_conflictRichestFeedWinsAndAlsoListed(t *testing.T) {
rich := feedRowInput{FeedID: feedA, FeedName: "A", Mapped: map[string]any{
"name": "Sony Bravia 65", "brand": "Sony", "color": "bela",
}}
poor := feedRowInput{FeedID: feedB, FeedName: "B", Mapped: map[string]any{"name": "TV SONY"}}
got, src := mergeFeedRows([]feedRowInput{poor, rich}) // input order must not matter
if got["name"] != "Sony Bravia 65" {
t.Fatalf("name = %v", got["name"])
}
fs := src.Fields["name"]
if !fs.Conflict || len(fs.Also) != 1 || fs.Also[0].FeedName != "B" {
t.Errorf("name source = %+v", fs)
}
}
func TestMergeFeedRows_sameValueDifferentCaseIsNotConflict(t *testing.T) {
a := feedRowInput{FeedID: feedA, FeedName: "A", Mapped: map[string]any{"brand": "Sony", "x": "1"}}
b := feedRowInput{FeedID: feedB, FeedName: "B", Mapped: map[string]any{"brand": " SONY "}}
_, src := mergeFeedRows([]feedRowInput{a, b})
if src.Fields["brand"].Conflict {
t.Errorf("equal values flagged as conflict: %+v", src.Fields["brand"])
}
}
func TestMergeFeedRows_emptyValuesNeverWin(t *testing.T) {
a := feedRowInput{FeedID: feedA, FeedName: "A", Mapped: map[string]any{"brand": " ", "name": "TV", "x": "1", "y": "2"}}
b := feedRowInput{FeedID: feedB, FeedName: "B", Mapped: map[string]any{"brand": "Sony"}}
got, src := mergeFeedRows([]feedRowInput{a, b})
if got["brand"] != "Sony" || src.Fields["brand"].FeedName != "B" {
t.Errorf("brand = %v from %+v", got["brand"], src.Fields["brand"])
}
}
func TestMergeFeedRows_imagesAreUnioned(t *testing.T) {
a := feedRowInput{FeedID: feedA, FeedName: "A", Mapped: map[string]any{
"more_images": "https://i/1.jpg,https://i/2.jpg", "name": "x", "brand": "y",
}}
b := feedRowInput{FeedID: feedB, FeedName: "B", Mapped: map[string]any{
"more_images": "https://i/2.jpg\nhttps://i/3.jpg",
}}
got, src := mergeFeedRows([]feedRowInput{a, b})
if got["more_images"] != "https://i/1.jpg,https://i/2.jpg,https://i/3.jpg" {
t.Errorf("more_images = %v", got["more_images"])
}
if len(src.Fields["more_images"].MergedBy) != 2 {
t.Errorf("merged_from = %+v", src.Fields["more_images"].MergedBy)
}
}
func TestMergeFeedRows_singleFeedListKeptVerbatim(t *testing.T) {
a := feedRowInput{FeedID: feedA, FeedName: "A", Mapped: map[string]any{
"more_images": "https://i/1.jpg https://i/2.jpg",
}}
got, _ := mergeFeedRows([]feedRowInput{a})
if got["more_images"] != "https://i/1.jpg https://i/2.jpg" {
t.Errorf("single-feed list was rewritten: %q", got["more_images"])
}
}
func TestMergeFeedRows_specificationsUnionPrimaryWinsOnKeyClash(t *testing.T) {
a := feedRowInput{FeedID: feedA, FeedName: "A", Mapped: map[string]any{
"name": "TV", "brand": "Sony",
"specifications": map[string]string{"diagonal": "65\"", "color": "bela"},
}}
b := feedRowInput{FeedID: feedB, FeedName: "B", Mapped: map[string]any{
"specifications": map[string]any{"diagonal": "164 cm", "hdmi": "4", "empty": ""},
}}
got, src := mergeFeedRows([]feedRowInput{a, b})
specs := got["specifications"].(map[string]any)
if specs["diagonal"] != "65\"" || specs["hdmi"] != "4" || specs["color"] != "bela" {
t.Errorf("specs = %v", specs)
}
if _, ok := specs["empty"]; ok {
t.Error("empty spec value must be dropped")
}
fs := src.Fields["specifications"]
if fs.Keys["hdmi"] != "B" || fs.Keys["diagonal"] != "A" || len(fs.MergedBy) != 2 {
t.Errorf("spec sources = %+v", fs)
}
}
func TestMergeFeedRows_deterministicRegardlessOfOrder(t *testing.T) {
mk := func(id uuid.UUID, n string) feedRowInput {
return feedRowInput{FeedID: id, FeedName: n, Mapped: map[string]any{"name": n + " name", "brand": n}}
}
rows := []feedRowInput{mk(feedC, "C"), mk(feedA, "A"), mk(feedB, "B")}
first, _ := mergeFeedRows(rows)
rev := []feedRowInput{rows[2], rows[1], rows[0]}
second, _ := mergeFeedRows(rev)
if first["name"] != second["name"] || first["brand"] != second["brand"] {
t.Errorf("order-dependent merge: %v vs %v", first, second)
}
}
func TestMergeFeedRows_doesNotMutateInputs(t *testing.T) {
a := feedRowInput{FeedID: feedA, FeedName: "A", Mapped: map[string]any{"name": "TV", "_sync_changes": []any{"new"}}}
b := feedRowInput{FeedID: feedB, FeedName: "B", Mapped: map[string]any{"brand": "Sony"}}
merged, _ := mergeFeedRows([]feedRowInput{a, b})
if _, ok := merged[syncChangesMappedKey]; ok {
t.Error("_sync_changes must not be merged")
}
if _, ok := a.Mapped["brand"]; ok {
t.Error("input row mutated")
}
}
func TestMergeFeedRows_empty(t *testing.T) {
got, src := mergeFeedRows(nil)
if len(got) != 0 || len(src.Fields) != 0 {
t.Errorf("got %v %v", got, src)
}
}
+56 -14
View File
@@ -38,6 +38,10 @@ type pendingProduct struct {
RawData map[string]string
MappedData map[string]any
ContentHash string
// Cross-feed merge result (primary locale only); empty means "leave as is".
Sources string // raw_products.feed_field_sources JSON
FeedIDsJSON string // raw_products.feed_ids JSON array
PrimaryFeed string // richest feed, becomes raw_products.feed_id
}
// Sync downloads the feed URL, parses CSV/XML, applies mappings, and upserts raw_products
@@ -468,34 +472,50 @@ const (
upsertSQLInsertSet = `
INSERT INTO raw_products (
company_id, gtin, feed_id, raw_data, mapped_data, sync_job_id,
is_processed, processing_status, updated_at, source_localizations
is_processed, processing_status, updated_at, source_localizations,
feed_ids, feed_field_sources
)
SELECT $1, v.gtin, $2, v.raw_data::jsonb, v.mapped_data::jsonb, $3, false, 'unprocessed', now(),
jsonb_build_object($7::text, v.mapped_data::jsonb)
FROM unnest($4::text[], $5::text[], $6::text[]) AS v(gtin, raw_data, mapped_data)
SELECT $1, v.gtin, COALESCE(NULLIF(v.primary_feed, '')::uuid, $2), v.raw_data::jsonb, v.mapped_data::jsonb, $3, false, 'unprocessed', now(),
jsonb_build_object($7::text, v.mapped_data::jsonb),
NULLIF(v.feed_ids, '')::jsonb, NULLIF(v.sources, '')::jsonb
FROM unnest($4::text[], $5::text[], $6::text[], $9::text[], $10::text[], $11::text[])
AS v(gtin, raw_data, mapped_data, primary_feed, feed_ids, sources)
ON CONFLICT (company_id, gtin) DO UPDATE SET
feed_id = EXCLUDED.feed_id,
raw_data = CASE WHEN $8 THEN EXCLUDED.raw_data ELSE raw_products.raw_data END,
mapped_data = CASE WHEN $8 THEN EXCLUDED.mapped_data ELSE raw_products.mapped_data END,
source_localizations = jsonb_set(COALESCE(raw_products.source_localizations,'{}'::jsonb),ARRAY[$7::text],EXCLUDED.mapped_data,true),
feed_ids = CASE WHEN $8 AND EXCLUDED.feed_ids IS NOT NULL THEN EXCLUDED.feed_ids ELSE raw_products.feed_ids END,
feed_field_sources = CASE WHEN $8 AND EXCLUDED.feed_field_sources IS NOT NULL THEN EXCLUDED.feed_field_sources ELSE raw_products.feed_field_sources END,
sync_job_id = EXCLUDED.sync_job_id,
is_processed = CASE WHEN $8 THEN false ELSE raw_products.is_processed END,
processing_status = CASE WHEN $8 THEN 'unprocessed' ELSE raw_products.processing_status END,
updated_at = now()`
// Touch: content unchanged, but the owning feed / contributing feeds / field
// sources may still have changed (another feed was added), so refresh those.
upsertSQLTouchSet = `
UPDATE raw_products SET sync_job_id = $3, feed_id = $4, updated_at = now()
WHERE company_id = $1 AND id = ANY($2::uuid[])`
UPDATE raw_products AS r SET
sync_job_id = $3,
feed_id = COALESCE(NULLIF(v.primary_feed, '')::uuid, $4),
feed_ids = CASE WHEN v.feed_ids <> '' THEN v.feed_ids::jsonb ELSE r.feed_ids END,
feed_field_sources = CASE WHEN v.sources <> '' THEN v.sources::jsonb ELSE r.feed_field_sources END,
updated_at = now()
FROM unnest($2::uuid[], $5::text[], $6::text[], $7::text[]) AS v(id, primary_feed, feed_ids, sources)
WHERE r.company_id = $1 AND r.id = v.id`
upsertSQLUpdateSet = `
UPDATE raw_products AS r SET
feed_id = $2,
feed_id = COALESCE(NULLIF(v.primary_feed, '')::uuid, $2),
raw_data = CASE WHEN $8 THEN v.raw_data::jsonb ELSE r.raw_data END,
mapped_data = CASE WHEN $8 THEN v.mapped_data::jsonb ELSE r.mapped_data END,
source_localizations = jsonb_set(COALESCE(r.source_localizations,'{}'::jsonb),ARRAY[$7::text],v.mapped_data::jsonb,true),
feed_ids = CASE WHEN $8 AND v.feed_ids <> '' THEN v.feed_ids::jsonb ELSE r.feed_ids END,
feed_field_sources = CASE WHEN $8 AND v.sources <> '' THEN v.sources::jsonb ELSE r.feed_field_sources END,
sync_job_id = $3,
is_processed = CASE WHEN $8 THEN false ELSE r.is_processed END,
processing_status = CASE WHEN $8 THEN 'unprocessed' ELSE r.processing_status END,
updated_at = now()
FROM unnest($4::uuid[], $5::text[], $6::text[]) AS v(id, raw_data, mapped_data)
FROM unnest($4::uuid[], $5::text[], $6::text[], $9::text[], $10::text[], $11::text[])
AS v(id, raw_data, mapped_data, primary_feed, feed_ids, sources)
WHERE r.id = v.id AND r.company_id = $1`
)
@@ -514,6 +534,10 @@ type upsertOp struct {
rawJSON []byte
mappedJSON []byte
changes []string
// Cross-feed merge metadata (empty when the merge did not run).
primaryFeed string
feedIDs string
sources string
}
// classifyUpsertOps decides insert / touch / update per row without DB I/O so a chunk
@@ -539,7 +563,8 @@ func classifyUpsertOps(chunk []pendingProduct, existing map[string]existingProdu
}
ops = append(ops, upsertOp{
kind: upsertOpInsert, gtin: p.GTIN, rawJSON: rawJSON, mappedJSON: mappedJSON,
changes: []string{"new"},
changes: []string{"new"},
primaryFeed: p.PrimaryFeed, feedIDs: p.FeedIDsJSON, sources: p.Sources,
})
continue
}
@@ -562,7 +587,10 @@ func classifyUpsertOps(chunk []pendingProduct, existing map[string]existingProdu
continue
}
if bytesEqualJSON(stripSyncChangesBytes(existingMapped), plainJSON) {
ops = append(ops, upsertOp{kind: upsertOpTouch, id: ex.ID})
ops = append(ops, upsertOp{
kind: upsertOpTouch, id: ex.ID,
primaryFeed: p.PrimaryFeed, feedIDs: p.FeedIDsJSON, sources: p.Sources,
})
continue
}
changes := detectMappedChanges(existingMapped, cleanMapped)
@@ -574,7 +602,8 @@ func classifyUpsertOps(chunk []pendingProduct, existing map[string]existingProdu
}
ops = append(ops, upsertOp{
kind: upsertOpUpdate, id: ex.ID, rawJSON: rawJSON, mappedJSON: mappedJSON,
changes: changes,
changes: changes,
primaryFeed: p.PrimaryFeed, feedIDs: p.FeedIDsJSON, sources: p.Sources,
})
}
return ops, skipped
@@ -651,6 +680,13 @@ func (s *Service) upsertChunk(ctx context.Context, companyID, feedID, jobID uuid
if !ok {
locale = syncLocale{code: company.LoadLanguage(ctx, s.Pool, companyID), primary: true}
}
// Several vendor feeds can carry the same EAN: store this feed's row and merge all
// feeds' data before comparing against the existing product.
if locale.primary {
if err := s.mergeChunkAcrossFeeds(ctx, companyID, feedID, chunk); err != nil {
return 0, 0, 0, deltas, err
}
}
ops, skipped := classifyUpsertOps(chunk, existing, locale)
if len(ops) == 0 {
deltas.Skipped = skipped
@@ -664,34 +700,40 @@ func (s *Service) upsertChunk(ctx context.Context, companyID, feedID, jobID uuid
gtinCol := make([]string, len(inserts))
rawCol := make([]string, len(inserts))
mappedCol := make([]string, len(inserts))
primCol, idsCol, srcCol := make([]string, len(inserts)), make([]string, len(inserts)), make([]string, len(inserts))
for i, op := range inserts {
gtinCol[i] = op.gtin
rawCol[i] = string(op.rawJSON)
mappedCol[i] = string(op.mappedJSON)
primCol[i], idsCol[i], srcCol[i] = op.primaryFeed, op.feedIDs, op.sources
deltas.addChanges(op.changes)
}
batch.Queue(upsertSQLInsertSet, companyID, feedID, jobID, gtinCol, rawCol, mappedCol, locale.code, locale.primary)
batch.Queue(upsertSQLInsertSet, companyID, feedID, jobID, gtinCol, rawCol, mappedCol, locale.code, locale.primary, primCol, idsCol, srcCol)
queued++
}
if len(touches) > 0 {
ids := make([]uuid.UUID, len(touches))
primCol, idsCol, srcCol := make([]string, len(touches)), make([]string, len(touches)), make([]string, len(touches))
for i, op := range touches {
ids[i] = op.id
primCol[i], idsCol[i], srcCol[i] = op.primaryFeed, op.feedIDs, op.sources
}
batch.Queue(upsertSQLTouchSet, companyID, ids, jobID, feedID)
batch.Queue(upsertSQLTouchSet, companyID, ids, jobID, feedID, primCol, idsCol, srcCol)
queued++
}
if len(updates) > 0 {
ids := make([]uuid.UUID, len(updates))
rawCol := make([]string, len(updates))
mappedCol := make([]string, len(updates))
primCol, idsCol, srcCol := make([]string, len(updates)), make([]string, len(updates)), make([]string, len(updates))
for i, op := range updates {
ids[i] = op.id
rawCol[i] = string(op.rawJSON)
mappedCol[i] = string(op.mappedJSON)
primCol[i], idsCol[i], srcCol[i] = op.primaryFeed, op.feedIDs, op.sources
deltas.addChanges(op.changes)
}
batch.Queue(upsertSQLUpdateSet, companyID, feedID, jobID, ids, rawCol, mappedCol, locale.code, locale.primary)
batch.Queue(upsertSQLUpdateSet, companyID, feedID, jobID, ids, rawCol, mappedCol, locale.code, locale.primary, primCol, idsCol, srcCol)
queued++
}
+4 -9
View File
@@ -290,15 +290,10 @@ func TestUpsertSQLIsSetBased(t *testing.T) {
"update": upsertSQLUpdateSet,
} {
lower := strings.ToLower(sql)
switch name {
case "insert", "update":
if !strings.Contains(lower, "unnest(") {
t.Fatalf("%s missing unnest: %s", name, sql)
}
case "touch":
if !strings.Contains(lower, "any(") {
t.Fatalf("touch missing ANY: %s", sql)
}
// Touch also joins through unnest now: it refreshes the owning feed and the
// per-field sources of every touched row in one statement.
if !strings.Contains(lower, "unnest(") {
t.Fatalf("%s missing unnest: %s", name, sql)
}
if strings.Contains(lower, "values ($1") {
t.Fatalf("%s still per-row VALUES form", name)
@@ -0,0 +1,36 @@
-- +goose Up
-- One row per (company, EAN, feed): the feed's own mapped data, kept separately so a
-- product that appears in several vendor feeds can be merged instead of the last
-- synced feed overwriting the others. raw_products.mapped_data stays the merged view.
CREATE TABLE IF NOT EXISTS raw_product_feed_rows (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
company_id UUID NOT NULL REFERENCES companies(id) ON DELETE CASCADE,
gtin TEXT NOT NULL,
feed_id UUID NOT NULL REFERENCES input_feeds(id) ON DELETE CASCADE,
raw_data JSONB NOT NULL DEFAULT '{}'::jsonb,
mapped_data JSONB NOT NULL DEFAULT '{}'::jsonb,
content_hash TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (company_id, gtin, feed_id)
);
CREATE INDEX IF NOT EXISTS raw_product_feed_rows_company_gtin_idx
ON raw_product_feed_rows (company_id, gtin);
CREATE INDEX IF NOT EXISTS raw_product_feed_rows_feed_idx
ON raw_product_feed_rows (feed_id);
-- Which feed supplied each merged field: {"feeds":[…],"fields":{"description":{…}}}.
ALTER TABLE raw_products ADD COLUMN IF NOT EXISTS feed_field_sources JSONB;
-- Existing products were written by exactly one feed (raw_products.feed_id); keep that
-- feed's data as its row so the first sync of another feed merges with it.
INSERT INTO raw_product_feed_rows (company_id, gtin, feed_id, raw_data, mapped_data)
SELECT company_id, gtin, feed_id, COALESCE(raw_data, '{}'::jsonb), COALESCE(mapped_data, '{}'::jsonb) - '_sync_changes'
FROM raw_products
WHERE feed_id IS NOT NULL
ON CONFLICT (company_id, gtin, feed_id) DO NOTHING;
-- +goose Down
ALTER TABLE raw_products DROP COLUMN IF EXISTS feed_field_sources;
DROP TABLE IF EXISTS raw_product_feed_rows;
@@ -31,6 +31,7 @@
productAttributeDiff,
productFeedFieldSummary,
productFeedMappedEntries,
productFeedSources,
productFeedSyncLabel,
productHasEprel,
productHasSpecs,
@@ -506,6 +507,7 @@
const enrichment = $derived.by(() => (product ? productEnrichmentStates(product) : null));
const feedFields = $derived.by(() => productFeedFieldSummary(product, categories));
const feedMapped = $derived.by(() => productFeedMappedEntries(product, categories));
const feedSources = $derived.by(() => productFeedSources(product));
const feedSync = $derived.by(() => (product ? productFeedSyncLabel(product) : ""));
const feedFilledCount = $derived(feedMapped.filter((f) => f.ok).length);
const coverageCount = $derived(
@@ -1171,6 +1173,14 @@
when: formatRelativeUpdated(product?.feed_last_synced_at) || i18n.t("products.edit.neverRecorded")
})}
</p>
{#if feedSources && feedSources.feeds.length > 1}
<p class="mt-0.5 text-xs font-medium text-foreground">
{i18n.t("products.edit.mergedFromFeeds", {
count: feedSources.feeds.length,
names: feedSources.feeds.join(", ")
})}
</p>
{/if}
</div>
<p class="text-xs text-muted-foreground">
{i18n.t("products.edit.feedFilledCount", { filled: feedFilledCount, total: feedMapped.length })}
@@ -1201,6 +1211,20 @@
{:else if field.preferred}
<span class="text-[11px] text-muted-foreground">{i18n.t("products.edit.core")}</span>
{/if}
{#if field.source && field.source.feedName}
<div class="mt-0.5 text-[11px] text-primary" data-testid="field-source">
{#if field.source.mergedFrom.length > 1}
{i18n.t("products.edit.fieldCombinedFrom", { names: field.source.mergedFrom.join(", ") })}
{:else}
{i18n.t("products.edit.fieldFromFeed", { name: field.source.feedName })}
{/if}
</div>
{#if field.source.conflict && field.source.also.length > 0}
<div class="text-[11px] text-chart-amber">
{i18n.t("products.edit.fieldAlsoIn", { names: field.source.also.join(", ") })}
</div>
{/if}
{/if}
</td>
<td class="px-3 py-2.5">
{#if field.multiline}
+63 -1
View File
@@ -117,6 +117,8 @@ export type ProductRow = {
attributes?: unknown;
processed_attributes?: unknown;
mapped_data?: unknown;
/** Which feed supplied each merged field; see productFeedSources(). */
feed_field_sources?: unknown;
/** Precomputed first image URL on lean list rows (see catalog.listMainImageSQL). */
main_image?: string | null;
has_name?: boolean | null;
@@ -545,12 +547,70 @@ export function productFeedFieldSummary(
}
/** Which feed supplied one merged field (from raw_products.feed_field_sources). */
export type FeedFieldSourceInfo = {
feedName: string;
/** Another feed had a different value; this feed's value won. */
conflict: boolean;
/** Names of the feeds whose different value lost. */
also: string[];
/** Lists / specifications built from several feeds. */
mergedFrom: string[];
/** specifications: spec key -> feed name. */
keys: Record<string, string>;
};
export type FeedSourcesSummary = {
/** Feeds that contributed at least one field, richest first. */
feeds: string[];
fields: Record<string, FeedFieldSourceInfo>;
};
function sourceNames(raw: unknown): string[] {
if (!Array.isArray(raw)) return [];
const out: string[] = [];
for (const item of raw) {
const rec = asRecord(item);
const name = typeof rec?.feed_name === "string" ? rec.feed_name.trim() : "";
if (name && !out.includes(name)) out.push(name);
}
return out;
}
/** Per-field feed attribution for a product merged from one or more feeds, or null. */
export function productFeedSources(
product: ProductRow | null | undefined
): FeedSourcesSummary | null {
const root = asRecord(product?.feed_field_sources);
const rawFields = asRecord(root?.fields);
if (!root || !rawFields) return null;
const fields: Record<string, FeedFieldSourceInfo> = {};
for (const [key, value] of Object.entries(rawFields)) {
const rec = asRecord(value);
if (!rec) continue;
const keys: Record<string, string> = {};
for (const [k, v] of Object.entries(asRecord(rec.keys) ?? {})) {
if (typeof v === "string") keys[k] = v;
}
fields[key.toLowerCase()] = {
feedName: typeof rec.feed_name === "string" ? rec.feed_name : "",
conflict: rec.conflict === true,
also: sourceNames(rec.also),
mergedFrom: sourceNames(rec.merged_from),
keys
};
}
return { feeds: sourceNames(root.feeds), fields };
}
export type FeedMappedEntry = {
key: string;
value: string;
ok: boolean;
preferred: boolean;
multiline: boolean;
/** Set when the product was merged and the feed that supplied this field is known. */
source?: FeedFieldSourceInfo;
};
/** Full mapped_data inventory for the Feed tab (preferred keys first, then A–Z). */
@@ -560,6 +620,7 @@ export function productFeedMappedEntries(
): FeedMappedEntry[] {
const mapped = asRecord(product?.mapped_data);
if (!mapped) return [];
const sources = productFeedSources(product);
const preferred = [
"name",
"title",
@@ -592,7 +653,8 @@ export function productFeedMappedEntries(
value: formatted || "—",
ok: formatted.trim() !== "",
preferred: preferredRank.has(key.toLowerCase()),
multiline
multiline,
source: formatted.trim() !== "" ? sources?.fields[key.toLowerCase()] : undefined
};
});
}
+4
View File
@@ -5109,6 +5109,10 @@ export const en: MessageDict = {
"products.edit.feedSource": "Feed source",
"products.edit.updatedRelative": "· updated {when}",
"products.edit.viewAllFeedFields": "View all feed fields ({filled}/{total})",
"products.edit.mergedFromFeeds": "Merged from {count} feeds: {names}",
"products.edit.fieldFromFeed": "from {name}",
"products.edit.fieldAlsoIn": "also in {names} (different value, not used)",
"products.edit.fieldCombinedFrom": "combined from {names}",
"products.edit.productIdentity": "Product identity",
"products.edit.images": "Images",
"products.edit.imageAlt": "Product image {index}: {name}",
+4
View File
@@ -123,6 +123,10 @@ export const sl: MessageDict = {
"products.edit.metaNotGenerated": "ni ustvarjeno",
"products.edit.metaLengthHint": "naslov 50-60 / opis 120-155 znakov",
"products.edit.seoMetaDisabled": "Ni v uporabi",
"products.edit.mergedFromFeeds": "Združeno iz {count} virov: {names}",
"products.edit.fieldFromFeed": "iz vira {name}",
"products.edit.fieldAlsoIn": "tudi v {names} (drugačna vrednost, ni uporabljena)",
"products.edit.fieldCombinedFrom": "združeno iz {names}",
"products.edit.seoMetaDisabledHint": "SEO meta je za to podjetje izklopljen, zato ga obdelava ne ustvari.",
"categories.promptSection.translatedExample": "Preveden primer",
"categories.promptSection.useExample": "Uporabi primer",