strapi-plugin-bulk-updater 1.7.0 → 1.7.2
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.
- package/dist/_chunks/{BulkUpdater-Cnzgw4UH.js → BulkUpdater-BdsfPqoX.js} +85 -41
- package/dist/_chunks/BulkUpdater-BdsfPqoX.js.map +1 -0
- package/dist/_chunks/{BulkUpdater-CV49TvOV.mjs → BulkUpdater-KWmfElh6.mjs} +85 -41
- package/dist/_chunks/BulkUpdater-KWmfElh6.mjs.map +1 -0
- package/dist/_chunks/{SettingsPage-DXRWLRp_.mjs → SettingsPage-BdwchEyi.mjs} +2 -2
- package/dist/_chunks/{SettingsPage-DXRWLRp_.mjs.map → SettingsPage-BdwchEyi.mjs.map} +1 -1
- package/dist/_chunks/{SettingsPage-w_Lz-N0V.js → SettingsPage-DqJ_zBde.js} +2 -2
- package/dist/_chunks/{SettingsPage-w_Lz-N0V.js.map → SettingsPage-DqJ_zBde.js.map} +1 -1
- package/dist/_chunks/{ValidationRulesTab-eN_vH3TB.mjs → ValidationRulesTab-DUtycMm1.mjs} +23 -3
- package/dist/_chunks/ValidationRulesTab-DUtycMm1.mjs.map +1 -0
- package/dist/_chunks/{ValidationRulesTab-of8bIzre.js → ValidationRulesTab-DVvVevbW.js} +23 -3
- package/dist/_chunks/ValidationRulesTab-DVvVevbW.js.map +1 -0
- package/dist/_chunks/{index-C2HoRm23.js → index-BZ5NTSJQ.js} +12 -4
- package/dist/_chunks/index-BZ5NTSJQ.js.map +1 -0
- package/dist/_chunks/{index-2DodYa70.mjs → index-C9zsPQim.mjs} +12 -4
- package/dist/_chunks/index-C9zsPQim.mjs.map +1 -0
- package/dist/admin/index.js +1 -1
- package/dist/admin/index.mjs +1 -1
- package/dist/server/index.js +757 -298
- package/dist/server/index.js.map +1 -1
- package/dist/server/index.mjs +757 -298
- package/dist/server/index.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/_chunks/BulkUpdater-CV49TvOV.mjs.map +0 -1
- package/dist/_chunks/BulkUpdater-Cnzgw4UH.js.map +0 -1
- package/dist/_chunks/ValidationRulesTab-eN_vH3TB.mjs.map +0 -1
- package/dist/_chunks/ValidationRulesTab-of8bIzre.js.map +0 -1
- package/dist/_chunks/index-2DodYa70.mjs.map +0 -1
- package/dist/_chunks/index-C2HoRm23.js.map +0 -1
package/dist/server/index.mjs
CHANGED
|
@@ -16,6 +16,10 @@ const PERMISSIONS = {
|
|
|
16
16
|
// CSV Management
|
|
17
17
|
csvExport: `plugin::${PLUGIN_ID}.csv.export`,
|
|
18
18
|
csvImport: `plugin::${PLUGIN_ID}.csv.import`,
|
|
19
|
+
csvSubmitForChecker: `plugin::${PLUGIN_ID}.csv.submit-for-checker`,
|
|
20
|
+
csvForceRunNow: `plugin::${PLUGIN_ID}.csv.force-run-now`,
|
|
21
|
+
csvQueueForOffPeak: `plugin::${PLUGIN_ID}.csv.queue-for-off-peak`,
|
|
22
|
+
csvPreFlightDryRun: `plugin::${PLUGIN_ID}.csv.pre-flight-dry-run`,
|
|
19
23
|
// Audit Trail
|
|
20
24
|
auditView: `plugin::${PLUGIN_ID}.audit.view`,
|
|
21
25
|
auditDetails: `plugin::${PLUGIN_ID}.audit.details`,
|
|
@@ -102,6 +106,34 @@ const BULK_UPDATER_PERMISSION_ACTIONS = [
|
|
|
102
106
|
pluginName: PLUGIN_ID,
|
|
103
107
|
subCategory: "CSV Management"
|
|
104
108
|
},
|
|
109
|
+
{
|
|
110
|
+
section: "plugins",
|
|
111
|
+
displayName: "CSV Submit For Checker",
|
|
112
|
+
uid: "csv.submit-for-checker",
|
|
113
|
+
pluginName: PLUGIN_ID,
|
|
114
|
+
subCategory: "CSV Management"
|
|
115
|
+
},
|
|
116
|
+
{
|
|
117
|
+
section: "plugins",
|
|
118
|
+
displayName: "CSV Force Run Now",
|
|
119
|
+
uid: "csv.force-run-now",
|
|
120
|
+
pluginName: PLUGIN_ID,
|
|
121
|
+
subCategory: "CSV Management"
|
|
122
|
+
},
|
|
123
|
+
{
|
|
124
|
+
section: "plugins",
|
|
125
|
+
displayName: "CSV Queue For Off-Peak",
|
|
126
|
+
uid: "csv.queue-for-off-peak",
|
|
127
|
+
pluginName: PLUGIN_ID,
|
|
128
|
+
subCategory: "CSV Management"
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
section: "plugins",
|
|
132
|
+
displayName: "CSV Run Pre-Flight Dry Run",
|
|
133
|
+
uid: "csv.pre-flight-dry-run",
|
|
134
|
+
pluginName: PLUGIN_ID,
|
|
135
|
+
subCategory: "CSV Management"
|
|
136
|
+
},
|
|
105
137
|
{
|
|
106
138
|
section: "plugins",
|
|
107
139
|
displayName: "View Audit History",
|
|
@@ -184,7 +216,27 @@ const BATCH_UPDATE_POLICY_CONFIG = {
|
|
|
184
216
|
mode: "any",
|
|
185
217
|
enforceBatchUpdateExecutionMode: true
|
|
186
218
|
};
|
|
187
|
-
|
|
219
|
+
const CSV_SUBMIT_BATCH_POLICY_CONFIG = {
|
|
220
|
+
actions: [
|
|
221
|
+
PERMISSIONS.csvImport,
|
|
222
|
+
PERMISSIONS.csvSubmitForChecker,
|
|
223
|
+
PERMISSIONS.csvForceRunNow,
|
|
224
|
+
PERMISSIONS.csvQueueForOffPeak
|
|
225
|
+
],
|
|
226
|
+
mode: "any",
|
|
227
|
+
enforceCsvSubmitExecutionMode: true
|
|
228
|
+
};
|
|
229
|
+
const WORKSPACE_MODE_PERMISSIONS = {
|
|
230
|
+
maker_checker: PERMISSIONS.workspaceSubmitForChecker,
|
|
231
|
+
queue_offpeak: PERMISSIONS.workspaceQueueForOffPeak,
|
|
232
|
+
immediate: PERMISSIONS.workspaceForceRunNow
|
|
233
|
+
};
|
|
234
|
+
const CSV_MODE_PERMISSIONS = {
|
|
235
|
+
maker_checker: PERMISSIONS.csvSubmitForChecker,
|
|
236
|
+
queue_offpeak: PERMISSIONS.csvQueueForOffPeak,
|
|
237
|
+
immediate: PERMISSIONS.csvForceRunNow
|
|
238
|
+
};
|
|
239
|
+
function resolveExecutionModeRequiredPermissions(body, modePermissionMap, checkPreviewOrigin) {
|
|
188
240
|
const rawMode = body?.executionMode;
|
|
189
241
|
const effectiveMode = rawMode === void 0 ? "immediate" : rawMode;
|
|
190
242
|
if (typeof effectiveMode !== "string" || !["maker_checker", "queue_offpeak", "immediate"].includes(effectiveMode)) {
|
|
@@ -194,20 +246,23 @@ function resolveBatchUpdateRequiredPermissions(body) {
|
|
|
194
246
|
reason: `Unsupported or unauthorized execution mode "${String(rawMode)}".`
|
|
195
247
|
};
|
|
196
248
|
}
|
|
197
|
-
const required = [
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
const isPreviewInitiated = body?.initiatedFromPreview === true || body?.initiatedFromPreview === "true" || body?.source === "preview" || body?.executionSource === "preview";
|
|
206
|
-
if (isPreviewInitiated) {
|
|
207
|
-
required.push(PERMISSIONS.workspaceProceedToExecute);
|
|
249
|
+
const required = [
|
|
250
|
+
modePermissionMap[effectiveMode]
|
|
251
|
+
];
|
|
252
|
+
if (checkPreviewOrigin) {
|
|
253
|
+
const isPreviewInitiated = body?.initiatedFromPreview === true || body?.initiatedFromPreview === "true" || body?.source === "preview" || body?.executionSource === "preview";
|
|
254
|
+
if (isPreviewInitiated) {
|
|
255
|
+
required.push(PERMISSIONS.workspaceProceedToExecute);
|
|
256
|
+
}
|
|
208
257
|
}
|
|
209
258
|
return { valid: true, actions: required };
|
|
210
259
|
}
|
|
260
|
+
function resolveBatchUpdateRequiredPermissions(body) {
|
|
261
|
+
return resolveExecutionModeRequiredPermissions(body, WORKSPACE_MODE_PERMISSIONS, true);
|
|
262
|
+
}
|
|
263
|
+
function resolveCsvSubmitRequiredPermissions(body) {
|
|
264
|
+
return resolveExecutionModeRequiredPermissions(body, CSV_MODE_PERMISSIONS, false);
|
|
265
|
+
}
|
|
211
266
|
function setForbiddenResponse(ctx, message = "You do not have permission to perform this action.") {
|
|
212
267
|
if (ctx) {
|
|
213
268
|
ctx.status = 403;
|
|
@@ -226,6 +281,7 @@ const hasPermissionsPolicy = (policyContext, config, { strapi } = {}) => {
|
|
|
226
281
|
let actions = [];
|
|
227
282
|
let mode = "all";
|
|
228
283
|
let enforceBatchMode = false;
|
|
284
|
+
let enforceCsvMode = false;
|
|
229
285
|
if (Array.isArray(config)) {
|
|
230
286
|
actions = config;
|
|
231
287
|
} else if (config && typeof config === "object") {
|
|
@@ -234,6 +290,7 @@ const hasPermissionsPolicy = (policyContext, config, { strapi } = {}) => {
|
|
|
234
290
|
mode = "any";
|
|
235
291
|
}
|
|
236
292
|
enforceBatchMode = Boolean(config.enforceBatchUpdateExecutionMode);
|
|
293
|
+
enforceCsvMode = Boolean(config.enforceCsvSubmitExecutionMode);
|
|
237
294
|
} else if (typeof config === "string") {
|
|
238
295
|
actions = [config];
|
|
239
296
|
}
|
|
@@ -246,8 +303,8 @@ const hasPermissionsPolicy = (policyContext, config, { strapi } = {}) => {
|
|
|
246
303
|
return true;
|
|
247
304
|
}
|
|
248
305
|
let batchModeActions = null;
|
|
249
|
-
if (enforceBatchMode) {
|
|
250
|
-
const resolved = resolveBatchUpdateRequiredPermissions(ctx?.request?.body);
|
|
306
|
+
if (enforceBatchMode || enforceCsvMode) {
|
|
307
|
+
const resolved = enforceCsvMode ? resolveCsvSubmitRequiredPermissions(ctx?.request?.body) : resolveBatchUpdateRequiredPermissions(ctx?.request?.body);
|
|
251
308
|
if (!resolved.valid) {
|
|
252
309
|
setForbiddenResponse(ctx, resolved.reason || "You do not have permission to perform this action.");
|
|
253
310
|
return false;
|
|
@@ -285,6 +342,14 @@ const hasPermissionsPolicy = (policyContext, config, { strapi } = {}) => {
|
|
|
285
342
|
}
|
|
286
343
|
return true;
|
|
287
344
|
};
|
|
345
|
+
const CSV_READ_PERMISSIONS = [
|
|
346
|
+
PERMISSIONS.csvExport,
|
|
347
|
+
PERMISSIONS.csvImport,
|
|
348
|
+
PERMISSIONS.csvSubmitForChecker,
|
|
349
|
+
PERMISSIONS.csvForceRunNow,
|
|
350
|
+
PERMISSIONS.csvQueueForOffPeak,
|
|
351
|
+
PERMISSIONS.csvPreFlightDryRun
|
|
352
|
+
];
|
|
288
353
|
function requirePermissions(actions, mode = "all") {
|
|
289
354
|
return [
|
|
290
355
|
{
|
|
@@ -308,8 +373,7 @@ const routes = {
|
|
|
308
373
|
policies: requirePermissions(
|
|
309
374
|
[
|
|
310
375
|
PERMISSIONS.workspaceView,
|
|
311
|
-
|
|
312
|
-
PERMISSIONS.csvImport,
|
|
376
|
+
...CSV_READ_PERMISSIONS,
|
|
313
377
|
PERMISSIONS.validationView
|
|
314
378
|
],
|
|
315
379
|
"any"
|
|
@@ -322,7 +386,7 @@ const routes = {
|
|
|
322
386
|
handler: "bulkUpdater.getCollectionEntries",
|
|
323
387
|
config: {
|
|
324
388
|
policies: requirePermissions(
|
|
325
|
-
[PERMISSIONS.workspaceView,
|
|
389
|
+
[PERMISSIONS.workspaceView, ...CSV_READ_PERMISSIONS],
|
|
326
390
|
"any"
|
|
327
391
|
)
|
|
328
392
|
}
|
|
@@ -333,7 +397,7 @@ const routes = {
|
|
|
333
397
|
handler: "bulkUpdater.getRelationOptions",
|
|
334
398
|
config: {
|
|
335
399
|
policies: requirePermissions(
|
|
336
|
-
[PERMISSIONS.workspaceView,
|
|
400
|
+
[PERMISSIONS.workspaceView, ...CSV_READ_PERMISSIONS],
|
|
337
401
|
"any"
|
|
338
402
|
)
|
|
339
403
|
}
|
|
@@ -344,7 +408,7 @@ const routes = {
|
|
|
344
408
|
handler: "bulkUpdater.getMediaOptions",
|
|
345
409
|
config: {
|
|
346
410
|
policies: requirePermissions(
|
|
347
|
-
[PERMISSIONS.workspaceView,
|
|
411
|
+
[PERMISSIONS.workspaceView, ...CSV_READ_PERMISSIONS],
|
|
348
412
|
"any"
|
|
349
413
|
)
|
|
350
414
|
}
|
|
@@ -431,6 +495,9 @@ const routes = {
|
|
|
431
495
|
PERMISSIONS.workspaceView,
|
|
432
496
|
PERMISSIONS.workspaceExecute,
|
|
433
497
|
PERMISSIONS.csvImport,
|
|
498
|
+
PERMISSIONS.csvSubmitForChecker,
|
|
499
|
+
PERMISSIONS.csvForceRunNow,
|
|
500
|
+
PERMISSIONS.csvQueueForOffPeak,
|
|
434
501
|
PERMISSIONS.auditView,
|
|
435
502
|
PERMISSIONS.approvalView
|
|
436
503
|
],
|
|
@@ -523,7 +590,7 @@ const routes = {
|
|
|
523
590
|
path: "/csv/template/:uid",
|
|
524
591
|
handler: "csv.getTemplate",
|
|
525
592
|
config: {
|
|
526
|
-
policies: requirePermissions(
|
|
593
|
+
policies: requirePermissions(CSV_READ_PERMISSIONS, "any")
|
|
527
594
|
}
|
|
528
595
|
},
|
|
529
596
|
{
|
|
@@ -563,7 +630,7 @@ const routes = {
|
|
|
563
630
|
path: "/csv/import",
|
|
564
631
|
handler: "csv.importCsv",
|
|
565
632
|
config: {
|
|
566
|
-
policies: requirePermissions(PERMISSIONS.
|
|
633
|
+
policies: requirePermissions(PERMISSIONS.csvForceRunNow)
|
|
567
634
|
}
|
|
568
635
|
},
|
|
569
636
|
{
|
|
@@ -571,7 +638,7 @@ const routes = {
|
|
|
571
638
|
path: "/csv/import-chunk",
|
|
572
639
|
handler: "csv.importChunk",
|
|
573
640
|
config: {
|
|
574
|
-
policies: requirePermissions(PERMISSIONS.
|
|
641
|
+
policies: requirePermissions(PERMISSIONS.csvForceRunNow)
|
|
575
642
|
}
|
|
576
643
|
},
|
|
577
644
|
{
|
|
@@ -579,7 +646,7 @@ const routes = {
|
|
|
579
646
|
path: "/csv/validate-preflight",
|
|
580
647
|
handler: "csv.validatePreflight",
|
|
581
648
|
config: {
|
|
582
|
-
policies: requirePermissions(PERMISSIONS.
|
|
649
|
+
policies: requirePermissions(PERMISSIONS.csvPreFlightDryRun)
|
|
583
650
|
}
|
|
584
651
|
},
|
|
585
652
|
{
|
|
@@ -587,7 +654,12 @@ const routes = {
|
|
|
587
654
|
path: "/csv/submit-batch",
|
|
588
655
|
handler: "csv.submitBatch",
|
|
589
656
|
config: {
|
|
590
|
-
policies:
|
|
657
|
+
policies: [
|
|
658
|
+
{
|
|
659
|
+
name: "plugin::bulk-updater.hasPermissions",
|
|
660
|
+
config: CSV_SUBMIT_BATCH_POLICY_CONFIG
|
|
661
|
+
}
|
|
662
|
+
]
|
|
591
663
|
}
|
|
592
664
|
}
|
|
593
665
|
]
|
|
@@ -668,7 +740,15 @@ const contentTypes = {
|
|
|
668
740
|
schema: auditLog
|
|
669
741
|
}
|
|
670
742
|
};
|
|
743
|
+
const { AsyncLocalStorage } = require("async_hooks");
|
|
671
744
|
const CRASH_GUARD_SYMBOL = Symbol.for("strapi-plugin-bulk-updater.undiciCrashGuardInstalled");
|
|
745
|
+
const rollbackContextStorage = new AsyncLocalStorage();
|
|
746
|
+
function runInRollbackContext(fn) {
|
|
747
|
+
return rollbackContextStorage.run(true, fn);
|
|
748
|
+
}
|
|
749
|
+
function isRollbackContext() {
|
|
750
|
+
return rollbackContextStorage.getStore() === true;
|
|
751
|
+
}
|
|
672
752
|
let activeBulkOperations = 0;
|
|
673
753
|
function getActiveBulkOperationCount() {
|
|
674
754
|
return activeBulkOperations;
|
|
@@ -1033,7 +1113,8 @@ const auditController = ({ strapi }) => ({
|
|
|
1033
1113
|
const { batchId } = ctx.params;
|
|
1034
1114
|
const service = strapi.plugin("bulk-updater").service("audit");
|
|
1035
1115
|
const currentUser = ctx.state.user;
|
|
1036
|
-
const
|
|
1116
|
+
const confirmOverwrite = Boolean(ctx.request?.body?.confirmOverwrite);
|
|
1117
|
+
const result = await service.rollbackBatch(batchId, currentUser, { confirmOverwrite });
|
|
1037
1118
|
ctx.body = result;
|
|
1038
1119
|
} catch (err) {
|
|
1039
1120
|
ctx.status = 400;
|
|
@@ -1115,6 +1196,13 @@ const validationRulesController = ({ strapi }) => ({
|
|
|
1115
1196
|
}
|
|
1116
1197
|
}
|
|
1117
1198
|
});
|
|
1199
|
+
function ensureCsvAuthorized(ctx, policyConfig, strapi) {
|
|
1200
|
+
const hasAuthContext = Boolean(
|
|
1201
|
+
ctx?.state?.userAbility || Array.isArray(ctx?.state?.permissions) || Array.isArray(ctx?.state?.user?.permissions) || ctx?.state?.user?.isSuperAdmin !== void 0
|
|
1202
|
+
);
|
|
1203
|
+
if (!hasAuthContext) return true;
|
|
1204
|
+
return hasPermissionsPolicy(ctx, policyConfig, { strapi });
|
|
1205
|
+
}
|
|
1118
1206
|
const csvController = ({ strapi }) => ({
|
|
1119
1207
|
async getTemplate(ctx) {
|
|
1120
1208
|
try {
|
|
@@ -1223,6 +1311,9 @@ const csvController = ({ strapi }) => ({
|
|
|
1223
1311
|
},
|
|
1224
1312
|
async importCsv(ctx) {
|
|
1225
1313
|
try {
|
|
1314
|
+
if (!ensureCsvAuthorized(ctx, { actions: [PERMISSIONS.csvForceRunNow] }, strapi)) {
|
|
1315
|
+
return;
|
|
1316
|
+
}
|
|
1226
1317
|
const { uid, csvText, mode, publish, publishStrategy, unreviewedConsent } = ctx.request.body;
|
|
1227
1318
|
if (!uid) {
|
|
1228
1319
|
ctx.status = 400;
|
|
@@ -1252,6 +1343,9 @@ const csvController = ({ strapi }) => ({
|
|
|
1252
1343
|
},
|
|
1253
1344
|
async importChunk(ctx) {
|
|
1254
1345
|
try {
|
|
1346
|
+
if (!ensureCsvAuthorized(ctx, { actions: [PERMISSIONS.csvForceRunNow] }, strapi)) {
|
|
1347
|
+
return;
|
|
1348
|
+
}
|
|
1255
1349
|
const { uid, rows, batchId, isFirstChunk, isLastChunk, startRowNumber, mode, publish, publishStrategy, unreviewedConsent, originalHeaders } = ctx.request.body;
|
|
1256
1350
|
if (!uid) {
|
|
1257
1351
|
ctx.status = 400;
|
|
@@ -1286,7 +1380,10 @@ const csvController = ({ strapi }) => ({
|
|
|
1286
1380
|
},
|
|
1287
1381
|
async validatePreflight(ctx) {
|
|
1288
1382
|
try {
|
|
1289
|
-
|
|
1383
|
+
if (!ensureCsvAuthorized(ctx, { actions: [PERMISSIONS.csvPreFlightDryRun] }, strapi)) {
|
|
1384
|
+
return;
|
|
1385
|
+
}
|
|
1386
|
+
const { uid, rows, mode, originalHeaders } = ctx.request.body;
|
|
1290
1387
|
if (!uid) {
|
|
1291
1388
|
ctx.status = 400;
|
|
1292
1389
|
ctx.body = { success: false, error: "Target collection UID is required." };
|
|
@@ -1299,7 +1396,8 @@ const csvController = ({ strapi }) => ({
|
|
|
1299
1396
|
}
|
|
1300
1397
|
const csvService2 = strapi.plugin("bulk-updater").service("csv");
|
|
1301
1398
|
const result = await csvService2.validatePreflight(uid, rows, {
|
|
1302
|
-
mode: mode === "update" ? "update" : mode === "create_or_override" ? "create_or_override" : "auto"
|
|
1399
|
+
mode: mode === "update" ? "update" : mode === "create_or_override" ? "create_or_override" : "auto",
|
|
1400
|
+
originalHeaders: Array.isArray(originalHeaders) ? originalHeaders.map(String) : void 0
|
|
1303
1401
|
});
|
|
1304
1402
|
ctx.body = result;
|
|
1305
1403
|
} catch (err) {
|
|
@@ -1309,6 +1407,9 @@ const csvController = ({ strapi }) => ({
|
|
|
1309
1407
|
},
|
|
1310
1408
|
async submitBatch(ctx) {
|
|
1311
1409
|
try {
|
|
1410
|
+
if (!ensureCsvAuthorized(ctx, CSV_SUBMIT_BATCH_POLICY_CONFIG, strapi)) {
|
|
1411
|
+
return;
|
|
1412
|
+
}
|
|
1312
1413
|
const { uid, rows, executionMode, makerNotes, forceImmediate, mode, publish, publishStrategy, unreviewedConsent, unreviewedCount } = ctx.request.body;
|
|
1313
1414
|
if (!uid) {
|
|
1314
1415
|
ctx.status = 400;
|
|
@@ -2461,6 +2562,8 @@ function buildExportColumnPlan(strapi, uid, documents, options = {}) {
|
|
|
2461
2562
|
if (exportMode === "selective" && hasSelectedColumns) {
|
|
2462
2563
|
const columns2 = [];
|
|
2463
2564
|
const headers = [];
|
|
2565
|
+
const seenSelected = /* @__PURE__ */ new Set();
|
|
2566
|
+
const cleanSelectedColumns = [];
|
|
2464
2567
|
columns2.push({
|
|
2465
2568
|
header: "documentId",
|
|
2466
2569
|
kind: "system",
|
|
@@ -2476,50 +2579,61 @@ function buildExportColumnPlan(strapi, uid, documents, options = {}) {
|
|
|
2476
2579
|
headers.push("slug");
|
|
2477
2580
|
for (const rawCol of options.selectedColumns) {
|
|
2478
2581
|
const colName = String(rawCol).trim();
|
|
2479
|
-
if (!colName || colName === "documentId" || colName === "slug" || colName === "__bulk_updater_metadata" || colName === "_bulk_updater_metadata") {
|
|
2480
|
-
continue;
|
|
2481
|
-
}
|
|
2482
|
-
if (headers.includes(colName)) {
|
|
2582
|
+
if (!colName || colName === "documentId" || colName === "slug" || colName === "__bulk_updater_metadata" || colName === "_bulk_updater_metadata" || seenSelected.has(colName)) {
|
|
2483
2583
|
continue;
|
|
2484
2584
|
}
|
|
2585
|
+
seenSelected.add(colName);
|
|
2586
|
+
cleanSelectedColumns.push(colName);
|
|
2587
|
+
let baseDescriptor;
|
|
2485
2588
|
if (colName.includes(".")) {
|
|
2486
2589
|
const rootKey = colName.split(".")[0];
|
|
2487
2590
|
const rootField = schema.fields[rootKey];
|
|
2488
2591
|
const isRepeated = rootField?.category === "component_repeatable" || rootField?.category === "dynamiczone" || rootField?.rawType === "dynamiczone" || Array.isArray(documents) && documents.some((d) => Array.isArray(d?.[rootKey]));
|
|
2489
|
-
|
|
2490
|
-
header: colName,
|
|
2592
|
+
baseDescriptor = {
|
|
2491
2593
|
kind: "selective_nested",
|
|
2492
2594
|
rootKey,
|
|
2493
2595
|
isRepeatedNested: Boolean(isRepeated),
|
|
2494
2596
|
field: rootField
|
|
2495
|
-
}
|
|
2496
|
-
headers.push(colName);
|
|
2597
|
+
};
|
|
2497
2598
|
} else {
|
|
2498
2599
|
const field = schema.fields[colName];
|
|
2499
2600
|
if (field) {
|
|
2500
|
-
|
|
2501
|
-
header: colName,
|
|
2601
|
+
baseDescriptor = {
|
|
2502
2602
|
kind: "field",
|
|
2503
2603
|
rootKey: colName,
|
|
2504
2604
|
field
|
|
2505
|
-
}
|
|
2506
|
-
headers.push(colName);
|
|
2605
|
+
};
|
|
2507
2606
|
} else {
|
|
2508
|
-
|
|
2509
|
-
header: colName,
|
|
2607
|
+
baseDescriptor = {
|
|
2510
2608
|
kind: "selective_nested",
|
|
2511
2609
|
rootKey: colName,
|
|
2512
2610
|
isRepeatedNested: false
|
|
2513
|
-
}
|
|
2514
|
-
headers.push(colName);
|
|
2611
|
+
};
|
|
2515
2612
|
}
|
|
2516
2613
|
}
|
|
2614
|
+
const beforeHeader = `${colName}_before`;
|
|
2615
|
+
const targetHeader = `${colName}_target`;
|
|
2616
|
+
columns2.push({
|
|
2617
|
+
...baseDescriptor,
|
|
2618
|
+
header: beforeHeader,
|
|
2619
|
+
role: "before",
|
|
2620
|
+
targetKey: colName
|
|
2621
|
+
});
|
|
2622
|
+
headers.push(beforeHeader);
|
|
2623
|
+
columns2.push({
|
|
2624
|
+
...baseDescriptor,
|
|
2625
|
+
header: targetHeader,
|
|
2626
|
+
role: "target",
|
|
2627
|
+
targetKey: colName
|
|
2628
|
+
});
|
|
2629
|
+
headers.push(targetHeader);
|
|
2517
2630
|
}
|
|
2518
2631
|
return {
|
|
2519
2632
|
exportMode,
|
|
2633
|
+
columnLayout: "before_target",
|
|
2520
2634
|
columns: columns2,
|
|
2521
2635
|
headers,
|
|
2522
|
-
selectedColumns:
|
|
2636
|
+
selectedColumns: cleanSelectedColumns
|
|
2523
2637
|
};
|
|
2524
2638
|
}
|
|
2525
2639
|
const targetObjectField = resolveTargetObjectField(schema, exportMode);
|
|
@@ -2577,6 +2691,9 @@ function extractRowFlattenedMetadata(plan, doc) {
|
|
|
2577
2691
|
exportMode: plan.exportMode
|
|
2578
2692
|
};
|
|
2579
2693
|
if (plan.exportMode === "selective") {
|
|
2694
|
+
if (plan.columnLayout === "before_target") {
|
|
2695
|
+
out.columnLayout = "before_target";
|
|
2696
|
+
}
|
|
2580
2697
|
out.selectedColumns = plan.selectedColumns || plan.headers.filter((h) => h !== "documentId" && h !== "slug");
|
|
2581
2698
|
return out;
|
|
2582
2699
|
}
|
|
@@ -2627,8 +2744,9 @@ function serializePlannedCell(col, doc, serializeFieldFallback) {
|
|
|
2627
2744
|
return doc?.[col.header] ?? "";
|
|
2628
2745
|
}
|
|
2629
2746
|
if (col.kind === "selective_nested") {
|
|
2747
|
+
const lookupKey = col.targetKey || col.header;
|
|
2630
2748
|
if (col.isRepeatedNested) {
|
|
2631
|
-
const matches = getAllNestedValues(doc,
|
|
2749
|
+
const matches = getAllNestedValues(doc, lookupKey);
|
|
2632
2750
|
if (!matches || matches.length === 0) {
|
|
2633
2751
|
return "";
|
|
2634
2752
|
}
|
|
@@ -2647,7 +2765,7 @@ function serializePlannedCell(col, doc, serializeFieldFallback) {
|
|
|
2647
2765
|
});
|
|
2648
2766
|
return JSON.stringify(occurrences);
|
|
2649
2767
|
} else {
|
|
2650
|
-
const val = getDeepProp(doc,
|
|
2768
|
+
const val = getDeepProp(doc, lookupKey);
|
|
2651
2769
|
if (val === void 0 || val === null) return "";
|
|
2652
2770
|
if (val instanceof Date) return val.toISOString();
|
|
2653
2771
|
if (Array.isArray(val) || isPlainObject(val)) return JSON.stringify(val);
|
|
@@ -2738,8 +2856,20 @@ function inspectRowMetadataMode(rawRow) {
|
|
|
2738
2856
|
error: `Unsupported CSV exportMode "${parsed.exportMode}" in metadata.`
|
|
2739
2857
|
};
|
|
2740
2858
|
}
|
|
2859
|
+
let columnLayout;
|
|
2860
|
+
if (parsed.columnLayout !== void 0) {
|
|
2861
|
+
const rawLayout = String(parsed.columnLayout).trim().toLowerCase();
|
|
2862
|
+
if (rawLayout !== "before_target") {
|
|
2863
|
+
return {
|
|
2864
|
+
mode: rawMode,
|
|
2865
|
+
error: `Unsupported CSV columnLayout "${parsed.columnLayout}" in metadata.`
|
|
2866
|
+
};
|
|
2867
|
+
}
|
|
2868
|
+
columnLayout = "before_target";
|
|
2869
|
+
}
|
|
2741
2870
|
return {
|
|
2742
2871
|
mode: rawMode,
|
|
2872
|
+
...columnLayout ? { columnLayout } : {},
|
|
2743
2873
|
targetObjectField: typeof parsed.targetObjectField === "string" && parsed.targetObjectField.trim() ? parsed.targetObjectField.trim() : void 0,
|
|
2744
2874
|
targetObjectState: parsed.targetObjectState,
|
|
2745
2875
|
applicableFields: Array.isArray(parsed.applicableFields) ? parsed.applicableFields : void 0,
|
|
@@ -2765,6 +2895,189 @@ function detectCsvBatchExportMode(rows) {
|
|
|
2765
2895
|
const first = Array.from(seenModes)[0];
|
|
2766
2896
|
return { mode: first || "legacy" };
|
|
2767
2897
|
}
|
|
2898
|
+
const PRESERVED_SYSTEM_AND_STATUS_KEYS = /* @__PURE__ */ new Set([
|
|
2899
|
+
"__bulk_updater_metadata",
|
|
2900
|
+
"_bulk_updater_metadata",
|
|
2901
|
+
"documentId",
|
|
2902
|
+
"document_id",
|
|
2903
|
+
"Document ID",
|
|
2904
|
+
"Document Id",
|
|
2905
|
+
"docId",
|
|
2906
|
+
"id",
|
|
2907
|
+
"ID",
|
|
2908
|
+
"Id",
|
|
2909
|
+
"slug",
|
|
2910
|
+
"locale",
|
|
2911
|
+
"Locale",
|
|
2912
|
+
"strapi_locale",
|
|
2913
|
+
"status",
|
|
2914
|
+
"Status",
|
|
2915
|
+
"STATUS",
|
|
2916
|
+
"Published Status",
|
|
2917
|
+
"published_status",
|
|
2918
|
+
"strapi_status",
|
|
2919
|
+
"publishedAt",
|
|
2920
|
+
"published_at",
|
|
2921
|
+
"PublishedAt"
|
|
2922
|
+
]);
|
|
2923
|
+
function findDuplicateCsvHeaders(headers) {
|
|
2924
|
+
if (!Array.isArray(headers) || headers.length === 0) return [];
|
|
2925
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2926
|
+
const duplicates = [];
|
|
2927
|
+
for (const raw of headers) {
|
|
2928
|
+
const trimmed = String(raw || "").trim();
|
|
2929
|
+
if (!trimmed) continue;
|
|
2930
|
+
if (seen.has(trimmed)) {
|
|
2931
|
+
if (!duplicates.includes(trimmed)) {
|
|
2932
|
+
duplicates.push(trimmed);
|
|
2933
|
+
}
|
|
2934
|
+
} else {
|
|
2935
|
+
seen.add(trimmed);
|
|
2936
|
+
}
|
|
2937
|
+
}
|
|
2938
|
+
return duplicates;
|
|
2939
|
+
}
|
|
2940
|
+
function hasCanonicalSchemaTarget(schema, key) {
|
|
2941
|
+
if (!schema || !key) return false;
|
|
2942
|
+
if (schema.fields && Object.prototype.hasOwnProperty.call(schema.fields, key)) {
|
|
2943
|
+
return true;
|
|
2944
|
+
}
|
|
2945
|
+
const bracketIdx = key.indexOf("[");
|
|
2946
|
+
const dotIdx = key.indexOf(".");
|
|
2947
|
+
let rootKey = key;
|
|
2948
|
+
if (bracketIdx > 0 && (dotIdx === -1 || bracketIdx < dotIdx)) {
|
|
2949
|
+
rootKey = key.slice(0, bracketIdx);
|
|
2950
|
+
} else if (dotIdx > 0) {
|
|
2951
|
+
rootKey = key.slice(0, dotIdx);
|
|
2952
|
+
}
|
|
2953
|
+
return Boolean(rootKey && schema.fields && Object.prototype.hasOwnProperty.call(schema.fields, rootKey));
|
|
2954
|
+
}
|
|
2955
|
+
function normalizeSelectiveBeforeTargetRow(rawRow, rowInfo, schema) {
|
|
2956
|
+
if (!rawRow || typeof rawRow !== "object") {
|
|
2957
|
+
return {
|
|
2958
|
+
normalizedRow: rawRow,
|
|
2959
|
+
isBeforeTarget: false,
|
|
2960
|
+
ignoredBeforeColumns: [],
|
|
2961
|
+
mappedTargetFields: [],
|
|
2962
|
+
errors: []
|
|
2963
|
+
};
|
|
2964
|
+
}
|
|
2965
|
+
if (rowInfo.mode === "selective" && rowInfo.columnLayout === "before_target") {
|
|
2966
|
+
const normalizedRow = {};
|
|
2967
|
+
const ignoredBeforeColumns = [];
|
|
2968
|
+
const mappedTargetFields = [];
|
|
2969
|
+
const errors2 = [];
|
|
2970
|
+
const selectedCols = Array.isArray(rowInfo.selectedColumns) ? rowInfo.selectedColumns.map((c) => String(c).trim()).filter(Boolean) : [];
|
|
2971
|
+
const beforeSet = /* @__PURE__ */ new Set();
|
|
2972
|
+
const targetMap = /* @__PURE__ */ new Map();
|
|
2973
|
+
for (const col of selectedCols) {
|
|
2974
|
+
beforeSet.add(`${col}_before`);
|
|
2975
|
+
targetMap.set(`${col}_target`, col);
|
|
2976
|
+
}
|
|
2977
|
+
if (selectedCols.length > 0) {
|
|
2978
|
+
const hasAnyTargetCol = selectedCols.some(
|
|
2979
|
+
(col) => Object.prototype.hasOwnProperty.call(rawRow, `${col}_target`)
|
|
2980
|
+
);
|
|
2981
|
+
const presentBeforeCols = selectedCols.filter(
|
|
2982
|
+
(col) => Object.prototype.hasOwnProperty.call(rawRow, `${col}_before`)
|
|
2983
|
+
);
|
|
2984
|
+
if (!hasAnyTargetCol && presentBeforeCols.length > 0) {
|
|
2985
|
+
const expectedTargets = presentBeforeCols.map((col) => `${col}_target`);
|
|
2986
|
+
errors2.push(
|
|
2987
|
+
`Missing Target column(s) [${expectedTargets.join(", ")}] in Before/Target CSV. Import requires "<field>_target" headers.`
|
|
2988
|
+
);
|
|
2989
|
+
}
|
|
2990
|
+
}
|
|
2991
|
+
for (const [k, v] of Object.entries(rawRow)) {
|
|
2992
|
+
if (PRESERVED_SYSTEM_AND_STATUS_KEYS.has(k)) {
|
|
2993
|
+
normalizedRow[k] = v;
|
|
2994
|
+
continue;
|
|
2995
|
+
}
|
|
2996
|
+
if (beforeSet.size > 0) {
|
|
2997
|
+
if (beforeSet.has(k)) {
|
|
2998
|
+
ignoredBeforeColumns.push(k);
|
|
2999
|
+
continue;
|
|
3000
|
+
}
|
|
3001
|
+
if (targetMap.has(k)) {
|
|
3002
|
+
const canonicalKey = targetMap.get(k);
|
|
3003
|
+
normalizedRow[canonicalKey] = v;
|
|
3004
|
+
mappedTargetFields.push(canonicalKey);
|
|
3005
|
+
}
|
|
3006
|
+
} else {
|
|
3007
|
+
if (k.endsWith("_before")) {
|
|
3008
|
+
ignoredBeforeColumns.push(k);
|
|
3009
|
+
continue;
|
|
3010
|
+
}
|
|
3011
|
+
if (k.endsWith("_target")) {
|
|
3012
|
+
const canonicalKey = k.slice(0, -7);
|
|
3013
|
+
if (canonicalKey) {
|
|
3014
|
+
normalizedRow[canonicalKey] = v;
|
|
3015
|
+
mappedTargetFields.push(canonicalKey);
|
|
3016
|
+
}
|
|
3017
|
+
}
|
|
3018
|
+
}
|
|
3019
|
+
}
|
|
3020
|
+
return {
|
|
3021
|
+
normalizedRow,
|
|
3022
|
+
isBeforeTarget: true,
|
|
3023
|
+
ignoredBeforeColumns,
|
|
3024
|
+
mappedTargetFields,
|
|
3025
|
+
errors: errors2
|
|
3026
|
+
};
|
|
3027
|
+
}
|
|
3028
|
+
if (rowInfo.mode === "legacy" && schema) {
|
|
3029
|
+
const pairedBases = /* @__PURE__ */ new Map();
|
|
3030
|
+
for (const key of Object.keys(rawRow)) {
|
|
3031
|
+
if (PRESERVED_SYSTEM_AND_STATUS_KEYS.has(key) || !key.endsWith("_target")) continue;
|
|
3032
|
+
const base = key.slice(0, -7);
|
|
3033
|
+
if (!base) continue;
|
|
3034
|
+
const beforeKey = `${base}_before`;
|
|
3035
|
+
const isLiteralTargetAttr = Boolean(schema.fields && Object.prototype.hasOwnProperty.call(schema.fields, key));
|
|
3036
|
+
const isLiteralBeforeAttr = Boolean(schema.fields && Object.prototype.hasOwnProperty.call(schema.fields, beforeKey));
|
|
3037
|
+
if (!isLiteralTargetAttr && !isLiteralBeforeAttr && Object.prototype.hasOwnProperty.call(rawRow, beforeKey) && hasCanonicalSchemaTarget(schema, base)) {
|
|
3038
|
+
pairedBases.set(base, { beforeKey, targetKey: key });
|
|
3039
|
+
}
|
|
3040
|
+
}
|
|
3041
|
+
if (pairedBases.size > 0) {
|
|
3042
|
+
const beforeSet = /* @__PURE__ */ new Set();
|
|
3043
|
+
const targetMap = /* @__PURE__ */ new Map();
|
|
3044
|
+
for (const [base, pair] of pairedBases.entries()) {
|
|
3045
|
+
beforeSet.add(pair.beforeKey);
|
|
3046
|
+
targetMap.set(pair.targetKey, base);
|
|
3047
|
+
}
|
|
3048
|
+
const normalizedRow = {};
|
|
3049
|
+
const ignoredBeforeColumns = [];
|
|
3050
|
+
const mappedTargetFields = [];
|
|
3051
|
+
for (const [k, v] of Object.entries(rawRow)) {
|
|
3052
|
+
if (beforeSet.has(k)) {
|
|
3053
|
+
ignoredBeforeColumns.push(k);
|
|
3054
|
+
continue;
|
|
3055
|
+
}
|
|
3056
|
+
if (targetMap.has(k)) {
|
|
3057
|
+
const canonicalKey = targetMap.get(k);
|
|
3058
|
+
normalizedRow[canonicalKey] = v;
|
|
3059
|
+
mappedTargetFields.push(canonicalKey);
|
|
3060
|
+
continue;
|
|
3061
|
+
}
|
|
3062
|
+
normalizedRow[k] = v;
|
|
3063
|
+
}
|
|
3064
|
+
return {
|
|
3065
|
+
normalizedRow,
|
|
3066
|
+
isBeforeTarget: true,
|
|
3067
|
+
ignoredBeforeColumns,
|
|
3068
|
+
mappedTargetFields,
|
|
3069
|
+
errors: []
|
|
3070
|
+
};
|
|
3071
|
+
}
|
|
3072
|
+
}
|
|
3073
|
+
return {
|
|
3074
|
+
normalizedRow: rawRow,
|
|
3075
|
+
isBeforeTarget: false,
|
|
3076
|
+
ignoredBeforeColumns: [],
|
|
3077
|
+
mappedTargetFields: [],
|
|
3078
|
+
errors: []
|
|
3079
|
+
};
|
|
3080
|
+
}
|
|
2768
3081
|
function parseFirstLevelCellValue(rawCell, annotatedType, existingPropValue) {
|
|
2769
3082
|
if (rawCell === null || rawCell === void 0) return { value: null };
|
|
2770
3083
|
if (typeof rawCell !== "string") return { value: rawCell };
|
|
@@ -3273,6 +3586,7 @@ function serializeDocumentsToCsv(strapi, uid, documents, options = {}) {
|
|
|
3273
3586
|
locale: doc.locale || void 0,
|
|
3274
3587
|
exportedAt,
|
|
3275
3588
|
...flattenedMeta.exportMode ? { exportMode: flattenedMeta.exportMode } : {},
|
|
3589
|
+
...flattenedMeta.columnLayout ? { columnLayout: flattenedMeta.columnLayout } : {},
|
|
3276
3590
|
...flattenedMeta.selectedColumns ? { selectedColumns: flattenedMeta.selectedColumns } : {},
|
|
3277
3591
|
...flattenedMeta.targetObjectField ? { targetObjectField: flattenedMeta.targetObjectField } : {},
|
|
3278
3592
|
...flattenedMeta.targetObjectState ? { targetObjectState: flattenedMeta.targetObjectState } : {},
|
|
@@ -3740,18 +4054,30 @@ async function prepareCsvRowMutation(strapi, uid, existingDoc, rawRow, options =
|
|
|
3740
4054
|
const warnings = [];
|
|
3741
4055
|
const isPartialUpdate = options.isPartialUpdate !== false;
|
|
3742
4056
|
const isCreate = options.isCreate !== void 0 ? options.isCreate : !existingDoc;
|
|
3743
|
-
const
|
|
4057
|
+
const rawUnescapedRow = {};
|
|
3744
4058
|
for (const [k, v] of Object.entries(rawRow || {})) {
|
|
3745
4059
|
let cleanVal = v;
|
|
3746
4060
|
if (typeof cleanVal === "string" && /^'[=+@-]/.test(cleanVal)) {
|
|
3747
4061
|
cleanVal = cleanVal.substring(1);
|
|
3748
4062
|
}
|
|
3749
|
-
|
|
4063
|
+
rawUnescapedRow[k] = cleanVal;
|
|
3750
4064
|
}
|
|
3751
|
-
const rowInfo = inspectRowMetadataMode(
|
|
4065
|
+
const rowInfo = inspectRowMetadataMode(rawUnescapedRow);
|
|
3752
4066
|
if (rowInfo.error) {
|
|
3753
4067
|
errors2.push(rowInfo.error);
|
|
3754
4068
|
}
|
|
4069
|
+
const beforeTargetNorm = normalizeSelectiveBeforeTargetRow(rawUnescapedRow, rowInfo, schema);
|
|
4070
|
+
if (beforeTargetNorm.errors.length > 0) {
|
|
4071
|
+
errors2.push(...beforeTargetNorm.errors);
|
|
4072
|
+
return {
|
|
4073
|
+
payload: {},
|
|
4074
|
+
errors: errors2,
|
|
4075
|
+
warnings,
|
|
4076
|
+
detectedMode: rowInfo.mode,
|
|
4077
|
+
rowMeta: rowInfo
|
|
4078
|
+
};
|
|
4079
|
+
}
|
|
4080
|
+
const unescapedRow = beforeTargetNorm.normalizedRow;
|
|
3755
4081
|
const detectedMode = rowInfo.mode;
|
|
3756
4082
|
if (options.expectedExportMode && detectedMode !== options.expectedExportMode) {
|
|
3757
4083
|
errors2.push(
|
|
@@ -3881,6 +4207,18 @@ async function prepareCsvRowMutation(strapi, uid, existingDoc, rawRow, options =
|
|
|
3881
4207
|
}
|
|
3882
4208
|
} else if (field.category === "json") {
|
|
3883
4209
|
targetVal = parseFirstLevelCellValue(strCell, "object", currentVal).value;
|
|
4210
|
+
} else if (field.category === "blocks") {
|
|
4211
|
+
if (trimmed.startsWith("[") || trimmed.startsWith("{")) {
|
|
4212
|
+
try {
|
|
4213
|
+
const parsedBlocks = JSON.parse(trimmed);
|
|
4214
|
+
targetVal = Array.isArray(parsedBlocks) ? parsedBlocks : [parsedBlocks];
|
|
4215
|
+
} catch {
|
|
4216
|
+
errors2.push(`Column "${colKey}": Invalid JSON blocks value.`);
|
|
4217
|
+
continue;
|
|
4218
|
+
}
|
|
4219
|
+
} else {
|
|
4220
|
+
targetVal = [{ type: "paragraph", children: [{ type: "text", text: strCell }] }];
|
|
4221
|
+
}
|
|
3884
4222
|
} else if (field.category === "relation_to_one") {
|
|
3885
4223
|
targetVal = resolveRelationPayload(strCell, false);
|
|
3886
4224
|
} else if (field.category === "relation_to_many") {
|
|
@@ -3892,7 +4230,24 @@ async function prepareCsvRowMutation(strapi, uid, existingDoc, rawRow, options =
|
|
|
3892
4230
|
} else {
|
|
3893
4231
|
targetVal = strCell;
|
|
3894
4232
|
}
|
|
3895
|
-
|
|
4233
|
+
let hasFieldChanged = true;
|
|
4234
|
+
if (field?.category === "relation_to_one" || field?.category === "relation_to_many") {
|
|
4235
|
+
if (targetVal && typeof targetVal === "object" && Array.isArray(targetVal.set) && !targetVal.connect && !targetVal.disconnect) {
|
|
4236
|
+
const existingDocIds = Array.isArray(currentVal) ? currentVal.map((item) => String(item?.documentId || item?.id || item)).filter(Boolean) : currentVal && typeof currentVal === "object" ? currentVal.documentId || currentVal.id ? [String(currentVal.documentId || currentVal.id)] : [] : currentVal !== null && currentVal !== void 0 && currentVal !== "" ? [String(currentVal)] : [];
|
|
4237
|
+
hasFieldChanged = !deepEqualValues(targetVal.set, existingDocIds);
|
|
4238
|
+
} else {
|
|
4239
|
+
hasFieldChanged = !deepEqualValues(targetVal, currentVal);
|
|
4240
|
+
}
|
|
4241
|
+
} else if (field?.category === "media_single") {
|
|
4242
|
+
const existingMediaId = currentVal && typeof currentVal === "object" ? currentVal.id ?? null : currentVal ?? null;
|
|
4243
|
+
hasFieldChanged = (targetVal ?? null) !== existingMediaId;
|
|
4244
|
+
} else if (field?.category === "media_to_many") {
|
|
4245
|
+
const existingMediaIds = Array.isArray(currentVal) ? currentVal.map((f) => f && typeof f === "object" ? f.id : f).filter((v) => v !== void 0 && v !== null) : [];
|
|
4246
|
+
hasFieldChanged = !deepEqualValues(Array.isArray(targetVal) ? targetVal : [], existingMediaIds);
|
|
4247
|
+
} else {
|
|
4248
|
+
hasFieldChanged = !deepEqualValues(targetVal, currentVal);
|
|
4249
|
+
}
|
|
4250
|
+
if (hasFieldChanged) {
|
|
3896
4251
|
payload[colKey] = targetVal;
|
|
3897
4252
|
hasRowChanges = true;
|
|
3898
4253
|
}
|
|
@@ -9244,6 +9599,96 @@ function withRollbackLock(fn) {
|
|
|
9244
9599
|
}
|
|
9245
9600
|
});
|
|
9246
9601
|
}
|
|
9602
|
+
function getDiffEntryKey(item) {
|
|
9603
|
+
const loc = item?.locale && item.locale !== "null" && item.locale !== "undefined" ? item.locale : "";
|
|
9604
|
+
return `${item.uid}@@@${item.documentId}@@@${loc}`;
|
|
9605
|
+
}
|
|
9606
|
+
function getRevertibleDiffs(diffs) {
|
|
9607
|
+
if (!Array.isArray(diffs)) return [];
|
|
9608
|
+
return diffs.filter(
|
|
9609
|
+
(item) => item?.status === "updated" && item?.uid && item?.documentId && item?.attribute
|
|
9610
|
+
);
|
|
9611
|
+
}
|
|
9612
|
+
function computeRollbackOverlap(sortedHistory, targetIdx) {
|
|
9613
|
+
const empty = {
|
|
9614
|
+
hasOverlap: false,
|
|
9615
|
+
newerActiveBatchIds: [],
|
|
9616
|
+
affectedDocumentIds: [],
|
|
9617
|
+
affectedEntryCount: 0
|
|
9618
|
+
};
|
|
9619
|
+
if (targetIdx <= 0 || targetIdx >= sortedHistory.length) {
|
|
9620
|
+
return empty;
|
|
9621
|
+
}
|
|
9622
|
+
const targetDiffs = getRevertibleDiffs(sortedHistory[targetIdx]?.diffs);
|
|
9623
|
+
if (targetDiffs.length === 0) {
|
|
9624
|
+
return empty;
|
|
9625
|
+
}
|
|
9626
|
+
const targetEntryKeys = new Set(targetDiffs.map(getDiffEntryKey));
|
|
9627
|
+
const newerActiveBatchIds = [];
|
|
9628
|
+
const affectedEntryKeySet = /* @__PURE__ */ new Set();
|
|
9629
|
+
const affectedDocumentIdSet = /* @__PURE__ */ new Set();
|
|
9630
|
+
for (let i = 0; i < targetIdx; i++) {
|
|
9631
|
+
const newer = sortedHistory[i];
|
|
9632
|
+
if (!newer || newer.isRolledBack) continue;
|
|
9633
|
+
const newerDiffs = getRevertibleDiffs(newer.diffs);
|
|
9634
|
+
let batchOverlaps = false;
|
|
9635
|
+
for (const nd of newerDiffs) {
|
|
9636
|
+
const key = getDiffEntryKey(nd);
|
|
9637
|
+
if (targetEntryKeys.has(key)) {
|
|
9638
|
+
batchOverlaps = true;
|
|
9639
|
+
affectedEntryKeySet.add(key);
|
|
9640
|
+
if (nd.documentId) affectedDocumentIdSet.add(String(nd.documentId));
|
|
9641
|
+
}
|
|
9642
|
+
}
|
|
9643
|
+
if (batchOverlaps && newer.batchId) {
|
|
9644
|
+
newerActiveBatchIds.push(String(newer.batchId));
|
|
9645
|
+
}
|
|
9646
|
+
}
|
|
9647
|
+
return {
|
|
9648
|
+
hasOverlap: newerActiveBatchIds.length > 0,
|
|
9649
|
+
newerActiveBatchIds,
|
|
9650
|
+
affectedDocumentIds: Array.from(affectedDocumentIdSet),
|
|
9651
|
+
affectedEntryCount: affectedEntryKeySet.size
|
|
9652
|
+
};
|
|
9653
|
+
}
|
|
9654
|
+
function isBatchRollbackEligible(rec) {
|
|
9655
|
+
if (!rec || rec.isRolledBack) return false;
|
|
9656
|
+
const rawDiffs = Array.isArray(rec.diffs) ? rec.diffs : [];
|
|
9657
|
+
if (rawDiffs.length === 0) return true;
|
|
9658
|
+
return getRevertibleDiffs(rawDiffs).length > 0;
|
|
9659
|
+
}
|
|
9660
|
+
function enrichAuditHistoryWithRollbackMeta(sortedHistory) {
|
|
9661
|
+
const latestRecord = sortedHistory.length > 0 ? sortedHistory[0] : null;
|
|
9662
|
+
return sortedHistory.map((rec, idx) => ({
|
|
9663
|
+
...rec,
|
|
9664
|
+
isLatestEligible: Boolean(
|
|
9665
|
+
latestRecord && rec.batchId === latestRecord.batchId && !latestRecord.isRolledBack
|
|
9666
|
+
),
|
|
9667
|
+
isRollbackEligible: isBatchRollbackEligible(rec),
|
|
9668
|
+
overlapWarning: !rec?.isRolledBack ? computeRollbackOverlap(sortedHistory, idx) : { hasOverlap: false, newerActiveBatchIds: [], affectedDocumentIds: [], affectedEntryCount: 0 }
|
|
9669
|
+
}));
|
|
9670
|
+
}
|
|
9671
|
+
function validateRollbackCandidate(sortedHistory, batchId, confirmOverwrite) {
|
|
9672
|
+
const targetIdx = sortedHistory.findIndex((r) => r.batchId === batchId);
|
|
9673
|
+
if (targetIdx === -1) {
|
|
9674
|
+
throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
|
|
9675
|
+
}
|
|
9676
|
+
const targetRecord = sortedHistory[targetIdx];
|
|
9677
|
+
if (targetRecord.isRolledBack) {
|
|
9678
|
+
throw new Error(`Batch "${batchId}" has already been rolled back.`);
|
|
9679
|
+
}
|
|
9680
|
+
const rawDiffs = Array.isArray(targetRecord.diffs) ? targetRecord.diffs : [];
|
|
9681
|
+
if (rawDiffs.length > 0 && getRevertibleDiffs(rawDiffs).length === 0) {
|
|
9682
|
+
throw new Error(`Batch "${batchId}" has no revertible updates to roll back.`);
|
|
9683
|
+
}
|
|
9684
|
+
const overlap = computeRollbackOverlap(sortedHistory, targetIdx);
|
|
9685
|
+
if (overlap.hasOverlap && !confirmOverwrite) {
|
|
9686
|
+
throw new Error(
|
|
9687
|
+
`Historical rollback of batch "${batchId}" overlaps newer active batch(es) [${overlap.newerActiveBatchIds.join(", ")}] on ${overlap.affectedEntryCount} entry/entries and will overwrite newer changes/status with pre-batch snapshots. Pass confirmOverwrite=true to proceed.`
|
|
9688
|
+
);
|
|
9689
|
+
}
|
|
9690
|
+
return { targetRecord, overlap };
|
|
9691
|
+
}
|
|
9247
9692
|
const auditService = ({ strapi }) => ({
|
|
9248
9693
|
/**
|
|
9249
9694
|
* Detects whether Strapi Enterprise Native Audit Log service is available.
|
|
@@ -9474,13 +9919,7 @@ const auditService = ({ strapi }) => ({
|
|
|
9474
9919
|
const stored = await store.get({}) || { history: [] };
|
|
9475
9920
|
const rawHistory = Array.isArray(stored.history) ? stored.history : [];
|
|
9476
9921
|
const sortedHistory = sortAuditRecordsDesc(rawHistory);
|
|
9477
|
-
const
|
|
9478
|
-
const history = sortedHistory.map((rec) => ({
|
|
9479
|
-
...rec,
|
|
9480
|
-
isLatestEligible: Boolean(
|
|
9481
|
-
latestRecord && rec.batchId === latestRecord.batchId && !latestRecord.isRolledBack
|
|
9482
|
-
)
|
|
9483
|
-
}));
|
|
9922
|
+
const history = enrichAuditHistoryWithRollbackMeta(sortedHistory);
|
|
9484
9923
|
return {
|
|
9485
9924
|
enabled: true,
|
|
9486
9925
|
mode: "store",
|
|
@@ -9526,13 +9965,7 @@ const auditService = ({ strapi }) => ({
|
|
|
9526
9965
|
createdAt: r.createdAt
|
|
9527
9966
|
}));
|
|
9528
9967
|
const sortedHistory = sortAuditRecordsDesc(normalized);
|
|
9529
|
-
const
|
|
9530
|
-
const history = sortedHistory.map((rec) => ({
|
|
9531
|
-
...rec,
|
|
9532
|
-
isLatestEligible: Boolean(
|
|
9533
|
-
latestRecord && rec.batchId === latestRecord.batchId && !latestRecord.isRolledBack
|
|
9534
|
-
)
|
|
9535
|
-
}));
|
|
9968
|
+
const history = enrichAuditHistoryWithRollbackMeta(sortedHistory);
|
|
9536
9969
|
return {
|
|
9537
9970
|
enabled: true,
|
|
9538
9971
|
mode: config.mode,
|
|
@@ -9552,243 +9985,246 @@ const auditService = ({ strapi }) => ({
|
|
|
9552
9985
|
* Helper to revert diff items back to original values
|
|
9553
9986
|
*/
|
|
9554
9987
|
async revertDiffItems(diffs, userId) {
|
|
9555
|
-
|
|
9556
|
-
|
|
9557
|
-
|
|
9558
|
-
|
|
9559
|
-
|
|
9560
|
-
|
|
9561
|
-
|
|
9562
|
-
|
|
9563
|
-
|
|
9564
|
-
|
|
9565
|
-
|
|
9566
|
-
|
|
9567
|
-
|
|
9568
|
-
|
|
9569
|
-
|
|
9570
|
-
|
|
9571
|
-
|
|
9572
|
-
|
|
9573
|
-
|
|
9574
|
-
|
|
9575
|
-
|
|
9576
|
-
|
|
9577
|
-
|
|
9578
|
-
|
|
9579
|
-
|
|
9580
|
-
|
|
9581
|
-
|
|
9582
|
-
|
|
9583
|
-
|
|
9584
|
-
|
|
9585
|
-
|
|
9586
|
-
|
|
9587
|
-
|
|
9588
|
-
|
|
9589
|
-
|
|
9590
|
-
|
|
9591
|
-
|
|
9592
|
-
|
|
9593
|
-
|
|
9594
|
-
|
|
9595
|
-
|
|
9596
|
-
|
|
9597
|
-
|
|
9598
|
-
|
|
9599
|
-
|
|
9600
|
-
|
|
9601
|
-
|
|
9602
|
-
const
|
|
9603
|
-
|
|
9604
|
-
|
|
9605
|
-
|
|
9606
|
-
|
|
9607
|
-
|
|
9608
|
-
|
|
9609
|
-
|
|
9610
|
-
|
|
9611
|
-
|
|
9612
|
-
|
|
9613
|
-
|
|
9614
|
-
|
|
9615
|
-
|
|
9616
|
-
|
|
9617
|
-
|
|
9618
|
-
|
|
9619
|
-
|
|
9620
|
-
|
|
9621
|
-
if (reverted.errors.length > 0) {
|
|
9622
|
-
throw new Error(reverted.errors.join("; "));
|
|
9623
|
-
}
|
|
9624
|
-
restoredRoot = reverted.updateData[rootKey];
|
|
9625
|
-
} else {
|
|
9626
|
-
let workingRoot = existingRoot;
|
|
9627
|
-
for (const dzDiff of item.dynamicZoneDiffs) {
|
|
9628
|
-
const parsedDz = parseDynamicZonePath(dzDiff.attribute || item.attribute);
|
|
9629
|
-
const dzParts = parsedDz.cleanPath.split(".").slice(1);
|
|
9630
|
-
const targetIndexes = dzDiff.index !== void 0 ? [dzDiff.index] : parsedDz.targetIndex !== void 0 ? [parsedDz.targetIndex] : void 0;
|
|
9631
|
-
workingRoot = setDeepProperty(workingRoot, dzParts, dzDiff.oldValue ?? null, {
|
|
9632
|
-
targetIndexes,
|
|
9633
|
-
targetComponentUid: dzDiff.componentUid || parsedDz.targetComponentUid,
|
|
9634
|
-
strapi
|
|
9988
|
+
return runInRollbackContext(async () => {
|
|
9989
|
+
const revertedEntryKeys = /* @__PURE__ */ new Set();
|
|
9990
|
+
const rollbackDetails = [];
|
|
9991
|
+
for (const item of diffs) {
|
|
9992
|
+
if (item.status === "updated" && item.uid && item.documentId && item.attribute) {
|
|
9993
|
+
try {
|
|
9994
|
+
const ct = strapi.contentTypes[item.uid];
|
|
9995
|
+
if (!ct) {
|
|
9996
|
+
throw new Error(`Content type "${item.uid}" does not exist in schema.`);
|
|
9997
|
+
}
|
|
9998
|
+
const isRel = item.oldValue && typeof item.oldValue === "object" && item.oldValue.isRelation;
|
|
9999
|
+
let rollbackPayload;
|
|
10000
|
+
if (isRel) {
|
|
10001
|
+
const oldDocIds = Array.isArray(item.oldValue.documentIds) ? item.oldValue.documentIds : [];
|
|
10002
|
+
rollbackPayload = { set: oldDocIds };
|
|
10003
|
+
} else {
|
|
10004
|
+
rollbackPayload = item.oldValue ?? null;
|
|
10005
|
+
}
|
|
10006
|
+
const parsed = parseDynamicZonePath(item.attribute);
|
|
10007
|
+
const rootKey = parsed.rootKey;
|
|
10008
|
+
const rootAttrDef = ct.attributes?.[rootKey];
|
|
10009
|
+
const isComponent = rootAttrDef?.type === "component";
|
|
10010
|
+
const isDynamicZone = rootAttrDef?.type === "dynamiczone";
|
|
10011
|
+
const isNested = item.attribute.includes(".") || item.attribute.includes("[") || isComponent || isDynamicZone || isDeepComponentField(ct, strapi.components, item.attribute);
|
|
10012
|
+
const isLocalized = Boolean(ct?.pluginOptions?.i18n?.localized) && item.locale && item.locale !== "null" && item.locale !== "undefined";
|
|
10013
|
+
const isDraftAndPublish = Boolean(ct?.options?.draftAndPublish ?? item.isDraftAndPublish);
|
|
10014
|
+
const populateOption = isNested ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
|
|
10015
|
+
const findOneArgs = { documentId: item.documentId };
|
|
10016
|
+
if (populateOption) {
|
|
10017
|
+
findOneArgs.populate = populateOption;
|
|
10018
|
+
}
|
|
10019
|
+
if (isLocalized) {
|
|
10020
|
+
findOneArgs.locale = item.locale;
|
|
10021
|
+
}
|
|
10022
|
+
const currentDoc = await strapi.documents(item.uid).findOne(findOneArgs);
|
|
10023
|
+
if (!currentDoc) {
|
|
10024
|
+
throw new Error(`Document "${item.documentId}" not found in collection "${item.uid}".`);
|
|
10025
|
+
}
|
|
10026
|
+
if (isNested && (isComponent || isDynamicZone || rootAttrDef)) {
|
|
10027
|
+
const isRootDz = isDynamicZone;
|
|
10028
|
+
const existingRoot = currentDoc?.[rootKey] || (isRootDz ? [] : {});
|
|
10029
|
+
let restoredRoot;
|
|
10030
|
+
if (Array.isArray(item.dynamicZoneDiffs) && item.dynamicZoneDiffs.length > 0) {
|
|
10031
|
+
const hasStructuredSegments = item.dynamicZoneDiffs.some(
|
|
10032
|
+
(dz) => Array.isArray(dz?.segments) && dz.segments.length > 0
|
|
10033
|
+
);
|
|
10034
|
+
if (hasStructuredSegments) {
|
|
10035
|
+
const occUpdates = item.dynamicZoneDiffs.map((dzDiff) => {
|
|
10036
|
+
const isRelDiff = dzDiff.oldValue && typeof dzDiff.oldValue === "object" && dzDiff.oldValue.isRelation;
|
|
10037
|
+
const val = isRelDiff ? { mode: "set", documentIds: Array.isArray(dzDiff.oldValue.documentIds) ? dzDiff.oldValue.documentIds : [] } : dzDiff.oldValue ?? null;
|
|
10038
|
+
return {
|
|
10039
|
+
occurrenceKey: dzDiff.occurrenceKey,
|
|
10040
|
+
segments: dzDiff.segments,
|
|
10041
|
+
dynamicZoneIndex: dzDiff.index,
|
|
10042
|
+
componentId: dzDiff.componentId,
|
|
10043
|
+
componentUid: dzDiff.componentUid,
|
|
10044
|
+
value: val
|
|
10045
|
+
};
|
|
10046
|
+
});
|
|
10047
|
+
const reverted = await applyOccurrenceUpdatesToDocument({
|
|
10048
|
+
strapi,
|
|
10049
|
+
contentType: ct,
|
|
10050
|
+
allComponents: strapi.components,
|
|
10051
|
+
currentDoc,
|
|
10052
|
+
attribute: item.attribute,
|
|
10053
|
+
updates: occUpdates
|
|
9635
10054
|
});
|
|
10055
|
+
if (reverted.errors.length > 0) {
|
|
10056
|
+
throw new Error(reverted.errors.join("; "));
|
|
10057
|
+
}
|
|
10058
|
+
restoredRoot = reverted.updateData[rootKey];
|
|
10059
|
+
} else {
|
|
10060
|
+
let workingRoot = existingRoot;
|
|
10061
|
+
for (const dzDiff of item.dynamicZoneDiffs) {
|
|
10062
|
+
const parsedDz = parseDynamicZonePath(dzDiff.attribute || item.attribute);
|
|
10063
|
+
const dzParts = parsedDz.cleanPath.split(".").slice(1);
|
|
10064
|
+
const targetIndexes = dzDiff.index !== void 0 ? [dzDiff.index] : parsedDz.targetIndex !== void 0 ? [parsedDz.targetIndex] : void 0;
|
|
10065
|
+
workingRoot = setDeepProperty(workingRoot, dzParts, dzDiff.oldValue ?? null, {
|
|
10066
|
+
targetIndexes,
|
|
10067
|
+
targetComponentUid: dzDiff.componentUid || parsedDz.targetComponentUid,
|
|
10068
|
+
strapi
|
|
10069
|
+
});
|
|
10070
|
+
}
|
|
10071
|
+
restoredRoot = workingRoot;
|
|
9636
10072
|
}
|
|
9637
|
-
|
|
10073
|
+
} else {
|
|
10074
|
+
const parts = parsed.cleanPath.split(".");
|
|
10075
|
+
const pathParts = parts.slice(1);
|
|
10076
|
+
const targetIndexes = parsed.targetIndex !== void 0 ? [parsed.targetIndex] : void 0;
|
|
10077
|
+
const targetComponentUid = parsed.targetComponentUid;
|
|
10078
|
+
restoredRoot = setDeepProperty(existingRoot, pathParts, rollbackPayload, {
|
|
10079
|
+
targetIndexes,
|
|
10080
|
+
targetComponentUid,
|
|
10081
|
+
strapi
|
|
10082
|
+
});
|
|
9638
10083
|
}
|
|
9639
|
-
|
|
9640
|
-
|
|
9641
|
-
|
|
9642
|
-
|
|
9643
|
-
|
|
9644
|
-
|
|
9645
|
-
targetIndexes,
|
|
9646
|
-
targetComponentUid,
|
|
9647
|
-
strapi
|
|
10084
|
+
await strapi.documents(item.uid).update({
|
|
10085
|
+
documentId: item.documentId,
|
|
10086
|
+
...isLocalized ? { locale: item.locale } : {},
|
|
10087
|
+
data: {
|
|
10088
|
+
[rootKey]: restoredRoot
|
|
10089
|
+
}
|
|
9648
10090
|
});
|
|
9649
|
-
}
|
|
9650
|
-
|
|
9651
|
-
|
|
9652
|
-
|
|
9653
|
-
|
|
9654
|
-
|
|
9655
|
-
}
|
|
9656
|
-
});
|
|
9657
|
-
} else {
|
|
9658
|
-
await strapi.documents(item.uid).update({
|
|
9659
|
-
documentId: item.documentId,
|
|
9660
|
-
...isLocalized ? { locale: item.locale } : {},
|
|
9661
|
-
data: {
|
|
9662
|
-
[item.attribute]: rollbackPayload
|
|
9663
|
-
}
|
|
9664
|
-
});
|
|
9665
|
-
}
|
|
9666
|
-
let targetStatus = void 0;
|
|
9667
|
-
if (item.previousStatus === "published" || item.previousStatus === "modified" || item.previousStatus === "draft") {
|
|
9668
|
-
targetStatus = item.previousStatus;
|
|
9669
|
-
} else if (item.hadPublishedVersion === false) {
|
|
9670
|
-
targetStatus = "draft";
|
|
9671
|
-
} else if (item.hadPublishedVersion === true) {
|
|
9672
|
-
targetStatus = "published";
|
|
9673
|
-
}
|
|
9674
|
-
if (isDraftAndPublish && !targetStatus) {
|
|
9675
|
-
let publishedCounterpart = null;
|
|
9676
|
-
try {
|
|
9677
|
-
const docSvc = strapi.documents(item.uid);
|
|
9678
|
-
if (typeof docSvc.findMany === "function") {
|
|
9679
|
-
const pubs = await docSvc.findMany({
|
|
9680
|
-
status: "published",
|
|
9681
|
-
filters: { documentId: item.documentId },
|
|
9682
|
-
fields: ["documentId", "publishedAt"],
|
|
9683
|
-
limit: 1,
|
|
9684
|
-
...isLocalized ? { locale: item.locale } : {}
|
|
9685
|
-
});
|
|
9686
|
-
if (pubs && pubs.length > 0) {
|
|
9687
|
-
publishedCounterpart = pubs[0];
|
|
10091
|
+
} else {
|
|
10092
|
+
await strapi.documents(item.uid).update({
|
|
10093
|
+
documentId: item.documentId,
|
|
10094
|
+
...isLocalized ? { locale: item.locale } : {},
|
|
10095
|
+
data: {
|
|
10096
|
+
[item.attribute]: rollbackPayload
|
|
9688
10097
|
}
|
|
9689
|
-
}
|
|
9690
|
-
} catch {
|
|
10098
|
+
});
|
|
9691
10099
|
}
|
|
9692
|
-
|
|
9693
|
-
|
|
9694
|
-
|
|
10100
|
+
let targetStatus = void 0;
|
|
10101
|
+
if (item.previousStatus === "published" || item.previousStatus === "modified" || item.previousStatus === "draft") {
|
|
10102
|
+
targetStatus = item.previousStatus;
|
|
10103
|
+
} else if (item.hadPublishedVersion === false) {
|
|
9695
10104
|
targetStatus = "draft";
|
|
10105
|
+
} else if (item.hadPublishedVersion === true) {
|
|
10106
|
+
targetStatus = "published";
|
|
9696
10107
|
}
|
|
9697
|
-
|
|
9698
|
-
|
|
9699
|
-
const docSvc = strapi.documents(item.uid);
|
|
9700
|
-
if (targetStatus === "published") {
|
|
10108
|
+
if (isDraftAndPublish && !targetStatus) {
|
|
10109
|
+
let publishedCounterpart = null;
|
|
9701
10110
|
try {
|
|
9702
|
-
|
|
9703
|
-
|
|
9704
|
-
|
|
10111
|
+
const docSvc = strapi.documents(item.uid);
|
|
10112
|
+
if (typeof docSvc.findMany === "function") {
|
|
10113
|
+
const pubs = await docSvc.findMany({
|
|
10114
|
+
status: "published",
|
|
10115
|
+
filters: { documentId: item.documentId },
|
|
10116
|
+
fields: ["documentId", "publishedAt"],
|
|
10117
|
+
limit: 1,
|
|
9705
10118
|
...isLocalized ? { locale: item.locale } : {}
|
|
9706
10119
|
});
|
|
10120
|
+
if (pubs && pubs.length > 0) {
|
|
10121
|
+
publishedCounterpart = pubs[0];
|
|
10122
|
+
}
|
|
9707
10123
|
}
|
|
9708
|
-
} catch
|
|
9709
|
-
strapi.log.warn(
|
|
9710
|
-
`[bulk-updater] Failed to auto-publish rollback for ${item.uid}/${item.documentId}:`,
|
|
9711
|
-
publishErr?.message
|
|
9712
|
-
);
|
|
10124
|
+
} catch {
|
|
9713
10125
|
}
|
|
9714
|
-
|
|
9715
|
-
|
|
9716
|
-
|
|
9717
|
-
|
|
9718
|
-
|
|
9719
|
-
|
|
9720
|
-
|
|
9721
|
-
|
|
9722
|
-
|
|
9723
|
-
|
|
10126
|
+
if (publishedCounterpart?.publishedAt || currentDoc?.publishedAt) {
|
|
10127
|
+
targetStatus = "published";
|
|
10128
|
+
} else {
|
|
10129
|
+
targetStatus = "draft";
|
|
10130
|
+
}
|
|
10131
|
+
}
|
|
10132
|
+
if (isDraftAndPublish) {
|
|
10133
|
+
const docSvc = strapi.documents(item.uid);
|
|
10134
|
+
if (targetStatus === "published") {
|
|
10135
|
+
try {
|
|
10136
|
+
if (typeof docSvc.publish === "function") {
|
|
10137
|
+
await docSvc.publish({
|
|
10138
|
+
documentId: item.documentId,
|
|
9724
10139
|
...isLocalized ? { locale: item.locale } : {}
|
|
9725
10140
|
});
|
|
9726
|
-
|
|
10141
|
+
}
|
|
10142
|
+
} catch (publishErr) {
|
|
10143
|
+
strapi.log.warn(
|
|
10144
|
+
`[bulk-updater] Failed to auto-publish rollback for ${item.uid}/${item.documentId}:`,
|
|
10145
|
+
publishErr?.message
|
|
10146
|
+
);
|
|
10147
|
+
}
|
|
10148
|
+
} else if (targetStatus === "draft") {
|
|
10149
|
+
try {
|
|
10150
|
+
if (typeof docSvc.unpublish === "function") {
|
|
10151
|
+
let hasPublished = false;
|
|
10152
|
+
if (typeof docSvc.findMany === "function") {
|
|
10153
|
+
const pubs = await docSvc.findMany({
|
|
10154
|
+
status: "published",
|
|
10155
|
+
filters: { documentId: item.documentId },
|
|
10156
|
+
fields: ["documentId", "publishedAt"],
|
|
10157
|
+
limit: 1,
|
|
10158
|
+
...isLocalized ? { locale: item.locale } : {}
|
|
10159
|
+
});
|
|
10160
|
+
if (pubs && pubs.length > 0) {
|
|
10161
|
+
hasPublished = true;
|
|
10162
|
+
}
|
|
10163
|
+
} else if (currentDoc?.publishedAt) {
|
|
9727
10164
|
hasPublished = true;
|
|
9728
10165
|
}
|
|
9729
|
-
|
|
9730
|
-
|
|
9731
|
-
|
|
9732
|
-
|
|
9733
|
-
|
|
9734
|
-
|
|
9735
|
-
...isLocalized ? { locale: item.locale } : {}
|
|
9736
|
-
});
|
|
10166
|
+
if (hasPublished) {
|
|
10167
|
+
await docSvc.unpublish({
|
|
10168
|
+
documentId: item.documentId,
|
|
10169
|
+
...isLocalized ? { locale: item.locale } : {}
|
|
10170
|
+
});
|
|
10171
|
+
}
|
|
9737
10172
|
}
|
|
10173
|
+
} catch (unpubErr) {
|
|
10174
|
+
strapi.log.warn(
|
|
10175
|
+
`[bulk-updater] Failed to unpublish rollback for ${item.uid}/${item.documentId}:`,
|
|
10176
|
+
unpubErr?.message
|
|
10177
|
+
);
|
|
9738
10178
|
}
|
|
9739
|
-
} catch (unpubErr) {
|
|
9740
|
-
strapi.log.warn(
|
|
9741
|
-
`[bulk-updater] Failed to unpublish rollback for ${item.uid}/${item.documentId}:`,
|
|
9742
|
-
unpubErr?.message
|
|
9743
|
-
);
|
|
9744
10179
|
}
|
|
9745
10180
|
}
|
|
9746
|
-
|
|
9747
|
-
|
|
9748
|
-
|
|
10181
|
+
try {
|
|
10182
|
+
await recordContentHistoryVersion(strapi, {
|
|
10183
|
+
uid: item.uid,
|
|
10184
|
+
documentId: item.documentId,
|
|
10185
|
+
userId,
|
|
10186
|
+
statusOverride: isDraftAndPublish ? targetStatus : "published"
|
|
10187
|
+
});
|
|
10188
|
+
} catch {
|
|
10189
|
+
}
|
|
10190
|
+
try {
|
|
10191
|
+
const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
|
|
10192
|
+
if (bulkService?.invalidateCache) {
|
|
10193
|
+
bulkService.invalidateCache(item.uid);
|
|
10194
|
+
}
|
|
10195
|
+
} catch {
|
|
10196
|
+
}
|
|
10197
|
+
const entryKey = `${item.uid}@@@${item.documentId}@@@${isLocalized ? item.locale : ""}`;
|
|
10198
|
+
revertedEntryKeys.add(entryKey);
|
|
10199
|
+
rollbackDetails.push({
|
|
9749
10200
|
uid: item.uid,
|
|
9750
10201
|
documentId: item.documentId,
|
|
9751
|
-
|
|
9752
|
-
|
|
10202
|
+
label: item.label,
|
|
10203
|
+
attribute: item.attribute,
|
|
10204
|
+
revertedTo: item.oldValue,
|
|
10205
|
+
status: "reverted",
|
|
10206
|
+
restoredLifecycleStatus: isDraftAndPublish ? targetStatus : "published"
|
|
10207
|
+
});
|
|
10208
|
+
} catch (err) {
|
|
10209
|
+
rollbackDetails.push({
|
|
10210
|
+
uid: item.uid,
|
|
10211
|
+
documentId: item.documentId,
|
|
10212
|
+
label: item.label,
|
|
10213
|
+
status: "error",
|
|
10214
|
+
message: err.message
|
|
9753
10215
|
});
|
|
9754
|
-
} catch {
|
|
9755
|
-
}
|
|
9756
|
-
try {
|
|
9757
|
-
const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
|
|
9758
|
-
if (bulkService?.invalidateCache) {
|
|
9759
|
-
bulkService.invalidateCache(item.uid);
|
|
9760
|
-
}
|
|
9761
|
-
} catch {
|
|
9762
10216
|
}
|
|
9763
|
-
revertedCount++;
|
|
9764
|
-
rollbackDetails.push({
|
|
9765
|
-
uid: item.uid,
|
|
9766
|
-
documentId: item.documentId,
|
|
9767
|
-
label: item.label,
|
|
9768
|
-
attribute: item.attribute,
|
|
9769
|
-
revertedTo: item.oldValue,
|
|
9770
|
-
status: "reverted",
|
|
9771
|
-
restoredLifecycleStatus: isDraftAndPublish ? targetStatus : "published"
|
|
9772
|
-
});
|
|
9773
|
-
} catch (err) {
|
|
9774
|
-
rollbackDetails.push({
|
|
9775
|
-
uid: item.uid,
|
|
9776
|
-
documentId: item.documentId,
|
|
9777
|
-
label: item.label,
|
|
9778
|
-
status: "error",
|
|
9779
|
-
message: err.message
|
|
9780
|
-
});
|
|
9781
10217
|
}
|
|
9782
10218
|
}
|
|
9783
|
-
|
|
9784
|
-
|
|
10219
|
+
return { revertedCount: revertedEntryKeys.size, rollbackDetails };
|
|
10220
|
+
});
|
|
9785
10221
|
},
|
|
9786
10222
|
/**
|
|
9787
|
-
* Performs deterministic rollback of
|
|
9788
|
-
*
|
|
9789
|
-
*
|
|
10223
|
+
* Performs deterministic rollback of an eligible batch (latest or historical).
|
|
10224
|
+
* Already rolled-back updates, non-revertible batches, and pending/failed/executing batches are rejected.
|
|
10225
|
+
* Historical batches overlapping newer active batches on shared entries require `confirmOverwrite: true`.
|
|
9790
10226
|
*/
|
|
9791
|
-
async rollbackBatch(batchId, currentUser) {
|
|
10227
|
+
async rollbackBatch(batchId, currentUser, options) {
|
|
9792
10228
|
return withRollbackLock(async () => {
|
|
9793
10229
|
const config = this.getAuditConfig();
|
|
9794
10230
|
if (!config.enabled) {
|
|
@@ -9827,17 +10263,11 @@ const auditService = ({ strapi }) => ({
|
|
|
9827
10263
|
throw new Error("No completed update records found in audit trail.");
|
|
9828
10264
|
}
|
|
9829
10265
|
const sortedHistory2 = sortAuditRecordsDesc(rawHistory);
|
|
9830
|
-
const targetRecord2
|
|
9831
|
-
|
|
9832
|
-
|
|
9833
|
-
|
|
9834
|
-
|
|
9835
|
-
if (latestRecord2.batchId !== batchId) {
|
|
9836
|
-
throw new Error("Only the latest completed update can be rolled back. Older batch updates cannot be rolled back.");
|
|
9837
|
-
}
|
|
9838
|
-
if (targetRecord2.isRolledBack) {
|
|
9839
|
-
throw new Error(`Batch "${batchId}" has already been rolled back.`);
|
|
9840
|
-
}
|
|
10266
|
+
const { targetRecord: targetRecord2, overlap: overlap2 } = validateRollbackCandidate(
|
|
10267
|
+
sortedHistory2,
|
|
10268
|
+
batchId,
|
|
10269
|
+
options?.confirmOverwrite
|
|
10270
|
+
);
|
|
9841
10271
|
const diffs2 = Array.isArray(targetRecord2.diffs) ? targetRecord2.diffs : [];
|
|
9842
10272
|
const { revertedCount: revertedCount2, rollbackDetails: rollbackDetails2 } = await this.revertDiffItems(diffs2, currentUser?.id);
|
|
9843
10273
|
const recordIndex = rawHistory.findIndex((r) => r.batchId === batchId);
|
|
@@ -9872,6 +10302,7 @@ const auditService = ({ strapi }) => ({
|
|
|
9872
10302
|
success: true,
|
|
9873
10303
|
batchId,
|
|
9874
10304
|
revertedCount: revertedCount2,
|
|
10305
|
+
overwrittenBatchIds: overlap2.hasOverlap ? overlap2.newerActiveBatchIds : [],
|
|
9875
10306
|
details: rollbackDetails2
|
|
9876
10307
|
};
|
|
9877
10308
|
}
|
|
@@ -9904,17 +10335,11 @@ const auditService = ({ strapi }) => ({
|
|
|
9904
10335
|
createdAt: r.createdAt
|
|
9905
10336
|
}));
|
|
9906
10337
|
const sortedHistory = sortAuditRecordsDesc(normalizedHistory);
|
|
9907
|
-
const targetRecord =
|
|
9908
|
-
|
|
9909
|
-
|
|
9910
|
-
|
|
9911
|
-
|
|
9912
|
-
if (latestRecord.batchId !== batchId) {
|
|
9913
|
-
throw new Error("Only the latest completed update can be rolled back. Older batch updates cannot be rolled back.");
|
|
9914
|
-
}
|
|
9915
|
-
if (targetRecord.isRolledBack) {
|
|
9916
|
-
throw new Error(`Batch "${batchId}" has already been rolled back.`);
|
|
9917
|
-
}
|
|
10338
|
+
const { targetRecord, overlap } = validateRollbackCandidate(
|
|
10339
|
+
sortedHistory,
|
|
10340
|
+
batchId,
|
|
10341
|
+
options?.confirmOverwrite
|
|
10342
|
+
);
|
|
9918
10343
|
const diffs = Array.isArray(targetRecord.diffs) ? targetRecord.diffs : [];
|
|
9919
10344
|
const { revertedCount, rollbackDetails } = await this.revertDiffItems(diffs, currentUser?.id);
|
|
9920
10345
|
const updateData = {};
|
|
@@ -9949,6 +10374,7 @@ const auditService = ({ strapi }) => ({
|
|
|
9949
10374
|
success: true,
|
|
9950
10375
|
batchId,
|
|
9951
10376
|
revertedCount,
|
|
10377
|
+
overwrittenBatchIds: overlap.hasOverlap ? overlap.newerActiveBatchIds : [],
|
|
9952
10378
|
details: rollbackDetails
|
|
9953
10379
|
};
|
|
9954
10380
|
});
|
|
@@ -10959,8 +11385,10 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
|
|
|
10959
11385
|
failedRows: [],
|
|
10960
11386
|
diffs: []
|
|
10961
11387
|
};
|
|
11388
|
+
const duplicateHeaders = findDuplicateCsvHeaders(originalHeaders);
|
|
10962
11389
|
const batchModeInfo = detectCsvBatchExportMode(rows);
|
|
10963
|
-
|
|
11390
|
+
const batchLevelError = duplicateHeaders.length > 0 ? `Duplicate CSV column header(s) detected: [${duplicateHeaders.join(", ")}]. Each column header must be unique.` : batchModeInfo.error;
|
|
11391
|
+
if (batchLevelError) {
|
|
10964
11392
|
for (let i = 0; i < rows.length; i++) {
|
|
10965
11393
|
const rowNumber = startRowNumber + i;
|
|
10966
11394
|
const row = rows[i];
|
|
@@ -10971,7 +11399,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
|
|
|
10971
11399
|
stats,
|
|
10972
11400
|
rowNumber,
|
|
10973
11401
|
row,
|
|
10974
|
-
|
|
11402
|
+
batchLevelError,
|
|
10975
11403
|
docId || void 0,
|
|
10976
11404
|
originalHeaders
|
|
10977
11405
|
);
|
|
@@ -10980,11 +11408,11 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
|
|
|
10980
11408
|
collectionName: ct.info?.displayName || uid,
|
|
10981
11409
|
documentId: docId || `(Row #${rowNumber})`,
|
|
10982
11410
|
label: `Row #${rowNumber}`,
|
|
10983
|
-
attribute: "__bulk_updater_metadata",
|
|
11411
|
+
attribute: duplicateHeaders.length > 0 ? duplicateHeaders[0] : "__bulk_updater_metadata",
|
|
10984
11412
|
oldValue: null,
|
|
10985
11413
|
newValue: null,
|
|
10986
11414
|
status: "error",
|
|
10987
|
-
message:
|
|
11415
|
+
message: batchLevelError
|
|
10988
11416
|
});
|
|
10989
11417
|
}
|
|
10990
11418
|
return stats;
|
|
@@ -11806,6 +12234,7 @@ const csvService = ({ strapi }) => ({
|
|
|
11806
12234
|
}
|
|
11807
12235
|
const { mode = "auto" } = options;
|
|
11808
12236
|
const attrs = ct.attributes || {};
|
|
12237
|
+
const schema = discoverSchema(strapi, uid);
|
|
11809
12238
|
let validationRulesService2 = null;
|
|
11810
12239
|
let activeRules = [];
|
|
11811
12240
|
try {
|
|
@@ -11830,6 +12259,28 @@ const csvService = ({ strapi }) => ({
|
|
|
11830
12259
|
};
|
|
11831
12260
|
const errors2 = [];
|
|
11832
12261
|
const warnings = [];
|
|
12262
|
+
const duplicateHeaders = findDuplicateCsvHeaders(options.originalHeaders);
|
|
12263
|
+
if (duplicateHeaders.length > 0) {
|
|
12264
|
+
errors2.push({
|
|
12265
|
+
row: 1,
|
|
12266
|
+
error: `Duplicate CSV column header(s) detected: [${duplicateHeaders.join(", ")}]. Each column header must be unique.`
|
|
12267
|
+
});
|
|
12268
|
+
return {
|
|
12269
|
+
success: true,
|
|
12270
|
+
detectedExportMode: "invalid",
|
|
12271
|
+
totalRows: rows.length,
|
|
12272
|
+
validRows: 0,
|
|
12273
|
+
estimatedUpdates: 0,
|
|
12274
|
+
estimatedCreates: 0,
|
|
12275
|
+
lifecycleStats,
|
|
12276
|
+
hasErrors: true,
|
|
12277
|
+
hasWarnings: false,
|
|
12278
|
+
errors: errors2,
|
|
12279
|
+
warnings: [],
|
|
12280
|
+
totalErrorCount: errors2.length,
|
|
12281
|
+
totalWarningCount: 0
|
|
12282
|
+
};
|
|
12283
|
+
}
|
|
11833
12284
|
const batchModeInfo = detectCsvBatchExportMode(rows);
|
|
11834
12285
|
if (batchModeInfo.error) {
|
|
11835
12286
|
errors2.push({
|
|
@@ -11943,7 +12394,10 @@ const csvService = ({ strapi }) => ({
|
|
|
11943
12394
|
}
|
|
11944
12395
|
}
|
|
11945
12396
|
}
|
|
11946
|
-
|
|
12397
|
+
const rowMetaInfo = inspectRowMetadataMode(row);
|
|
12398
|
+
const beforeTargetNorm = normalizeSelectiveBeforeTargetRow(row, rowMetaInfo, schema);
|
|
12399
|
+
const normalizedScanRow = beforeTargetNorm.normalizedRow;
|
|
12400
|
+
for (const [colKey, rawVal] of Object.entries(normalizedScanRow)) {
|
|
11947
12401
|
if (!rawVal || rawVal.trim() === "") continue;
|
|
11948
12402
|
const normalizedKey = colKey.toLowerCase().replace(/[\s_-]/g, "");
|
|
11949
12403
|
if (SYSTEM_FIELD_KEYS.has(normalizedKey)) continue;
|
|
@@ -12657,6 +13111,9 @@ const index = {
|
|
|
12657
13111
|
}
|
|
12658
13112
|
});
|
|
12659
13113
|
strapi.documents.use(async (context, next) => {
|
|
13114
|
+
if (isRollbackContext()) {
|
|
13115
|
+
return await next();
|
|
13116
|
+
}
|
|
12660
13117
|
if (typeof context.uid === "string" && context.uid.startsWith("plugin::bulk-updater.")) {
|
|
12661
13118
|
return await next();
|
|
12662
13119
|
}
|
|
@@ -12846,6 +13303,7 @@ export {
|
|
|
12846
13303
|
extractHeadingsFromRichText,
|
|
12847
13304
|
extractMetadataFromRow,
|
|
12848
13305
|
extractRowFlattenedMetadata,
|
|
13306
|
+
findDuplicateCsvHeaders,
|
|
12849
13307
|
formatErrorCsvFilename,
|
|
12850
13308
|
formatErrorWithCause,
|
|
12851
13309
|
formatRelationState,
|
|
@@ -12860,6 +13318,7 @@ export {
|
|
|
12860
13318
|
isValidDocumentId,
|
|
12861
13319
|
normalizeExportMode,
|
|
12862
13320
|
normalizeRuleQuotas,
|
|
13321
|
+
normalizeSelectiveBeforeTargetRow,
|
|
12863
13322
|
parseBoolean,
|
|
12864
13323
|
parseCsvToMatrix,
|
|
12865
13324
|
parseCsvToRecords,
|