This commit is contained in:
greeneclipse committed 2026-10-14 16:54:39 +02:00
1 parent 176b1fe47f
commit 3bfeb6b61e
8 files changed
+264 -32

No files matched your search

+1 -1
View File
@@ -340,7 +340,7 @@ func extractCSVSchema(data []byte) ([]SchemaField, int, string, error) {
}
cols := make([]string, len(header))
for i, h := range header {
cols[i] = strings.TrimSpace(h)
cols[i] = strings.TrimSpace(strings.TrimPrefix(h, "\uFEFF"))
}
acc := map[string]*fieldAcc{}
+1 -2
View File
@@ -123,7 +123,6 @@ func parseMappings(raw any) []FieldMapping {
}
}
// fieldMappingFromUIEntry unwraps dashboard rows shaped like
// {"key":"Export/Item/ID","mapping":{"fieldName":"id","xpath":"Export/Item/ID"}}.
func fieldMappingFromUIEntry(item any) (FieldMapping, bool) {
@@ -262,7 +261,7 @@ func normalizeSpecKeys(in map[string]string) map[string]string {
}
func lookupRow(row map[string]string, key string) (string, bool) {
key = strings.Trim(strings.TrimSpace(key), "/")
key = strings.Trim(strings.TrimSpace(strings.TrimPrefix(key, "\uFEFF")), "/")
if key == "" {
return "", false
}
+1 -1
View File
@@ -64,7 +64,7 @@ func parseCSV(r io.Reader, onRow func(feedRow) error) (int, error) {
}
cols := make([]string, len(header))
for i, h := range header {
cols[i] = strings.TrimSpace(h)
cols[i] = strings.TrimSpace(strings.TrimPrefix(h, "\uFEFF"))
}
count := 0
for {
+98 -21
View File
@@ -7,6 +7,8 @@ import (
"encoding/json"
"errors"
"io"
"sort"
"strconv"
"strings"
"github.com/google/uuid"
@@ -22,8 +24,12 @@ type syncStats struct {
Unchanged int
Progress int
ContentHash string
MappingHash string
UnchangedFeed bool
Deltas syncDeltaCounts
MissingGTIN int
MissingRows []int
SourceColumns []string
}
type pendingProduct struct {
@@ -180,9 +186,10 @@ func (s *Service) persistFeedSyncMeta(ctx context.Context, companyID, feedID, jo
UPDATE input_feeds SET last_synced_at = now(), updated_at = now(),
options = COALESCE(options, '{}'::jsonb) || jsonb_build_object(
'last_content_hash', to_jsonb($2::text),
'last_mapping_hash', to_jsonb($5::text),
'last_sync_deltas', $3::jsonb
)
WHERE id = $1 AND company_id = $4`, feedID, stats.ContentHash, deltaJSON, companyID)
WHERE id = $1 AND company_id = $4`, feedID, stats.ContentHash, deltaJSON, companyID, stats.MappingHash)
return err
}
@@ -276,14 +283,6 @@ func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUI
}
stats.ContentHash = hash
prev, _ := s.lastContentHash(ctx, feedID)
if prev != "" && prev == hash {
stats.UnchangedFeed = true
stats.Progress = 100
_ = s.updateJobProgress(ctx, jobID, stats)
return stats, nil
}
mappingsRaw, mapErr := s.loadMappingsRaw(ctx, companyID, feedID)
if mapErr != nil && !errors.Is(mapErr, pgx.ErrNoRows) {
return stats, mapErr
@@ -292,6 +291,28 @@ func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUI
if len(mappings) == 0 {
return stats, ClientMsg("no field mappings defined for feed")
}
stats.MappingHash = sha256Hex([]byte(mustJSON(mappingsRaw)))
prev, err := s.lastSuccessfulSync(ctx, feedID)
if err != nil {
return stats, err
}
previousMappingHash := ""
if opts, ok := feed["options"].(map[string]any); ok {
previousMappingHash, _ = opts["last_mapping_hash"].(string)
}
if prev.ContentHash != "" && prev.ContentHash == hash &&
previousMappingHash != "" && previousMappingHash == stats.MappingHash {
// Only bypass parsing if source AND mapping configuration match a valid
// previous sync. Legacy zero-import runs and changed mappings reprocess.
stats.UnchangedFeed = true
stats.Total = prev.Total
stats.Skipped = prev.Skipped
stats.Unchanged = prev.Total - prev.Skipped
stats.Progress = 100
_ = s.updateJobProgress(ctx, jobID, stats)
return stats, nil
}
itemPath := "item"
if path := itemPathFromMappings(mappingsRaw); path != "" {
@@ -349,6 +370,16 @@ func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUI
mapped, gtin := applyMappings(row, mappings)
if gtin == "" {
stats.Skipped++
stats.MissingGTIN++
if len(stats.MissingRows) < 5 {
stats.MissingRows = append(stats.MissingRows, stats.Total)
}
if len(stats.SourceColumns) == 0 {
for col := range row {
stats.SourceColumns = append(stats.SourceColumns, strings.TrimPrefix(col, "\uFEFF"))
}
sort.Strings(stats.SourceColumns)
}
return nil
}
rawCopy := make(map[string]string, len(row))
@@ -384,6 +415,9 @@ func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUI
if err := flush(true); err != nil {
return stats, err
}
if stats.Synced+stats.Unchanged == 0 {
return stats, ClientMsg(syncSkipDiagnostics(stats))
}
stats.Progress = 100
_ = s.updateJobProgress(ctx, jobID, stats)
return stats, nil
@@ -743,6 +777,10 @@ func (s *Service) updateJobProgress(ctx context.Context, jobID uuid.UUID, stats
}
func (s *Service) completeJob(ctx context.Context, jobID uuid.UUID, stats syncStats) error {
warning := ""
if stats.Skipped > 0 {
warning = syncSkipDiagnostics(stats)
}
_, err := s.Pool.Exec(ctx, `
UPDATE feed_sync_jobs SET
status = 'completed',
@@ -753,9 +791,10 @@ func (s *Service) completeJob(ctx context.Context, jobID uuid.UUID, stats syncSt
products_unchanged = $5,
progress = 100,
content_hash = NULLIF($6, ''),
error = NULLIF($7, ''),
updated_at = now()
WHERE id = $1`,
jobID, stats.Synced, stats.Total, stats.Skipped, stats.Unchanged, stats.ContentHash)
jobID, stats.Synced, stats.Total, stats.Skipped, stats.Unchanged, stats.ContentHash, truncateErr(warning))
return err
}
@@ -777,22 +816,60 @@ func (s *Service) failJob(ctx context.Context, jobID uuid.UUID, msg string, stat
return err
}
func (s *Service) lastContentHash(ctx context.Context, feedID uuid.UUID) (string, error) {
var hash *string
// lastSuccessfulSync only caches a file when at least one product was accepted.
// In particular, historical "completed 0 / 127 skipped" jobs must be reprocessed.
type syncedSourceSummary struct {
ContentHash string
Total int
Skipped int
}
func (s *Service) lastSuccessfulSync(ctx context.Context, feedID uuid.UUID) (syncedSourceSummary, error) {
var prev syncedSourceSummary
err := s.Pool.QueryRow(ctx, `
SELECT content_hash FROM feed_sync_jobs
WHERE feed_id = $1 AND status = 'completed' AND content_hash IS NOT NULL AND content_hash <> ''
ORDER BY completed_at DESC NULLS LAST LIMIT 1`, feedID).Scan(&hash)
SELECT content_hash, products_total, products_skipped FROM feed_sync_jobs
WHERE feed_id = $1 AND status = 'completed'
AND content_hash IS NOT NULL AND content_hash <> ''
AND products_total > 0
AND (products_synced > 0 OR products_unchanged > 0)
AND products_skipped = 0
ORDER BY completed_at DESC NULLS LAST LIMIT 1`, feedID).
Scan(&prev.ContentHash, &prev.Total, &prev.Skipped)
if errors.Is(err, pgx.ErrNoRows) {
return "", nil
return syncedSourceSummary{}, nil
}
if err != nil {
return "", err
return prev, err
}
// syncSkipDiagnostics is persisted in feed_sync_jobs.error and displayed in Sync History.
// It intentionally reports source columns and row numbers, not individual product data.
func syncSkipDiagnostics(stats syncStats) string {
if stats.Skipped == 0 {
return ""
}
if hash == nil {
return "", nil
msg := strconv.Itoa(stats.Skipped) + " of " + strconv.Itoa(stats.Total) + " product rows skipped."
if stats.MissingGTIN > 0 {
msg += " " + strconv.Itoa(stats.MissingGTIN) + " rows have no recognized GTIN."
msg += " Map an identifier column to GTIN or supply a non-empty gtin/ean/upc/barcode column."
if len(stats.MissingRows) > 0 {
rows := make([]string, len(stats.MissingRows))
for i, row := range stats.MissingRows {
rows[i] = strconv.Itoa(row)
}
msg += " Example data rows: " + strings.Join(rows, ", ") + "."
}
if len(stats.SourceColumns) > 0 {
cols := stats.SourceColumns
if len(cols) > 12 {
cols = cols[:12]
}
msg += " Source columns include: " + strings.Join(cols, ", ") + "."
}
}
return *hash, nil
if other := stats.Skipped - stats.MissingGTIN; other > 0 {
msg += " " + strconv.Itoa(other) + " rows could not be serialized for import."
}
return msg
}
func (s *Service) loadMappingsRaw(ctx context.Context, companyID, feedID uuid.UUID) (any, error) {
@@ -0,0 +1,78 @@
package feeds
import (
"strings"
"testing"
)
// Regression: Excel/UTF-8-SIG CSV headers include a BOM on the first column.
// This silently skipped every Grohe row (127/127) when the first column was gtin.
func TestParseCSVStripsUTF8BOMFromGTIN(t *testing.T) {
csvBody := "\ufeffgtin,sku,title\r\n4005176980640,32917KS0,Grohe Minta\r\n4005176980641,32917KS1,Grohe Test\r\n"
mappings := []FieldMapping{
{Source: "gtin", Target: "gtin"},
{Source: "title", Target: "title"},
}
var got []string
count, err := parseCSV(strings.NewReader(csvBody), func(row feedRow) error {
if _, hasBOM := row["\ufeffgtin"]; hasBOM {
t.Fatal("BOM was not removed from first CSV header")
}
mapped, gtin := applyMappings(row, mappings)
if mapped["title"] == "" || gtin == "" {
t.Fatalf("missing recognized mapped values: %v, gtin %q", mapped, gtin)
}
got = append(got, gtin)
return nil
})
if err != nil || count != 2 || len(got) != 2 || got[0] != "4005176980640" {
t.Fatalf("count=%d gtins=%v err=%v", count, got, err)
}
}
func TestCSVLegacySavedBOMMappingIsRecognized(t *testing.T) {
mapping := []FieldMapping{{Source: "\ufeffgtin", Target: "gtin"}}
_, err := parseCSV(strings.NewReader("\ufeffgtin,title\n4005176980640,Grohe\n"), func(row feedRow) error {
_, gtin := applyMappings(row, mapping)
if gtin != "4005176980640" {
t.Fatalf("legacy BOM mapping could not read normalized header: %q", gtin)
}
return nil
})
if err != nil {
t.Fatal(err)
}
}
func TestExtractCSVSchemaStripsUTF8BOM(t *testing.T) {
fields, rows, _, err := extractCSVSchema([]byte("\ufeffgtin,title\n4005176980640,Grohe\n"))
if err != nil || rows != 1 {
t.Fatalf("rows=%d err=%v", rows, err)
}
found := false
for _, field := range fields {
if strings.Contains(field.Path, "\ufeff") {
t.Fatalf("schema still exposes BOM: %q", field.Path)
}
if field.Path == "gtin" {
found = true
}
}
if !found {
t.Fatalf("GTIN absent from schema fields: %v", fields)
}
}
func TestSyncSkipDiagnosticsExplainsEmptyImport(t *testing.T) {
stats := syncStats{Total: 127, Skipped: 127, MissingGTIN: 127,
MissingRows: []int{1, 2, 3}, SourceColumns: []string{"sku", "title"}}
msg := syncSkipDiagnostics(stats)
for _, term := range []string{"127 of 127", "GTIN", "sku", "title", "1, 2, 3"} {
if !strings.Contains(msg, term) {
t.Fatalf("diagnostic %q missing %q", msg, term)
}
}
if syncSkipDiagnostics(syncStats{Total: 2}) != "" {
t.Fatal("no skipped rows should have no warning")
}
}