@wix/bex-core 2.401.0 → 2.403.0

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.
Files changed (58) hide show
  1. package/dist/cjs/hooks/useImport.js +5 -0
  2. package/dist/cjs/hooks/useImport.js.map +1 -1
  3. package/dist/cjs/state/CustomFieldModalState.js +5 -1
  4. package/dist/cjs/state/CustomFieldModalState.js.map +1 -1
  5. package/dist/cjs/state/ImportState/ImportState.js +130 -38
  6. package/dist/cjs/state/ImportState/ImportState.js.map +1 -1
  7. package/dist/cjs/state/ImportState/__tests__/ImportState.engine.spec.js +316 -0
  8. package/dist/cjs/state/ImportState/__tests__/ImportState.engine.spec.js.map +1 -1
  9. package/dist/cjs/state/ImportState/detectFieldType.js +37 -16
  10. package/dist/cjs/state/ImportState/detectFieldType.js.map +1 -1
  11. package/dist/cjs/state/ImportState/fieldEdit.js +2 -1
  12. package/dist/cjs/state/ImportState/fieldEdit.js.map +1 -1
  13. package/dist/cjs/state/ImportState/findExistingImportIds.js +35 -0
  14. package/dist/cjs/state/ImportState/findExistingImportIds.js.map +1 -0
  15. package/dist/cjs/state/ImportState/importSampling.js +2 -1
  16. package/dist/cjs/state/ImportState/importSampling.js.map +1 -1
  17. package/dist/cjs/types/FieldTypeDefinition.js.map +1 -1
  18. package/dist/cjs/types/FieldsSource.js.map +1 -1
  19. package/dist/cjs/types/SchemaSource.js +1 -0
  20. package/dist/cjs/types/SchemaSource.js.map +1 -1
  21. package/dist/esm/hooks/useImport.js +6 -1
  22. package/dist/esm/hooks/useImport.js.map +1 -1
  23. package/dist/esm/state/CustomFieldModalState.js +6 -1
  24. package/dist/esm/state/CustomFieldModalState.js.map +1 -1
  25. package/dist/esm/state/ImportState/ImportState.js +131 -42
  26. package/dist/esm/state/ImportState/ImportState.js.map +1 -1
  27. package/dist/esm/state/ImportState/__tests__/ImportState.engine.spec.js +242 -0
  28. package/dist/esm/state/ImportState/__tests__/ImportState.engine.spec.js.map +1 -1
  29. package/dist/esm/state/ImportState/detectFieldType.js +39 -11
  30. package/dist/esm/state/ImportState/detectFieldType.js.map +1 -1
  31. package/dist/esm/state/ImportState/fieldEdit.js +1 -0
  32. package/dist/esm/state/ImportState/fieldEdit.js.map +1 -1
  33. package/dist/esm/state/ImportState/findExistingImportIds.js +24 -0
  34. package/dist/esm/state/ImportState/findExistingImportIds.js.map +1 -0
  35. package/dist/esm/state/ImportState/importSampling.js +1 -0
  36. package/dist/esm/state/ImportState/importSampling.js.map +1 -1
  37. package/dist/esm/types/FieldTypeDefinition.js.map +1 -1
  38. package/dist/esm/types/SchemaSource.js +1 -0
  39. package/dist/esm/types/SchemaSource.js.map +1 -1
  40. package/dist/types/hooks/useImport.d.ts +6 -3
  41. package/dist/types/hooks/useImport.d.ts.map +1 -1
  42. package/dist/types/state/CustomFieldModalState.d.ts.map +1 -1
  43. package/dist/types/state/ImportState/ImportState.d.ts +11 -7
  44. package/dist/types/state/ImportState/ImportState.d.ts.map +1 -1
  45. package/dist/types/state/ImportState/detectFieldType.d.ts +2 -2
  46. package/dist/types/state/ImportState/detectFieldType.d.ts.map +1 -1
  47. package/dist/types/state/ImportState/fieldEdit.d.ts.map +1 -1
  48. package/dist/types/state/ImportState/findExistingImportIds.d.ts +3 -0
  49. package/dist/types/state/ImportState/findExistingImportIds.d.ts.map +1 -0
  50. package/dist/types/state/ImportState/importSampling.d.ts +1 -0
  51. package/dist/types/state/ImportState/importSampling.d.ts.map +1 -1
  52. package/dist/types/types/FieldTypeDefinition.d.ts +6 -3
  53. package/dist/types/types/FieldTypeDefinition.d.ts.map +1 -1
  54. package/dist/types/types/FieldsSource.d.ts +3 -1
  55. package/dist/types/types/FieldsSource.d.ts.map +1 -1
  56. package/dist/types/types/SchemaSource.d.ts +4 -0
  57. package/dist/types/types/SchemaSource.d.ts.map +1 -1
  58. package/package.json +4 -4
@@ -17,10 +17,11 @@ var _detectFieldType = require("./detectFieldType");
17
17
  var _importFieldCompatibility = require("./importFieldCompatibility");
18
18
  var _fieldEdit = require("./fieldEdit");
19
19
  var _newFieldDraft = require("./newFieldDraft");
20
+ var _importSampling = require("./importSampling");
20
21
  var _ImportStateBIReporter = require("./ImportStateBIReporter");
21
22
  /** Outcome of a server-side import job, derived from the job's progress. */
22
23
 
23
- /** A rejected row: its index into `csvRows` and the server's failure reason. */
24
+ /** A rejected row: its index in the input rows and the reason it failed. */
24
25
 
25
26
  /**
26
27
  * Optional snapshot taken before the import runs, returning a `restore` used to
@@ -340,6 +341,11 @@ class ImportState {
340
341
  (0, _defineProperty2.default)(this, "_detectColumnType", void 0);
341
342
  (0, _defineProperty2.default)(this, "_isValueCompatible", void 0);
342
343
  (0, _defineProperty2.default)(this, "discardChangesModal", new _ConditionalModalState.ConditionalModalState());
344
+ (0, _defineProperty2.default)(this, "_createFieldValidator", void 0);
345
+ (0, _defineProperty2.default)(this, "_fieldsSource", void 0);
346
+ (0, _defineProperty2.default)(this, "_getExistingIds", void 0);
347
+ (0, _defineProperty2.default)(this, "_uploadedRows", undefined);
348
+ (0, _defineProperty2.default)(this, "_validationFailures", []);
343
349
  (0, _defineProperty2.default)(this, "currentStep", 'upload');
344
350
  (0, _defineProperty2.default)(this, "importStatus", {
345
351
  ..._model.queryStatus.idle
@@ -398,6 +404,9 @@ class ImportState {
398
404
  this.config = props.config ?? buildImportConfig(props.fieldsSource, props.collection, props.importInputs);
399
405
  this.importModalState = props.importModalState;
400
406
  this.translate = props.translate;
407
+ this._createFieldValidator = props.createFieldValidator;
408
+ this._fieldsSource = props.fieldsSource;
409
+ this._getExistingIds = props.getExistingIds;
401
410
  this.errorHandler = props.errorHandler;
402
411
  this.showToast = props.showToast;
403
412
  this.downloadCsv = props.downloadCsv;
@@ -660,6 +669,8 @@ class ImportState {
660
669
  this.importStatus = {
661
670
  ..._model.queryStatus.idle
662
671
  };
672
+ this._uploadedRows = undefined;
673
+ this._validationFailures = [];
663
674
  this.fileName = '';
664
675
  this.csvHeaders = [];
665
676
  this.csvRows = [];
@@ -804,9 +815,10 @@ class ImportState {
804
815
  // Unmatched columns default to creating a new field (type inferred from
805
816
  // the column's data) when the consumer supplied `updateSchema`;
806
817
  // otherwise they default to skip.
807
- mapping[header] = this.canCreateNewField ? {
818
+ const fieldType = this._detectColumnType(this._newFieldValues(index));
819
+ mapping[header] = this.canCreateNewField && fieldType !== 'multiReference' ? {
808
820
  kind: 'new',
809
- fieldType: this._detectColumnType(this._columnValues(index))
821
+ fieldType
810
822
  } : null;
811
823
  }
812
824
  });
@@ -830,6 +842,9 @@ class ImportState {
830
842
  _columnValues(columnIndex) {
831
843
  return this._columnSamples[columnIndex] ?? [];
832
844
  }
845
+ _newFieldValues(columnIndex) {
846
+ return this.csvRows.slice(0, _importSampling.NEW_FIELD_SAMPLE_SIZE).map(row => row[columnIndex] ?? '');
847
+ }
833
848
 
834
849
  // Puts the `_id`-mapped column first (CAIRO-4418), preserving CSV order for the
835
850
  // rest. Returns a fresh array so the snapshot doesn't alias `csvHeaders`.
@@ -931,34 +946,37 @@ class ImportState {
931
946
  });
932
947
  }
933
948
 
934
- /**
935
- * Builds a re-importable CSV of the rows the server rejected and hands it to
936
- * `downloadCsv`. Each failed row is prefixed with a leading "why it failed"
937
- * column holding the server's error message, so the user can see and fix each
938
- * reason. The failed rows (and their reasons) come from the job's movement
939
- * logs, mapped back to the parsed `csvRows` we still hold in memory.
940
- */
949
+ /** Downloads validation failures and server rejections with their reasons. */
941
950
  async downloadFailedRows() {
942
951
  var _this$downloadCsv;
943
952
  this.bi.onSummaryCtaClicked('Download failed items CSV');
944
- const jobId = this._jobId;
945
- if (!jobId) {
946
- return;
947
- }
948
- let failures;
949
- try {
950
- failures = await this._fetchFailedRows(jobId);
951
- } catch (error) {
952
- console.error('Fetching failed rows report failed', error);
953
- return;
953
+ let serverFailures = [];
954
+ if (this._jobId && this.result.failed > this._validationFailures.length) {
955
+ try {
956
+ serverFailures = await this._fetchFailedRows(this._jobId);
957
+ } catch (error) {
958
+ console.error('Fetching failed rows report failed', error);
959
+ return;
960
+ }
954
961
  }
955
- const rows = failures.map(({
962
+ const rows = [...this._validationFailures.map(({
956
963
  index,
957
964
  reason
958
- }) => {
959
- const row = this.csvRows[index];
960
- return row != null ? [reason, ...row] : null;
961
- }).filter(row => row != null);
965
+ }) => ({
966
+ row: this.csvRows[index],
967
+ reason
968
+ })), ...serverFailures.map(({
969
+ index,
970
+ reason
971
+ }) => ({
972
+ row: (this._uploadedRows ?? this.csvRows)[index],
973
+ reason
974
+ }))].filter(({
975
+ row
976
+ }) => row != null).map(({
977
+ row,
978
+ reason
979
+ }) => [reason, ...row]);
962
980
  if (rows.length === 0) {
963
981
  return;
964
982
  }
@@ -995,7 +1013,7 @@ class ImportState {
995
1013
  }
996
1014
  const fileLine = Number((_exec = /\d+/.exec(log.sourceItemId)) == null ? void 0 : _exec[0]);
997
1015
  const index = fileLine - 2;
998
- if (Number.isInteger(index) && index >= 0 && index < this.csvRows.length) {
1016
+ if (Number.isInteger(index) && index >= 0 && index < (this._uploadedRows ?? this.csvRows).length) {
999
1017
  failures.push({
1000
1018
  index,
1001
1019
  reason: log.failure.description ?? ''
@@ -1020,11 +1038,11 @@ class ImportState {
1020
1038
  }
1021
1039
  setNewFieldMapping(header) {
1022
1040
  const index = this.csvHeaders.indexOf(header);
1023
- const fieldType = index >= 0 ? this._detectColumnType(this._columnValues(index)) : 'text';
1041
+ const fieldType = index >= 0 ? this._detectColumnType(this._newFieldValues(index)) : 'text';
1024
1042
  const prev = this.mappingByHeader[header] ?? null;
1025
1043
  const next = {
1026
1044
  kind: 'new',
1027
- fieldType
1045
+ fieldType: fieldType === 'multiReference' ? 'text' : fieldType
1028
1046
  };
1029
1047
  this.mappingByHeader = {
1030
1048
  ...this.mappingByHeader,
@@ -1134,8 +1152,8 @@ class ImportState {
1134
1152
  * a failed job so `startImport` surfaces the error state; partial success is
1135
1153
  * reported via `result.failed` and the partial toast.
1136
1154
  */
1137
- async _runImportJob(resolvedMapping) {
1138
- const csv = (0, _rewriteCsv.rewriteParsedCsvForImport)(this.csvHeaders, this.csvRows, resolvedMapping);
1155
+ async _runImportJob(resolvedMapping, rows) {
1156
+ const csv = (0, _rewriteCsv.rewriteParsedCsvForImport)(this.csvHeaders, rows, resolvedMapping);
1139
1157
  const file = new File([csv], this.fileName || 'import.csv', {
1140
1158
  type: 'text/csv'
1141
1159
  });
@@ -1231,8 +1249,9 @@ class ImportState {
1231
1249
  _applyJobProgress(job) {
1232
1250
  const progress = job.progress;
1233
1251
  const succeeded = (progress == null ? void 0 : progress.itemsSuccessful) ?? 0;
1234
- const failed = (progress == null ? void 0 : progress.itemsRejected) ?? 0;
1235
- const current = (progress == null ? void 0 : progress.current) ?? succeeded + failed;
1252
+ const rejected = (progress == null ? void 0 : progress.itemsRejected) ?? 0;
1253
+ const failed = rejected + this._validationFailures.length;
1254
+ const current = ((progress == null ? void 0 : progress.current) ?? succeeded + rejected) + this._validationFailures.length;
1236
1255
  // The server splits successful items into created (new) and updated
1237
1256
  // (existing) — the summary step reports each. Some jobs omit this split
1238
1257
  // entirely (`itemsSuccessfulInfo` absent); in that case treat every success
@@ -1241,8 +1260,7 @@ class ImportState {
1241
1260
  const created = successInfo ? successInfo.itemsCreated ?? 0 : succeeded;
1242
1261
  const updated = (successInfo == null ? void 0 : successInfo.itemsUpdated) ?? 0;
1243
1262
 
1244
- // `totalCount` is fixed up front in `startImport` from the CSV row count
1245
- // (one uploaded row per CSV row); polling only advances `processedCount`.
1263
+ // Validation failures are already processed; the job advances the rest.
1246
1264
  (0, _mobx.runInAction)(() => {
1247
1265
  this.processedCount = Math.min(current, this.totalCount);
1248
1266
  this.result = {
@@ -1416,6 +1434,65 @@ class ImportState {
1416
1434
  console.error('ImportState config.onImportCompleted failed', error);
1417
1435
  }
1418
1436
  }
1437
+ async _validateRows(mapping, signal) {
1438
+ var _this$_getExistingIds;
1439
+ const rows = [];
1440
+ const failedRows = [];
1441
+ const idIndex = this.csvHeaders.findIndex(header => mapping[header] === this.idFieldKey);
1442
+ const skipExisting = this.writePolicy === _types.WritePolicy.SKIP_EXISTING;
1443
+ const ids = [...new Set(this.csvRows.map(row => row[idIndex]).filter(Boolean))];
1444
+ const skippedIds = new Set(skipExisting && ids.length ? await ((_this$_getExistingIds = this._getExistingIds) == null ? void 0 : _this$_getExistingIds.call(this, ids, signal)) : []);
1445
+ const columns = this.csvHeaders.map(header => {
1446
+ var _this$_pendingFieldsM, _this$_fieldsSource, _sourceField$validati, _this$_createFieldVal;
1447
+ const fieldId = mapping[header];
1448
+ if (!fieldId || fieldId === this.idFieldKey) {
1449
+ return undefined;
1450
+ }
1451
+ const sourceField = ((_this$_pendingFieldsM = this._pendingFieldsMap) == null ? void 0 : _this$_pendingFieldsM[fieldId]) ?? ((_this$_fieldsSource = this._fieldsSource) == null ? void 0 : _this$_fieldsSource.fields.find(field => field.id === fieldId));
1452
+ if (sourceField != null && sourceField.isSystem) {
1453
+ return undefined;
1454
+ }
1455
+ const configField = this.fields.find(field => field.id === fieldId);
1456
+ const field = {
1457
+ ...(sourceField ?? {
1458
+ id: fieldId,
1459
+ displayName: (configField == null ? void 0 : configField.header) || fieldId,
1460
+ type: 'UNKNOWN'
1461
+ }),
1462
+ validation: {
1463
+ ...(sourceField == null ? void 0 : sourceField.validation),
1464
+ required: !!(configField != null && configField.required || sourceField != null && (_sourceField$validati = sourceField.validation) != null && _sourceField$validati.required)
1465
+ }
1466
+ };
1467
+ return ((_this$_createFieldVal = this._createFieldValidator) == null ? void 0 : _this$_createFieldVal.call(this, field)) ?? (raw => {
1468
+ var _field$validation;
1469
+ return (_field$validation = field.validation) != null && _field$validation.required && !raw ? [this.translate('cairo.editableTable.field.validation.required', {
1470
+ fieldName: field.displayName
1471
+ })] : [];
1472
+ });
1473
+ });
1474
+ this.csvRows.forEach((row, index) => {
1475
+ if (skippedIds.has(row[idIndex])) {
1476
+ return;
1477
+ }
1478
+ const reasons = columns.flatMap((validate, columnIndex) => (validate == null ? void 0 : validate(row[columnIndex] ?? '')) ?? []);
1479
+ if (reasons.length) {
1480
+ failedRows.push({
1481
+ index,
1482
+ reason: reasons.join('; ')
1483
+ });
1484
+ } else {
1485
+ rows.push(row);
1486
+ if (skipExisting && row[idIndex]) {
1487
+ skippedIds.add(row[idIndex]);
1488
+ }
1489
+ }
1490
+ });
1491
+ return {
1492
+ rows,
1493
+ failedRows
1494
+ };
1495
+ }
1419
1496
  async startImport() {
1420
1497
  if (!this.hasMappings) {
1421
1498
  return;
@@ -1448,9 +1525,8 @@ class ImportState {
1448
1525
  }
1449
1526
  this._cancelled = false;
1450
1527
  this._abortController = new AbortController();
1451
-
1452
- // One uploaded row per CSV row (the rewrite drops columns, not rows), so the
1453
- // total is known up front from the parsed CSV and stays fixed through polling.
1528
+ this._validationFailures = [];
1529
+ this._uploadedRows = undefined;
1454
1530
  const totalCount = this.csvRows.length;
1455
1531
  (0, _mobx.runInAction)(() => {
1456
1532
  this.currentStep = 'progress';
@@ -1488,8 +1564,13 @@ class ImportState {
1488
1564
  // before uploading. A creation failure surfaces as the error state with a
1489
1565
  // "Try again" CTA, like an upload/job failure.
1490
1566
  let resolvedMapping;
1567
+ let prepared;
1491
1568
  try {
1492
1569
  resolvedMapping = await this._resolveFieldMapping();
1570
+ if (this._cancelled) {
1571
+ return;
1572
+ }
1573
+ prepared = await this._validateRows(resolvedMapping, this._abortController.signal);
1493
1574
  } catch (error) {
1494
1575
  (0, _mobx.runInAction)(() => {
1495
1576
  this.importStatus = {
@@ -1506,7 +1587,18 @@ class ImportState {
1506
1587
  if (this._cancelled) {
1507
1588
  return;
1508
1589
  }
1509
- const promise = this._runImportJob(resolvedMapping);
1590
+ const uploadedRows = prepared.rows;
1591
+ this._uploadedRows = uploadedRows;
1592
+ this._validationFailures = prepared.failedRows;
1593
+ (0, _mobx.runInAction)(() => {
1594
+ this.result = {
1595
+ ...this.result,
1596
+ failed: this._validationFailures.length
1597
+ };
1598
+ this.processedCount = this._validationFailures.length;
1599
+ this.totalCount = uploadedRows.length + this._validationFailures.length;
1600
+ });
1601
+ const promise = uploadedRows.length ? this._runImportJob(resolvedMapping, uploadedRows) : Promise.resolve(this.result);
1510
1602
  this.importStatus = {
1511
1603
  ..._model.queryStatus.loading,
1512
1604
  promise