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) } }