strapi-plugin-bulk-updater 1.5.15 → 1.5.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -72,10 +72,11 @@ function parseCsvRows(csvText) {
72
72
  }
73
73
  return rows;
74
74
  }
75
- function parseCsv(csvText) {
75
+ function parseCsvWithHeaders(csvText) {
76
76
  const rows = parseCsvRows(csvText);
77
- if (rows.length < 2) return [];
77
+ if (rows.length === 0) return { headers: [], records: [] };
78
78
  const headers = rows[0].map((h) => h.trim());
79
+ if (rows.length < 2) return { headers, records: [] };
79
80
  const records = [];
80
81
  for (let i = 1; i < rows.length; i++) {
81
82
  const row = rows[i];
@@ -89,7 +90,125 @@ function parseCsv(csvText) {
89
90
  });
90
91
  records.push(record);
91
92
  }
92
- return records;
93
+ return { headers, records };
94
+ }
95
+ function escapeCsvCell(val) {
96
+ if (val === null || val === void 0) return "";
97
+ let str = "";
98
+ if (val instanceof Date) {
99
+ str = val.toISOString();
100
+ } else if (typeof val === "object") {
101
+ str = JSON.stringify(val);
102
+ } else {
103
+ str = String(val);
104
+ }
105
+ str = str.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
106
+ if (/^[=+@-]/.test(str)) {
107
+ str = `'${str}`;
108
+ }
109
+ if (str.includes(",") || str.includes('"') || str.includes("\n") || str.includes("\r")) {
110
+ return `"${str.replace(/"/g, '""')}"`;
111
+ }
112
+ return str;
113
+ }
114
+ function sanitizeUserErrorMessage(msg) {
115
+ if (msg === null || msg === void 0) return "Error processing row";
116
+ const raw = typeof msg === "string" ? msg : String(msg);
117
+ const cleanedLines = raw.split(/\r?\n/).filter((line) => !/^\s+at\s+.+(\(.+\)|:\d+:\d+)\s*$/.test(line)).map((line) => line.trim()).filter(Boolean);
118
+ return cleanedLines.join(" ").trim() || "Error processing row";
119
+ }
120
+ function resolveErrorColumnName(existingHeaders) {
121
+ const existingLower = new Set(
122
+ existingHeaders.map((h) => String(h || "").trim().toLowerCase())
123
+ );
124
+ if (!existingLower.has("error")) return "Error";
125
+ if (!existingLower.has("import error")) return "Import Error";
126
+ let suffix = 2;
127
+ while (existingLower.has(`import error (${suffix})`)) {
128
+ suffix++;
129
+ }
130
+ return `Import Error (${suffix})`;
131
+ }
132
+ function formatErrorCsvFilename(collectionTypeOrUid, date = /* @__PURE__ */ new Date()) {
133
+ const rawSegment = collectionTypeOrUid ? String(collectionTypeOrUid).split(".").pop() || String(collectionTypeOrUid) : "collection";
134
+ const safeType = rawSegment.replace(/[^a-zA-Z0-9_-]+/g, "_").replace(/^_+|_+$/g, "") || "collection";
135
+ const pad = (n) => String(n).padStart(2, "0");
136
+ const stamp = `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}_${pad(
137
+ date.getHours()
138
+ )}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
139
+ return `error_${safeType}_${stamp}.csv`;
140
+ }
141
+ function buildErrorCsv(options) {
142
+ const { headers, failedRows } = options || {};
143
+ if (!Array.isArray(failedRows) || failedRows.length === 0) {
144
+ return {
145
+ csvContent: "",
146
+ headers: headers ? [...headers] : [],
147
+ errorColumnName: "Error",
148
+ errorCount: 0
149
+ };
150
+ }
151
+ const groupedByRow = /* @__PURE__ */ new Map();
152
+ for (const item of failedRows) {
153
+ if (!item || typeof item !== "object") continue;
154
+ const rowNum = typeof item.row === "number" && !isNaN(item.row) ? item.row : groupedByRow.size + 2;
155
+ const msg = sanitizeUserErrorMessage(item.error);
156
+ const existing = groupedByRow.get(rowNum);
157
+ if (existing) {
158
+ if (!existing.messages.includes(msg)) {
159
+ existing.messages.push(msg);
160
+ }
161
+ } else {
162
+ groupedByRow.set(rowNum, {
163
+ row: rowNum,
164
+ documentId: item.documentId,
165
+ messages: [msg],
166
+ originalRow: item.originalRow && typeof item.originalRow === "object" ? item.originalRow : {}
167
+ });
168
+ }
169
+ }
170
+ const orderedEntries = Array.from(groupedByRow.values()).sort((a, b) => a.row - b.row);
171
+ if (orderedEntries.length === 0) {
172
+ return {
173
+ csvContent: "",
174
+ headers: headers ? [...headers] : [],
175
+ errorColumnName: "Error",
176
+ errorCount: 0
177
+ };
178
+ }
179
+ let baseHeaders = [];
180
+ if (Array.isArray(headers) && headers.length > 0) {
181
+ baseHeaders = [...headers];
182
+ } else {
183
+ const keySet = /* @__PURE__ */ new Set();
184
+ for (const entry of orderedEntries) {
185
+ for (const k of Object.keys(entry.originalRow || {})) {
186
+ if (!keySet.has(k)) {
187
+ keySet.add(k);
188
+ baseHeaders.push(k);
189
+ }
190
+ }
191
+ }
192
+ }
193
+ const errorColumnName = resolveErrorColumnName(baseHeaders);
194
+ const finalHeaders = [...baseHeaders, errorColumnName];
195
+ const lines = [];
196
+ lines.push(finalHeaders.map(escapeCsvCell).join(","));
197
+ for (const entry of orderedEntries) {
198
+ const cells = baseHeaders.map((h) => {
199
+ const val = entry.originalRow ? entry.originalRow[h] : "";
200
+ return escapeCsvCell(val === void 0 || val === null ? "" : val);
201
+ });
202
+ cells.push(escapeCsvCell(entry.messages.join("; ")));
203
+ lines.push(cells.join(","));
204
+ }
205
+ const csvContent = "\uFEFF" + lines.join("\r\n") + "\r\n";
206
+ return {
207
+ csvContent,
208
+ headers: finalHeaders,
209
+ errorColumnName,
210
+ errorCount: orderedEntries.length
211
+ };
93
212
  }
94
213
  const LIFECYCLE_STATUS_WORDS = /* @__PURE__ */ new Set([
95
214
  "pending review",
@@ -261,7 +380,7 @@ function CsvManagerTab() {
261
380
  const [selectedRuleId, setSelectedRuleId] = useState("");
262
381
  const [importMode, setImportMode] = useState("auto");
263
382
  const [publishOnImport, setPublishOnImport] = useState(true);
264
- const [csvRawText, setCsvRawText] = useState("");
383
+ const [originalHeaders, setOriginalHeaders] = useState([]);
265
384
  const [fileName, setFileName] = useState("");
266
385
  const [allParsedRecords, setAllParsedRecords] = useState([]);
267
386
  const [previewPage, setPreviewPage] = useState(1);
@@ -269,6 +388,8 @@ function CsvManagerTab() {
269
388
  const [importing, setImporting] = useState(false);
270
389
  const [importProgress, setImportProgress] = useState(null);
271
390
  const [importResult, setImportResult] = useState(null);
391
+ const [errorReport, setErrorReport] = useState(null);
392
+ const activeBatchIdRef = useRef(null);
272
393
  const [executionWindow, setExecutionWindow] = useState(null);
273
394
  const [preflightLoading, setPreflightLoading] = useState(false);
274
395
  const [preflightReport, setPreflightReport] = useState(null);
@@ -347,13 +468,15 @@ function CsvManagerTab() {
347
468
  if (countAbortControllerRef.current) {
348
469
  countAbortControllerRef.current.abort();
349
470
  }
471
+ activeBatchIdRef.current = null;
350
472
  setSelectedUid(newUid);
351
473
  setAllParsedRecords([]);
352
- setCsvRawText("");
474
+ setOriginalHeaders([]);
353
475
  setFileName("");
354
476
  setPreviewPage(1);
355
477
  setImportProgress(null);
356
478
  setImportResult(null);
479
+ setErrorReport(null);
357
480
  setPreflightReport(null);
358
481
  setPreflightLoading(false);
359
482
  setImporting(false);
@@ -565,43 +688,76 @@ function CsvManagerTab() {
565
688
  const handleFileUpload = (e) => {
566
689
  const file = e.target.files?.[0];
567
690
  if (!file) return;
691
+ activeBatchIdRef.current = null;
568
692
  setFileName(file.name);
569
693
  setImportResult(null);
570
694
  setImportProgress(null);
695
+ setPreflightReport(null);
696
+ setErrorReport(null);
697
+ setOriginalHeaders([]);
571
698
  const reader = new FileReader();
572
699
  reader.onload = (event) => {
573
700
  const text = event.target?.result;
574
- setCsvRawText(text);
575
701
  try {
576
- const records = parseCsv(text);
577
- const enriched = enrichCsvRowsWithLifecycle(records, collectionEntries);
578
- setAllParsedRecords(enriched);
702
+ const { headers, records } = parseCsvWithHeaders(text);
703
+ setOriginalHeaders(headers);
704
+ setAllParsedRecords(records);
579
705
  setPreviewPage(1);
580
706
  } catch (err) {
707
+ setOriginalHeaders([]);
581
708
  setAllParsedRecords([]);
582
709
  }
583
710
  };
584
711
  reader.readAsText(file);
585
712
  };
713
+ const handleDownloadErrorCsv = () => {
714
+ if (!errorReport || errorReport.uid !== selectedUid || errorReport.failedRows.length === 0) {
715
+ return;
716
+ }
717
+ const { csvContent } = buildErrorCsv({
718
+ headers: errorReport.headers,
719
+ failedRows: errorReport.failedRows
720
+ });
721
+ const targetType = selectedCol?.singularName || selectedUid;
722
+ const errFilename = formatErrorCsvFilename(targetType);
723
+ downloadCsvFile(csvContent, errFilename);
724
+ };
586
725
  const handleExecuteImport = async () => {
587
726
  if (!selectedUid || allParsedRecords.length === 0) return;
588
- let currentEntries = collectionEntries;
589
- if (currentEntries.length === 0) {
590
- currentEntries = await fetchAndEnrichEntries(selectedUid);
591
- }
592
- const enrichedRecords = enrichCsvRowsWithLifecycle(allParsedRecords, currentEntries);
593
- const totalRows = enrichedRecords.length;
594
- const CHUNK_SIZE = 100;
595
- const totalChunks = Math.ceil(totalRows / CHUNK_SIZE);
727
+ const runUid = selectedUid;
728
+ const runHeaders = originalHeaders;
729
+ const originalRecordsSnapshot = allParsedRecords;
596
730
  const batchId = `csv_batch_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`;
731
+ activeBatchIdRef.current = batchId;
597
732
  try {
598
733
  setImporting(true);
599
734
  setImportResult(null);
735
+ setErrorReport(null);
736
+ let currentEntries = collectionEntries;
737
+ if (currentEntries.length === 0) {
738
+ currentEntries = await fetchAndEnrichEntries(runUid);
739
+ }
740
+ if (activeBatchIdRef.current !== batchId) return;
741
+ const enrichedRecords = enrichCsvRowsWithLifecycle(originalRecordsSnapshot, currentEntries);
742
+ const totalRows = enrichedRecords.length;
743
+ const CHUNK_SIZE = 100;
744
+ const totalChunks = Math.ceil(totalRows / CHUNK_SIZE);
600
745
  let liveCreated = 0;
601
746
  let liveUpdated = 0;
602
747
  let liveSkipped = 0;
748
+ let liveNewWithoutDocId = 0;
603
749
  let liveErrors = 0;
604
750
  let finalResultData = null;
751
+ const accumulatedErrors = [];
752
+ const accumulatedFailedRows = [];
753
+ const accumulatedDiffs = [];
754
+ const mapOriginalRowForIndex = (rowNum, backendOrigRow) => {
755
+ const idx = typeof rowNum === "number" ? rowNum - 2 : -1;
756
+ if (idx >= 0 && idx < originalRecordsSnapshot.length) {
757
+ return originalRecordsSnapshot[idx];
758
+ }
759
+ return backendOrigRow && typeof backendOrigRow === "object" ? backendOrigRow : {};
760
+ };
605
761
  setImportProgress({
606
762
  currentChunk: 0,
607
763
  totalChunks,
@@ -614,53 +770,152 @@ function CsvManagerTab() {
614
770
  liveErrors: 0
615
771
  });
616
772
  for (let chunkIdx = 0; chunkIdx < totalChunks; chunkIdx++) {
773
+ if (activeBatchIdRef.current !== batchId) return;
617
774
  const startIdx = chunkIdx * CHUNK_SIZE;
618
775
  const endIdx = Math.min(startIdx + CHUNK_SIZE, totalRows);
619
776
  const chunkRows = enrichedRecords.slice(startIdx, endIdx);
620
777
  const isFirst = chunkIdx === 0;
621
778
  const isLast = chunkIdx === totalChunks - 1;
622
779
  const startRowNumber = startIdx + 2;
623
- const res = await post("/bulk-updater/csv/import-chunk", {
624
- uid: selectedUid,
625
- rows: chunkRows,
626
- batchId,
627
- isFirstChunk: isFirst,
628
- isLastChunk: isLast,
629
- startRowNumber,
630
- mode: importMode,
631
- publish: publishOnImport,
632
- publishStrategy,
633
- unreviewedConsent
634
- });
635
- if (!res.data || !res.data.success) {
636
- throw new Error(res.data?.error || `Chunk ${chunkIdx + 1} failed to process`);
637
- }
638
- const chunkStats = res.data.chunkStats;
639
- if (chunkStats) {
640
- liveCreated += chunkStats.created || 0;
641
- liveUpdated += chunkStats.updated || 0;
642
- liveSkipped += chunkStats.skipped || 0;
643
- liveErrors += chunkStats.errors?.length || 0;
644
- }
645
- const currentProgressPercent = Math.round((chunkIdx + 1) / totalChunks * 100);
646
- setImportProgress({
647
- currentChunk: chunkIdx + 1,
648
- totalChunks,
649
- percent: currentProgressPercent,
650
- processedRows: endIdx,
651
- totalRows,
652
- liveCreated,
653
- liveUpdated,
654
- liveSkipped,
655
- liveErrors
656
- });
657
- if (isLast) {
658
- finalResultData = res.data;
780
+ try {
781
+ const res = await post("/bulk-updater/csv/import-chunk", {
782
+ uid: runUid,
783
+ rows: chunkRows,
784
+ batchId,
785
+ isFirstChunk: isFirst,
786
+ isLastChunk: isLast,
787
+ startRowNumber,
788
+ mode: importMode,
789
+ publish: publishOnImport,
790
+ publishStrategy,
791
+ unreviewedConsent,
792
+ ...isFirst && runHeaders.length > 0 ? { originalHeaders: runHeaders } : {}
793
+ });
794
+ if (activeBatchIdRef.current !== batchId) return;
795
+ if (!res.data || !res.data.success) {
796
+ throw new Error(res.data?.error || `Chunk ${chunkIdx + 1} failed to process`);
797
+ }
798
+ const chunkStats = res.data.chunkStats;
799
+ if (chunkStats) {
800
+ liveCreated += chunkStats.created || 0;
801
+ liveUpdated += chunkStats.updated || 0;
802
+ liveSkipped += chunkStats.skipped || 0;
803
+ liveNewWithoutDocId += chunkStats.newWithoutDocId || 0;
804
+ liveErrors += chunkStats.errors?.length || 0;
805
+ if (Array.isArray(chunkStats.errors)) {
806
+ accumulatedErrors.push(...chunkStats.errors);
807
+ }
808
+ if (Array.isArray(chunkStats.failedRows) && chunkStats.failedRows.length > 0) {
809
+ for (const f of chunkStats.failedRows) {
810
+ accumulatedFailedRows.push({
811
+ row: f.row,
812
+ documentId: f.documentId,
813
+ error: f.error,
814
+ originalRow: mapOriginalRowForIndex(f.row, f.originalRow)
815
+ });
816
+ }
817
+ } else if (Array.isArray(chunkStats.errors) && chunkStats.errors.length > 0) {
818
+ for (const errItem of chunkStats.errors) {
819
+ accumulatedFailedRows.push({
820
+ row: errItem.row,
821
+ documentId: errItem.documentId,
822
+ error: errItem.error,
823
+ originalRow: mapOriginalRowForIndex(errItem.row)
824
+ });
825
+ }
826
+ }
827
+ if (Array.isArray(chunkStats.diffs)) {
828
+ accumulatedDiffs.push(...chunkStats.diffs);
829
+ }
830
+ }
831
+ const currentProgressPercent = Math.round((chunkIdx + 1) / totalChunks * 100);
832
+ setImportProgress({
833
+ currentChunk: chunkIdx + 1,
834
+ totalChunks,
835
+ percent: currentProgressPercent,
836
+ processedRows: endIdx,
837
+ totalRows,
838
+ liveCreated,
839
+ liveUpdated,
840
+ liveSkipped,
841
+ liveErrors
842
+ });
843
+ if (isLast) {
844
+ finalResultData = res.data;
845
+ }
846
+ } catch (chunkErr) {
847
+ if (isAbortError(chunkErr)) return;
848
+ if (activeBatchIdRef.current !== batchId) return;
849
+ const apiErrMsg = sanitizeUserErrorMessage(
850
+ chunkErr?.response?.data?.error?.message || chunkErr?.response?.data?.error || chunkErr?.message || `Chunk ${chunkIdx + 1} failed to process`
851
+ );
852
+ for (let j = startIdx; j < endIdx; j++) {
853
+ const rowNum = j + 2;
854
+ const rawRow = originalRecordsSnapshot[j] || {};
855
+ const rowDocId = extractDocId(rawRow) || void 0;
856
+ accumulatedErrors.push({
857
+ row: rowNum,
858
+ ...rowDocId ? { documentId: rowDocId } : {},
859
+ error: apiErrMsg
860
+ });
861
+ accumulatedFailedRows.push({
862
+ row: rowNum,
863
+ ...rowDocId ? { documentId: rowDocId } : {},
864
+ error: apiErrMsg,
865
+ originalRow: rawRow
866
+ });
867
+ liveSkipped++;
868
+ liveErrors++;
869
+ }
870
+ setImportResult({
871
+ success: false,
872
+ batchId,
873
+ stats: {
874
+ total: totalRows,
875
+ created: liveCreated,
876
+ updated: liveUpdated,
877
+ skipped: liveSkipped,
878
+ newWithoutDocId: liveNewWithoutDocId,
879
+ errors: accumulatedErrors,
880
+ diffs: accumulatedDiffs
881
+ }
882
+ });
883
+ if (accumulatedFailedRows.length > 0) {
884
+ setErrorReport({
885
+ uid: runUid,
886
+ batchId,
887
+ headers: runHeaders,
888
+ failedRows: accumulatedFailedRows
889
+ });
890
+ }
891
+ throw new Error(apiErrMsg);
659
892
  }
660
893
  }
894
+ if (activeBatchIdRef.current !== batchId) return;
661
895
  if (finalResultData && finalResultData.stats) {
662
896
  setImportResult(finalResultData);
663
897
  const stats = finalResultData.stats;
898
+ const finalFailedRows = accumulatedFailedRows.length > 0 ? accumulatedFailedRows : Array.isArray(stats.failedRows) && stats.failedRows.length > 0 ? stats.failedRows.map((f) => ({
899
+ row: f.row,
900
+ documentId: f.documentId,
901
+ error: f.error,
902
+ originalRow: mapOriginalRowForIndex(f.row, f.originalRow)
903
+ })) : Array.isArray(stats.errors) ? stats.errors.map((errItem) => ({
904
+ row: errItem.row,
905
+ documentId: errItem.documentId,
906
+ error: errItem.error,
907
+ originalRow: mapOriginalRowForIndex(errItem.row)
908
+ })) : [];
909
+ if (finalFailedRows.length > 0) {
910
+ setErrorReport({
911
+ uid: runUid,
912
+ batchId: finalResultData.batchId || batchId,
913
+ headers: runHeaders,
914
+ failedRows: finalFailedRows
915
+ });
916
+ } else {
917
+ setErrorReport(null);
918
+ }
664
919
  let notifMsg = `CSV Import complete: ${stats.created} created, ${stats.updated} updated across ${stats.total} records.`;
665
920
  if (stats.newWithoutDocId && stats.newWithoutDocId > 0) {
666
921
  notifMsg += ` (${stats.newWithoutDocId} new entries created due to omitted documentId)`;
@@ -677,7 +932,9 @@ function CsvManagerTab() {
677
932
  message: err.message || "Error processing CSV import batch"
678
933
  });
679
934
  } finally {
680
- setImporting(false);
935
+ if (activeBatchIdRef.current === batchId || activeBatchIdRef.current === null) {
936
+ setImporting(false);
937
+ }
681
938
  }
682
939
  };
683
940
  const handleRunPreflight = async () => {
@@ -1449,6 +1706,25 @@ function CsvManagerTab() {
1449
1706
  importResult.stats.errors.length - 10,
1450
1707
  " more error",
1451
1708
  importResult.stats.errors.length - 10 > 1 ? "s" : ""
1709
+ ] }),
1710
+ errorReport && errorReport.uid === selectedUid && (!importResult.batchId || errorReport.batchId === importResult.batchId) && errorReport.failedRows.length > 0 && /* @__PURE__ */ jsxs(Flex, { marginTop: 3, gap: 2, alignItems: "center", wrap: "wrap", children: [
1711
+ /* @__PURE__ */ jsxs(
1712
+ Button,
1713
+ {
1714
+ variant: "danger-light",
1715
+ size: "S",
1716
+ startIcon: /* @__PURE__ */ jsx(Download, {}),
1717
+ onClick: handleDownloadErrorCsv,
1718
+ children: [
1719
+ "Download Error CSV (",
1720
+ errorReport.failedRows.length.toLocaleString(),
1721
+ " failed row",
1722
+ errorReport.failedRows.length > 1 ? "s" : "",
1723
+ ")"
1724
+ ]
1725
+ }
1726
+ ),
1727
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: "Contains only failed rows with all original columns preserved and an Error column." })
1452
1728
  ] })
1453
1729
  ] }),
1454
1730
  importResult.stats.diffs && importResult.stats.diffs.length > 0 && /* @__PURE__ */ jsxs(Box, { marginTop: 3, padding: 3, background: "neutral0", hasRadius: true, style: { border: "1px solid #dcdce4" }, children: [
@@ -7911,4 +8187,4 @@ export {
7911
8187
  getSortOptionsForCollection,
7912
8188
  parseDynamicZonePath
7913
8189
  };
7914
- //# sourceMappingURL=BulkUpdater-DljSFIEd.mjs.map
8190
+ //# sourceMappingURL=BulkUpdater-Bj-8DvpD.mjs.map