@wix/bex-core 2.400.0 → 2.402.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 (61) hide show
  1. package/dist/cjs/hooks/useImport.js +7 -0
  2. package/dist/cjs/hooks/useImport.js.map +1 -1
  3. package/dist/cjs/state/ImportState/ImportState.js +188 -51
  4. package/dist/cjs/state/ImportState/ImportState.js.map +1 -1
  5. package/dist/cjs/state/ImportState/__tests__/ImportState.engine.spec.js +551 -0
  6. package/dist/cjs/state/ImportState/__tests__/ImportState.engine.spec.js.map +1 -1
  7. package/dist/cjs/state/ImportState/__tests__/buildImportConfig.spec.js +30 -4
  8. package/dist/cjs/state/ImportState/__tests__/buildImportConfig.spec.js.map +1 -1
  9. package/dist/cjs/state/ImportState/__tests__/importFieldCompatibility.spec.js +91 -0
  10. package/dist/cjs/state/ImportState/__tests__/importFieldCompatibility.spec.js.map +1 -0
  11. package/dist/cjs/state/ImportState/detectFieldType.js +3 -3
  12. package/dist/cjs/state/ImportState/detectFieldType.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/importFieldCompatibility.js +92 -0
  16. package/dist/cjs/state/ImportState/importFieldCompatibility.js.map +1 -0
  17. package/dist/cjs/state/ImportState/importSampling.js +6 -0
  18. package/dist/cjs/state/ImportState/importSampling.js.map +1 -0
  19. package/dist/cjs/state/ImportState/index.js.map +1 -1
  20. package/dist/cjs/types/Field.js.map +1 -1
  21. package/dist/cjs/types/FieldTypeDefinition.js.map +1 -1
  22. package/dist/esm/hooks/useImport.js +7 -1
  23. package/dist/esm/hooks/useImport.js.map +1 -1
  24. package/dist/esm/state/ImportState/ImportState.js +180 -51
  25. package/dist/esm/state/ImportState/ImportState.js.map +1 -1
  26. package/dist/esm/state/ImportState/__tests__/ImportState.engine.spec.js +421 -2
  27. package/dist/esm/state/ImportState/__tests__/ImportState.engine.spec.js.map +1 -1
  28. package/dist/esm/state/ImportState/__tests__/buildImportConfig.spec.js +32 -4
  29. package/dist/esm/state/ImportState/__tests__/buildImportConfig.spec.js.map +1 -1
  30. package/dist/esm/state/ImportState/__tests__/importFieldCompatibility.spec.js +99 -0
  31. package/dist/esm/state/ImportState/__tests__/importFieldCompatibility.spec.js.map +1 -0
  32. package/dist/esm/state/ImportState/detectFieldType.js +3 -3
  33. package/dist/esm/state/ImportState/detectFieldType.js.map +1 -1
  34. package/dist/esm/state/ImportState/findExistingImportIds.js +24 -0
  35. package/dist/esm/state/ImportState/findExistingImportIds.js.map +1 -0
  36. package/dist/esm/state/ImportState/importFieldCompatibility.js +102 -0
  37. package/dist/esm/state/ImportState/importFieldCompatibility.js.map +1 -0
  38. package/dist/esm/state/ImportState/importSampling.js +2 -0
  39. package/dist/esm/state/ImportState/importSampling.js.map +1 -0
  40. package/dist/esm/state/ImportState/index.js.map +1 -1
  41. package/dist/esm/types/FieldTypeDefinition.js.map +1 -1
  42. package/dist/types/hooks/useImport.d.ts +7 -3
  43. package/dist/types/hooks/useImport.d.ts.map +1 -1
  44. package/dist/types/state/ImportState/ImportState.d.ts +20 -8
  45. package/dist/types/state/ImportState/ImportState.d.ts.map +1 -1
  46. package/dist/types/state/ImportState/__tests__/importFieldCompatibility.spec.d.ts +2 -0
  47. package/dist/types/state/ImportState/__tests__/importFieldCompatibility.spec.d.ts.map +1 -0
  48. package/dist/types/state/ImportState/detectFieldType.d.ts.map +1 -1
  49. package/dist/types/state/ImportState/findExistingImportIds.d.ts +3 -0
  50. package/dist/types/state/ImportState/findExistingImportIds.d.ts.map +1 -0
  51. package/dist/types/state/ImportState/importFieldCompatibility.d.ts +4 -0
  52. package/dist/types/state/ImportState/importFieldCompatibility.d.ts.map +1 -0
  53. package/dist/types/state/ImportState/importSampling.d.ts +2 -0
  54. package/dist/types/state/ImportState/importSampling.d.ts.map +1 -0
  55. package/dist/types/state/ImportState/index.d.ts +1 -0
  56. package/dist/types/state/ImportState/index.d.ts.map +1 -1
  57. package/dist/types/types/Field.d.ts +4 -0
  58. package/dist/types/types/Field.d.ts.map +1 -1
  59. package/dist/types/types/FieldTypeDefinition.d.ts +3 -2
  60. package/dist/types/types/FieldTypeDefinition.d.ts.map +1 -1
  61. package/package.json +4 -4
@@ -5,12 +5,16 @@ exports.useCreateImport = useCreateImport;
5
5
  var _react = require("react");
6
6
  var _providers = require("../providers");
7
7
  var _state = require("../state");
8
+ var _findExistingImportIds = require("../state/ImportState/findExistingImportIds");
8
9
  function useCreateImport(params) {
9
10
  const {
10
11
  config,
12
+ createFieldValidator,
13
+ schemaSource,
11
14
  importInputs,
12
15
  fieldsSource,
13
16
  detectColumnType,
17
+ isValueCompatible,
14
18
  importModalState,
15
19
  reportBi
16
20
  } = params;
@@ -26,10 +30,13 @@ function useCreateImport(params) {
26
30
  return (0, _react.useCallback)(() => {
27
31
  return new _state.ImportState({
28
32
  config,
33
+ createFieldValidator,
34
+ getExistingIds: schemaSource ? (ids, signal) => (0, _findExistingImportIds.findExistingImportIds)(schemaSource, ids, signal, collection.query.asComputed.extra) : undefined,
29
35
  importInputs,
30
36
  fieldsSource,
31
37
  httpClient,
32
38
  detectColumnType,
39
+ isValueCompatible,
33
40
  collection,
34
41
  importModalState,
35
42
  showToast,
@@ -1 +1 @@
1
- {"version":3,"names":["_react","require","_providers","_state","useCreateImport","params","config","importInputs","fieldsSource","detectColumnType","importModalState","reportBi","container","useWixPatternsContainer","showToast","translate","errorHandler","window","httpClient","collection","useCollectionContext","useCallback","ImportState","downloadCsv","content","fileName","download","encodeURIComponent"],"sources":["../../../src/hooks/useImport.ts"],"sourcesContent":["import { useCallback } from 'react';\nimport { useWixPatternsContainer, useCollectionContext } from '../providers';\nimport {\n ModalState,\n ImportState,\n ResolvedImportConfig,\n ImportConfig,\n DetectColumnType,\n} from '../state';\nimport type { FieldsSource } from '../types/FieldsSource';\nimport { FiltersMap } from '../model';\nimport type { ReportBI } from '../services';\n\nexport interface UseImportParams {\n /** Consumer inputs (destination, extra fields, backup, …). The collection,\n * fields, and create-new-field are read from `fieldsSource`. */\n importInputs?: ImportConfig;\n /** The table's live fields source; `ImportState` builds the config from it. */\n fieldsSource?: FieldsSource;\n /** A fully pre-built config, used instead of building from the inputs/source. */\n config?: ResolvedImportConfig;\n detectColumnType?: DetectColumnType;\n importModalState: ModalState;\n /** BI reporter for the import funnel; defaults to the container's. */\n reportBi?: ReportBI;\n}\n\nexport function useCreateImport<T = unknown, F extends FiltersMap = FiltersMap>(\n params: UseImportParams,\n) {\n const {\n config,\n importInputs,\n fieldsSource,\n detectColumnType,\n importModalState,\n reportBi,\n } = params;\n const container = useWixPatternsContainer();\n const { showToast, translate, errorHandler, window, httpClient } = container;\n const collection = useCollectionContext<T, F>();\n\n return useCallback(() => {\n return new ImportState({\n config,\n importInputs,\n fieldsSource,\n httpClient,\n detectColumnType,\n collection,\n importModalState,\n showToast,\n translate,\n errorHandler,\n reportBi: reportBi ?? container.reportBi,\n downloadCsv: (content, fileName) => {\n window.download(\n `data:text/csv;charset=utf-8,${encodeURIComponent(content)}`,\n fileName,\n );\n },\n });\n }, []);\n}\n"],"mappings":";;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,UAAA,GAAAD,OAAA;AACA,IAAAE,MAAA,GAAAF,OAAA;AAyBO,SAASG,eAAeA,CAC7BC,MAAuB,EACvB;EACA,MAAM;IACJC,MAAM;IACNC,YAAY;IACZC,YAAY;IACZC,gBAAgB;IAChBC,gBAAgB;IAChBC;EACF,CAAC,GAAGN,MAAM;EACV,MAAMO,SAAS,GAAG,IAAAC,kCAAuB,EAAC,CAAC;EAC3C,MAAM;IAAEC,SAAS;IAAEC,SAAS;IAAEC,YAAY;IAAEC,MAAM;IAAEC;EAAW,CAAC,GAAGN,SAAS;EAC5E,MAAMO,UAAU,GAAG,IAAAC,+BAAoB,EAAO,CAAC;EAE/C,OAAO,IAAAC,kBAAW,EAAC,MAAM;IACvB,OAAO,IAAIC,kBAAW,CAAC;MACrBhB,MAAM;MACNC,YAAY;MACZC,YAAY;MACZU,UAAU;MACVT,gBAAgB;MAChBU,UAAU;MACVT,gBAAgB;MAChBI,SAAS;MACTC,SAAS;MACTC,YAAY;MACZL,QAAQ,EAAEA,QAAQ,IAAIC,SAAS,CAACD,QAAQ;MACxCY,WAAW,EAAEA,CAACC,OAAO,EAAEC,QAAQ,KAAK;QAClCR,MAAM,CAACS,QAAQ,CACb,+BAA+BC,kBAAkB,CAACH,OAAO,CAAC,EAAE,EAC5DC,QACF,CAAC;MACH;IACF,CAAC,CAAC;EACJ,CAAC,EAAE,EAAE,CAAC;AACR","ignoreList":[]}
1
+ {"version":3,"names":["_react","require","_providers","_state","_findExistingImportIds","useCreateImport","params","config","createFieldValidator","schemaSource","importInputs","fieldsSource","detectColumnType","isValueCompatible","importModalState","reportBi","container","useWixPatternsContainer","showToast","translate","errorHandler","window","httpClient","collection","useCollectionContext","useCallback","ImportState","getExistingIds","ids","signal","findExistingImportIds","query","asComputed","extra","undefined","downloadCsv","content","fileName","download","encodeURIComponent"],"sources":["../../../src/hooks/useImport.ts"],"sourcesContent":["import { useCallback } from 'react';\nimport { useWixPatternsContainer, useCollectionContext } from '../providers';\nimport {\n ModalState,\n ImportState,\n ResolvedImportConfig,\n ImportConfig,\n DetectColumnType,\n CreateImportFieldValidator,\n IsImportValueCompatible,\n} from '../state';\nimport { findExistingImportIds } from '../state/ImportState/findExistingImportIds';\nimport type { SchemaSource } from '../types/SchemaSource';\nimport type { FieldsSource } from '../types/FieldsSource';\nimport { FiltersMap } from '../model';\nimport type { ReportBI } from '../services';\n\nexport interface UseImportParams<T = unknown> {\n createFieldValidator?: CreateImportFieldValidator;\n schemaSource?: SchemaSource<T>;\n /** Consumer inputs (destination, extra fields, backup, …). The collection,\n * fields, and create-new-field are read from `fieldsSource`. */\n importInputs?: ImportConfig;\n /** The table's live fields source; `ImportState` builds the config from it. */\n fieldsSource?: FieldsSource;\n /** A fully pre-built config, used instead of building from the inputs/source. */\n config?: ResolvedImportConfig;\n detectColumnType?: DetectColumnType;\n isValueCompatible?: IsImportValueCompatible;\n importModalState: ModalState;\n /** BI reporter for the import funnel; defaults to the container's. */\n reportBi?: ReportBI;\n}\n\nexport function useCreateImport<T = unknown, F extends FiltersMap = FiltersMap>(\n params: UseImportParams<T>,\n) {\n const {\n config,\n createFieldValidator,\n schemaSource,\n importInputs,\n fieldsSource,\n detectColumnType,\n isValueCompatible,\n importModalState,\n reportBi,\n } = params;\n const container = useWixPatternsContainer();\n const { showToast, translate, errorHandler, window, httpClient } = container;\n const collection = useCollectionContext<T, F>();\n\n return useCallback(() => {\n return new ImportState({\n config,\n createFieldValidator,\n getExistingIds: schemaSource\n ? (ids, signal) =>\n findExistingImportIds(\n schemaSource,\n ids,\n signal,\n collection.query.asComputed.extra,\n )\n : undefined,\n importInputs,\n fieldsSource,\n httpClient,\n detectColumnType,\n isValueCompatible,\n collection,\n importModalState,\n showToast,\n translate,\n errorHandler,\n reportBi: reportBi ?? container.reportBi,\n downloadCsv: (content, fileName) => {\n window.download(\n `data:text/csv;charset=utf-8,${encodeURIComponent(content)}`,\n fileName,\n );\n },\n });\n }, []);\n}\n"],"mappings":";;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,UAAA,GAAAD,OAAA;AACA,IAAAE,MAAA,GAAAF,OAAA;AASA,IAAAG,sBAAA,GAAAH,OAAA;AAuBO,SAASI,eAAeA,CAC7BC,MAA0B,EAC1B;EACA,MAAM;IACJC,MAAM;IACNC,oBAAoB;IACpBC,YAAY;IACZC,YAAY;IACZC,YAAY;IACZC,gBAAgB;IAChBC,iBAAiB;IACjBC,gBAAgB;IAChBC;EACF,CAAC,GAAGT,MAAM;EACV,MAAMU,SAAS,GAAG,IAAAC,kCAAuB,EAAC,CAAC;EAC3C,MAAM;IAAEC,SAAS;IAAEC,SAAS;IAAEC,YAAY;IAAEC,MAAM;IAAEC;EAAW,CAAC,GAAGN,SAAS;EAC5E,MAAMO,UAAU,GAAG,IAAAC,+BAAoB,EAAO,CAAC;EAE/C,OAAO,IAAAC,kBAAW,EAAC,MAAM;IACvB,OAAO,IAAIC,kBAAW,CAAC;MACrBnB,MAAM;MACNC,oBAAoB;MACpBmB,cAAc,EAAElB,YAAY,GACxB,CAACmB,GAAG,EAAEC,MAAM,KACV,IAAAC,4CAAqB,EACnBrB,YAAY,EACZmB,GAAG,EACHC,MAAM,EACNN,UAAU,CAACQ,KAAK,CAACC,UAAU,CAACC,KAC9B,CAAC,GACHC,SAAS;MACbxB,YAAY;MACZC,YAAY;MACZW,UAAU;MACVV,gBAAgB;MAChBC,iBAAiB;MACjBU,UAAU;MACVT,gBAAgB;MAChBI,SAAS;MACTC,SAAS;MACTC,YAAY;MACZL,QAAQ,EAAEA,QAAQ,IAAIC,SAAS,CAACD,QAAQ;MACxCoB,WAAW,EAAEA,CAACC,OAAO,EAAEC,QAAQ,KAAK;QAClChB,MAAM,CAACiB,QAAQ,CACb,+BAA+BC,kBAAkB,CAACH,OAAO,CAAC,EAAE,EAC5DC,QACF,CAAC;MACH;IACF,CAAC,CAAC;EACJ,CAAC,EAAE,EAAE,CAAC;AACR","ignoreList":[]}
@@ -14,12 +14,13 @@ var _rewriteCsv = require("./rewriteCsv");
14
14
  var _hubJobClient = require("./hubJobClient");
15
15
  var _importJobPoller = require("./importJobPoller");
16
16
  var _detectFieldType = require("./detectFieldType");
17
+ var _importFieldCompatibility = require("./importFieldCompatibility");
17
18
  var _fieldEdit = require("./fieldEdit");
18
19
  var _newFieldDraft = require("./newFieldDraft");
19
20
  var _ImportStateBIReporter = require("./ImportStateBIReporter");
20
21
  /** Outcome of a server-side import job, derived from the job's progress. */
21
22
 
22
- /** A rejected row: its index into `csvRows` and the server's failure reason. */
23
+ /** A rejected row: its index in the input rows and the reason it failed. */
23
24
 
24
25
  /**
25
26
  * Optional snapshot taken before the import runs, returning a `restore` used to
@@ -50,7 +51,8 @@ var _ImportStateBIReporter = require("./ImportStateBIReporter");
50
51
  // `id`/`header`): a field the destination mandates. Consumers set it — the
51
52
  // schema-backed config forwards `validation.required`, manual/platformized
52
53
  // configs set it per field — and the mapping step blocks import while any
53
- // required field has no column mapped to it (CAIRO-4452).
54
+ // required field has no column mapped to it (CAIRO-4452). `type` hides the field
55
+ // from the mapping dropdown of columns whose data doesn't fit it (CAIRO-4392).
54
56
 
55
57
  // `NewFieldType`, `detectColumnType`, etc. are re-exported from the package via
56
58
  // the `ImportState` barrel (`./index`), which also exports `./detectFieldType`.
@@ -211,7 +213,11 @@ const buildImportConfig = (fieldsSource, collection, inputs = {}) => {
211
213
  return {
212
214
  id: f.id,
213
215
  header: f.displayName,
214
- required: (_f$validation = f.validation) == null ? void 0 : _f$validation.required
216
+ required: (_f$validation = f.validation) == null ? void 0 : _f$validation.required,
217
+ type: f.type,
218
+ ...(f.arrayMetadata && {
219
+ arrayMetadata: f.arrayMetadata
220
+ })
215
221
  };
216
222
  });
217
223
  return [...fields, ...live];
@@ -302,6 +308,21 @@ function uniqueFieldNameAndKey(header, usedNames, usedKeys, requestedKey) {
302
308
  displayName = `${header}-${suffix}`;
303
309
  }
304
310
  }
311
+ function uniqueColumnHeaders(headers) {
312
+ const reserved = new Set(headers);
313
+ const used = new Set();
314
+ return headers.map(header => {
315
+ let unique = header;
316
+ let suffix = 2;
317
+ while (used.has(unique)) {
318
+ do {
319
+ unique = `${header} (${suffix++})`;
320
+ } while (reserved.has(unique));
321
+ }
322
+ used.add(unique);
323
+ return unique;
324
+ });
325
+ }
305
326
  class ImportState {
306
327
  constructor(props) {
307
328
  // The import inputs, held by reference so a live schema-backed config's getters
@@ -317,7 +338,13 @@ class ImportState {
317
338
  (0, _defineProperty2.default)(this, "bi", void 0);
318
339
  (0, _defineProperty2.default)(this, "hubJobClient", void 0);
319
340
  (0, _defineProperty2.default)(this, "_detectColumnType", void 0);
341
+ (0, _defineProperty2.default)(this, "_isValueCompatible", void 0);
320
342
  (0, _defineProperty2.default)(this, "discardChangesModal", new _ConditionalModalState.ConditionalModalState());
343
+ (0, _defineProperty2.default)(this, "_createFieldValidator", void 0);
344
+ (0, _defineProperty2.default)(this, "_fieldsSource", void 0);
345
+ (0, _defineProperty2.default)(this, "_getExistingIds", void 0);
346
+ (0, _defineProperty2.default)(this, "_uploadedRows", undefined);
347
+ (0, _defineProperty2.default)(this, "_validationFailures", []);
321
348
  (0, _defineProperty2.default)(this, "currentStep", 'upload');
322
349
  (0, _defineProperty2.default)(this, "importStatus", {
323
350
  ..._model.queryStatus.idle
@@ -376,12 +403,16 @@ class ImportState {
376
403
  this.config = props.config ?? buildImportConfig(props.fieldsSource, props.collection, props.importInputs);
377
404
  this.importModalState = props.importModalState;
378
405
  this.translate = props.translate;
406
+ this._createFieldValidator = props.createFieldValidator;
407
+ this._fieldsSource = props.fieldsSource;
408
+ this._getExistingIds = props.getExistingIds;
379
409
  this.errorHandler = props.errorHandler;
380
410
  this.showToast = props.showToast;
381
411
  this.downloadCsv = props.downloadCsv;
382
412
  this.reportBi = props.reportBi ?? NOOP_REPORT_BI;
383
413
  this.bi = new _ImportStateBIReporter.ImportStateBIReporter(this);
384
414
  this._detectColumnType = props.detectColumnType ?? _detectFieldType.detectColumnType;
415
+ this._isValueCompatible = props.isValueCompatible;
385
416
  this.hubJobClient = (0, _hubJobClient.createHubJobClient)({
386
417
  httpClient: props.httpClient,
387
418
  errorHandler: props.errorHandler
@@ -392,6 +423,13 @@ class ImportState {
392
423
  fileName: _mobx.observable.ref,
393
424
  csvHeaders: _mobx.observable.ref,
394
425
  csvRows: _mobx.observable.ref,
426
+ // Auto-mapping reads these before the configuration step observes them.
427
+ _columnSamples: (0, _mobx.computed)({
428
+ keepAlive: true
429
+ }),
430
+ _compatibleFieldsByHeader: (0, _mobx.computed)({
431
+ keepAlive: true
432
+ }),
395
433
  orderedHeaders: _mobx.observable.ref,
396
434
  mappingByHeader: _mobx.observable.ref,
397
435
  writePolicy: _mobx.observable.ref,
@@ -535,6 +573,15 @@ class ImportState {
535
573
  get selectedFieldIds() {
536
574
  return new Set(Object.values(this.mappingByHeader).filter(m => (m == null ? void 0 : m.kind) === 'existing').map(m => m.fieldId));
537
575
  }
576
+ get _compatibleFieldsByHeader() {
577
+ const fields = this.fields;
578
+ return new Map(this.csvHeaders.map((header, index) => [header, new Set(fields.filter(field => !field.type || (0, _importFieldCompatibility.isImportColumnCompatible)(field.type, this._columnValues(index), field.arrayMetadata, this._isValueCompatible)).map(field => field.id))]));
579
+ }
580
+ fieldsForHeader(header) {
581
+ const compatibleIds = this._compatibleFieldsByHeader.get(header);
582
+ const mapping = this.mappingByHeader[header];
583
+ return this.fields.filter(field => field.type !== 'UNKNOWN' && ((compatibleIds == null ? void 0 : compatibleIds.has(field.id)) || (mapping == null ? void 0 : mapping.kind) === 'existing' && mapping.fieldId === field.id));
584
+ }
538
585
 
539
586
  /**
540
587
  * Required destination fields that no CSV column is mapped to (CAIRO-4452).
@@ -621,6 +668,8 @@ class ImportState {
621
668
  this.importStatus = {
622
669
  ..._model.queryStatus.idle
623
670
  };
671
+ this._uploadedRows = undefined;
672
+ this._validationFailures = [];
624
673
  this.fileName = '';
625
674
  this.csvHeaders = [];
626
675
  this.csvRows = [];
@@ -748,20 +797,19 @@ class ImportState {
748
797
  this.currentStep = 'configuration';
749
798
  }
750
799
  }
751
- getDefaultMapping(headers) {
800
+ getDefaultMapping(headers, originalHeaders) {
752
801
  const mapping = {};
753
- const fields = this.fields.map(field => ({
754
- id: field.id ?? '',
755
- header: field.header ?? ''
756
- }));
802
+ const matchedIds = new Set();
803
+ const fields = this.fields.filter(field => field.type !== 'UNKNOWN');
757
804
  headers.forEach((header, index) => {
758
- const normalizedHeader = normalize(header);
759
- const matched = fields.find(field => normalize(field.id) === normalizedHeader || normalize(field.header) === normalizedHeader);
805
+ const normalizedHeader = normalize(originalHeaders[index]);
806
+ const matched = fields.find(field => field.id != null && !matchedIds.has(field.id) && (normalize(field.id) === normalizedHeader || normalize(field.header ?? '') === normalizedHeader));
760
807
  if (matched != null && matched.id) {
761
808
  mapping[header] = {
762
809
  kind: 'existing',
763
810
  fieldId: matched.id
764
811
  };
812
+ matchedIds.add(matched.id);
765
813
  } else {
766
814
  // Unmatched columns default to creating a new field (type inferred from
767
815
  // the column's data) when the consumer supplied `updateSchema`;
@@ -774,12 +822,23 @@ class ImportState {
774
822
  });
775
823
  return mapping;
776
824
  }
777
-
778
- // The column's values, capped at the detection sample size — detection only
779
- // looks at the first `TYPE_SAMPLE_SIZE` values, so avoid copying the whole
780
- // column (a wide CSV would otherwise allocate rows × columns strings).
825
+ get _columnSamples() {
826
+ return this.csvHeaders.map((_, columnIndex) => {
827
+ const values = [];
828
+ for (const row of this.csvRows) {
829
+ const value = row[columnIndex] ?? '';
830
+ if (value.trim() !== '') {
831
+ values.push(value);
832
+ if (values.length === _detectFieldType.TYPE_SAMPLE_SIZE) {
833
+ break;
834
+ }
835
+ }
836
+ }
837
+ return values;
838
+ });
839
+ }
781
840
  _columnValues(columnIndex) {
782
- return this.csvRows.slice(0, _detectFieldType.TYPE_SAMPLE_SIZE).map(row => row[columnIndex] ?? '');
841
+ return this._columnSamples[columnIndex] ?? [];
783
842
  }
784
843
 
785
844
  // Puts the `_id`-mapped column first (CAIRO-4418), preserving CSV order for the
@@ -792,13 +851,14 @@ class ImportState {
792
851
  this._pendingFieldsMap = undefined;
793
852
  this._createdFields.clear();
794
853
  this.fileName = fileName;
795
- this.csvHeaders = parsedCsv.headers;
854
+ // Mapping, compatibility and upload rewriting all key columns by this name.
855
+ this.csvHeaders = uniqueColumnHeaders(parsedCsv.headers);
796
856
  this.csvRows = parsedCsv.rows;
797
- this.mappingByHeader = this.getDefaultMapping(parsedCsv.headers);
857
+ this.mappingByHeader = this.getDefaultMapping(this.csvHeaders, parsedCsv.headers);
798
858
  // Snapshot the row order for this file with the auto-mapped `_id` column
799
859
  // first. Reads `idMappedHeader`, so it must run after `mappingByHeader` is
800
860
  // set. Kept stable until the next file so mapping edits don't reorder rows.
801
- this.orderedHeaders = this._orderHeadersWithIdFirst(parsedCsv.headers);
861
+ this.orderedHeaders = this._orderHeadersWithIdFirst(this.csvHeaders);
802
862
  // A new file is a fresh import: start from the default policy so a prior
803
863
  // file's Skip choice doesn't silently carry over (only the new-file path
804
864
  // resets — remapping `_id` within the same file keeps the user's choice).
@@ -881,34 +941,37 @@ class ImportState {
881
941
  });
882
942
  }
883
943
 
884
- /**
885
- * Builds a re-importable CSV of the rows the server rejected and hands it to
886
- * `downloadCsv`. Each failed row is prefixed with a leading "why it failed"
887
- * column holding the server's error message, so the user can see and fix each
888
- * reason. The failed rows (and their reasons) come from the job's movement
889
- * logs, mapped back to the parsed `csvRows` we still hold in memory.
890
- */
944
+ /** Downloads validation failures and server rejections with their reasons. */
891
945
  async downloadFailedRows() {
892
946
  var _this$downloadCsv;
893
947
  this.bi.onSummaryCtaClicked('Download failed items CSV');
894
- const jobId = this._jobId;
895
- if (!jobId) {
896
- return;
897
- }
898
- let failures;
899
- try {
900
- failures = await this._fetchFailedRows(jobId);
901
- } catch (error) {
902
- console.error('Fetching failed rows report failed', error);
903
- return;
948
+ let serverFailures = [];
949
+ if (this._jobId && this.result.failed > this._validationFailures.length) {
950
+ try {
951
+ serverFailures = await this._fetchFailedRows(this._jobId);
952
+ } catch (error) {
953
+ console.error('Fetching failed rows report failed', error);
954
+ return;
955
+ }
904
956
  }
905
- const rows = failures.map(({
957
+ const rows = [...this._validationFailures.map(({
958
+ index,
959
+ reason
960
+ }) => ({
961
+ row: this.csvRows[index],
962
+ reason
963
+ })), ...serverFailures.map(({
906
964
  index,
907
965
  reason
908
- }) => {
909
- const row = this.csvRows[index];
910
- return row != null ? [reason, ...row] : null;
911
- }).filter(row => row != null);
966
+ }) => ({
967
+ row: (this._uploadedRows ?? this.csvRows)[index],
968
+ reason
969
+ }))].filter(({
970
+ row
971
+ }) => row != null).map(({
972
+ row,
973
+ reason
974
+ }) => [reason, ...row]);
912
975
  if (rows.length === 0) {
913
976
  return;
914
977
  }
@@ -945,7 +1008,7 @@ class ImportState {
945
1008
  }
946
1009
  const fileLine = Number((_exec = /\d+/.exec(log.sourceItemId)) == null ? void 0 : _exec[0]);
947
1010
  const index = fileLine - 2;
948
- if (Number.isInteger(index) && index >= 0 && index < this.csvRows.length) {
1011
+ if (Number.isInteger(index) && index >= 0 && index < (this._uploadedRows ?? this.csvRows).length) {
949
1012
  failures.push({
950
1013
  index,
951
1014
  reason: log.failure.description ?? ''
@@ -1084,8 +1147,8 @@ class ImportState {
1084
1147
  * a failed job so `startImport` surfaces the error state; partial success is
1085
1148
  * reported via `result.failed` and the partial toast.
1086
1149
  */
1087
- async _runImportJob(resolvedMapping) {
1088
- const csv = (0, _rewriteCsv.rewriteParsedCsvForImport)(this.csvHeaders, this.csvRows, resolvedMapping);
1150
+ async _runImportJob(resolvedMapping, rows) {
1151
+ const csv = (0, _rewriteCsv.rewriteParsedCsvForImport)(this.csvHeaders, rows, resolvedMapping);
1089
1152
  const file = new File([csv], this.fileName || 'import.csv', {
1090
1153
  type: 'text/csv'
1091
1154
  });
@@ -1181,8 +1244,9 @@ class ImportState {
1181
1244
  _applyJobProgress(job) {
1182
1245
  const progress = job.progress;
1183
1246
  const succeeded = (progress == null ? void 0 : progress.itemsSuccessful) ?? 0;
1184
- const failed = (progress == null ? void 0 : progress.itemsRejected) ?? 0;
1185
- const current = (progress == null ? void 0 : progress.current) ?? succeeded + failed;
1247
+ const rejected = (progress == null ? void 0 : progress.itemsRejected) ?? 0;
1248
+ const failed = rejected + this._validationFailures.length;
1249
+ const current = ((progress == null ? void 0 : progress.current) ?? succeeded + rejected) + this._validationFailures.length;
1186
1250
  // The server splits successful items into created (new) and updated
1187
1251
  // (existing) — the summary step reports each. Some jobs omit this split
1188
1252
  // entirely (`itemsSuccessfulInfo` absent); in that case treat every success
@@ -1191,8 +1255,7 @@ class ImportState {
1191
1255
  const created = successInfo ? successInfo.itemsCreated ?? 0 : succeeded;
1192
1256
  const updated = (successInfo == null ? void 0 : successInfo.itemsUpdated) ?? 0;
1193
1257
 
1194
- // `totalCount` is fixed up front in `startImport` from the CSV row count
1195
- // (one uploaded row per CSV row); polling only advances `processedCount`.
1258
+ // Validation failures are already processed; the job advances the rest.
1196
1259
  (0, _mobx.runInAction)(() => {
1197
1260
  this.processedCount = Math.min(current, this.totalCount);
1198
1261
  this.result = {
@@ -1366,6 +1429,65 @@ class ImportState {
1366
1429
  console.error('ImportState config.onImportCompleted failed', error);
1367
1430
  }
1368
1431
  }
1432
+ async _validateRows(mapping, signal) {
1433
+ var _this$_getExistingIds;
1434
+ const rows = [];
1435
+ const failedRows = [];
1436
+ const idIndex = this.csvHeaders.findIndex(header => mapping[header] === this.idFieldKey);
1437
+ const skipExisting = this.writePolicy === _types.WritePolicy.SKIP_EXISTING;
1438
+ const ids = [...new Set(this.csvRows.map(row => row[idIndex]).filter(Boolean))];
1439
+ const skippedIds = new Set(skipExisting && ids.length ? await ((_this$_getExistingIds = this._getExistingIds) == null ? void 0 : _this$_getExistingIds.call(this, ids, signal)) : []);
1440
+ const columns = this.csvHeaders.map(header => {
1441
+ var _this$_pendingFieldsM, _this$_fieldsSource, _sourceField$validati, _this$_createFieldVal;
1442
+ const fieldId = mapping[header];
1443
+ if (!fieldId || fieldId === this.idFieldKey) {
1444
+ return undefined;
1445
+ }
1446
+ 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));
1447
+ if (sourceField != null && sourceField.isSystem) {
1448
+ return undefined;
1449
+ }
1450
+ const configField = this.fields.find(field => field.id === fieldId);
1451
+ const field = {
1452
+ ...(sourceField ?? {
1453
+ id: fieldId,
1454
+ displayName: (configField == null ? void 0 : configField.header) || fieldId,
1455
+ type: 'UNKNOWN'
1456
+ }),
1457
+ validation: {
1458
+ ...(sourceField == null ? void 0 : sourceField.validation),
1459
+ required: !!(configField != null && configField.required || sourceField != null && (_sourceField$validati = sourceField.validation) != null && _sourceField$validati.required)
1460
+ }
1461
+ };
1462
+ return ((_this$_createFieldVal = this._createFieldValidator) == null ? void 0 : _this$_createFieldVal.call(this, field)) ?? (raw => {
1463
+ var _field$validation;
1464
+ return (_field$validation = field.validation) != null && _field$validation.required && !raw ? [this.translate('cairo.editableTable.field.validation.required', {
1465
+ fieldName: field.displayName
1466
+ })] : [];
1467
+ });
1468
+ });
1469
+ this.csvRows.forEach((row, index) => {
1470
+ if (skippedIds.has(row[idIndex])) {
1471
+ return;
1472
+ }
1473
+ const reasons = columns.flatMap((validate, columnIndex) => (validate == null ? void 0 : validate(row[columnIndex] ?? '')) ?? []);
1474
+ if (reasons.length) {
1475
+ failedRows.push({
1476
+ index,
1477
+ reason: reasons.join('; ')
1478
+ });
1479
+ } else {
1480
+ rows.push(row);
1481
+ if (skipExisting && row[idIndex]) {
1482
+ skippedIds.add(row[idIndex]);
1483
+ }
1484
+ }
1485
+ });
1486
+ return {
1487
+ rows,
1488
+ failedRows
1489
+ };
1490
+ }
1369
1491
  async startImport() {
1370
1492
  if (!this.hasMappings) {
1371
1493
  return;
@@ -1398,9 +1520,8 @@ class ImportState {
1398
1520
  }
1399
1521
  this._cancelled = false;
1400
1522
  this._abortController = new AbortController();
1401
-
1402
- // One uploaded row per CSV row (the rewrite drops columns, not rows), so the
1403
- // total is known up front from the parsed CSV and stays fixed through polling.
1523
+ this._validationFailures = [];
1524
+ this._uploadedRows = undefined;
1404
1525
  const totalCount = this.csvRows.length;
1405
1526
  (0, _mobx.runInAction)(() => {
1406
1527
  this.currentStep = 'progress';
@@ -1438,8 +1559,13 @@ class ImportState {
1438
1559
  // before uploading. A creation failure surfaces as the error state with a
1439
1560
  // "Try again" CTA, like an upload/job failure.
1440
1561
  let resolvedMapping;
1562
+ let prepared;
1441
1563
  try {
1442
1564
  resolvedMapping = await this._resolveFieldMapping();
1565
+ if (this._cancelled) {
1566
+ return;
1567
+ }
1568
+ prepared = await this._validateRows(resolvedMapping, this._abortController.signal);
1443
1569
  } catch (error) {
1444
1570
  (0, _mobx.runInAction)(() => {
1445
1571
  this.importStatus = {
@@ -1456,7 +1582,18 @@ class ImportState {
1456
1582
  if (this._cancelled) {
1457
1583
  return;
1458
1584
  }
1459
- const promise = this._runImportJob(resolvedMapping);
1585
+ const uploadedRows = prepared.rows;
1586
+ this._uploadedRows = uploadedRows;
1587
+ this._validationFailures = prepared.failedRows;
1588
+ (0, _mobx.runInAction)(() => {
1589
+ this.result = {
1590
+ ...this.result,
1591
+ failed: this._validationFailures.length
1592
+ };
1593
+ this.processedCount = this._validationFailures.length;
1594
+ this.totalCount = uploadedRows.length + this._validationFailures.length;
1595
+ });
1596
+ const promise = uploadedRows.length ? this._runImportJob(resolvedMapping, uploadedRows) : Promise.resolve(this.result);
1460
1597
  this.importStatus = {
1461
1598
  ..._model.queryStatus.loading,
1462
1599
  promise