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 != "" 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 }