strapi-plugin-bulk-updater 1.5.13 → 1.5.15

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.
@@ -1,7 +1,7 @@
1
1
  import { jsxs, jsx, Fragment } from "react/jsx-runtime";
2
- import React__default, { useState, useEffect, useMemo, useRef } from "react";
2
+ import React__default, { useRef, useState, useEffect, useMemo } from "react";
3
3
  import { useFetchClient, useNotification } from "@strapi/strapi/admin";
4
- import { Box, Flex, Typography, Button, Combobox, ComboboxOption, TextInput, SingleSelect, SingleSelectOption, Badge, Checkbox, Alert, Table, Thead, Tr, Th, Tbody, Td, Loader, Field } from "@strapi/design-system";
4
+ import { Box, Flex, Typography, Button, Combobox, ComboboxOption, Badge, SingleSelect, SingleSelectOption, TextInput, Checkbox, Alert, Table, Thead, Tr, Th, Tbody, Td, Loader, Field } from "@strapi/design-system";
5
5
  import { ArrowClockwise, Download, Upload, ChevronLeft, ChevronRight, Eye, Check, Cog, Play } from "@strapi/icons";
6
6
  import { i as isAbortError, V as ValidationRulesTab } from "./ValidationRulesTab-BtOCWK8E.mjs";
7
7
  function parseCsvRows(csvText) {
@@ -114,6 +114,16 @@ function isValidDocId(val) {
114
114
  }
115
115
  function extractDocId(row) {
116
116
  if (!row || typeof row !== "object") return "";
117
+ const metaRaw = row.__bulk_updater_metadata || row["__bulk_updater_metadata"];
118
+ if (metaRaw) {
119
+ try {
120
+ const meta = typeof metaRaw === "object" ? metaRaw : JSON.parse(metaRaw);
121
+ if (meta?.documentId && isValidDocId(String(meta.documentId).trim())) {
122
+ return String(meta.documentId).trim();
123
+ }
124
+ } catch {
125
+ }
126
+ }
117
127
  const candidates = [
118
128
  row.documentId,
119
129
  row.document_id,
@@ -224,11 +234,23 @@ function getEntryLifecycleStatus(entry, col, pendingBatches = []) {
224
234
  function CsvManagerTab() {
225
235
  const { get, post } = useFetchClient();
226
236
  const { toggleNotification } = useNotification();
237
+ const fileInputRef = useRef(null);
238
+ const countAbortControllerRef = useRef(null);
227
239
  const [collections, setCollections] = useState([]);
228
240
  const [loadingCollections, setLoadingCollections] = useState(true);
229
241
  const [selectedUid, setSelectedUid] = useState("");
230
242
  const [collectionEntries, setCollectionEntries] = useState([]);
231
243
  const [pendingBatches, setPendingBatches] = useState([]);
244
+ const [relationsMeta, setRelationsMeta] = useState({});
245
+ const [attributesMeta, setAttributesMeta] = useState({});
246
+ const [searchAttribute, setSearchAttribute] = useState("");
247
+ const [filterOperator, setFilterOperator] = useState("none");
248
+ const [filterQuery, setFilterQuery] = useState("");
249
+ const [entrySearch, setEntrySearch] = useState("");
250
+ const [matchingCount, setMatchingCount] = useState(null);
251
+ const [countLoading, setCountLoading] = useState(false);
252
+ const [searchRelationOptions, setSearchRelationOptions] = useState([]);
253
+ const [searchRelationOptionsLoading, setSearchRelationOptionsLoading] = useState(false);
232
254
  const [exportLimit, setExportLimit] = useState(0);
233
255
  const [exportLimitInput, setExportLimitInput] = useState("");
234
256
  const [exportingCollection, setExportingCollection] = useState(false);
@@ -276,10 +298,12 @@ function CsvManagerTab() {
276
298
  if (modelsRes.data?.collections) {
277
299
  loadedCollections = modelsRes.data.collections;
278
300
  setCollections(loadedCollections);
279
- if (loadedCollections.length > 0) {
280
- const firstUid = loadedCollections[0].uid;
281
- setSelectedUid(firstUid);
282
- }
301
+ }
302
+ if (modelsRes.data?.relationsMeta) {
303
+ setRelationsMeta(modelsRes.data.relationsMeta);
304
+ }
305
+ if (modelsRes.data?.attributesMeta) {
306
+ setAttributesMeta(modelsRes.data.attributesMeta);
283
307
  }
284
308
  if (rulesRes.data?.rules) {
285
309
  setRules(rulesRes.data.rules);
@@ -297,6 +321,96 @@ function CsvManagerTab() {
297
321
  setLoadingCollections(false);
298
322
  }
299
323
  };
324
+ const getAttrDepth = (attr) => attributesMeta[attr]?.depth ?? (attr.includes(".") ? attr.split(".").length - 1 : 0);
325
+ useEffect(() => {
326
+ if (searchAttribute && relationsMeta[searchAttribute]) {
327
+ fetchSearchRelationOptions(relationsMeta[searchAttribute].targetUid);
328
+ } else {
329
+ setSearchRelationOptions([]);
330
+ }
331
+ }, [searchAttribute, relationsMeta]);
332
+ const fetchSearchRelationOptions = async (targetUid) => {
333
+ try {
334
+ setSearchRelationOptionsLoading(true);
335
+ const res = await get(`/bulk-updater/relation-options?targetUid=${encodeURIComponent(targetUid)}`);
336
+ if (res.data && res.data.success) {
337
+ setSearchRelationOptions(res.data.options || []);
338
+ }
339
+ } catch {
340
+ setSearchRelationOptions([]);
341
+ } finally {
342
+ setSearchRelationOptionsLoading(false);
343
+ }
344
+ };
345
+ const handleCollectionChange = (newUid) => {
346
+ if (newUid === selectedUid) return;
347
+ if (countAbortControllerRef.current) {
348
+ countAbortControllerRef.current.abort();
349
+ }
350
+ setSelectedUid(newUid);
351
+ setAllParsedRecords([]);
352
+ setCsvRawText("");
353
+ setFileName("");
354
+ setPreviewPage(1);
355
+ setImportProgress(null);
356
+ setImportResult(null);
357
+ setPreflightReport(null);
358
+ setPreflightLoading(false);
359
+ setImporting(false);
360
+ if (fileInputRef.current) {
361
+ fileInputRef.current.value = "";
362
+ }
363
+ setSearchAttribute("");
364
+ setFilterOperator("none");
365
+ setFilterQuery("");
366
+ setEntrySearch("");
367
+ setMatchingCount(null);
368
+ setCountLoading(Boolean(newUid));
369
+ };
370
+ useEffect(() => {
371
+ if (!selectedUid) {
372
+ setMatchingCount(null);
373
+ setCountLoading(false);
374
+ return;
375
+ }
376
+ setCountLoading(true);
377
+ const timer = setTimeout(async () => {
378
+ if (countAbortControllerRef.current) {
379
+ countAbortControllerRef.current.abort();
380
+ }
381
+ const controller = new AbortController();
382
+ countAbortControllerRef.current = controller;
383
+ try {
384
+ const params = new URLSearchParams({
385
+ page: "1",
386
+ pageSize: "1"
387
+ });
388
+ if (searchAttribute) {
389
+ params.set("attribute", searchAttribute);
390
+ params.set("searchAttribute", searchAttribute);
391
+ }
392
+ if (filterOperator && filterOperator !== "none") {
393
+ params.set("filterOperator", filterOperator);
394
+ if (filterQuery) params.set("filterQuery", filterQuery);
395
+ }
396
+ if (entrySearch && entrySearch.trim()) {
397
+ params.set("search", entrySearch.trim());
398
+ }
399
+ const res = await get(`/bulk-updater/collections/${selectedUid}/entries?${params.toString()}`, {
400
+ signal: controller.signal
401
+ });
402
+ if (res.data) {
403
+ const total = res.data.pagination?.total ?? (Array.isArray(res.data.entries) ? res.data.entries.length : 0);
404
+ setMatchingCount(total);
405
+ }
406
+ } catch (err) {
407
+ if (!isAbortError(err)) ;
408
+ } finally {
409
+ setCountLoading(false);
410
+ }
411
+ }, 300);
412
+ return () => clearTimeout(timer);
413
+ }, [selectedUid, searchAttribute, filterOperator, filterQuery, entrySearch]);
300
414
  const fetchAndEnrichEntries = async (colUid, cols = collections, batches = pendingBatches) => {
301
415
  if (!colUid) return [];
302
416
  try {
@@ -379,7 +493,17 @@ function CsvManagerTab() {
379
493
  if (!selectedUid || exportingCollection) return;
380
494
  try {
381
495
  setExportingCollection(true);
382
- const res = await get(`/bulk-updater/csv/export/${selectedUid}?limit=${exportLimit}`);
496
+ const queryParams = new URLSearchParams();
497
+ if (exportLimit > 0) queryParams.set("limit", String(exportLimit));
498
+ if (searchAttribute) queryParams.set("searchAttribute", searchAttribute);
499
+ if (filterOperator && filterOperator !== "none") {
500
+ queryParams.set("filterOperator", filterOperator);
501
+ if (filterQuery) queryParams.set("filterQuery", filterQuery);
502
+ }
503
+ if (entrySearch && entrySearch.trim()) {
504
+ queryParams.set("search", entrySearch.trim());
505
+ }
506
+ const res = await get(`/bulk-updater/csv/export/${selectedUid}?${queryParams.toString()}`);
383
507
  const csvStr = res.data?.csvContent || (typeof res.data === "string" ? res.data : "");
384
508
  const filename = res.data?.filename || `${selectedUid.split(".").pop()}_export.csv`;
385
509
  downloadCsvFile(csvStr, filename);
@@ -663,23 +787,15 @@ function CsvManagerTab() {
663
787
  {
664
788
  value: selectedUid || void 0,
665
789
  autocomplete: { type: "list", filter: "contains" },
666
- placeholder: "Search & select a collection...",
790
+ placeholder: "Select Collection Type...",
667
791
  disabled: loadingCollections,
668
792
  clearLabel: "Clear collection selection",
669
- onClear: () => {
670
- setSelectedUid("");
671
- setImportResult(null);
672
- setImportProgress(null);
673
- },
793
+ onClear: () => handleCollectionChange(""),
674
794
  onFocus: (e) => {
675
795
  e.target.select();
676
796
  },
677
797
  onChange: (val) => {
678
- if (val && typeof val === "string") {
679
- setSelectedUid(val);
680
- setImportResult(null);
681
- setImportProgress(null);
682
- }
798
+ handleCollectionChange(val ? String(val) : "");
683
799
  },
684
800
  children: collections.map((col) => /* @__PURE__ */ jsxs(ComboboxOption, { value: col.uid, textValue: `${col.displayName} (${col.uid})`, children: [
685
801
  col.displayName,
@@ -705,7 +821,139 @@ function CsvManagerTab() {
705
821
  ] }) }),
706
822
  /* @__PURE__ */ jsxs(Box, { padding: 5, background: "neutral100", hasRadius: true, children: [
707
823
  /* @__PURE__ */ jsx(Typography, { variant: "delta", tag: "h3", fontWeight: "bold", marginBottom: 2, children: "1. Export Data to CSV" }),
708
- /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", marginBottom: 4, children: "Extract entire collections without artificial limits (streams 10,000+ records in paged chunks) or pinpoint records violating validation quotas." }),
824
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", marginBottom: 4, children: "Extract entire collections or filtered subsets without artificial limits (streams 10,000+ records in paged chunks) or pinpoint records violating validation quotas." }),
825
+ selectedUid ? /* @__PURE__ */ jsxs(Box, { padding: 4, background: "neutral0", hasRadius: true, marginBottom: 4, style: { border: "1px solid #eaeaef" }, children: [
826
+ /* @__PURE__ */ jsxs(Flex, { justifyContent: "space-between", alignItems: "center", marginBottom: 3, children: [
827
+ /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral700", textTransform: "uppercase", children: "Search & Filter Collection Before Export" }),
828
+ /* @__PURE__ */ jsxs(Flex, { gap: 2, alignItems: "center", children: [
829
+ countLoading ? /* @__PURE__ */ jsx(Badge, { backgroundColor: "neutral150", textColor: "neutral700", size: "S", children: "Calculating matching records..." }) : matchingCount !== null ? /* @__PURE__ */ jsxs(
830
+ Badge,
831
+ {
832
+ backgroundColor: matchingCount > 0 ? "success100" : "warning100",
833
+ textColor: matchingCount > 0 ? "success700" : "warning700",
834
+ size: "S",
835
+ children: [
836
+ matchingCount.toLocaleString(),
837
+ " matching records found"
838
+ ]
839
+ }
840
+ ) : null,
841
+ (searchAttribute || filterOperator !== "none" || entrySearch.trim()) && /* @__PURE__ */ jsx(
842
+ Button,
843
+ {
844
+ variant: "ghost",
845
+ size: "S",
846
+ onClick: () => {
847
+ setSearchAttribute("");
848
+ setFilterOperator("none");
849
+ setFilterQuery("");
850
+ setEntrySearch("");
851
+ },
852
+ children: "Clear Filters"
853
+ }
854
+ )
855
+ ] })
856
+ ] }),
857
+ /* @__PURE__ */ jsxs(Flex, { gap: 3, alignItems: "flex-end", wrap: "wrap", children: [
858
+ /* @__PURE__ */ jsxs(Box, { style: { width: 280, minWidth: 230 }, children: [
859
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", fontWeight: "bold", textColor: "neutral800", marginBottom: 1, display: "block", children: "Search Attribute" }),
860
+ /* @__PURE__ */ jsx(
861
+ Combobox,
862
+ {
863
+ autocomplete: { type: "list", filter: "contains" },
864
+ placeholder: "Select Search Attribute...",
865
+ value: searchAttribute || void 0,
866
+ clearLabel: "Reset search attribute",
867
+ onClear: () => setSearchAttribute(""),
868
+ onFocus: (e) => {
869
+ e.target.select();
870
+ },
871
+ onChange: (val) => {
872
+ if (val && typeof val === "string" && val !== "__none__") {
873
+ setSearchAttribute(val);
874
+ }
875
+ },
876
+ children: (selectedCol?.attributes || []).map((attr) => {
877
+ const rel = relationsMeta[attr];
878
+ const depth = getAttrDepth(attr);
879
+ const badgeText = rel ? `relation ${rel.targetDisplayName}` : depth > 0 ? `L${depth} component` : "";
880
+ const textValue = badgeText ? `${attr} ${badgeText}` : attr;
881
+ return /* @__PURE__ */ jsx(ComboboxOption, { value: attr, textValue, children: /* @__PURE__ */ jsxs(Flex, { justifyContent: "space-between", alignItems: "center", width: "100%", gap: 2, children: [
882
+ /* @__PURE__ */ jsx(Typography, { variant: "omega", fontWeight: attr === searchAttribute ? "bold" : "regular", children: attr }),
883
+ rel ? /* @__PURE__ */ jsxs(Badge, { backgroundColor: "secondary100", textColor: "secondary700", size: "S", children: [
884
+ "relation ➔ ",
885
+ rel.targetDisplayName
886
+ ] }) : depth > 0 ? /* @__PURE__ */ jsxs(Badge, { backgroundColor: depth === 1 ? "neutral150" : depth === 2 ? "primary100" : "secondary100", textColor: depth === 1 ? "neutral700" : depth === 2 ? "primary700" : "secondary700", size: "S", children: [
887
+ "L",
888
+ depth,
889
+ " component"
890
+ ] }) : null
891
+ ] }) }, `search_${attr}`);
892
+ })
893
+ },
894
+ `csv-search-attr-${selectedUid}`
895
+ )
896
+ ] }),
897
+ /* @__PURE__ */ jsxs(Box, { style: { width: 200, minWidth: 170 }, children: [
898
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", fontWeight: "bold", textColor: "neutral800", marginBottom: 1, display: "block", children: searchAttribute ? `Condition for "${searchAttribute}"` : "Filter condition" }),
899
+ /* @__PURE__ */ jsxs(
900
+ SingleSelect,
901
+ {
902
+ value: filterOperator,
903
+ disabled: !searchAttribute,
904
+ onChange: (val) => setFilterOperator(String(val)),
905
+ children: [
906
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "none", children: "Show All (No Value Filter)" }),
907
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "empty", children: "Is Empty or Null" }),
908
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "not_empty", children: "Is Not Empty" }),
909
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "equals", children: "Equals Exact Text" }),
910
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "contains", children: "Contains Substring" }),
911
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "starts_with", children: "Starts With" })
912
+ ]
913
+ }
914
+ )
915
+ ] }),
916
+ (filterOperator === "equals" || filterOperator === "contains" || filterOperator === "starts_with") && /* @__PURE__ */ jsxs(Box, { style: { flex: 1, minWidth: 200 }, children: [
917
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", fontWeight: "bold", textColor: "neutral800", marginBottom: 1, display: "block", children: searchAttribute ? `Value for "${searchAttribute}"` : "Value to match" }),
918
+ searchAttribute && relationsMeta[searchAttribute] ? /* @__PURE__ */ jsx(
919
+ Combobox,
920
+ {
921
+ autocomplete: { type: "list", filter: "contains" },
922
+ placeholder: searchRelationOptionsLoading ? "Loading entities..." : `Search & pick ${relationsMeta[searchAttribute].targetDisplayName} or type text...`,
923
+ value: filterQuery,
924
+ onClear: () => setFilterQuery(""),
925
+ onChange: (val) => {
926
+ if (typeof val === "string") {
927
+ setFilterQuery(val);
928
+ }
929
+ },
930
+ onInputChange: (e) => {
931
+ setFilterQuery(e.target.value);
932
+ },
933
+ children: searchRelationOptions.map((opt) => /* @__PURE__ */ jsx(ComboboxOption, { value: opt.label, textValue: opt.label, children: opt.label }, opt.documentId))
934
+ }
935
+ ) : /* @__PURE__ */ jsx(
936
+ TextInput,
937
+ {
938
+ placeholder: "Type value to match...",
939
+ value: filterQuery,
940
+ onChange: (e) => setFilterQuery(e.target.value)
941
+ }
942
+ )
943
+ ] }),
944
+ /* @__PURE__ */ jsxs(Box, { style: { flex: 1, minWidth: 200 }, children: [
945
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", fontWeight: "bold", textColor: "neutral800", marginBottom: 1, display: "block", children: "Full-text Entry Search" }),
946
+ /* @__PURE__ */ jsx(
947
+ TextInput,
948
+ {
949
+ placeholder: "Search title, name, or text across records...",
950
+ value: entrySearch,
951
+ onChange: (e) => setEntrySearch(e.target.value)
952
+ }
953
+ )
954
+ ] })
955
+ ] })
956
+ ] }) : /* @__PURE__ */ jsx(Box, { padding: 4, background: "neutral0", hasRadius: true, marginBottom: 4, style: { border: "1px solid #eaeaef", textAlign: "center" }, children: /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral500", children: "Please select a Target Collection Type above to configure search filters and export data." }) }),
709
957
  /* @__PURE__ */ jsxs(Flex, { gap: 4, wrap: "wrap", alignItems: "flex-end", marginTop: 3, children: [
710
958
  /* @__PURE__ */ jsxs(Box, { style: { width: 220 }, children: [
711
959
  /* @__PURE__ */ jsx(Typography, { variant: "pi", fontWeight: "bold", textColor: "neutral800", marginBottom: 1, display: "block", children: "Records to Download" }),
@@ -758,9 +1006,9 @@ function CsvManagerTab() {
758
1006
  variant: "default",
759
1007
  startIcon: /* @__PURE__ */ jsx(Download, {}),
760
1008
  onClick: handleExportCollection,
761
- disabled: !selectedUid || exportingCollection,
1009
+ disabled: !selectedUid || exportingCollection || matchingCount === 0,
762
1010
  loading: exportingCollection,
763
- children: exportingCollection ? "Preparing CSV download..." : `Export ${exportLimit === 0 ? "All" : exportLimit.toLocaleString()} ${selectedCol?.displayName || "Collection"} Records (.csv)`
1011
+ children: exportingCollection ? "Preparing CSV download..." : countLoading ? "Export (...) Records (.csv)" : matchingCount !== null ? exportLimit > 0 && matchingCount > exportLimit ? `Export First ${exportLimit.toLocaleString()} of (${matchingCount.toLocaleString()}) Records (.csv)` : `Export (${matchingCount.toLocaleString()}) ${selectedCol?.displayName || "Collection"} Records (.csv)` : `Export ${exportLimit === 0 ? "All" : exportLimit.toLocaleString()} ${selectedCol?.displayName || "Collection"} Records (.csv)`
764
1012
  }
765
1013
  ),
766
1014
  rules.length > 0 && /* @__PURE__ */ jsxs(Flex, { gap: 2, alignItems: "center", style: { marginLeft: "auto" }, children: [
@@ -841,6 +1089,7 @@ function CsvManagerTab() {
841
1089
  type: "file",
842
1090
  accept: ".csv",
843
1091
  id: "csv-file-input",
1092
+ ref: fileInputRef,
844
1093
  style: { display: "none" },
845
1094
  onChange: handleFileUpload
846
1095
  }
@@ -3721,24 +3970,8 @@ const BulkUpdater = () => {
3721
3970
  const MODELS_CACHE_KEY = "strapi_bulk_updater_models_cache";
3722
3971
  const LAST_ATTR_KEY = "strapi_bulk_updater_last_attr";
3723
3972
  const LAST_COLLECTION_KEY = "strapi_bulk_updater_last_collection";
3724
- const getInitialCollectionUid = () => {
3725
- try {
3726
- const stored = localStorage.getItem(LAST_COLLECTION_KEY);
3727
- if (stored) return stored;
3728
- } catch {
3729
- }
3730
- return "";
3731
- };
3732
- const [selectedCollectionUid, setSelectedCollectionUid] = useState(getInitialCollectionUid);
3733
- const getInitialAttribute = () => {
3734
- try {
3735
- const stored = localStorage.getItem(LAST_ATTR_KEY);
3736
- if (stored) return stored;
3737
- } catch {
3738
- }
3739
- return "";
3740
- };
3741
- const [selectedAttribute, setSelectedAttribute] = useState(getInitialAttribute);
3973
+ const [selectedCollectionUid, setSelectedCollectionUid] = useState("");
3974
+ const [selectedAttribute, setSelectedAttribute] = useState("");
3742
3975
  const [attributeValue, setAttributeValue] = useState("");
3743
3976
  const [selectedEntries, setSelectedEntries] = useState({});
3744
3977
  const [expandedDzEntries, setExpandedDzEntries] = useState({});
@@ -3812,6 +4045,7 @@ const BulkUpdater = () => {
3812
4045
  const [filterOperator, setFilterOperator] = useState("none");
3813
4046
  const [filterQuery, setFilterQuery] = useState("");
3814
4047
  const [entrySearch, setEntrySearch] = useState("");
4048
+ const abortControllersRef = useRef({});
3815
4049
  const [statusFilter, setStatusFilter] = useState("all");
3816
4050
  const isFilterActive = Boolean(searchAttribute && searchAttribute !== selectedAttribute) || filterOperator !== "none" && (["empty", "not_empty"].includes(filterOperator) || Boolean(filterQuery.trim())) || Boolean(entrySearch.trim()) || Boolean(statusFilter !== "all") || Boolean(useRegex && regexPattern.trim());
3817
4051
  const [lastResults, setLastResults] = useState(null);
@@ -3862,7 +4096,19 @@ const BulkUpdater = () => {
3862
4096
  const [rollingBackBatchId, setRollingBackBatchId] = useState(null);
3863
4097
  const [expandedDiffBatchId, setExpandedDiffBatchId] = useState(null);
3864
4098
  const [auditNotice, setAuditNotice] = useState(null);
3865
- const latestActiveBatch = auditHistory.find((rec) => !rec.isRolledBack);
4099
+ const sortedAuditHistory = useMemo(() => {
4100
+ return [...auditHistory].sort((a, b) => {
4101
+ const timeA = a.executedAt || a.createdAt ? new Date(a.executedAt || a.createdAt).getTime() : 0;
4102
+ const validTimeA = Number.isNaN(timeA) ? 0 : timeA;
4103
+ const timeB = b.executedAt || b.createdAt ? new Date(b.executedAt || b.createdAt).getTime() : 0;
4104
+ const validTimeB = Number.isNaN(timeB) ? 0 : timeB;
4105
+ if (validTimeB !== validTimeA) return validTimeB - validTimeA;
4106
+ if (typeof a.id === "number" && typeof b.id === "number") return b.id - a.id;
4107
+ return String(b.id || b.batchId || "").localeCompare(String(a.id || a.batchId || ""));
4108
+ });
4109
+ }, [auditHistory]);
4110
+ const latestCompletedBatch = sortedAuditHistory.length > 0 ? sortedAuditHistory[0] : null;
4111
+ const latestActiveBatch = latestCompletedBatch && !latestCompletedBatch.isRolledBack ? latestCompletedBatch : null;
3866
4112
  const applyModelsData = (data) => {
3867
4113
  if (!data) return;
3868
4114
  const attrs = data.attributes || [];
@@ -3911,28 +4157,14 @@ const BulkUpdater = () => {
3911
4157
  setAttributesMeta(data.attributesMeta);
3912
4158
  }
3913
4159
  let resolvedColUid = selectedCollectionUid;
3914
- let storedCol = null;
3915
- try {
3916
- storedCol = localStorage.getItem(LAST_COLLECTION_KEY);
3917
- } catch {
3918
- }
3919
- if (!resolvedColUid || !cols.some((c) => c.uid === resolvedColUid)) {
3920
- resolvedColUid = storedCol && cols.some((c) => c.uid === storedCol) ? storedCol : cols[0]?.uid || "";
4160
+ if (resolvedColUid && !cols.some((c) => c.uid === resolvedColUid)) {
4161
+ resolvedColUid = "";
3921
4162
  }
3922
4163
  setSelectedCollectionUid(resolvedColUid);
3923
- try {
3924
- if (resolvedColUid) localStorage.setItem(LAST_COLLECTION_KEY, resolvedColUid);
3925
- } catch {
3926
- }
3927
- const activeCol = cols.find((c) => c.uid === resolvedColUid) || cols[0];
4164
+ const activeCol = resolvedColUid ? cols.find((c) => c.uid === resolvedColUid) : null;
3928
4165
  const activeAttrs = activeCol?.attributes || [];
3929
4166
  setAttributes(activeAttrs);
3930
- let storedAttr = null;
3931
- try {
3932
- storedAttr = localStorage.getItem(LAST_ATTR_KEY);
3933
- } catch {
3934
- }
3935
- const resolvedAttr = storedAttr && activeAttrs.includes(storedAttr) ? storedAttr : selectedAttribute && activeAttrs.includes(selectedAttribute) ? selectedAttribute : "";
4167
+ const resolvedAttr = selectedAttribute && activeAttrs.includes(selectedAttribute) ? selectedAttribute : "";
3936
4168
  setSelectedAttribute(resolvedAttr);
3937
4169
  if (resolvedAttr && data.relationsMeta && data.relationsMeta[resolvedAttr]) {
3938
4170
  fetchRelationOptions(data.relationsMeta[resolvedAttr].targetUid);
@@ -4013,7 +4245,14 @@ const BulkUpdater = () => {
4013
4245
  params.set("sortField", sortField);
4014
4246
  params.set("sortOrder", sortOrder);
4015
4247
  }
4016
- const res = await get(`/bulk-updater/collections/${colUid}/entries?${params.toString()}`);
4248
+ if (abortControllersRef.current[colUid]) {
4249
+ abortControllersRef.current[colUid].abort();
4250
+ }
4251
+ const controller = new AbortController();
4252
+ abortControllersRef.current[colUid] = controller;
4253
+ const res = await get(`/bulk-updater/collections/${colUid}/entries?${params.toString()}`, {
4254
+ signal: controller.signal
4255
+ });
4017
4256
  if (res.data && (res.data.success || res.data.entries !== void 0)) {
4018
4257
  const fetchedEntries = res.data.entries || [];
4019
4258
  const pageNum = res.data.pagination?.page ?? targetPage ?? 1;
@@ -4155,6 +4394,9 @@ const BulkUpdater = () => {
4155
4394
  }, [collections, selectedCollectionUid]);
4156
4395
  const handleCollectionChange = (newUid) => {
4157
4396
  if (newUid === selectedCollectionUid) return;
4397
+ if (abortControllersRef.current) {
4398
+ Object.values(abortControllersRef.current).forEach((ctrl) => ctrl.abort());
4399
+ }
4158
4400
  setSelectedCollectionUid(newUid);
4159
4401
  try {
4160
4402
  if (newUid) {
@@ -4244,59 +4486,40 @@ const BulkUpdater = () => {
4244
4486
  });
4245
4487
  }, [depthFilteredAttributes, relationsMeta, selectedAttribute, componentDepth, attributesMeta]);
4246
4488
  const memoizedSearchComboboxOptions = useMemo(() => {
4247
- return /* @__PURE__ */ jsxs(Fragment, { children: [
4248
- /* @__PURE__ */ jsx(
4249
- ComboboxOption,
4250
- {
4251
- value: "__default__",
4252
- textValue: `Same as Update Attribute (${selectedAttribute || "None"}) default`,
4253
- children: /* @__PURE__ */ jsxs(Flex, { justifyContent: "space-between", alignItems: "center", width: "100%", gap: 2, children: [
4254
- /* @__PURE__ */ jsxs(Typography, { variant: "omega", fontStyle: "italic", textColor: "neutral600", children: [
4255
- "-- Same as Update Attribute (",
4256
- selectedAttribute || "None",
4257
- ") --"
4258
- ] }),
4259
- /* @__PURE__ */ jsx(Badge, { backgroundColor: "neutral150", textColor: "neutral600", size: "S", children: "Default" })
4260
- ] })
4261
- }
4262
- ),
4263
- depthFilteredAttributes.map((attr) => {
4264
- const rel = relationsMeta[attr];
4265
- const depth = getAttrDepth(attr);
4266
- const badgeText = rel ? `relation ${rel.targetDisplayName}` : depth > 0 ? `L${depth} component` : "";
4267
- const textValue = badgeText ? `${attr} ${badgeText}` : attr;
4268
- return /* @__PURE__ */ jsx(ComboboxOption, { value: attr, textValue, children: /* @__PURE__ */ jsxs(Flex, { justifyContent: "space-between", alignItems: "center", width: "100%", gap: 2, children: [
4269
- /* @__PURE__ */ jsx(Typography, { variant: "omega", fontWeight: attr === searchAttribute ? "bold" : "regular", children: attr }),
4270
- rel ? /* @__PURE__ */ jsxs(Badge, { backgroundColor: "secondary100", textColor: "secondary700", size: "S", children: [
4271
- "relation ➔ ",
4272
- rel.targetDisplayName
4273
- ] }) : depth > 0 ? /* @__PURE__ */ jsxs(Badge, { backgroundColor: depth === 1 ? "neutral150" : depth === 2 ? "primary100" : "secondary100", textColor: depth === 1 ? "neutral700" : depth === 2 ? "primary700" : "secondary700", size: "S", children: [
4274
- "L",
4275
- depth,
4276
- " component"
4277
- ] }) : null
4278
- ] }) }, `search_${attr}`);
4279
- })
4280
- ] });
4489
+ return /* @__PURE__ */ jsx(Fragment, { children: depthFilteredAttributes.map((attr) => {
4490
+ const rel = relationsMeta[attr];
4491
+ const depth = getAttrDepth(attr);
4492
+ const badgeText = rel ? `relation ${rel.targetDisplayName}` : depth > 0 ? `L${depth} component` : "";
4493
+ const textValue = badgeText ? `${attr} ${badgeText}` : attr;
4494
+ return /* @__PURE__ */ jsx(ComboboxOption, { value: attr, textValue, children: /* @__PURE__ */ jsxs(Flex, { justifyContent: "space-between", alignItems: "center", width: "100%", gap: 2, children: [
4495
+ /* @__PURE__ */ jsx(Typography, { variant: "omega", fontWeight: attr === searchAttribute ? "bold" : "regular", children: attr }),
4496
+ rel ? /* @__PURE__ */ jsxs(Badge, { backgroundColor: "secondary100", textColor: "secondary700", size: "S", children: [
4497
+ "relation ➔ ",
4498
+ rel.targetDisplayName
4499
+ ] }) : depth > 0 ? /* @__PURE__ */ jsxs(Badge, { backgroundColor: depth === 1 ? "neutral150" : depth === 2 ? "primary100" : "secondary100", textColor: depth === 1 ? "neutral700" : depth === 2 ? "primary700" : "secondary700", size: "S", children: [
4500
+ "L",
4501
+ depth,
4502
+ " component"
4503
+ ] }) : null
4504
+ ] }) }, `search_${attr}`);
4505
+ }) });
4281
4506
  }, [depthFilteredAttributes, relationsMeta, searchAttribute, selectedAttribute, componentDepth, attributesMeta]);
4282
4507
  const handleSearchAttributeChange = (newAttr) => {
4283
4508
  const finalAttr = newAttr === "__default__" ? "" : newAttr;
4284
4509
  setSearchAttribute(finalAttr);
4285
- if (collections.length > 0) {
4286
- collections.forEach((col) => {
4287
- loadCollectionPage(
4288
- col.uid,
4289
- 1,
4290
- void 0,
4291
- void 0,
4292
- void 0,
4293
- filterOperator,
4294
- filterQuery,
4295
- entrySearch,
4296
- true,
4297
- finalAttr
4298
- );
4299
- });
4510
+ if (selectedCollectionUid) {
4511
+ loadCollectionPage(
4512
+ selectedCollectionUid,
4513
+ 1,
4514
+ void 0,
4515
+ void 0,
4516
+ void 0,
4517
+ filterOperator,
4518
+ filterQuery,
4519
+ entrySearch,
4520
+ true,
4521
+ finalAttr
4522
+ );
4300
4523
  }
4301
4524
  };
4302
4525
  const handleCollectionPageSizeChange = (colUid, newSize) => {
@@ -5392,7 +5615,7 @@ const BulkUpdater = () => {
5392
5615
  Combobox,
5393
5616
  {
5394
5617
  autocomplete: { type: "list", filter: "contains" },
5395
- placeholder: "Search Collection Type...",
5618
+ placeholder: "Select Collection Type...",
5396
5619
  value: selectedCollectionUid || void 0,
5397
5620
  clearLabel: "Clear collection selection",
5398
5621
  onClear: () => handleCollectionChange(""),
@@ -5493,8 +5716,8 @@ const BulkUpdater = () => {
5493
5716
  Combobox,
5494
5717
  {
5495
5718
  autocomplete: { type: "list", filter: "contains" },
5496
- placeholder: searchAttribute || `Same as Update (${selectedAttribute || "None"})`,
5497
- value: searchAttribute || "__default__",
5719
+ placeholder: "Select Search Attribute...",
5720
+ value: searchAttribute || void 0,
5498
5721
  clearLabel: "Reset search attribute",
5499
5722
  onClear: () => handleSearchAttributeChange(""),
5500
5723
  onFocus: (e) => {
@@ -5513,8 +5736,9 @@ const BulkUpdater = () => {
5513
5736
  /* @__PURE__ */ jsx(Box, { style: { width: 200, minWidth: 170 }, children: /* @__PURE__ */ jsxs(
5514
5737
  SingleSelect,
5515
5738
  {
5516
- label: effectiveSearchAttribute ? `Condition for "${effectiveSearchAttribute}"` : "Filter condition",
5739
+ label: searchAttribute ? `Condition for "${searchAttribute}"` : "Filter condition",
5517
5740
  value: filterOperator,
5741
+ disabled: !searchAttribute,
5518
5742
  onChange: (val) => setFilterOperator(String(val)),
5519
5743
  children: [
5520
5744
  /* @__PURE__ */ jsx(SingleSelectOption, { value: "none", children: "Show All (No Value Filter)" }),
@@ -6282,7 +6506,7 @@ const BulkUpdater = () => {
6282
6506
  Combobox,
6283
6507
  {
6284
6508
  autocomplete: { type: "list", filter: "contains" },
6285
- placeholder: "Search attribute by name or relation...",
6509
+ placeholder: "Select Attribute to Update...",
6286
6510
  value: selectedAttribute || void 0,
6287
6511
  clearLabel: "Clear attribute selection",
6288
6512
  onClear: () => handleAttributeChange(""),
@@ -6763,7 +6987,7 @@ const BulkUpdater = () => {
6763
6987
  /* @__PURE__ */ jsx(Typography, { variant: "beta", textColor: "neutral600", children: "No batch operations recorded in the audit trail yet." }),
6764
6988
  /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral500", display: "block", marginTop: 2, children: "When you execute a bulk update in the editor, its transactional diff will be logged here." })
6765
6989
  ] }),
6766
- auditHistory.length > 0 && /* @__PURE__ */ jsx(Box, { className: "bulk-updater-table-container", style: { width: "100%", maxWidth: "100%", minWidth: 0, overflowX: "auto" }, children: /* @__PURE__ */ jsxs(Table, { colCount: 6, rowCount: auditHistory.length + 1, style: { width: "100%" }, children: [
6990
+ sortedAuditHistory.length > 0 && /* @__PURE__ */ jsx(Box, { className: "bulk-updater-table-container", style: { width: "100%", maxWidth: "100%", minWidth: 0, overflowX: "auto" }, children: /* @__PURE__ */ jsxs(Table, { colCount: 6, rowCount: sortedAuditHistory.length + 1, style: { width: "100%" }, children: [
6767
6991
  /* @__PURE__ */ jsx(Thead, { children: /* @__PURE__ */ jsxs(Tr, { children: [
6768
6992
  /* @__PURE__ */ jsx(Th, { style: { minWidth: 140 }, children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", children: "Date & Time" }) }),
6769
6993
  /* @__PURE__ */ jsx(Th, { style: { minWidth: 130 }, children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", children: "Performed By" }) }),
@@ -6772,9 +6996,12 @@ const BulkUpdater = () => {
6772
6996
  /* @__PURE__ */ jsx(Th, { style: { minWidth: 120 }, children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", children: "Status" }) }),
6773
6997
  /* @__PURE__ */ jsx(Th, { style: { minWidth: 160, textAlign: "right" }, children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", children: "Actions" }) })
6774
6998
  ] }) }),
6775
- /* @__PURE__ */ jsx(Tbody, { children: auditHistory.map((rec) => {
6999
+ /* @__PURE__ */ jsx(Tbody, { children: sortedAuditHistory.map((rec) => {
6776
7000
  const isExpanded = expandedDiffBatchId === rec.batchId;
6777
7001
  const dateStr = new Date(rec.executedAt).toLocaleString();
7002
+ const isLatestEligible = Boolean(
7003
+ rec.isLatestEligible ?? (latestCompletedBatch && rec.batchId === latestCompletedBatch.batchId && !latestCompletedBatch.isRolledBack)
7004
+ );
6778
7005
  return /* @__PURE__ */ jsxs(React__default.Fragment, { children: [
6779
7006
  /* @__PURE__ */ jsxs(
6780
7007
  Tr,
@@ -6876,7 +7103,7 @@ const BulkUpdater = () => {
6876
7103
  children: isExpanded ? "Hide Diffs" : "View Diffs"
6877
7104
  }
6878
7105
  ),
6879
- !rec.isRolledBack && /* @__PURE__ */ jsx(
7106
+ !rec.isRolledBack && (isLatestEligible ? /* @__PURE__ */ jsx(
6880
7107
  Button,
6881
7108
  {
6882
7109
  variant: "danger",
@@ -6885,7 +7112,23 @@ const BulkUpdater = () => {
6885
7112
  onClick: () => handleRollback(rec.batchId),
6886
7113
  children: "Rollback"
6887
7114
  }
6888
- )
7115
+ ) : /* @__PURE__ */ jsx(
7116
+ "span",
7117
+ {
7118
+ title: "Only the latest completed update can be rolled back.",
7119
+ style: { display: "inline-flex", cursor: "not-allowed" },
7120
+ children: /* @__PURE__ */ jsx(
7121
+ Button,
7122
+ {
7123
+ variant: "danger",
7124
+ size: "S",
7125
+ disabled: true,
7126
+ style: { opacity: 0.4, pointerEvents: "none" },
7127
+ children: "Rollback"
7128
+ }
7129
+ )
7130
+ }
7131
+ ))
6889
7132
  ] }) })
6890
7133
  ]
6891
7134
  }
@@ -7668,4 +7911,4 @@ export {
7668
7911
  getSortOptionsForCollection,
7669
7912
  parseDynamicZonePath
7670
7913
  };
7671
- //# sourceMappingURL=BulkUpdater-GPpE8YW2.mjs.map
7914
+ //# sourceMappingURL=BulkUpdater-DljSFIEd.mjs.map