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")
}
}
@@ -24,6 +24,8 @@ import {
sortFeedListRows,
statusBadgeLabel,
statusBadgeTone,
syncJobDiagnostic,
syncJobDisplayStatus,
syncJobProductsLabel,
syncJobStatusTone,
type FeedListRow
@@ -117,6 +119,31 @@ describe("syncJobStatusTone", () => {
});
});
describe("sync history diagnostics", () => {
it("marks historical all-skipped completed jobs as invalid", () => {
const bad = { status: "completed", products_synced: 0, products_unchanged: 0, products_total: 127, products_skipped: 127 };
assert.equal(syncJobDisplayStatus(bad), "skipped all");
assert.match(syncJobDiagnostic(bad), /All 127 rows were skipped/);
assert.match(syncJobStatusTone(syncJobDisplayStatus(bad)), /destructive/);
});
it("shows backend skip details for failed and partial jobs", () => {
const failed = { status: "failed", error: "Missing GTIN in rows 1, 2" };
assert.equal(syncJobDisplayStatus(failed), "failed");
assert.equal(syncJobDiagnostic(failed), failed.error);
const partial = { status: "completed", products_synced: 10, products_total: 12, products_skipped: 2, error: "2 rows missing GTIN" };
assert.equal(syncJobDisplayStatus(partial), "partial");
assert.equal(syncJobDiagnostic(partial), partial.error);
assert.match(syncJobStatusTone(syncJobDisplayStatus(partial)), /amber/);
});
it("a successful identical feed reports unchanged products, not zero", () => {
const ok = { status: "completed", products_synced: 0, products_total: 127, products_unchanged: 127 };
assert.equal(syncJobDisplayStatus(ok), "completed");
assert.equal(syncJobProductsLabel(ok), "0 / 127 · 127 unchanged");
});
});
describe("syncJobProductsLabel", () => {
it("formats synced/total and optional deltas", () => {
assert.equal(syncJobProductsLabel({ products_synced: 3 }), "3");
+29 -2
View File
@@ -23,6 +23,8 @@ export type FeedListRow = {
};
export type FeedSyncJobLike = {
status?: string | null;
error?: string | null;
products_synced?: number | null;
products_total?: number | null;
products_skipped?: number | null;
@@ -143,15 +145,40 @@ export function sortFeedListRows(
return [...list].sort((a, b) => compareFeedListRows(a, b, field, direction));
}
/** Report historical bad 0/N completed syncs as a problem, never a success. */
export function syncJobDisplayStatus(job: FeedSyncJobLike): string {
const status = String(job.status ?? "unknown").toLowerCase();
if (status === "completed" && Number(job.products_synced ?? 0) === 0 &&
Number(job.products_unchanged ?? 0) === 0) {
if (Number(job.products_skipped ?? 0) > 0) return "skipped all";
return "empty";
}
if (status === "completed" && Number(job.products_skipped ?? 0) > 0) return "partial";
return status;
}
export function syncJobDiagnostic(job: FeedSyncJobLike): string {
const explicit = String(job.error ?? "").trim();
if (explicit) return explicit;
const status = syncJobDisplayStatus(job);
if (status === "skipped all") {
return `All ${Number(job.products_skipped ?? 0)} rows were skipped. Check that GTIN is mapped and the source CSV header is recognized.`;
}
if (status === "empty") {
return "No products were imported. Check the CSV source and field mappings.";
}
return "";
}
export function syncJobStatusTone(status: string | null | undefined): string {
const s = String(status ?? "").toLowerCase();
if (s === "completed" || s === "success" || s === "ok") {
return "border-chart-green/40 bg-card-green text-foreground";
}
if (s === "failed" || s === "error") {
if (s === "failed" || s === "error" || s === "skipped all" || s === "empty") {
return "border-destructive/40 bg-card-red text-foreground";
}
if (s === "running" || s === "pending" || s === "queued" || s === "processing") {
if (s === "partial" || s === "running" || s === "pending" || s === "queued" || s === "processing") {
return "border-chart-amber/50 bg-chart-amber/15 text-foreground";
}
return "border-border bg-muted text-foreground";
+29 -5
View File
@@ -74,6 +74,8 @@
nextSortState,
parseSyncIntervalMinutes,
sortFeedListRows,
syncJobDiagnostic,
syncJobDisplayStatus,
syncJobProductsLabel,
syncJobStatusTone
} from "$lib/feeds-list-controls";
@@ -686,7 +688,29 @@
notifyError(error, { alert: "sync_fail" });
return;
}
const diagnostic = syncJobDiagnostic(job);
const displayStatus = syncJobDisplayStatus(job);
if (displayStatus === "skipped all" || displayStatus === "empty") {
error = diagnostic || i18n.t("feeds.syncFailed");
notifyError(error, {
alert: "sync_fail",
actions: [{ label: i18n.t("feeds.mapFields"), href: `/feeds/${id}/mapping` }]
});
await load();
return;
}
const products = syncJobProductsLabel(job);
if (diagnostic) {
// Valid rows were imported; do not show a contradictory full-success toast.
success = i18n.t("flash.feed.syncFinishedNamed", {
name: feed.name ?? id,
status: "partial",
products
});
notifyError(diagnostic, { alert: "sync_partial" });
await load();
return;
}
success = i18n.t("flash.feed.syncFinishedNamed", { name: feed.name ?? id, status, products });
notifySuccess(i18n.t("toast.feed.syncFinished"), {
alert: "sync_done",
@@ -1385,12 +1409,12 @@
{#each historyJobs as job (job.id)}
<TableRow>
<TableCell>
<Badge variant="outline" class={`capitalize ${syncJobStatusTone(job.status)}`}>
{job.status ?? "—"}
<Badge variant="outline" class={`capitalize ${syncJobStatusTone(syncJobDisplayStatus(job))}`}>
{syncJobDisplayStatus(job)}
</Badge>
{#if job.error}
<p class="mt-1 max-w-xs truncate text-xs text-destructive" title={String(job.error)}>
{job.error}
{#if syncJobDiagnostic(job)}
<p class="mt-1 max-w-sm whitespace-normal break-words text-xs text-destructive">
{syncJobDiagnostic(job)}
</p>
{/if}
</TableCell>