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

+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) {