@commercetools/sync-actions 7.0.0-rc.2 → 7.1.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 (36) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -1
  3. package/dist/{sync-actions.cjs.js → commercetools-sync-actions.cjs.dev.js} +323 -1786
  4. package/dist/commercetools-sync-actions.cjs.js +7 -0
  5. package/dist/commercetools-sync-actions.cjs.prod.js +3747 -0
  6. package/dist/{sync-actions.es.js → commercetools-sync-actions.esm.js} +227 -1723
  7. package/package.json +16 -11
  8. package/dist/sync-actions.umd.js +0 -5207
  9. package/dist/sync-actions.umd.min.js +0 -1
  10. package/lib/cart-discounts-actions.js +0 -31
  11. package/lib/cart-discounts.js +0 -70
  12. package/lib/categories.js +0 -106
  13. package/lib/category-actions.js +0 -117
  14. package/lib/channels.js +0 -0
  15. package/lib/customer-actions.js +0 -125
  16. package/lib/customer-group-actions.js +0 -23
  17. package/lib/customer-group.js +0 -70
  18. package/lib/customers.js +0 -95
  19. package/lib/discount-codes-actions.js +0 -31
  20. package/lib/discount-codes.js +0 -80
  21. package/lib/index.js +0 -90
  22. package/lib/inventories.js +0 -89
  23. package/lib/inventory-actions.js +0 -42
  24. package/lib/order-actions.js +0 -71
  25. package/lib/orders.js +0 -89
  26. package/lib/product-actions.js +0 -779
  27. package/lib/product-discounts-actions.js +0 -27
  28. package/lib/product-discounts.js +0 -71
  29. package/lib/products.js +0 -208
  30. package/lib/utils/clone.js +0 -9
  31. package/lib/utils/common-actions.js +0 -157
  32. package/lib/utils/create-build-actions.js +0 -74
  33. package/lib/utils/create-build-array-actions.js +0 -146
  34. package/lib/utils/create-map-action-group.js +0 -35
  35. package/lib/utils/diffpatcher.js +0 -93
  36. package/lib/utils/find-matching-pairs.js +0 -67
@@ -0,0 +1,3747 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var flatten = require('lodash.flatten');
6
+ var isEqual = require('lodash.isequal');
7
+ var isNil = require('lodash.isnil');
8
+ var jsondiffpatch = require('jsondiffpatch');
9
+ var forEach = require('lodash.foreach');
10
+ var uniqWith = require('lodash.uniqwith');
11
+ var intersection = require('lodash.intersection');
12
+ var without = require('lodash.without');
13
+ var fastEquals = require('fast-equals');
14
+ var sortBy = require('lodash.sortby');
15
+
16
+ function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
17
+
18
+ function _interopNamespace(e) {
19
+ if (e && e.__esModule) return e;
20
+ var n = Object.create(null);
21
+ if (e) {
22
+ Object.keys(e).forEach(function (k) {
23
+ if (k !== 'default') {
24
+ var d = Object.getOwnPropertyDescriptor(e, k);
25
+ Object.defineProperty(n, k, d.get ? d : {
26
+ enumerable: true,
27
+ get: function () { return e[k]; }
28
+ });
29
+ }
30
+ });
31
+ }
32
+ n["default"] = e;
33
+ return Object.freeze(n);
34
+ }
35
+
36
+ var flatten__default = /*#__PURE__*/_interopDefault(flatten);
37
+ var isEqual__default = /*#__PURE__*/_interopDefault(isEqual);
38
+ var isNil__default = /*#__PURE__*/_interopDefault(isNil);
39
+ var jsondiffpatch__namespace = /*#__PURE__*/_interopNamespace(jsondiffpatch);
40
+ var forEach__default = /*#__PURE__*/_interopDefault(forEach);
41
+ var uniqWith__default = /*#__PURE__*/_interopDefault(uniqWith);
42
+ var intersection__default = /*#__PURE__*/_interopDefault(intersection);
43
+ var without__default = /*#__PURE__*/_interopDefault(without);
44
+ var sortBy__default = /*#__PURE__*/_interopDefault(sortBy);
45
+
46
+ function _arrayWithHoles(r) {
47
+ if (Array.isArray(r)) return r;
48
+ }
49
+
50
+ function _iterableToArrayLimit(r, l) {
51
+ var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
52
+ if (null != t) {
53
+ var e,
54
+ n,
55
+ i,
56
+ u,
57
+ a = [],
58
+ f = !0,
59
+ o = !1;
60
+ try {
61
+ if (i = (t = t.call(r)).next, 0 === l) {
62
+ if (Object(t) !== t) return;
63
+ f = !1;
64
+ } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
65
+ } catch (r) {
66
+ o = !0, n = r;
67
+ } finally {
68
+ try {
69
+ if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
70
+ } finally {
71
+ if (o) throw n;
72
+ }
73
+ }
74
+ return a;
75
+ }
76
+ }
77
+
78
+ function _arrayLikeToArray(r, a) {
79
+ (null == a || a > r.length) && (a = r.length);
80
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
81
+ return n;
82
+ }
83
+
84
+ function _unsupportedIterableToArray(r, a) {
85
+ if (r) {
86
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
87
+ var t = {}.toString.call(r).slice(8, -1);
88
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
89
+ }
90
+ }
91
+
92
+ function _nonIterableRest() {
93
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
94
+ }
95
+
96
+ function _slicedToArray(r, e) {
97
+ return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
98
+ }
99
+
100
+ function _toPrimitive(t, r) {
101
+ if ("object" != typeof t || !t) return t;
102
+ var e = t[Symbol.toPrimitive];
103
+ if (void 0 !== e) {
104
+ var i = e.call(t, r || "default");
105
+ if ("object" != typeof i) return i;
106
+ throw new TypeError("@@toPrimitive must return a primitive value.");
107
+ }
108
+ return ("string" === r ? String : Number)(t);
109
+ }
110
+
111
+ function _toPropertyKey(t) {
112
+ var i = _toPrimitive(t, "string");
113
+ return "symbol" == typeof i ? i : i + "";
114
+ }
115
+
116
+ function _defineProperty(e, r, t) {
117
+ return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
118
+ value: t,
119
+ enumerable: !0,
120
+ configurable: !0,
121
+ writable: !0
122
+ }) : e[r] = t, e;
123
+ }
124
+
125
+ function ownKeys(e, r) {
126
+ var t = Object.keys(e);
127
+ if (Object.getOwnPropertySymbols) {
128
+ var o = Object.getOwnPropertySymbols(e);
129
+ r && (o = o.filter(function (r) {
130
+ return Object.getOwnPropertyDescriptor(e, r).enumerable;
131
+ })), t.push.apply(t, o);
132
+ }
133
+ return t;
134
+ }
135
+ function _objectSpread2(e) {
136
+ for (var r = 1; r < arguments.length; r++) {
137
+ var t = null != arguments[r] ? arguments[r] : {};
138
+ r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
139
+ _defineProperty(e, r, t[r]);
140
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
141
+ Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
142
+ });
143
+ }
144
+ return e;
145
+ }
146
+
147
+ function _objectWithoutPropertiesLoose(r, e) {
148
+ if (null == r) return {};
149
+ var t = {};
150
+ for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
151
+ if (-1 !== e.indexOf(n)) continue;
152
+ t[n] = r[n];
153
+ }
154
+ return t;
155
+ }
156
+
157
+ function _objectWithoutProperties(e, t) {
158
+ if (null == e) return {};
159
+ var o,
160
+ r,
161
+ i = _objectWithoutPropertiesLoose(e, t);
162
+ if (Object.getOwnPropertySymbols) {
163
+ var n = Object.getOwnPropertySymbols(e);
164
+ for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);
165
+ }
166
+ return i;
167
+ }
168
+
169
+ var _excluded$2 = ["prices"];
170
+ function applyOnBeforeDiff(before, now, fn) {
171
+ return fn && typeof fn === 'function' ? fn(before, now) : [before, now];
172
+ }
173
+ var createPriceComparator = function createPriceComparator(price) {
174
+ return {
175
+ value: {
176
+ currencyCode: price.value.currencyCode
177
+ },
178
+ channel: price.channel,
179
+ country: price.country,
180
+ customerGroup: price.customerGroup,
181
+ validFrom: price.validFrom,
182
+ validUntil: price.validUntil
183
+ };
184
+ };
185
+ function arePricesStructurallyEqual(oldPrice, newPrice) {
186
+ var oldPriceComparison = createPriceComparator(oldPrice);
187
+ var newPriceComparison = createPriceComparator(newPrice);
188
+ return isEqual__default["default"](newPriceComparison, oldPriceComparison);
189
+ }
190
+ function extractPriceFromPreviousVariant(newPrice, previousVariant) {
191
+ if (!previousVariant) return null;
192
+ var price = previousVariant.prices.find(function (oldPrice) {
193
+ return arePricesStructurallyEqual(oldPrice, newPrice);
194
+ });
195
+ return price || null;
196
+ }
197
+ function injectMissingPriceIds(nextVariants, previousVariants) {
198
+ return nextVariants.map(function (newVariant) {
199
+ var prices = newVariant.prices,
200
+ restOfVariant = _objectWithoutProperties(newVariant, _excluded$2);
201
+ if (!prices) return restOfVariant;
202
+ var oldVariant = previousVariants.find(function (previousVariant) {
203
+ return !isNil__default["default"](previousVariant.id) && previousVariant.id === newVariant.id || !isNil__default["default"](previousVariant.key) && previousVariant.key === newVariant.key || !isNil__default["default"](previousVariant.sku) && previousVariant.sku === newVariant.sku;
204
+ });
205
+ return _objectSpread2(_objectSpread2({}, restOfVariant), {}, {
206
+ prices: prices.map(function (price) {
207
+ var newPrice = _objectSpread2({}, price);
208
+ var oldPrice = extractPriceFromPreviousVariant(price, oldVariant);
209
+ if (oldPrice) {
210
+ // copy ID if not provided
211
+ if (!newPrice.id) newPrice.id = oldPrice.id;
212
+ if (isNil__default["default"](newPrice.value.type)) newPrice.value.type = oldPrice.value.type;
213
+ if (isNil__default["default"](newPrice.value.fractionDigits)) newPrice.value.fractionDigits = oldPrice.value.fractionDigits;
214
+ }
215
+ return newPrice;
216
+ })
217
+ });
218
+ });
219
+ }
220
+ function createBuildActions(differ, doMapActions, onBeforeDiff) {
221
+ var buildActionsConfig = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
222
+ return function buildActions(now, before) {
223
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
224
+ if (!now || !before) throw new Error('Missing either `newObj` or `oldObj` ' + 'in order to build update actions');
225
+ var _applyOnBeforeDiff = applyOnBeforeDiff(before, now, onBeforeDiff),
226
+ _applyOnBeforeDiff2 = _slicedToArray(_applyOnBeforeDiff, 2),
227
+ processedBefore = _applyOnBeforeDiff2[0],
228
+ processedNow = _applyOnBeforeDiff2[1];
229
+ if (processedNow.variants && processedBefore.variants) processedNow.variants = injectMissingPriceIds(processedNow.variants, processedBefore.variants);
230
+ var diffed = differ(processedBefore, processedNow);
231
+ if (!buildActionsConfig.withHints && !diffed) return [];
232
+ return doMapActions(diffed, processedNow, processedBefore, options);
233
+ };
234
+ }
235
+
236
+ // Array of action groups which need to be allowed or ignored.
237
+ // Example:
238
+ // [
239
+ // { type: 'base', group: 'ignore' },
240
+ // { type: 'prices', group: 'allow' },
241
+ // { type: 'variants', group: 'ignore' },
242
+ // ]
243
+ function createMapActionGroup() {
244
+ var actionGroups = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
245
+ return function mapActionGroup(type, fn) {
246
+ if (!Object.keys(actionGroups).length) return fn();
247
+ var found = actionGroups.find(function (c) {
248
+ return c.type === type;
249
+ });
250
+ if (!found) return [];
251
+
252
+ // Keep `black` for backwards compatibility.
253
+ if (found.group === 'ignore' || found.group === 'black') return [];
254
+ // Keep `white` for backwards compatibility.
255
+ if (found.group === 'allow' || found.group === 'white') return fn();
256
+ throw new Error("Action group '".concat(found.group, "' not supported. Use either \"allow\" or \"ignore\"."));
257
+ };
258
+ }
259
+
260
+ function _arrayWithoutHoles(r) {
261
+ if (Array.isArray(r)) return _arrayLikeToArray(r);
262
+ }
263
+
264
+ function _iterableToArray(r) {
265
+ if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
266
+ }
267
+
268
+ function _nonIterableSpread() {
269
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
270
+ }
271
+
272
+ function _toConsumableArray(r) {
273
+ return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
274
+ }
275
+
276
+ function _typeof(o) {
277
+ "@babel/helpers - typeof";
278
+
279
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
280
+ return typeof o;
281
+ } : function (o) {
282
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
283
+ }, _typeof(o);
284
+ }
285
+
286
+ function objectHash(obj, index) {
287
+ var objIndex = "$$index:".concat(index);
288
+ return _typeof(obj) === 'object' && obj !== null ? obj.id || obj.name || obj.url || objIndex : objIndex;
289
+ }
290
+ var diffpatcher = jsondiffpatch__namespace.create({
291
+ objectHash: objectHash,
292
+ arrays: {
293
+ // detect items moved inside the array
294
+ detectMove: true,
295
+ // value of items moved is not included in deltas
296
+ includeValueOnMove: false
297
+ },
298
+ textDiff: {
299
+ /**
300
+ * jsondiffpatch uses a very fine-grained diffing algorithm for long strings to easily identify
301
+ * what changed between strings. However, we don't actually care about what changed, just
302
+ * if the string changed at all. So we set the minimum length to diff to a very large number to avoid
303
+ * using the very slow algorithm.
304
+ * See https://github.com/benjamine/jsondiffpatch/blob/master/docs/deltas.md#text-diffs.
305
+ */
306
+ minLength: Number.MAX_SAFE_INTEGER
307
+ }
308
+ });
309
+ function diff(oldObj, newObj) {
310
+ return diffpatcher.diff(oldObj, newObj);
311
+ }
312
+ function patch(obj, delta) {
313
+ return diffpatcher.patch(obj, delta);
314
+ }
315
+ function getDeltaValue(arr, originalObject) {
316
+ if (!Array.isArray(arr)) throw new Error('Expected array to extract delta value');
317
+ if (arr.length === 1) return arr[0]; // new
318
+
319
+ if (arr.length === 2) return arr[1]; // update
320
+
321
+ if (arr.length === 3 && arr[2] === 0) return undefined; // delete
322
+
323
+ if (arr.length === 3 && arr[2] === 2) {
324
+ // text diff
325
+ if (!originalObject) throw new Error('Cannot apply patch to long text diff. Missing original object.');
326
+ // try to apply patch to given object based on delta value
327
+ return patch(originalObject, arr);
328
+ }
329
+ if (arr.length === 3 && arr[2] === 3)
330
+ // array move
331
+ throw new Error('Detected an array move, it should not happen as ' + '`includeValueOnMove` should be set to false');
332
+ throw new Error("Got unsupported number ".concat(arr[2], " in delta value"));
333
+ }
334
+
335
+ var _excluded$1 = ["actions"];
336
+ var Actions = {
337
+ setCustomType: 'setCustomType',
338
+ setCustomField: 'setCustomField'
339
+ };
340
+ var hasSingleCustomFieldChanged = function hasSingleCustomFieldChanged(diff) {
341
+ return Array.isArray(diff.custom);
342
+ };
343
+ var haveMultipleCustomFieldsChanged = function haveMultipleCustomFieldsChanged(diff) {
344
+ return Boolean(diff.custom.fields);
345
+ };
346
+ var hasCustomTypeChanged = function hasCustomTypeChanged(diff) {
347
+ return Boolean(diff.custom.type);
348
+ };
349
+ var extractCustomType = function extractCustomType(diff, previousObject) {
350
+ return Array.isArray(diff.custom.type) ? getDeltaValue(diff.custom.type, previousObject) : diff.custom.type;
351
+ };
352
+ var extractTypeId = function extractTypeId(type, nextObject) {
353
+ return Array.isArray(type.id) ? getDeltaValue(type.id) : nextObject.custom.type.id;
354
+ };
355
+ var extractTypeKey = function extractTypeKey(type, nextObject) {
356
+ return Array.isArray(type.key) ? getDeltaValue(type.key) : nextObject.custom.type.key;
357
+ };
358
+ var extractTypeFields = function extractTypeFields(diffedFields, nextFields) {
359
+ return Array.isArray(diffedFields) ? getDeltaValue(diffedFields) : nextFields;
360
+ };
361
+ var extractFieldValue = function extractFieldValue(newFields, fieldName) {
362
+ return newFields[fieldName];
363
+ };
364
+ function actionsMapCustom(diff, newObj, oldObj) {
365
+ var customProps = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {
366
+ actions: {}
367
+ };
368
+ var actions = [];
369
+ var customPropsActions = customProps.actions,
370
+ options = _objectWithoutProperties(customProps, _excluded$1);
371
+ var actionGroup = _objectSpread2(_objectSpread2({}, Actions), customPropsActions);
372
+ if (!diff.custom) return actions;
373
+ if (hasSingleCustomFieldChanged(diff)) {
374
+ // If custom is not defined on the new or old category
375
+ var custom = getDeltaValue(diff.custom, oldObj);
376
+ actions.push(_objectSpread2(_objectSpread2({
377
+ action: actionGroup.setCustomType
378
+ }, options), custom));
379
+ } else if (hasCustomTypeChanged(diff)) {
380
+ // If custom is set to an empty object on the new or old category
381
+ var type = extractCustomType(diff, oldObj);
382
+ if (!type) actions.push(_objectSpread2({
383
+ action: actionGroup.setCustomType
384
+ }, options));else if (type.id) actions.push(_objectSpread2(_objectSpread2({
385
+ action: actionGroup.setCustomType
386
+ }, options), {}, {
387
+ type: {
388
+ typeId: 'type',
389
+ id: extractTypeId(type, newObj)
390
+ },
391
+ fields: extractTypeFields(diff.custom.fields, newObj.custom.fields)
392
+ }));else if (type.key) actions.push(_objectSpread2(_objectSpread2({
393
+ action: actionGroup.setCustomType
394
+ }, options), {}, {
395
+ type: {
396
+ typeId: 'type',
397
+ key: extractTypeKey(type, newObj)
398
+ },
399
+ fields: extractTypeFields(diff.custom.fields, newObj.custom.fields)
400
+ }));
401
+ } else if (haveMultipleCustomFieldsChanged(diff)) {
402
+ var customFieldsActions = Object.keys(diff.custom.fields).map(function (name) {
403
+ return _objectSpread2(_objectSpread2({
404
+ action: actionGroup.setCustomField
405
+ }, options), {}, {
406
+ name: name,
407
+ value: extractFieldValue(newObj.custom.fields, name)
408
+ });
409
+ });
410
+ actions.push.apply(actions, _toConsumableArray(customFieldsActions));
411
+ }
412
+ return actions;
413
+ }
414
+
415
+ var REGEX_NUMBER$4 = new RegExp(/^\d+$/);
416
+ var REGEX_UNDERSCORE_NUMBER$4 = new RegExp(/^_\d+$/);
417
+ var ADD_ACTIONS = 'create';
418
+ var REMOVE_ACTIONS = 'remove';
419
+ var CHANGE_ACTIONS = 'change';
420
+
421
+ /**
422
+ * Tests a delta to see if it represents a create action.
423
+ * eg. delta:
424
+ * {
425
+ * 0: [ { foo: 'bar' } ]
426
+ * }
427
+ *
428
+ * @param {object} obj The delta generated by the diffpatcher
429
+ * @param {string} key key of generated delta to examine
430
+ * @return {Boolean} Returns true if delta represents a create action,
431
+ * false otherwise
432
+ */
433
+ function isCreateAction(obj, key) {
434
+ return REGEX_NUMBER$4.test(key) && Array.isArray(obj[key]) && obj[key].length === 1;
435
+ }
436
+
437
+ /**
438
+ * Tests a delta to see if it represents a change action.
439
+ * eg. delta:
440
+ *
441
+ * {
442
+ * 0: {
443
+ * foo: ['bar', 'baz']
444
+ * }
445
+ * }
446
+ * @param {object} obj The delta generated by the diffpatcher
447
+ * @param {string} key key of generated delta to examine
448
+ * @return {Boolean} Returns true if delta represents a change action,
449
+ * false otherwise
450
+ */
451
+ function isChangeAction(obj, key) {
452
+ return REGEX_NUMBER$4.test(key) && (_typeof(obj[key]) === 'object' || typeof obj[key] === 'string');
453
+ }
454
+
455
+ /**
456
+ * Tests a delta to see if it represents a remove action.
457
+ * eg. delta:
458
+ *
459
+ * {
460
+ * _0: [ 'foo', 0, 0 ]
461
+ * }
462
+ * @param {object} obj The delta generated by the diffpatcher
463
+ * @param {string} key key of generated delta to examine
464
+ * @return {Boolean} Returns true if delta represents a remove action,
465
+ * false otherwise
466
+ */
467
+ function isRemoveAction$1(obj, key) {
468
+ return REGEX_UNDERSCORE_NUMBER$4.test(key) && Array.isArray(obj[key]) && obj[key].length === 3 && (_typeof(obj[key][0]) === 'object' || typeof obj[key][0] === 'string') && obj[key][1] === 0 && obj[key][2] === 0;
469
+ }
470
+
471
+ /**
472
+ * Generate + configure a function to build actions for nested objects
473
+ * @param {string} key key of the attribute containing the array of
474
+ * nested objects
475
+ * @param {object} config configuration object that can contain the keys
476
+ * [ADD_ACTIONS, REMOVE_ACTIONS, CHANGE_ACTIONS], each of
477
+ * which is a function. The function should accept the old + new arrays and
478
+ * return an action object.
479
+ * @return {Array} The generated array of actions
480
+ */
481
+ function createBuildArrayActions(key, config) {
482
+ return function buildArrayActions(diff, oldObj, newObj) {
483
+ var addActions = [];
484
+ var removeActions = [];
485
+ var changeActions = [];
486
+ if (diff[key]) {
487
+ var arrayDelta = diff[key];
488
+ Object.keys(arrayDelta).forEach(function (index) {
489
+ if (config[ADD_ACTIONS] && isCreateAction(arrayDelta, index)) {
490
+ var actionGenerator = config[ADD_ACTIONS];
491
+ // When adding a new element you don't need the oldObj
492
+ var action = actionGenerator(newObj[key][index], parseInt(index, 10));
493
+ if (action) addActions.push(action);
494
+ } else if (config[CHANGE_ACTIONS] && isChangeAction(arrayDelta, index)) {
495
+ var _actionGenerator = config[CHANGE_ACTIONS];
496
+ // When changing an existing element you need both old + new
497
+ var _action = _actionGenerator(oldObj[key][index], newObj[key][index], parseInt(index, 10));
498
+ if (_action) changeActions.push(_action);
499
+ } else if (config[REMOVE_ACTIONS] && isRemoveAction$1(arrayDelta, index)) {
500
+ var realIndex = index.replace('_', '');
501
+ var _actionGenerator2 = config[REMOVE_ACTIONS];
502
+ // When removing an existing element you don't need the newObj
503
+ var _action2 = _actionGenerator2(oldObj[key][realIndex], parseInt(realIndex, 10));
504
+ if (_action2) removeActions.push(_action2);
505
+ }
506
+ });
507
+ }
508
+ return changeActions.concat(removeActions, addActions);
509
+ };
510
+ }
511
+
512
+ function toAssetIdentifier$1(asset) {
513
+ var assetIdentifier = asset.id ? {
514
+ assetId: asset.id
515
+ } : {
516
+ assetKey: asset.key
517
+ };
518
+ return assetIdentifier;
519
+ }
520
+ function actionsMapAssets$1(diff, oldObj, newObj) {
521
+ var handler = createBuildArrayActions('assets', _defineProperty(_defineProperty(_defineProperty({}, ADD_ACTIONS, function (newAsset) {
522
+ return {
523
+ action: 'addAsset',
524
+ asset: newAsset
525
+ };
526
+ }), REMOVE_ACTIONS, function (oldAsset) {
527
+ return _objectSpread2({
528
+ action: 'removeAsset'
529
+ }, toAssetIdentifier$1(oldAsset));
530
+ }), CHANGE_ACTIONS, function (oldAsset, newAsset) {
531
+ return (
532
+ // here we could use more atomic update actions (e.g. changeAssetName)
533
+ // but for now we use the simpler approach to first remove and then
534
+ // re-add the asset - which reduces the code complexity
535
+ [_objectSpread2({
536
+ action: 'removeAsset'
537
+ }, toAssetIdentifier$1(oldAsset)), {
538
+ action: 'addAsset',
539
+ asset: newAsset
540
+ }]
541
+ );
542
+ }));
543
+ return handler(diff, oldObj, newObj);
544
+ }
545
+
546
+ function clone(obj) {
547
+ return JSON.parse(JSON.stringify(obj));
548
+ }
549
+
550
+ var normalizeValue = function normalizeValue(value) {
551
+ return typeof value === 'string' ? value.trim() : value;
552
+ };
553
+ var createIsEmptyValue = function createIsEmptyValue(emptyValues) {
554
+ return function (value) {
555
+ return emptyValues.some(function (emptyValue) {
556
+ return emptyValue === normalizeValue(value);
557
+ });
558
+ };
559
+ };
560
+
561
+ /* actions that start with 'set' can generate undefined valued */
562
+ var isOptionalField = function isOptionalField(action) {
563
+ return action.startsWith('set');
564
+ };
565
+
566
+ /**
567
+ * Builds actions for simple object properties, given a list of actions
568
+ * E.g. [{ action: `changeName`, key: 'name' }]
569
+ *
570
+ * @param {Array} options.actions - a list of actions to be built
571
+ * based on the given property
572
+ * @param {Object} options.diff - the diff object
573
+ * @param {Object} options.oldObj - the object that needs to be updated
574
+ * @param {Object} options.newObj - the new representation of the object
575
+ * @param {Boolean} options.shouldOmitEmptyString - a flag to determine if we should treat an empty string a NON-value
576
+ * @param {Boolean} options.shouldUnsetOmittedProperties - a flag to determine if we should unset fields which are omitted in the newObj
577
+ * @param {Boolean} options.shouldPreventUnsettingRequiredFields - a flag to determine if required fields should be unset
578
+ */
579
+ function buildBaseAttributesActions(_ref) {
580
+ var actions = _ref.actions,
581
+ diff = _ref.diff,
582
+ oldObj = _ref.oldObj,
583
+ newObj = _ref.newObj,
584
+ shouldOmitEmptyString = _ref.shouldOmitEmptyString,
585
+ shouldUnsetOmittedProperties = _ref.shouldUnsetOmittedProperties,
586
+ shouldPreventUnsettingRequiredFields = _ref.shouldPreventUnsettingRequiredFields;
587
+ var isEmptyValue = createIsEmptyValue(shouldOmitEmptyString ? [undefined, null, ''] : [undefined, null]);
588
+ return actions.map(function (item) {
589
+ var key = item.key; // e.g.: name, description, ...
590
+ var actionKey = item.actionKey || item.key;
591
+ var delta = diff[key];
592
+ var before = oldObj[key];
593
+ var now = newObj[key];
594
+ var isNotDefinedBefore = isEmptyValue(oldObj[key]);
595
+ var isNotDefinedNow = isEmptyValue(newObj[key]);
596
+ var isOmitted = !Object.keys(newObj).includes(key);
597
+ if (!delta) return undefined;
598
+ if (isNotDefinedNow && !isOptionalField(item.action) && shouldPreventUnsettingRequiredFields) return undefined;
599
+ if (isNotDefinedNow && isNotDefinedBefore) return undefined;
600
+ if (!isNotDefinedNow && isNotDefinedBefore)
601
+ // no value previously set
602
+ return _defineProperty({
603
+ action: item.action
604
+ }, actionKey, now);
605
+
606
+ /* no new value */
607
+ if (isNotDefinedNow && isOmitted && !shouldUnsetOmittedProperties) return undefined;
608
+ if (isNotDefinedNow)
609
+ // value unset
610
+ return {
611
+ action: item.action
612
+ };
613
+
614
+ // We need to clone `before` as `patch` will mutate it
615
+ var patched = patch(clone(before), delta);
616
+ return _defineProperty({
617
+ action: item.action
618
+ }, actionKey, patched);
619
+ }).filter(function (action) {
620
+ return !isNil__default["default"](action);
621
+ });
622
+ }
623
+
624
+ /**
625
+ * Builds actions for simple reference objects, given a list of actions
626
+ * E.g. [{ action: `setTaxCategory`, key: 'taxCategory' }]
627
+ *
628
+ * @param {Array} options.actions - a list of actions to be built
629
+ * based on the given property
630
+ * @param {Object} options.diff - the diff object
631
+ * @param {Object} options.oldObj - the object that needs to be updated
632
+ * @param {Object} options.newObj - the new representation of the object
633
+ */
634
+ function buildReferenceActions(_ref4) {
635
+ var actions = _ref4.actions,
636
+ diff = _ref4.diff,
637
+ newObj = _ref4.newObj;
638
+ return actions.map(function (item) {
639
+ var action = item.action;
640
+ var key = item.key;
641
+ if (diff[key] && (
642
+ // The `key` value was added or removed
643
+ Array.isArray(diff[key]) ||
644
+ // The `key` value id changed
645
+ diff[key].id)) {
646
+ var newValue = Array.isArray(diff[key]) ? getDeltaValue(diff[key]) : newObj[key];
647
+ if (!newValue) return {
648
+ action: action
649
+ };
650
+
651
+ // When the `id` of the object is undefined
652
+ if (!newValue.id) {
653
+ return _defineProperty({
654
+ action: action
655
+ }, key, {
656
+ typeId: newValue.typeId,
657
+ key: newValue.key
658
+ });
659
+ }
660
+ return _defineProperty({
661
+ action: action
662
+ }, key, {
663
+ typeId: newValue.typeId,
664
+ id: newValue.id
665
+ });
666
+ }
667
+ return undefined;
668
+ }).filter(function (action) {
669
+ return action;
670
+ });
671
+ }
672
+
673
+ var baseActionsList$l = [{
674
+ action: 'changeName',
675
+ key: 'name'
676
+ }, {
677
+ action: 'changeSlug',
678
+ key: 'slug'
679
+ }, {
680
+ action: 'setDescription',
681
+ key: 'description'
682
+ }, {
683
+ action: 'changeOrderHint',
684
+ key: 'orderHint'
685
+ }, {
686
+ action: 'setExternalId',
687
+ key: 'externalId'
688
+ }, {
689
+ action: 'setKey',
690
+ key: 'key'
691
+ }];
692
+ var metaActionsList$1 = [{
693
+ action: 'setMetaTitle',
694
+ key: 'metaTitle'
695
+ }, {
696
+ action: 'setMetaKeywords',
697
+ key: 'metaKeywords'
698
+ }, {
699
+ action: 'setMetaDescription',
700
+ key: 'metaDescription'
701
+ }];
702
+ var referenceActionsList$3 = [{
703
+ action: 'changeParent',
704
+ key: 'parent'
705
+ }];
706
+
707
+ /**
708
+ * SYNC FUNCTIONS
709
+ */
710
+
711
+ function actionsMapBase$l(diff, oldObj, newObj) {
712
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
713
+ return buildBaseAttributesActions({
714
+ actions: baseActionsList$l,
715
+ diff: diff,
716
+ oldObj: oldObj,
717
+ newObj: newObj,
718
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
719
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties,
720
+ shouldPreventUnsettingRequiredFields: config.shouldPreventUnsettingRequiredFields
721
+ });
722
+ }
723
+ function actionsMapReferences$3(diff, oldObj, newObj) {
724
+ return buildReferenceActions({
725
+ actions: referenceActionsList$3,
726
+ diff: diff,
727
+ oldObj: oldObj,
728
+ newObj: newObj
729
+ });
730
+ }
731
+ function actionsMapMeta$1(diff, oldObj, newObj) {
732
+ return buildBaseAttributesActions({
733
+ actions: metaActionsList$1,
734
+ diff: diff,
735
+ oldObj: oldObj,
736
+ newObj: newObj
737
+ });
738
+ }
739
+
740
+ var CUSTOM = 'custom';
741
+
742
+ /**
743
+ * @function copyEmptyArrayProps
744
+ * @description Create new key with empty array value on `newobj` for the arrays exist on `oldObj` and doesnt exist on `newobj`
745
+ * One use case is to easily compare two object without generating this error `Cannot read property '0' of undefined`
746
+ * @param {Object} oldObj
747
+ * @param {Object} newObj
748
+ * @returns {Array} Ordered Array [oldObj, newObj]
749
+ */
750
+ function copyEmptyArrayProps() {
751
+ var oldObj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
752
+ var newObj = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
753
+ if (!isNil__default["default"](oldObj) && !isNil__default["default"](newObj)) {
754
+ var nextObjectWithEmptyArray = Object.entries(oldObj).reduce(function (merged, _ref) {
755
+ var _ref2 = _slicedToArray(_ref, 2),
756
+ key = _ref2[0],
757
+ value = _ref2[1];
758
+ // Ignore CUSTOM key as this object is dynamic and its up to the user to dynamically change it
759
+ // todo, it would be better if we pass it as ignored keys param
760
+ if (key === CUSTOM) return merged;
761
+ if (Array.isArray(value) && newObj[key] && newObj[key].length >= 1) {
762
+ /* eslint-disable no-plusplus */
763
+ var hashMapValue = value.reduce(function (acc, val) {
764
+ acc[val.id] = val;
765
+ return acc;
766
+ }, {});
767
+ for (var i = 0; i < newObj[key].length; i++) {
768
+ if (!isNil__default["default"](newObj[key][i]) && _typeof(newObj[key][i]) === 'object' && !isNil__default["default"](newObj[key][i].id)) {
769
+ // Since its unordered array elements then check if the element on `oldObj` exists by id
770
+ var foundObject = hashMapValue[newObj[key][i].id];
771
+ if (!isNil__default["default"](foundObject)) {
772
+ var _copyEmptyArrayProps = copyEmptyArrayProps(foundObject, newObj[key][i]),
773
+ _copyEmptyArrayProps2 = _slicedToArray(_copyEmptyArrayProps, 2),
774
+ nestedObject = _copyEmptyArrayProps2[1];
775
+ if (Object.isFrozen(merged[key])) {
776
+ /* eslint-disable no-param-reassign */
777
+ merged[key] = merged[key].slice();
778
+ }
779
+ /* eslint-disable no-param-reassign */
780
+ merged[key][i] = nestedObject;
781
+ }
782
+ }
783
+ }
784
+ return merged;
785
+ }
786
+ if (Array.isArray(value)) {
787
+ merged[key] = isNil__default["default"](newObj[key]) ? [] : newObj[key];
788
+ return merged;
789
+ }
790
+ if (!isNil__default["default"](newObj[key]) && _typeof(value) === 'object' &&
791
+ // Ignore Date as this will create invalid object since typeof date === 'object' return true
792
+ // ex: {date: new Date()} will result {date: {}}
793
+ !(value instanceof Date)) {
794
+ var _copyEmptyArrayProps3 = copyEmptyArrayProps(value, newObj[key]),
795
+ _copyEmptyArrayProps4 = _slicedToArray(_copyEmptyArrayProps3, 2),
796
+ _nestedObject = _copyEmptyArrayProps4[1];
797
+ merged[key] = _nestedObject;
798
+ return merged;
799
+ }
800
+ return merged;
801
+ }, _objectSpread2({}, newObj));
802
+ return [oldObj, nextObjectWithEmptyArray];
803
+ }
804
+ return [oldObj, newObj];
805
+ }
806
+
807
+ function createCategoryMapActions(mapActionGroup, syncActionConfig) {
808
+ return function doMapActions(diff, newObj, oldObj) {
809
+ var allActions = [];
810
+ allActions.push(mapActionGroup('base', function () {
811
+ return actionsMapBase$l(diff, oldObj, newObj, syncActionConfig);
812
+ }));
813
+ allActions.push(mapActionGroup('references', function () {
814
+ return actionsMapReferences$3(diff, oldObj, newObj);
815
+ }));
816
+ allActions.push(mapActionGroup('meta', function () {
817
+ return actionsMapMeta$1(diff, oldObj, newObj);
818
+ }));
819
+ allActions.push(mapActionGroup('custom', function () {
820
+ return actionsMapCustom(diff, newObj, oldObj);
821
+ }));
822
+ allActions.push(mapActionGroup('assets', function () {
823
+ return actionsMapAssets$1(diff, oldObj, newObj);
824
+ }));
825
+ return flatten__default["default"](allActions);
826
+ };
827
+ }
828
+ var categories = (function (actionGroupList, syncActionConfig) {
829
+ // actionGroupList contains information about which action groups
830
+ // are allowed or ignored
831
+
832
+ // createMapActionGroup returns function 'mapActionGroup' that takes params:
833
+ // - action group name
834
+ // - callback function that should return a list of actions that correspond
835
+ // to the for the action group
836
+
837
+ // this resulting function mapActionGroup will call the callback function
838
+ // for allowed action groups and return the return value of the callback
839
+ // It will return an empty array for ignored action groups
840
+ var mapActionGroup = createMapActionGroup(actionGroupList);
841
+ var doMapActions = createCategoryMapActions(mapActionGroup, syncActionConfig);
842
+ var buildActions = createBuildActions(diff, doMapActions, copyEmptyArrayProps);
843
+ return {
844
+ buildActions: buildActions
845
+ };
846
+ });
847
+
848
+ var isEmptyValue = createIsEmptyValue([undefined, null, '']);
849
+ var baseActionsList$k = [{
850
+ action: 'setSalutation',
851
+ key: 'salutation'
852
+ }, {
853
+ action: 'changeEmail',
854
+ key: 'email'
855
+ }, {
856
+ action: 'setFirstName',
857
+ key: 'firstName'
858
+ }, {
859
+ action: 'setLastName',
860
+ key: 'lastName'
861
+ }, {
862
+ action: 'setMiddleName',
863
+ key: 'middleName'
864
+ }, {
865
+ action: 'setTitle',
866
+ key: 'title'
867
+ }, {
868
+ action: 'setCustomerNumber',
869
+ key: 'customerNumber'
870
+ }, {
871
+ action: 'setExternalId',
872
+ key: 'externalId'
873
+ }, {
874
+ action: 'setCompanyName',
875
+ key: 'companyName'
876
+ }, {
877
+ action: 'setDateOfBirth',
878
+ key: 'dateOfBirth'
879
+ }, {
880
+ action: 'setLocale',
881
+ key: 'locale'
882
+ }, {
883
+ action: 'setVatId',
884
+ key: 'vatId'
885
+ }, {
886
+ action: 'setStores',
887
+ key: 'stores'
888
+ }, {
889
+ action: 'setKey',
890
+ key: 'key'
891
+ }];
892
+ var setDefaultBaseActionsList = [{
893
+ action: 'setDefaultBillingAddress',
894
+ key: 'defaultBillingAddressId',
895
+ actionKey: 'addressId'
896
+ }, {
897
+ action: 'setDefaultShippingAddress',
898
+ key: 'defaultShippingAddressId',
899
+ actionKey: 'addressId'
900
+ }];
901
+ var referenceActionsList$2 = [{
902
+ action: 'setCustomerGroup',
903
+ key: 'customerGroup'
904
+ }];
905
+ var authenticationModeActionsList = [{
906
+ action: 'setAuthenticationMode',
907
+ key: 'authenticationMode',
908
+ value: 'password'
909
+ }];
910
+
911
+ /**
912
+ * SYNC FUNCTIONS
913
+ */
914
+
915
+ function actionsMapBase$k(diff, oldObj, newObj) {
916
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
917
+ return buildBaseAttributesActions({
918
+ actions: baseActionsList$k,
919
+ diff: diff,
920
+ oldObj: oldObj,
921
+ newObj: newObj,
922
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
923
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties,
924
+ shouldPreventUnsettingRequiredFields: config.shouldPreventUnsettingRequiredFields
925
+ });
926
+ }
927
+ function actionsMapSetDefaultBase(diff, oldObj, newObj) {
928
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
929
+ return buildBaseAttributesActions({
930
+ actions: setDefaultBaseActionsList,
931
+ diff: diff,
932
+ oldObj: oldObj,
933
+ newObj: newObj,
934
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
935
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties,
936
+ shouldPreventUnsettingRequiredFields: config.shouldPreventUnsettingRequiredFields
937
+ });
938
+ }
939
+ function actionsMapReferences$2(diff, oldObj, newObj) {
940
+ return buildReferenceActions({
941
+ actions: referenceActionsList$2,
942
+ diff: diff,
943
+ oldObj: oldObj,
944
+ newObj: newObj
945
+ });
946
+ }
947
+ function actionsMapAddresses(diff, oldObj, newObj) {
948
+ var handler = createBuildArrayActions('addresses', _defineProperty(_defineProperty(_defineProperty({}, ADD_ACTIONS, function (newObject) {
949
+ return {
950
+ action: 'addAddress',
951
+ address: newObject
952
+ };
953
+ }), REMOVE_ACTIONS, function (objectToRemove) {
954
+ return {
955
+ action: 'removeAddress',
956
+ addressId: objectToRemove.id
957
+ };
958
+ }), CHANGE_ACTIONS, function (oldObject, updatedObject) {
959
+ return {
960
+ action: 'changeAddress',
961
+ addressId: oldObject.id,
962
+ address: updatedObject
963
+ };
964
+ }));
965
+ return handler(diff, oldObj, newObj);
966
+ }
967
+ function actionsMapBillingAddresses(diff, oldObj, newObj) {
968
+ var handler = createBuildArrayActions('billingAddressIds', _defineProperty(_defineProperty({}, ADD_ACTIONS, function (addressId) {
969
+ return {
970
+ action: 'addBillingAddressId',
971
+ addressId: addressId
972
+ };
973
+ }), REMOVE_ACTIONS, function (addressId) {
974
+ return {
975
+ action: 'removeBillingAddressId',
976
+ addressId: addressId
977
+ };
978
+ }));
979
+ return handler(diff, oldObj, newObj);
980
+ }
981
+ function actionsMapShippingAddresses(diff, oldObj, newObj) {
982
+ var handler = createBuildArrayActions('shippingAddressIds', _defineProperty(_defineProperty({}, ADD_ACTIONS, function (addressId) {
983
+ return {
984
+ action: 'addShippingAddressId',
985
+ addressId: addressId
986
+ };
987
+ }), REMOVE_ACTIONS, function (addressId) {
988
+ return {
989
+ action: 'removeShippingAddressId',
990
+ addressId: addressId
991
+ };
992
+ }));
993
+ return handler(diff, oldObj, newObj);
994
+ }
995
+ function actionsMapAuthenticationModes(diff, oldObj, newObj) {
996
+ // eslint-disable-next-line no-use-before-define
997
+ return buildAuthenticationModeActions({
998
+ actions: authenticationModeActionsList,
999
+ diff: diff,
1000
+ oldObj: oldObj,
1001
+ newObj: newObj
1002
+ });
1003
+ }
1004
+ function buildAuthenticationModeActions(_ref) {
1005
+ var actions = _ref.actions,
1006
+ diff = _ref.diff,
1007
+ oldObj = _ref.oldObj,
1008
+ newObj = _ref.newObj;
1009
+ return actions.map(function (item) {
1010
+ var key = item.key;
1011
+ var value = item.value || item.key;
1012
+ var delta = diff[key];
1013
+ var before = oldObj[key];
1014
+ var now = newObj[key];
1015
+ var isNotDefinedBefore = isEmptyValue(oldObj[key]);
1016
+ var isNotDefinedNow = isEmptyValue(newObj[key]);
1017
+ var authenticationModes = ['Password', 'ExternalAuth'];
1018
+ if (!delta) return undefined;
1019
+ if (isNotDefinedNow && isNotDefinedBefore) return undefined;
1020
+ if (newObj.authenticationMode === 'Password' && !newObj.password) throw new Error('Cannot set to Password authentication mode without password');
1021
+ if ('authenticationMode' in newObj && !authenticationModes.includes(newObj.authenticationMode)) throw new Error('Invalid Authentication Mode');
1022
+ if (!isNotDefinedNow && isNotDefinedBefore) {
1023
+ // no value previously set
1024
+ if (newObj.authenticationMode === 'ExternalAuth') return {
1025
+ action: item.action,
1026
+ authMode: now
1027
+ };
1028
+ return _defineProperty({
1029
+ action: item.action,
1030
+ authMode: now
1031
+ }, value, newObj.password);
1032
+ }
1033
+
1034
+ /* no new value */
1035
+ if (isNotDefinedNow && !{}.hasOwnProperty.call(newObj, key)) return undefined;
1036
+ if (isNotDefinedNow && {}.hasOwnProperty.call(newObj, key))
1037
+ // value unset
1038
+ return undefined;
1039
+
1040
+ // We need to clone `before` as `patch` will mutate it
1041
+ var patched = patch(clone(before), delta);
1042
+ if (newObj.authenticationMode === 'ExternalAuth') return {
1043
+ action: item.action,
1044
+ authMode: patched
1045
+ };
1046
+ return _defineProperty({
1047
+ action: item.action,
1048
+ authMode: patched
1049
+ }, value, newObj.password);
1050
+ }).filter(function (action) {
1051
+ return !isNil__default["default"](action);
1052
+ });
1053
+ }
1054
+
1055
+ function createCustomerMapActions(mapActionGroup, syncActionConfig) {
1056
+ return function doMapActions(diff, newObj, oldObj) {
1057
+ var allActions = [];
1058
+ allActions.push(mapActionGroup('base', function () {
1059
+ return actionsMapBase$k(diff, oldObj, newObj, syncActionConfig);
1060
+ }));
1061
+ allActions.push(mapActionGroup('references', function () {
1062
+ return actionsMapReferences$2(diff, oldObj, newObj);
1063
+ }));
1064
+ allActions.push(mapActionGroup('addresses', function () {
1065
+ return actionsMapAddresses(diff, oldObj, newObj);
1066
+ }));
1067
+ allActions.push(mapActionGroup('base', function () {
1068
+ return actionsMapSetDefaultBase(diff, oldObj, newObj, syncActionConfig);
1069
+ }));
1070
+ allActions.push(mapActionGroup('billingAddressIds', function () {
1071
+ return actionsMapBillingAddresses(diff, oldObj, newObj);
1072
+ }));
1073
+ allActions.push(mapActionGroup('shippingAddressIds', function () {
1074
+ return actionsMapShippingAddresses(diff, oldObj, newObj);
1075
+ }));
1076
+ allActions.push(mapActionGroup('custom', function () {
1077
+ return actionsMapCustom(diff, newObj, oldObj);
1078
+ }));
1079
+ allActions.push(mapActionGroup('authenticationModes', function () {
1080
+ return actionsMapAuthenticationModes(diff, oldObj, newObj);
1081
+ }));
1082
+ return flatten__default["default"](allActions);
1083
+ };
1084
+ }
1085
+ var customers = (function (actionGroupList, syncActionConfig) {
1086
+ // actionGroupList contains information about which action groups
1087
+ // are allowed or ignored
1088
+
1089
+ // createMapActionGroup returns function 'mapActionGroup' that takes params:
1090
+ // - action group name
1091
+ // - callback function that should return a list of actions that correspond
1092
+ // to the for the action group
1093
+
1094
+ // this resulting function mapActionGroup will call the callback function
1095
+ // for allowed action groups and return the return value of the callback
1096
+ // It will return an empty array for ignored action groups
1097
+ var mapActionGroup = createMapActionGroup(actionGroupList);
1098
+ var doMapActions = createCustomerMapActions(mapActionGroup, syncActionConfig);
1099
+ var buildActions = createBuildActions(diff, doMapActions, copyEmptyArrayProps);
1100
+ return {
1101
+ buildActions: buildActions
1102
+ };
1103
+ });
1104
+
1105
+ var baseActionsList$j = [{
1106
+ action: 'changeQuantity',
1107
+ key: 'quantityOnStock',
1108
+ actionKey: 'quantity'
1109
+ }, {
1110
+ action: 'setRestockableInDays',
1111
+ key: 'restockableInDays'
1112
+ }, {
1113
+ action: 'setExpectedDelivery',
1114
+ key: 'expectedDelivery'
1115
+ }];
1116
+ var referenceActionsList$1 = [{
1117
+ action: 'setSupplyChannel',
1118
+ key: 'supplyChannel'
1119
+ }];
1120
+
1121
+ /**
1122
+ * SYNC FUNCTIONS
1123
+ */
1124
+
1125
+ function actionsMapBase$j(diff, oldObj, newObj) {
1126
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
1127
+ return buildBaseAttributesActions({
1128
+ actions: baseActionsList$j,
1129
+ diff: diff,
1130
+ oldObj: oldObj,
1131
+ newObj: newObj,
1132
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
1133
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties,
1134
+ shouldPreventUnsettingRequiredFields: config.shouldPreventUnsettingRequiredFields
1135
+ });
1136
+ }
1137
+ function actionsMapReferences$1(diff, oldObj, newObj) {
1138
+ return buildReferenceActions({
1139
+ actions: referenceActionsList$1,
1140
+ diff: diff,
1141
+ oldObj: oldObj,
1142
+ newObj: newObj
1143
+ });
1144
+ }
1145
+
1146
+ function createInventoryMapActions(mapActionGroup, syncActionConfig) {
1147
+ return function doMapActions(diff, newObj, oldObj) {
1148
+ var allActions = [];
1149
+ allActions.push(mapActionGroup('base', function () {
1150
+ return actionsMapBase$j(diff, oldObj, newObj, syncActionConfig);
1151
+ }));
1152
+ allActions.push(mapActionGroup('references', function () {
1153
+ return actionsMapReferences$1(diff, oldObj, newObj);
1154
+ }));
1155
+ allActions.push(mapActionGroup('custom', function () {
1156
+ return actionsMapCustom(diff, newObj, oldObj);
1157
+ }));
1158
+ return flatten__default["default"](allActions);
1159
+ };
1160
+ }
1161
+ var inventories = (function (actionGroupList, syncActionConfig) {
1162
+ // actionGroupList contains information about which action groups
1163
+ // are allowed or ignored
1164
+
1165
+ // createMapActionGroup returns function 'mapActionGroup' that takes params:
1166
+ // - action group name
1167
+ // - callback function that should return a list of actions that correspond
1168
+ // to the for the action group
1169
+
1170
+ // this resulting function mapActionGroup will call the callback function
1171
+ // for allowed action groups and return the return value of the callback
1172
+ // It will return an empty array for ignored action groups
1173
+ var mapActionGroup = createMapActionGroup(actionGroupList);
1174
+ var doMapActions = createInventoryMapActions(mapActionGroup, syncActionConfig);
1175
+ var buildActions = createBuildActions(diff, doMapActions);
1176
+ return {
1177
+ buildActions: buildActions
1178
+ };
1179
+ });
1180
+
1181
+ function extractMatchingPairs(hashMap, key, before, now) {
1182
+ var oldObjPos;
1183
+ var newObjPos;
1184
+ var oldObj;
1185
+ var newObj;
1186
+ if (hashMap[key]) {
1187
+ oldObjPos = hashMap[key][0];
1188
+ newObjPos = hashMap[key][1];
1189
+ if (before && before[oldObjPos]) oldObj = before[oldObjPos];
1190
+ if (now && now[newObjPos]) newObj = now[newObjPos];
1191
+ }
1192
+ return {
1193
+ oldObj: oldObj,
1194
+ newObj: newObj
1195
+ };
1196
+ }
1197
+
1198
+ var REGEX_NUMBER$3 = new RegExp(/^\d+$/);
1199
+ var REGEX_UNDERSCORE_NUMBER$3 = new RegExp(/^_\d+$/);
1200
+ function preProcessCollection() {
1201
+ var collection = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
1202
+ var identifier = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'id';
1203
+ return collection.reduce(function (acc, currentValue, currentIndex) {
1204
+ acc.refByIndex[String(currentIndex)] = currentValue[identifier];
1205
+ acc.refByIdentifier[currentValue[identifier]] = String(currentIndex);
1206
+ return acc;
1207
+ }, {
1208
+ refByIndex: {},
1209
+ refByIdentifier: {}
1210
+ });
1211
+ }
1212
+
1213
+ // creates a hash of a location of an item in collection1 and collection2
1214
+ function findMatchingPairs(diff) {
1215
+ var before = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
1216
+ var now = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
1217
+ var identifier = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'id';
1218
+ var result = {};
1219
+ var _preProcessCollection = preProcessCollection(before, identifier),
1220
+ beforeObjRefByIdentifier = _preProcessCollection.refByIdentifier,
1221
+ beforeObjRefByIndex = _preProcessCollection.refByIndex;
1222
+ var _preProcessCollection2 = preProcessCollection(now, identifier),
1223
+ nowObjRefByIdentifier = _preProcessCollection2.refByIdentifier,
1224
+ nowObjRefByIndex = _preProcessCollection2.refByIndex;
1225
+ forEach__default["default"](diff, function (item, key) {
1226
+ if (REGEX_NUMBER$3.test(key)) {
1227
+ var matchingIdentifier = nowObjRefByIndex[key];
1228
+ result[key] = [beforeObjRefByIdentifier[matchingIdentifier], key];
1229
+ } else if (REGEX_UNDERSCORE_NUMBER$3.test(key)) {
1230
+ var index = key.substring(1);
1231
+ var _matchingIdentifier = beforeObjRefByIndex[index];
1232
+ result[key] = [index, nowObjRefByIdentifier[_matchingIdentifier]];
1233
+ }
1234
+ });
1235
+ return result;
1236
+ }
1237
+
1238
+ var REGEX_NUMBER$2 = new RegExp(/^\d+$/);
1239
+ var REGEX_UNDERSCORE_NUMBER$2 = new RegExp(/^_\d+$/);
1240
+ var baseActionsList$i = [{
1241
+ action: 'changeName',
1242
+ key: 'name'
1243
+ }, {
1244
+ action: 'changeSlug',
1245
+ key: 'slug'
1246
+ }, {
1247
+ action: 'setDescription',
1248
+ key: 'description'
1249
+ }, {
1250
+ action: 'setSearchKeywords',
1251
+ key: 'searchKeywords'
1252
+ }, {
1253
+ action: 'setKey',
1254
+ key: 'key'
1255
+ }, {
1256
+ action: 'setPriceMode',
1257
+ key: 'priceMode'
1258
+ }];
1259
+ var baseAssetActionsList = [{
1260
+ action: 'setAssetKey',
1261
+ key: 'key',
1262
+ actionKey: 'assetKey'
1263
+ }, {
1264
+ action: 'changeAssetName',
1265
+ key: 'name'
1266
+ }, {
1267
+ action: 'setAssetDescription',
1268
+ key: 'description'
1269
+ }, {
1270
+ action: 'setAssetTags',
1271
+ key: 'tags'
1272
+ }, {
1273
+ action: 'setAssetSources',
1274
+ key: 'sources'
1275
+ }];
1276
+ var metaActionsList = [{
1277
+ action: 'setMetaTitle',
1278
+ key: 'metaTitle'
1279
+ }, {
1280
+ action: 'setMetaDescription',
1281
+ key: 'metaDescription'
1282
+ }, {
1283
+ action: 'setMetaKeywords',
1284
+ key: 'metaKeywords'
1285
+ }];
1286
+ var referenceActionsList = [{
1287
+ action: 'setTaxCategory',
1288
+ key: 'taxCategory'
1289
+ }, {
1290
+ action: 'transitionState',
1291
+ key: 'state'
1292
+ }];
1293
+
1294
+ /**
1295
+ * HELPER FUNCTIONS
1296
+ */
1297
+
1298
+ var getIsAddAction = function getIsAddAction(key, resource) {
1299
+ return REGEX_NUMBER$2.test(key) && Array.isArray(resource) && resource.length;
1300
+ };
1301
+ var getIsUpdateAction = function getIsUpdateAction(key, resource) {
1302
+ return REGEX_NUMBER$2.test(key) && Object.keys(resource).length;
1303
+ };
1304
+ var getIsRemoveAction = function getIsRemoveAction(key, resource) {
1305
+ return REGEX_UNDERSCORE_NUMBER$2.test(key) && Number(resource[2]) === 0;
1306
+ };
1307
+ var getIsItemMovedAction = function getIsItemMovedAction(key, resource) {
1308
+ return REGEX_UNDERSCORE_NUMBER$2.test(key) && Number(resource[2]) === 3;
1309
+ };
1310
+ function _buildSkuActions(variantDiff, oldVariant) {
1311
+ if ({}.hasOwnProperty.call(variantDiff, 'sku')) {
1312
+ var newValue = getDeltaValue(variantDiff.sku);
1313
+ if (!newValue && !oldVariant.sku) return null;
1314
+ return {
1315
+ action: 'setSku',
1316
+ variantId: oldVariant.id,
1317
+ sku: newValue || null
1318
+ };
1319
+ }
1320
+ return null;
1321
+ }
1322
+ function _buildKeyActions(variantDiff, oldVariant) {
1323
+ if ({}.hasOwnProperty.call(variantDiff, 'key')) {
1324
+ var newValue = getDeltaValue(variantDiff.key);
1325
+ if (!newValue && !oldVariant.key) return null;
1326
+ return {
1327
+ action: 'setProductVariantKey',
1328
+ variantId: oldVariant.id,
1329
+ key: newValue || null
1330
+ };
1331
+ }
1332
+ return null;
1333
+ }
1334
+ function _buildNewSetAttributeAction(id, el, sameForAllAttributeNames) {
1335
+ var attributeName = el && el.name;
1336
+ if (!attributeName) return undefined;
1337
+ var action = {
1338
+ action: 'setAttribute',
1339
+ variantId: id,
1340
+ name: attributeName,
1341
+ value: el.value
1342
+ };
1343
+ if (sameForAllAttributeNames.indexOf(attributeName) !== -1) {
1344
+ action = _objectSpread2(_objectSpread2({}, action), {}, {
1345
+ action: 'setAttributeInAllVariants'
1346
+ });
1347
+ delete action.variantId;
1348
+ }
1349
+ return action;
1350
+ }
1351
+ function _buildSetAttributeAction(diffedValue, oldVariant, attribute, sameForAllAttributeNames) {
1352
+ if (!attribute) return undefined;
1353
+ var action = {
1354
+ action: 'setAttribute',
1355
+ variantId: oldVariant.id,
1356
+ name: attribute.name
1357
+ };
1358
+
1359
+ // Used as original object for patching long diff text
1360
+ var oldAttribute = oldVariant.attributes.find(function (a) {
1361
+ return a.name === attribute.name;
1362
+ }) || {};
1363
+ if (sameForAllAttributeNames.indexOf(attribute.name) !== -1) {
1364
+ action = _objectSpread2(_objectSpread2({}, action), {}, {
1365
+ action: 'setAttributeInAllVariants'
1366
+ });
1367
+ delete action.variantId;
1368
+ }
1369
+ if (Array.isArray(diffedValue)) action.value = getDeltaValue(diffedValue, oldAttribute.value);else if (typeof diffedValue === 'string')
1370
+ // LText: value: {en: "", de: ""}
1371
+ // Enum: value: {key: "foo", label: "Foo"}
1372
+ // LEnum: value: {key: "foo", label: {en: "Foo", de: "Foo"}}
1373
+ // Money: value: {centAmount: 123, currencyCode: ""}
1374
+ // *: value: ""
1375
+
1376
+ // normal
1377
+ action.value = getDeltaValue(diffedValue, oldAttribute.value);else if (diffedValue.centAmount || diffedValue.currencyCode)
1378
+ // Money
1379
+ action.value = {
1380
+ centAmount: diffedValue.centAmount ? getDeltaValue(diffedValue.centAmount) : attribute.value.centAmount,
1381
+ currencyCode: diffedValue.currencyCode ? getDeltaValue(diffedValue.currencyCode) : attribute.value.currencyCode
1382
+ };else if (diffedValue.key)
1383
+ // Enum / LEnum (use only the key)
1384
+ action.value = getDeltaValue(diffedValue.key);else if (_typeof(diffedValue) === 'object') if ({}.hasOwnProperty.call(diffedValue, '_t') && diffedValue._t === 'a') {
1385
+ // set-typed attribute
1386
+ action = _objectSpread2(_objectSpread2({}, action), {}, {
1387
+ value: attribute.value
1388
+ });
1389
+ } else {
1390
+ // LText
1391
+
1392
+ var updatedValue = Object.keys(diffedValue).reduce(function (acc, lang) {
1393
+ var patchedValue = getDeltaValue(diffedValue[lang], acc[lang]);
1394
+ return Object.assign(acc, _defineProperty({}, lang, patchedValue));
1395
+ }, _objectSpread2({}, oldAttribute.value));
1396
+ action.value = updatedValue;
1397
+ }
1398
+ return action;
1399
+ }
1400
+ function _buildVariantImagesAction(diffedImages) {
1401
+ var oldVariant = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1402
+ var newVariant = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1403
+ var actions = [];
1404
+ // generate a hashMap to be able to reference the right image from both ends
1405
+ var matchingImagePairs = findMatchingPairs(diffedImages, oldVariant.images, newVariant.images, 'url');
1406
+ forEach__default["default"](diffedImages, function (image, key) {
1407
+ var _extractMatchingPairs = extractMatchingPairs(matchingImagePairs, key, oldVariant.images, newVariant.images),
1408
+ oldObj = _extractMatchingPairs.oldObj,
1409
+ newObj = _extractMatchingPairs.newObj;
1410
+ if (REGEX_NUMBER$2.test(key)) {
1411
+ // New image
1412
+ if (Array.isArray(image) && image.length) actions.push({
1413
+ action: 'addExternalImage',
1414
+ variantId: oldVariant.id,
1415
+ image: getDeltaValue(image)
1416
+ });else if (_typeof(image) === 'object') if ({}.hasOwnProperty.call(image, 'url') && image.url.length === 2) {
1417
+ // There is a new image, remove the old one first.
1418
+ actions.push({
1419
+ action: 'removeImage',
1420
+ variantId: oldVariant.id,
1421
+ imageUrl: oldObj.url
1422
+ });
1423
+ actions.push({
1424
+ action: 'addExternalImage',
1425
+ variantId: oldVariant.id,
1426
+ image: newObj
1427
+ });
1428
+ } else if ({}.hasOwnProperty.call(image, 'label') && (image.label.length === 1 || image.label.length === 2)) actions.push({
1429
+ action: 'setImageLabel',
1430
+ variantId: oldVariant.id,
1431
+ imageUrl: oldObj.url,
1432
+ label: getDeltaValue(image.label)
1433
+ });
1434
+ } else if (REGEX_UNDERSCORE_NUMBER$2.test(key)) if (Array.isArray(image) && image.length === 3) {
1435
+ if (Number(image[2]) === 3)
1436
+ // image position changed
1437
+ actions.push({
1438
+ action: 'moveImageToPosition',
1439
+ variantId: oldVariant.id,
1440
+ imageUrl: oldObj.url,
1441
+ position: Number(image[1])
1442
+ });else if (Number(image[2]) === 0)
1443
+ // image removed
1444
+ actions.push({
1445
+ action: 'removeImage',
1446
+ variantId: oldVariant.id,
1447
+ imageUrl: oldObj.url
1448
+ });
1449
+ }
1450
+ });
1451
+ return actions;
1452
+ }
1453
+ function _buildVariantPricesAction(diffedPrices) {
1454
+ var oldVariant = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1455
+ var newVariant = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1456
+ var enableDiscounted = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
1457
+ var addPriceActions = [];
1458
+ var changePriceActions = [];
1459
+ var removePriceActions = [];
1460
+
1461
+ // generate a hashMap to be able to reference the right image from both ends
1462
+ var matchingPricePairs = findMatchingPairs(diffedPrices, oldVariant.prices, newVariant.prices);
1463
+ forEach__default["default"](diffedPrices, function (price, key) {
1464
+ var _extractMatchingPairs2 = extractMatchingPairs(matchingPricePairs, key, oldVariant.prices, newVariant.prices),
1465
+ oldObj = _extractMatchingPairs2.oldObj,
1466
+ newObj = _extractMatchingPairs2.newObj;
1467
+ if (getIsAddAction(key, price)) {
1468
+ // Remove read-only fields
1469
+ var patchedPrice = price.map(function (p) {
1470
+ var shallowClone = _objectSpread2({}, p);
1471
+ if (enableDiscounted !== true) delete shallowClone.discounted;
1472
+ return shallowClone;
1473
+ });
1474
+ addPriceActions.push({
1475
+ action: 'addPrice',
1476
+ variantId: oldVariant.id,
1477
+ price: getDeltaValue(patchedPrice)
1478
+ });
1479
+ return;
1480
+ }
1481
+ if (getIsUpdateAction(key, price)) {
1482
+ // Remove the discounted field and make sure that the price
1483
+ // still has other values, otherwise simply return
1484
+ var filteredPrice = _objectSpread2({}, price);
1485
+ if (enableDiscounted !== true) delete filteredPrice.discounted;
1486
+ if (Object.keys(filteredPrice).length) {
1487
+ // At this point price should have changed, simply pick the new one
1488
+ var newPrice = _objectSpread2({}, newObj);
1489
+ if (enableDiscounted !== true) delete newPrice.discounted;
1490
+ changePriceActions.push({
1491
+ action: 'changePrice',
1492
+ priceId: oldObj.id,
1493
+ price: newPrice
1494
+ });
1495
+ }
1496
+ return;
1497
+ }
1498
+ if (getIsRemoveAction(key, price)) {
1499
+ // price removed
1500
+ removePriceActions.push({
1501
+ action: 'removePrice',
1502
+ priceId: oldObj.id
1503
+ });
1504
+ }
1505
+ });
1506
+ return [addPriceActions, changePriceActions, removePriceActions];
1507
+ }
1508
+ function _buildVariantAttributesActions(attributes, oldVariant, newVariant, sameForAllAttributeNames) {
1509
+ var actions = [];
1510
+ if (!attributes) return actions;
1511
+ forEach__default["default"](attributes, function (value, key) {
1512
+ if (REGEX_NUMBER$2.test(key)) {
1513
+ if (Array.isArray(value)) {
1514
+ var id = oldVariant.id;
1515
+ var deltaValue = getDeltaValue(value);
1516
+ var setAction = _buildNewSetAttributeAction(id, deltaValue, sameForAllAttributeNames);
1517
+ if (setAction) actions.push(setAction);
1518
+ } else if (newVariant.attributes) {
1519
+ var _setAction = _buildSetAttributeAction(value.value, oldVariant, newVariant.attributes[key], sameForAllAttributeNames);
1520
+ if (_setAction) actions.push(_setAction);
1521
+ }
1522
+ } else if (REGEX_UNDERSCORE_NUMBER$2.test(key)) if (Array.isArray(value)) {
1523
+ // Ignore pure array moves!
1524
+ if (value.length === 3 && value[2] === 3) return;
1525
+ var _id = oldVariant.id;
1526
+ var _deltaValue = getDeltaValue(value);
1527
+ if (!_deltaValue) if (value[0] && value[0].name)
1528
+ // unset attribute if
1529
+ _deltaValue = {
1530
+ name: value[0].name
1531
+ };else _deltaValue = undefined;
1532
+ var _setAction2 = _buildNewSetAttributeAction(_id, _deltaValue, sameForAllAttributeNames);
1533
+ if (_setAction2) actions.push(_setAction2);
1534
+ } else {
1535
+ var index = key.substring(1);
1536
+ if (newVariant.attributes) {
1537
+ var _setAction3 = _buildSetAttributeAction(value.value, oldVariant, newVariant.attributes[index], sameForAllAttributeNames);
1538
+ if (_setAction3) actions.push(_setAction3);
1539
+ }
1540
+ }
1541
+ });
1542
+ return actions;
1543
+ }
1544
+ function toAssetIdentifier(asset) {
1545
+ var assetIdentifier = asset.id ? {
1546
+ assetId: asset.id
1547
+ } : {
1548
+ assetKey: asset.key
1549
+ };
1550
+ return assetIdentifier;
1551
+ }
1552
+ function toVariantIdentifier(variant) {
1553
+ var id = variant.id,
1554
+ sku = variant.sku;
1555
+ return id ? {
1556
+ variantId: id
1557
+ } : {
1558
+ sku: sku
1559
+ };
1560
+ }
1561
+ function _buildVariantChangeAssetOrderAction(diffAssets, oldVariant, newVariant) {
1562
+ var isAssetOrderChanged = Object.entries(diffAssets).find(function (entry) {
1563
+ return getIsItemMovedAction(entry[0], entry[1]);
1564
+ });
1565
+ if (!isAssetOrderChanged) {
1566
+ return [];
1567
+ }
1568
+ var assetIdsBefore = oldVariant.assets.map(function (_) {
1569
+ return _.id;
1570
+ });
1571
+ var assetIdsCurrent = newVariant.assets.map(function (_) {
1572
+ return _.id;
1573
+ }).filter(function (_) {
1574
+ return _ !== undefined;
1575
+ });
1576
+ var assetIdsToKeep = intersection__default["default"](assetIdsCurrent, assetIdsBefore);
1577
+ var assetIdsToRemove = without__default["default"].apply(void 0, [assetIdsBefore].concat(_toConsumableArray(assetIdsToKeep)));
1578
+ var changeAssetOrderAction = _objectSpread2({
1579
+ action: 'changeAssetOrder',
1580
+ assetOrder: assetIdsToKeep.concat(assetIdsToRemove)
1581
+ }, toVariantIdentifier(oldVariant));
1582
+ return [changeAssetOrderAction];
1583
+ }
1584
+ function _buildVariantAssetsActions(diffAssets, oldVariant, newVariant) {
1585
+ var assetActions = [];
1586
+
1587
+ // generate a hashMap to be able to reference the right asset from both ends
1588
+ var matchingAssetPairs = findMatchingPairs(diffAssets, oldVariant.assets, newVariant.assets);
1589
+ forEach__default["default"](diffAssets, function (asset, key) {
1590
+ var _extractMatchingPairs3 = extractMatchingPairs(matchingAssetPairs, key, oldVariant.assets, newVariant.assets),
1591
+ oldAsset = _extractMatchingPairs3.oldObj,
1592
+ newAsset = _extractMatchingPairs3.newObj;
1593
+ if (getIsAddAction(key, asset)) {
1594
+ assetActions.push(_objectSpread2(_objectSpread2({
1595
+ action: 'addAsset',
1596
+ asset: getDeltaValue(asset)
1597
+ }, toVariantIdentifier(newVariant)), {}, {
1598
+ position: Number(key)
1599
+ }));
1600
+ return;
1601
+ }
1602
+ if (getIsUpdateAction(key, asset)) {
1603
+ // todo add changeAssetOrder
1604
+ var basicActions = buildBaseAttributesActions({
1605
+ actions: baseAssetActionsList,
1606
+ diff: asset,
1607
+ oldObj: oldAsset,
1608
+ newObj: newAsset
1609
+ }).map(function (action) {
1610
+ // in case of 'setAssetKey' then the identifier will be only 'assetId'
1611
+ if (action.action === 'setAssetKey') {
1612
+ return _objectSpread2(_objectSpread2(_objectSpread2({}, action), toVariantIdentifier(oldVariant)), {}, {
1613
+ assetId: oldAsset.id
1614
+ });
1615
+ }
1616
+ return _objectSpread2(_objectSpread2(_objectSpread2({}, action), toVariantIdentifier(oldVariant)), toAssetIdentifier(oldAsset));
1617
+ });
1618
+ assetActions.push.apply(assetActions, _toConsumableArray(basicActions));
1619
+ if (asset.custom) {
1620
+ var customActions = actionsMapCustom(asset, newAsset, oldAsset, _objectSpread2(_objectSpread2({
1621
+ actions: {
1622
+ setCustomType: 'setAssetCustomType',
1623
+ setCustomField: 'setAssetCustomField'
1624
+ }
1625
+ }, toVariantIdentifier(oldVariant)), toAssetIdentifier(oldAsset)));
1626
+ assetActions.push.apply(assetActions, _toConsumableArray(customActions));
1627
+ }
1628
+ return;
1629
+ }
1630
+ if (getIsRemoveAction(key, asset)) {
1631
+ assetActions.push(_objectSpread2(_objectSpread2({
1632
+ action: 'removeAsset'
1633
+ }, toAssetIdentifier(oldAsset)), toVariantIdentifier(oldVariant)));
1634
+ }
1635
+ });
1636
+ var changedAssetOrderAction = _buildVariantChangeAssetOrderAction(diffAssets, oldVariant, newVariant);
1637
+ return [].concat(_toConsumableArray(changedAssetOrderAction), assetActions);
1638
+ }
1639
+
1640
+ /**
1641
+ * SYNC FUNCTIONS
1642
+ */
1643
+
1644
+ function actionsMapBase$i(diff, oldObj, newObj) {
1645
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
1646
+ return buildBaseAttributesActions({
1647
+ actions: baseActionsList$i,
1648
+ diff: diff,
1649
+ oldObj: oldObj,
1650
+ newObj: newObj,
1651
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
1652
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties
1653
+ });
1654
+ }
1655
+ function actionsMapMeta(diff, oldObj, newObj) {
1656
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
1657
+ return buildBaseAttributesActions({
1658
+ actions: metaActionsList,
1659
+ diff: diff,
1660
+ oldObj: oldObj,
1661
+ newObj: newObj,
1662
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
1663
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties
1664
+ });
1665
+ }
1666
+ function actionsMapAddVariants(diff, oldObj, newObj) {
1667
+ var handler = createBuildArrayActions('variants', _defineProperty({}, ADD_ACTIONS, function (newObject) {
1668
+ return _objectSpread2(_objectSpread2({}, newObject), {}, {
1669
+ action: 'addVariant'
1670
+ });
1671
+ }));
1672
+ return handler(diff, oldObj, newObj);
1673
+ }
1674
+ function actionsMapRemoveVariants(diff, oldObj, newObj) {
1675
+ var handler = createBuildArrayActions('variants', _defineProperty({}, REMOVE_ACTIONS, function (_ref) {
1676
+ var id = _ref.id;
1677
+ return {
1678
+ action: 'removeVariant',
1679
+ id: id
1680
+ };
1681
+ }));
1682
+ return handler(diff, oldObj, newObj);
1683
+ }
1684
+ function actionsMapReferences(diff, oldObj, newObj) {
1685
+ return buildReferenceActions({
1686
+ actions: referenceActionsList,
1687
+ diff: diff,
1688
+ oldObj: oldObj,
1689
+ newObj: newObj
1690
+ });
1691
+ }
1692
+ function actionsMapCategories(diff) {
1693
+ var actions = [];
1694
+ if (!diff.categories) return actions;
1695
+ var addToCategoryActions = [];
1696
+ var removeFromCategoryActions = [];
1697
+ forEach__default["default"](diff.categories, function (category) {
1698
+ if (Array.isArray(category)) {
1699
+ var action = {
1700
+ category: category[0]
1701
+ };
1702
+ if (category.length === 3) {
1703
+ // Ignore pure array moves!
1704
+ if (category[2] !== 3) {
1705
+ action.action = 'removeFromCategory';
1706
+ removeFromCategoryActions.push(action);
1707
+ }
1708
+ } else if (category.length === 1) {
1709
+ action.action = 'addToCategory';
1710
+ addToCategoryActions.push(action);
1711
+ }
1712
+ }
1713
+ });
1714
+
1715
+ // Make sure `removeFromCategory` actions come first
1716
+ return removeFromCategoryActions.concat(addToCategoryActions);
1717
+ }
1718
+ function actionsMapCategoryOrderHints(diff) {
1719
+ if (!diff.categoryOrderHints) return [];
1720
+ // Ignore this pattern as its means no changes happened [{},0,0]
1721
+ if (Array.isArray(diff.categoryOrderHints)) return [];
1722
+ return Object.keys(diff.categoryOrderHints).map(function (categoryId) {
1723
+ var hintChange = diff.categoryOrderHints[categoryId];
1724
+ var action = {
1725
+ action: 'setCategoryOrderHint',
1726
+ categoryId: categoryId
1727
+ };
1728
+ if (hintChange.length === 1)
1729
+ // item was added
1730
+ action.orderHint = hintChange[0];else if (hintChange.length === 2 && hintChange[1] !== 0)
1731
+ // item was changed
1732
+ action.orderHint = hintChange[1];
1733
+
1734
+ // else item was removed -> do not set 'orderHint' property
1735
+
1736
+ return action;
1737
+ });
1738
+ }
1739
+ function actionsMapAssets(diff, oldObj, newObj, variantHashMap) {
1740
+ var allAssetsActions = [];
1741
+ var variants = diff.variants;
1742
+ if (variants) forEach__default["default"](variants, function (variant, key) {
1743
+ var _extractMatchingPairs4 = extractMatchingPairs(variantHashMap, key, oldObj.variants, newObj.variants),
1744
+ oldVariant = _extractMatchingPairs4.oldObj,
1745
+ newVariant = _extractMatchingPairs4.newObj;
1746
+ if (variant.assets && (REGEX_UNDERSCORE_NUMBER$2.test(key) || REGEX_NUMBER$2.test(key))) {
1747
+ var assetActions = _buildVariantAssetsActions(variant.assets, oldVariant, newVariant);
1748
+ allAssetsActions = allAssetsActions.concat(assetActions);
1749
+ }
1750
+ });
1751
+ return allAssetsActions;
1752
+ }
1753
+ function actionsMapAttributes$1(diff, oldObj, newObj) {
1754
+ var sameForAllAttributeNames = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
1755
+ var variantHashMap = arguments.length > 4 ? arguments[4] : undefined;
1756
+ var actions = [];
1757
+ var variants = diff.variants;
1758
+ if (variants) forEach__default["default"](variants, function (variant, key) {
1759
+ var _extractMatchingPairs5 = extractMatchingPairs(variantHashMap, key, oldObj.variants, newObj.variants),
1760
+ oldVariant = _extractMatchingPairs5.oldObj,
1761
+ newVariant = _extractMatchingPairs5.newObj;
1762
+ if (REGEX_NUMBER$2.test(key) && !Array.isArray(variant)) {
1763
+ var skuAction = _buildSkuActions(variant, oldVariant);
1764
+ var keyAction = _buildKeyActions(variant, oldVariant);
1765
+ if (skuAction) actions.push(skuAction);
1766
+ if (keyAction) actions.push(keyAction);
1767
+ var attributes = variant.attributes;
1768
+ var attrActions = _buildVariantAttributesActions(attributes, oldVariant, newVariant, sameForAllAttributeNames);
1769
+ actions = actions.concat(attrActions);
1770
+ }
1771
+ });
1772
+
1773
+ // Ensure that an action is unique.
1774
+ // This is especially necessary for SFA attributes.
1775
+ return uniqWith__default["default"](actions, function (a, b) {
1776
+ return a.action === b.action && a.name === b.name && a.variantId === b.variantId;
1777
+ });
1778
+ }
1779
+ function actionsMapImages(diff, oldObj, newObj, variantHashMap) {
1780
+ var actions = [];
1781
+ var variants = diff.variants;
1782
+ if (variants) forEach__default["default"](variants, function (variant, key) {
1783
+ var _extractMatchingPairs6 = extractMatchingPairs(variantHashMap, key, oldObj.variants, newObj.variants),
1784
+ oldVariant = _extractMatchingPairs6.oldObj,
1785
+ newVariant = _extractMatchingPairs6.newObj;
1786
+ if (REGEX_UNDERSCORE_NUMBER$2.test(key) || REGEX_NUMBER$2.test(key)) {
1787
+ var vActions = _buildVariantImagesAction(variant.images, oldVariant, newVariant);
1788
+ actions = actions.concat(vActions);
1789
+ }
1790
+ });
1791
+ return actions;
1792
+ }
1793
+ function actionsMapPrices(diff, oldObj, newObj, variantHashMap, enableDiscounted) {
1794
+ var addPriceActions = [];
1795
+ var changePriceActions = [];
1796
+ var removePriceActions = [];
1797
+ var variants = diff.variants;
1798
+ if (variants) forEach__default["default"](variants, function (variant, key) {
1799
+ var _extractMatchingPairs7 = extractMatchingPairs(variantHashMap, key, oldObj.variants, newObj.variants),
1800
+ oldVariant = _extractMatchingPairs7.oldObj,
1801
+ newVariant = _extractMatchingPairs7.newObj;
1802
+ if (REGEX_UNDERSCORE_NUMBER$2.test(key) || REGEX_NUMBER$2.test(key)) {
1803
+ var _buildVariantPricesAc = _buildVariantPricesAction(variant.prices, oldVariant, newVariant, enableDiscounted),
1804
+ _buildVariantPricesAc2 = _slicedToArray(_buildVariantPricesAc, 3),
1805
+ addPriceAction = _buildVariantPricesAc2[0],
1806
+ changePriceAction = _buildVariantPricesAc2[1],
1807
+ removePriceAction = _buildVariantPricesAc2[2];
1808
+ addPriceActions = addPriceActions.concat(addPriceAction);
1809
+ changePriceActions = changePriceActions.concat(changePriceAction);
1810
+ removePriceActions = removePriceActions.concat(removePriceAction);
1811
+ }
1812
+ });
1813
+
1814
+ // price actions need to be in this below order
1815
+ return changePriceActions.concat(removePriceActions).concat(addPriceActions);
1816
+ }
1817
+ function actionsMapPricesCustom(diff, oldObj, newObj, variantHashMap) {
1818
+ var actions = [];
1819
+ var variants = diff.variants;
1820
+ if (variants) forEach__default["default"](variants, function (variant, key) {
1821
+ var _extractMatchingPairs8 = extractMatchingPairs(variantHashMap, key, oldObj.variants, newObj.variants),
1822
+ oldVariant = _extractMatchingPairs8.oldObj,
1823
+ newVariant = _extractMatchingPairs8.newObj;
1824
+ if (variant && variant.prices && (REGEX_UNDERSCORE_NUMBER$2.test(key) || REGEX_NUMBER$2.test(key))) {
1825
+ var priceHashMap = findMatchingPairs(variant.prices, oldVariant.prices, newVariant.prices);
1826
+ forEach__default["default"](variant.prices, function (price, index) {
1827
+ var _extractMatchingPairs9 = extractMatchingPairs(priceHashMap, index, oldVariant.prices, newVariant.prices),
1828
+ oldPrice = _extractMatchingPairs9.oldObj,
1829
+ newPrice = _extractMatchingPairs9.newObj;
1830
+ if (price.custom && (REGEX_UNDERSCORE_NUMBER$2.test(index) || REGEX_NUMBER$2.test(index))) {
1831
+ var generatedActions = actionsMapCustom(price, newPrice, oldPrice, {
1832
+ actions: {
1833
+ setCustomType: 'setProductPriceCustomType',
1834
+ setCustomField: 'setProductPriceCustomField'
1835
+ },
1836
+ priceId: oldPrice.id
1837
+ });
1838
+ actions = actions.concat(generatedActions);
1839
+ }
1840
+ });
1841
+ }
1842
+ });
1843
+ return actions;
1844
+ }
1845
+ function actionsMapMasterVariant(oldObj, newObj) {
1846
+ var createChangeMasterVariantAction = function createChangeMasterVariantAction(variantId) {
1847
+ return {
1848
+ action: 'changeMasterVariant',
1849
+ variantId: variantId
1850
+ };
1851
+ };
1852
+ var extractMasterVariantId = function extractMasterVariantId(fromObj) {
1853
+ var variants = Array.isArray(fromObj.variants) ? fromObj.variants : [];
1854
+ return variants[0] ? variants[0].id : undefined;
1855
+ };
1856
+ var newMasterVariantId = extractMasterVariantId(newObj);
1857
+ var oldMasterVariantId = extractMasterVariantId(oldObj);
1858
+
1859
+ // Old and new master master variant differ and a new master variant id exists
1860
+ if (newMasterVariantId && oldMasterVariantId !== newMasterVariantId) return [createChangeMasterVariantAction(newMasterVariantId)];
1861
+ return [];
1862
+ }
1863
+
1864
+ function createProductMapActions(mapActionGroup, syncActionConfig) {
1865
+ return function doMapActions(diff, newObj, oldObj) {
1866
+ var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
1867
+ var allActions = [];
1868
+ var sameForAllAttributeNames = options.sameForAllAttributeNames,
1869
+ enableDiscounted = options.enableDiscounted;
1870
+ var publish = newObj.publish,
1871
+ staged = newObj.staged;
1872
+ var variantHashMap = findMatchingPairs(diff.variants, oldObj.variants, newObj.variants);
1873
+ allActions.push(mapActionGroup('attributes', function () {
1874
+ return actionsMapAttributes$1(diff, oldObj, newObj, sameForAllAttributeNames || [], variantHashMap);
1875
+ }));
1876
+ allActions.push(mapActionGroup('variants', function () {
1877
+ return actionsMapAddVariants(diff, oldObj, newObj);
1878
+ }));
1879
+ allActions.push(actionsMapMasterVariant(oldObj, newObj));
1880
+ allActions.push(mapActionGroup('variants', function () {
1881
+ return actionsMapRemoveVariants(diff, oldObj, newObj);
1882
+ }));
1883
+ allActions.push(mapActionGroup('base', function () {
1884
+ return actionsMapBase$i(diff, oldObj, newObj, syncActionConfig);
1885
+ }));
1886
+ allActions.push(mapActionGroup('meta', function () {
1887
+ return actionsMapMeta(diff, oldObj, newObj);
1888
+ }));
1889
+ allActions.push(mapActionGroup('references', function () {
1890
+ return actionsMapReferences(diff, oldObj, newObj);
1891
+ }));
1892
+ allActions.push(mapActionGroup('images', function () {
1893
+ return actionsMapImages(diff, oldObj, newObj, variantHashMap);
1894
+ }));
1895
+ allActions.push(mapActionGroup('pricesCustom', function () {
1896
+ return actionsMapPricesCustom(diff, oldObj, newObj, variantHashMap);
1897
+ }));
1898
+ allActions.push(mapActionGroup('prices', function () {
1899
+ return actionsMapPrices(diff, oldObj, newObj, variantHashMap, enableDiscounted);
1900
+ }));
1901
+ allActions.push(mapActionGroup('categories', function () {
1902
+ return actionsMapCategories(diff);
1903
+ }));
1904
+ allActions.push(mapActionGroup('categoryOrderHints', function () {
1905
+ return actionsMapCategoryOrderHints(diff);
1906
+ }));
1907
+ allActions.push(mapActionGroup('assets', function () {
1908
+ return actionsMapAssets(diff, oldObj, newObj, variantHashMap);
1909
+ }));
1910
+ if (publish === true || staged === false) return flatten__default["default"](allActions).map(function (action) {
1911
+ return _objectSpread2(_objectSpread2({}, action), {}, {
1912
+ staged: false
1913
+ });
1914
+ });
1915
+ return flatten__default["default"](allActions);
1916
+ };
1917
+ }
1918
+ function moveMasterVariantsIntoVariants(before, now) {
1919
+ var _copyEmptyArrayProps = copyEmptyArrayProps(before, now),
1920
+ _copyEmptyArrayProps2 = _slicedToArray(_copyEmptyArrayProps, 2),
1921
+ beforeCopy = _copyEmptyArrayProps2[0],
1922
+ nowCopy = _copyEmptyArrayProps2[1];
1923
+ var move = function move(obj) {
1924
+ return _objectSpread2(_objectSpread2({}, obj), {}, {
1925
+ masterVariant: undefined,
1926
+ variants: [obj.masterVariant].concat(_toConsumableArray(obj.variants || []))
1927
+ });
1928
+ };
1929
+ var hasMasterVariant = function hasMasterVariant(obj) {
1930
+ return obj && obj.masterVariant;
1931
+ };
1932
+ return [hasMasterVariant(beforeCopy) ? move(beforeCopy) : beforeCopy, hasMasterVariant(nowCopy) ? move(nowCopy) : nowCopy];
1933
+ }
1934
+ var products = (function (actionGroupList, syncActionConfig) {
1935
+ var mapActionGroup = createMapActionGroup(actionGroupList);
1936
+ var doMapActions = createProductMapActions(mapActionGroup, syncActionConfig);
1937
+ var buildActions = createBuildActions(diff, doMapActions, moveMasterVariantsIntoVariants);
1938
+ return {
1939
+ buildActions: buildActions
1940
+ };
1941
+ });
1942
+
1943
+ var REGEX_NUMBER$1 = new RegExp(/^\d+$/);
1944
+ var REGEX_UNDERSCORE_NUMBER$1 = new RegExp(/^_\d+$/);
1945
+ var isAddAction = function isAddAction(key, resource) {
1946
+ return REGEX_NUMBER$1.test(key) && Array.isArray(resource) && resource.length;
1947
+ };
1948
+ var isRemoveAction = function isRemoveAction(key, resource) {
1949
+ return REGEX_UNDERSCORE_NUMBER$1.test(key) && Number(resource[2]) === 0;
1950
+ };
1951
+ var baseActionsList$h = [{
1952
+ action: 'changeOrderState',
1953
+ key: 'orderState'
1954
+ }, {
1955
+ action: 'changePaymentState',
1956
+ key: 'paymentState'
1957
+ }, {
1958
+ action: 'changeShipmentState',
1959
+ key: 'shipmentState'
1960
+ }];
1961
+
1962
+ /**
1963
+ * SYNC FUNCTIONS
1964
+ */
1965
+
1966
+ function actionsMapBase$h(diff, oldObj, newObj) {
1967
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
1968
+ return buildBaseAttributesActions({
1969
+ actions: baseActionsList$h,
1970
+ diff: diff,
1971
+ oldObj: oldObj,
1972
+ newObj: newObj,
1973
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
1974
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties,
1975
+ shouldPreventUnsettingRequiredFields: config.shouldPreventUnsettingRequiredFields
1976
+ });
1977
+ }
1978
+ function actionsMapDeliveries(diff, oldObj, newObj) {
1979
+ var deliveriesDiff = diff.shippingInfo;
1980
+ if (!deliveriesDiff) return [];
1981
+ var handler = createBuildArrayActions('deliveries', _defineProperty({}, ADD_ACTIONS, function (newObject) {
1982
+ return {
1983
+ action: 'addDelivery',
1984
+ items: newObject.items,
1985
+ parcels: newObject.parcels
1986
+ };
1987
+ }));
1988
+ return handler(deliveriesDiff, oldObj.shippingInfo, newObj.shippingInfo);
1989
+ }
1990
+ function _buildDeliveryParcelsAction(diffedParcels) {
1991
+ var oldDelivery = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1992
+ var newDelivery = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1993
+ var addParcelActions = [];
1994
+ var removeParcelActions = [];
1995
+
1996
+ // generate a hashMap to be able to reference the right image from both ends
1997
+ var matchingParcelPairs = findMatchingPairs(diffedParcels, oldDelivery.parcels, newDelivery.parcels);
1998
+ forEach__default["default"](diffedParcels, function (parcel, key) {
1999
+ var _extractMatchingPairs = extractMatchingPairs(matchingParcelPairs, key, oldDelivery.parcels, newDelivery.parcels),
2000
+ oldObj = _extractMatchingPairs.oldObj;
2001
+ if (isAddAction(key, parcel)) {
2002
+ addParcelActions.push(_objectSpread2({
2003
+ action: 'addParcelToDelivery',
2004
+ deliveryId: oldDelivery.id
2005
+ }, getDeltaValue(parcel)));
2006
+ return;
2007
+ }
2008
+ if (isRemoveAction(key, parcel)) {
2009
+ removeParcelActions.push({
2010
+ action: 'removeParcelFromDelivery',
2011
+ parcelId: oldObj.id
2012
+ });
2013
+ }
2014
+ });
2015
+ return [addParcelActions, removeParcelActions];
2016
+ }
2017
+ function _buildDeliveryItemsAction(diffedItems) {
2018
+ var newDelivery = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2019
+ var setDeliveryItemsAction = [];
2020
+ // If there is a diff it means that there were changes (update, adds or removes)
2021
+ // over the items, which means that `setDeliveryItems` change has happened over
2022
+ // the delivery
2023
+ if (diffedItems && Object.keys(diffedItems).length > 0) {
2024
+ setDeliveryItemsAction.push({
2025
+ action: 'setDeliveryItems',
2026
+ deliveryId: newDelivery.id,
2027
+ deliveryKey: newDelivery.key,
2028
+ items: newDelivery.items
2029
+ });
2030
+ }
2031
+ return [setDeliveryItemsAction];
2032
+ }
2033
+ function actionsMapParcels(diff, oldObj, newObj, deliveryHashMap) {
2034
+ var shippingInfo = diff.shippingInfo;
2035
+ if (!shippingInfo) return [];
2036
+ var deliveries = shippingInfo.deliveries;
2037
+ if (!deliveries) return [];
2038
+ var addParcelActions = [];
2039
+ var removeParcelActions = [];
2040
+ if (deliveries) forEach__default["default"](deliveries, function (delivery, key) {
2041
+ var _extractMatchingPairs2 = extractMatchingPairs(deliveryHashMap, key, oldObj.shippingInfo.deliveries, newObj.shippingInfo.deliveries),
2042
+ oldDelivery = _extractMatchingPairs2.oldObj,
2043
+ newDelivery = _extractMatchingPairs2.newObj;
2044
+ if (REGEX_UNDERSCORE_NUMBER$1.test(key) || REGEX_NUMBER$1.test(key)) {
2045
+ var _buildDeliveryParcels = _buildDeliveryParcelsAction(delivery.parcels, oldDelivery, newDelivery),
2046
+ _buildDeliveryParcels2 = _slicedToArray(_buildDeliveryParcels, 2),
2047
+ addParcelAction = _buildDeliveryParcels2[0],
2048
+ removeParcelAction = _buildDeliveryParcels2[1];
2049
+ addParcelActions = addParcelActions.concat(addParcelAction);
2050
+ removeParcelActions = removeParcelActions.concat(removeParcelAction);
2051
+ }
2052
+ });
2053
+ return removeParcelActions.concat(addParcelActions);
2054
+ }
2055
+ function actionsMapDeliveryItems(diff, oldObj, newObj, deliveryHashMap) {
2056
+ var shippingInfo = diff.shippingInfo;
2057
+ if (!shippingInfo) return [];
2058
+ var deliveries = shippingInfo.deliveries;
2059
+ if (!deliveries) return [];
2060
+ var setDeliveryItemsActions = [];
2061
+ forEach__default["default"](deliveries, function (delivery, key) {
2062
+ var _extractMatchingPairs3 = extractMatchingPairs(deliveryHashMap, key, oldObj.shippingInfo.deliveries, newObj.shippingInfo.deliveries),
2063
+ newDelivery = _extractMatchingPairs3.newObj;
2064
+ if (REGEX_UNDERSCORE_NUMBER$1.test(key) || REGEX_NUMBER$1.test(key)) {
2065
+ var _buildDeliveryItemsAc = _buildDeliveryItemsAction(delivery.items, newDelivery),
2066
+ _buildDeliveryItemsAc2 = _slicedToArray(_buildDeliveryItemsAc, 1),
2067
+ setDeliveryItemsAction = _buildDeliveryItemsAc2[0];
2068
+ setDeliveryItemsActions = setDeliveryItemsActions.concat(setDeliveryItemsAction);
2069
+ }
2070
+ });
2071
+ return setDeliveryItemsActions;
2072
+ }
2073
+ function actionsMapReturnsInfo(diff, oldObj, newObj) {
2074
+ var returnInfoDiff = diff.returnInfo;
2075
+ if (!returnInfoDiff) return [];
2076
+ var handler = createBuildArrayActions('returnInfo', _defineProperty(_defineProperty({}, ADD_ACTIONS, function (newReturnInfo) {
2077
+ if (newReturnInfo.items) {
2078
+ return [_objectSpread2({
2079
+ action: 'addReturnInfo'
2080
+ }, newReturnInfo)];
2081
+ }
2082
+ return [];
2083
+ }), CHANGE_ACTIONS, function (oldSReturnInfo, newReturnInfo, key) {
2084
+ var _returnInfoDiff$key$i = returnInfoDiff[key].items,
2085
+ items = _returnInfoDiff$key$i === void 0 ? {} : _returnInfoDiff$key$i;
2086
+ if (Object.keys(items).length === 0) {
2087
+ return [];
2088
+ }
2089
+ return Object.keys(items).reduce(function (actions, index) {
2090
+ var item = newReturnInfo.items[index];
2091
+ if (items[index].shipmentState) {
2092
+ actions.push({
2093
+ action: 'setReturnShipmentState',
2094
+ returnItemId: item.id,
2095
+ shipmentState: item.shipmentState
2096
+ });
2097
+ }
2098
+ if (items[index].paymentState) {
2099
+ actions.push({
2100
+ action: 'setReturnPaymentState',
2101
+ returnItemId: item.id,
2102
+ paymentState: item.paymentState
2103
+ });
2104
+ }
2105
+ return actions;
2106
+ }, []);
2107
+ }));
2108
+ return handler(diff, oldObj, newObj);
2109
+ }
2110
+
2111
+ function createOrderMapActions(mapActionGroup, syncActionConfig) {
2112
+ return function doMapActions(diff, newObj, oldObj) {
2113
+ var allActions = [];
2114
+ var deliveryHashMap;
2115
+ if (diff.shippingInfo && diff.shippingInfo.deliveries) {
2116
+ deliveryHashMap = findMatchingPairs(diff.shippingInfo.deliveries, oldObj.shippingInfo.deliveries, newObj.shippingInfo.deliveries);
2117
+ }
2118
+ allActions.push(mapActionGroup('base', function () {
2119
+ return actionsMapBase$h(diff, oldObj, newObj, syncActionConfig);
2120
+ }));
2121
+ allActions.push(mapActionGroup('deliveries', function () {
2122
+ return actionsMapDeliveries(diff, oldObj, newObj);
2123
+ }));
2124
+ allActions.push(mapActionGroup('parcels', function () {
2125
+ return actionsMapParcels(diff, oldObj, newObj, deliveryHashMap);
2126
+ }));
2127
+ allActions.push(mapActionGroup('items', function () {
2128
+ return actionsMapDeliveryItems(diff, oldObj, newObj, deliveryHashMap);
2129
+ }));
2130
+ allActions.push(flatten__default["default"](mapActionGroup('returnInfo', function () {
2131
+ return actionsMapReturnsInfo(diff, oldObj, newObj);
2132
+ })));
2133
+ allActions.push(mapActionGroup('custom', function () {
2134
+ return actionsMapCustom(diff, newObj, oldObj);
2135
+ }));
2136
+ return flatten__default["default"](allActions);
2137
+ };
2138
+ }
2139
+ var orders = (function (actionGroupList, syncActionConfig) {
2140
+ // actionGroupList contains information about which action groups
2141
+ // are allowed or ignored
2142
+
2143
+ // createMapActionGroup returns function 'mapActionGroup' that takes params:
2144
+ // - action group name
2145
+ // - callback function that should return a list of actions that correspond
2146
+ // to the for the action group
2147
+
2148
+ // this resulting function mapActionGroup will call the callback function
2149
+ // for allowed action groups and return the return value of the callback
2150
+ // It will return an empty array for ignored action groups
2151
+ var mapActionGroup = createMapActionGroup(actionGroupList);
2152
+ var doMapActions = createOrderMapActions(mapActionGroup, syncActionConfig);
2153
+ var buildActions = createBuildActions(diff, doMapActions);
2154
+ return {
2155
+ buildActions: buildActions
2156
+ };
2157
+ });
2158
+
2159
+ var baseActionsList$g = [{
2160
+ action: 'setKey',
2161
+ key: 'key'
2162
+ }, {
2163
+ action: 'setRecurringOrderState',
2164
+ key: 'recurringOrderState'
2165
+ }, {
2166
+ action: 'transitionState',
2167
+ key: 'state'
2168
+ }];
2169
+ function actionsMapBase$g(diff, oldObj, newObj) {
2170
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
2171
+ return buildBaseAttributesActions({
2172
+ actions: baseActionsList$g,
2173
+ diff: diff,
2174
+ oldObj: oldObj,
2175
+ newObj: newObj,
2176
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
2177
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties,
2178
+ shouldPreventUnsettingRequiredFields: config.shouldPreventUnsettingRequiredFields
2179
+ });
2180
+ }
2181
+
2182
+ function createRecurringOrdersMapActions(mapActionGroup, syncActionConfig) {
2183
+ return function doMapActions(diff, newObj, oldObj) {
2184
+ var allActions = [];
2185
+ allActions.push(mapActionGroup('base', function () {
2186
+ return actionsMapBase$g(diff, oldObj, newObj, syncActionConfig);
2187
+ }));
2188
+ allActions.push(mapActionGroup('custom', function () {
2189
+ return actionsMapCustom(diff, newObj, oldObj);
2190
+ }));
2191
+ return flatten__default["default"](allActions);
2192
+ };
2193
+ }
2194
+ var recurringOrders = (function (actionGroupList, syncActionConfig) {
2195
+ var mapActionGroup = createMapActionGroup(actionGroupList);
2196
+ var doMapActions = createRecurringOrdersMapActions(mapActionGroup, syncActionConfig);
2197
+ var buildActions = createBuildActions(diff, doMapActions);
2198
+ return {
2199
+ buildActions: buildActions
2200
+ };
2201
+ });
2202
+
2203
+ var baseActionsList$f = [{
2204
+ action: 'changeIsActive',
2205
+ key: 'isActive'
2206
+ }, {
2207
+ action: 'changeName',
2208
+ key: 'name'
2209
+ }, {
2210
+ action: 'changePredicate',
2211
+ key: 'predicate'
2212
+ }, {
2213
+ action: 'changeSortOrder',
2214
+ key: 'sortOrder'
2215
+ }, {
2216
+ action: 'changeValue',
2217
+ key: 'value'
2218
+ }, {
2219
+ action: 'setDescription',
2220
+ key: 'description'
2221
+ }, {
2222
+ action: 'setValidFrom',
2223
+ key: 'validFrom'
2224
+ }, {
2225
+ action: 'setValidUntil',
2226
+ key: 'validUntil'
2227
+ }, {
2228
+ action: 'setKey',
2229
+ key: 'key'
2230
+ }];
2231
+ function actionsMapBase$f(diff, oldObj, newObj) {
2232
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
2233
+ return buildBaseAttributesActions({
2234
+ actions: baseActionsList$f,
2235
+ diff: diff,
2236
+ oldObj: oldObj,
2237
+ newObj: newObj,
2238
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
2239
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties,
2240
+ shouldPreventUnsettingRequiredFields: config.shouldPreventUnsettingRequiredFields
2241
+ });
2242
+ }
2243
+
2244
+ var validityActions = ['setValidFrom', 'setValidUntil'];
2245
+ var isValidityActions = function isValidityActions(actionName) {
2246
+ return validityActions.includes(actionName);
2247
+ };
2248
+ function combineValidityActions() {
2249
+ var actions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
2250
+ var _actions$filter = actions.filter(function (item) {
2251
+ return isValidityActions(item.action);
2252
+ }),
2253
+ _actions$filter2 = _slicedToArray(_actions$filter, 2),
2254
+ setValidFromAction = _actions$filter2[0],
2255
+ setValidUntilAction = _actions$filter2[1];
2256
+ if (setValidFromAction && setValidUntilAction) {
2257
+ return [].concat(_toConsumableArray(actions.filter(function (item) {
2258
+ return !isValidityActions(item.action);
2259
+ })), [{
2260
+ action: 'setValidFromAndUntil',
2261
+ validFrom: setValidFromAction.validFrom,
2262
+ validUntil: setValidUntilAction.validUntil
2263
+ }]);
2264
+ }
2265
+ return actions;
2266
+ }
2267
+
2268
+ function createProductDiscountsMapActions(mapActionGroup, syncActionConfig) {
2269
+ return function doMapActions(diff, newObj, oldObj) {
2270
+ var allActions = [];
2271
+ allActions.push(mapActionGroup('base', function () {
2272
+ return actionsMapBase$f(diff, oldObj, newObj, syncActionConfig);
2273
+ }));
2274
+ return combineValidityActions(flatten__default["default"](allActions));
2275
+ };
2276
+ }
2277
+ var productDiscounts = (function (actionGroupList) {
2278
+ var syncActionConfig = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2279
+ var mapActionGroup = createMapActionGroup(actionGroupList);
2280
+ var doMapActions = createProductDiscountsMapActions(mapActionGroup, syncActionConfig);
2281
+ var buildActions = createBuildActions(diff, doMapActions);
2282
+ return {
2283
+ buildActions: buildActions
2284
+ };
2285
+ });
2286
+
2287
+ var baseActionsList$e = [{
2288
+ action: 'changeIsActive',
2289
+ key: 'isActive'
2290
+ }, {
2291
+ action: 'setName',
2292
+ key: 'name'
2293
+ }, {
2294
+ action: 'setDescription',
2295
+ key: 'description'
2296
+ }, {
2297
+ action: 'setKey',
2298
+ key: 'key'
2299
+ }, {
2300
+ action: 'setCartPredicate',
2301
+ key: 'cartPredicate'
2302
+ }, {
2303
+ action: 'setMaxApplications',
2304
+ key: 'maxApplications'
2305
+ }, {
2306
+ action: 'setMaxApplicationsPerCustomer',
2307
+ key: 'maxApplicationsPerCustomer'
2308
+ }, {
2309
+ action: 'changeCartDiscounts',
2310
+ key: 'cartDiscounts'
2311
+ }, {
2312
+ action: 'setValidFrom',
2313
+ key: 'validFrom'
2314
+ }, {
2315
+ action: 'setValidUntil',
2316
+ key: 'validUntil'
2317
+ }, {
2318
+ action: 'changeGroups',
2319
+ key: 'groups'
2320
+ }];
2321
+ function actionsMapBase$e(diff, oldObj, newObj) {
2322
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
2323
+ return buildBaseAttributesActions({
2324
+ actions: baseActionsList$e,
2325
+ diff: diff,
2326
+ oldObj: oldObj,
2327
+ newObj: newObj,
2328
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
2329
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties,
2330
+ shouldPreventUnsettingRequiredFields: config.shouldPreventUnsettingRequiredFields
2331
+ });
2332
+ }
2333
+
2334
+ function createDiscountCodesMapActions(mapActionGroup, syncActionConfig) {
2335
+ return function doMapActions(diff, newObj, oldObj) {
2336
+ var allActions = [];
2337
+ allActions.push(mapActionGroup('base', function () {
2338
+ return actionsMapBase$e(diff, oldObj, newObj, syncActionConfig);
2339
+ }));
2340
+ allActions.push(mapActionGroup('custom', function () {
2341
+ return actionsMapCustom(diff, newObj, oldObj);
2342
+ }));
2343
+ return combineValidityActions(flatten__default["default"](allActions));
2344
+ };
2345
+ }
2346
+ var discountCodes = (function (actionGroupList) {
2347
+ var syncActionConfig = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2348
+ // actionGroupList contains information about which action groups
2349
+ // are allowed or ignored
2350
+
2351
+ // createMapActionGroup returns function 'mapActionGroup' that takes params:
2352
+ // - action group name
2353
+ // - callback function that should return a list of actions that correspond
2354
+ // to the for the action group
2355
+
2356
+ // this resulting function mapActionGroup will call the callback function
2357
+ // for allowed action groups and return the return value of the callback
2358
+ // It will return an empty array for ignored action groups
2359
+ var mapActionGroup = createMapActionGroup(actionGroupList);
2360
+ var doMapActions = createDiscountCodesMapActions(mapActionGroup, syncActionConfig);
2361
+ var buildActions = createBuildActions(diff, doMapActions);
2362
+ return {
2363
+ buildActions: buildActions
2364
+ };
2365
+ });
2366
+
2367
+ var baseActionsList$d = [{
2368
+ action: 'changeName',
2369
+ key: 'name'
2370
+ }, {
2371
+ action: 'setKey',
2372
+ key: 'key'
2373
+ }];
2374
+ function actionsMapBase$d(diff, oldObj, newObj) {
2375
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
2376
+ return buildBaseAttributesActions({
2377
+ actions: baseActionsList$d,
2378
+ diff: diff,
2379
+ oldObj: oldObj,
2380
+ newObj: newObj,
2381
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
2382
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties,
2383
+ shouldPreventUnsettingRequiredFields: config.shouldPreventUnsettingRequiredFields
2384
+ });
2385
+ }
2386
+
2387
+ function createCustomerGroupMapActions(mapActionGroup, syncActionConfig) {
2388
+ return function doMapActions(diff, newObj, oldObj) {
2389
+ var allActions = [];
2390
+ allActions.push(mapActionGroup('base', function () {
2391
+ return actionsMapBase$d(diff, oldObj, newObj, syncActionConfig);
2392
+ }));
2393
+ allActions.push(mapActionGroup('custom', function () {
2394
+ return actionsMapCustom(diff, newObj, oldObj);
2395
+ }));
2396
+ return flatten__default["default"](allActions);
2397
+ };
2398
+ }
2399
+ var customerGroup = (function (actionGroupList) {
2400
+ var syncActionConfig = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2401
+ var mapActionGroup = createMapActionGroup(actionGroupList);
2402
+ var doMapActions = createCustomerGroupMapActions(mapActionGroup, syncActionConfig);
2403
+ var buildActions = createBuildActions(diff, doMapActions);
2404
+ return {
2405
+ buildActions: buildActions
2406
+ };
2407
+ });
2408
+
2409
+ var baseActionsList$c = [{
2410
+ action: 'changeIsActive',
2411
+ key: 'isActive'
2412
+ }, {
2413
+ action: 'changeName',
2414
+ key: 'name'
2415
+ }, {
2416
+ action: 'changeCartPredicate',
2417
+ key: 'cartPredicate'
2418
+ }, {
2419
+ action: 'changeSortOrder',
2420
+ key: 'sortOrder'
2421
+ }, {
2422
+ action: 'changeValue',
2423
+ key: 'value'
2424
+ }, {
2425
+ action: 'changeRequiresDiscountCode',
2426
+ key: 'requiresDiscountCode'
2427
+ }, {
2428
+ action: 'changeTarget',
2429
+ key: 'target'
2430
+ }, {
2431
+ action: 'setDescription',
2432
+ key: 'description'
2433
+ }, {
2434
+ action: 'setValidFrom',
2435
+ key: 'validFrom'
2436
+ }, {
2437
+ action: 'setValidUntil',
2438
+ key: 'validUntil'
2439
+ }, {
2440
+ action: 'changeStackingMode',
2441
+ key: 'stackingMode'
2442
+ }, {
2443
+ action: 'setKey',
2444
+ key: 'key'
2445
+ }];
2446
+ function actionsMapBase$c(diff, oldObj, newObj) {
2447
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
2448
+ return buildBaseAttributesActions({
2449
+ actions: baseActionsList$c,
2450
+ diff: diff,
2451
+ oldObj: oldObj,
2452
+ newObj: newObj,
2453
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
2454
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties,
2455
+ shouldPreventUnsettingRequiredFields: config.shouldPreventUnsettingRequiredFields
2456
+ });
2457
+ }
2458
+
2459
+ function createCartDiscountsMapActions(mapActionGroup, syncActionConfig) {
2460
+ return function doMapActions(diff, newObj, oldObj) {
2461
+ var allActions = [];
2462
+ allActions.push(mapActionGroup('base', function () {
2463
+ return actionsMapBase$c(diff, oldObj, newObj, syncActionConfig);
2464
+ }));
2465
+ allActions.push(mapActionGroup('custom', function () {
2466
+ return actionsMapCustom(diff, newObj, oldObj);
2467
+ }));
2468
+ return combineValidityActions(flatten__default["default"](allActions));
2469
+ };
2470
+ }
2471
+ var cartDiscounts = (function (actionGroupList) {
2472
+ var syncActionConfig = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2473
+ var mapActionGroup = createMapActionGroup(actionGroupList);
2474
+ var doMapActions = createCartDiscountsMapActions(mapActionGroup, syncActionConfig);
2475
+ var buildActions = createBuildActions(diff, doMapActions);
2476
+ return {
2477
+ buildActions: buildActions
2478
+ };
2479
+ });
2480
+
2481
+ var _excluded = ["__typename"];
2482
+ function removeTypename(obj) {
2483
+ obj.__typename;
2484
+ var objWithoutTypename = _objectWithoutProperties(obj, _excluded);
2485
+ return objWithoutTypename;
2486
+ }
2487
+
2488
+ var baseActionsList$b = [{
2489
+ action: 'changeName',
2490
+ key: 'name'
2491
+ }, {
2492
+ action: 'setKey',
2493
+ key: 'key'
2494
+ }, {
2495
+ action: 'setDescription',
2496
+ key: 'description'
2497
+ }];
2498
+ function actionsMapBase$b(diff, oldObj, newObj) {
2499
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
2500
+ return buildBaseAttributesActions({
2501
+ actions: baseActionsList$b,
2502
+ diff: diff,
2503
+ oldObj: oldObj,
2504
+ newObj: newObj,
2505
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
2506
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties,
2507
+ shouldPreventUnsettingRequiredFields: config.shouldPreventUnsettingRequiredFields
2508
+ });
2509
+ }
2510
+ function actionsMapRates(diff, oldObj, newObj) {
2511
+ var handler = createBuildArrayActions('rates', _defineProperty(_defineProperty(_defineProperty({}, ADD_ACTIONS, function (newObject) {
2512
+ return {
2513
+ action: 'addTaxRate',
2514
+ taxRate: newObject
2515
+ };
2516
+ }), REMOVE_ACTIONS, function (objectToRemove) {
2517
+ return {
2518
+ action: 'removeTaxRate',
2519
+ taxRateId: objectToRemove.id
2520
+ };
2521
+ }), CHANGE_ACTIONS, function (oldObject, updatedObject) {
2522
+ var _oldObject$subRates;
2523
+ // filter out taxRates that were not changed
2524
+ // so the API doesn't return it with a different id
2525
+ // we need to remove __typename from the object to compare them
2526
+ var taxCategoryWithoutTypeName = removeTypename(oldObject);
2527
+ var oldObjectSubRatesWithoutTypename = (_oldObject$subRates = oldObject.subRates) === null || _oldObject$subRates === void 0 ? void 0 : _oldObject$subRates.map(removeTypename);
2528
+ var oldObjectWithoutTypename = _objectSpread2(_objectSpread2({}, taxCategoryWithoutTypeName), {}, {
2529
+ subRates: oldObjectSubRatesWithoutTypename
2530
+ });
2531
+ if (fastEquals.deepEqual(oldObjectWithoutTypename, updatedObject)) return null;
2532
+ return {
2533
+ action: 'replaceTaxRate',
2534
+ taxRateId: oldObject.id === updatedObject.id ? oldObject.id : updatedObject.id,
2535
+ taxRate: updatedObject
2536
+ };
2537
+ }));
2538
+ return handler(diff, oldObj, newObj);
2539
+ }
2540
+
2541
+ function createTaxCategoriesMapActions(mapActionGroup, syncActionConfig) {
2542
+ return function doMapActions(diff, newObj, oldObj) {
2543
+ var allActions = [];
2544
+ allActions.push(mapActionGroup('base', function () {
2545
+ return actionsMapBase$b(diff, oldObj, newObj, syncActionConfig);
2546
+ }));
2547
+ allActions.push(mapActionGroup('rates', function () {
2548
+ return actionsMapRates(diff, oldObj, newObj);
2549
+ }));
2550
+ return flatten__default["default"](allActions);
2551
+ };
2552
+ }
2553
+ var taxCategories = (function (actionGroupList, syncActionConfig) {
2554
+ // config contains information about which action groups
2555
+ // are allowed or ignored
2556
+
2557
+ // createMapActionGroup returns function 'mapActionGroup' that takes params:
2558
+ // - action group name
2559
+ // - callback function that should return a list of actions that correspond
2560
+ // to the for the action group
2561
+
2562
+ // this resulting function mapActionGroup will call the callback function
2563
+ // for allowed action groups and return the return value of the callback
2564
+ // It will return an empty array for ignored action groups
2565
+ var mapActionGroup = createMapActionGroup(actionGroupList);
2566
+ var doMapActions = createTaxCategoriesMapActions(mapActionGroup, syncActionConfig);
2567
+ var buildActions = createBuildActions(diff, doMapActions);
2568
+ return {
2569
+ buildActions: buildActions
2570
+ };
2571
+ });
2572
+
2573
+ var baseActionsList$a = [{
2574
+ action: 'changeName',
2575
+ key: 'name'
2576
+ }, {
2577
+ action: 'setDescription',
2578
+ key: 'description'
2579
+ }, {
2580
+ action: 'setKey',
2581
+ key: 'key'
2582
+ }];
2583
+ var hasLocation = function hasLocation(locations, otherLocation) {
2584
+ return locations.some(function (location) {
2585
+ return location.country === otherLocation.country;
2586
+ });
2587
+ };
2588
+ function actionsMapBase$a(diff, oldObj, newObj) {
2589
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
2590
+ return buildBaseAttributesActions({
2591
+ actions: baseActionsList$a,
2592
+ diff: diff,
2593
+ oldObj: oldObj,
2594
+ newObj: newObj,
2595
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
2596
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties,
2597
+ shouldPreventUnsettingRequiredFields: config.shouldPreventUnsettingRequiredFields
2598
+ });
2599
+ }
2600
+ function actionsMapLocations(diff, oldObj, newObj) {
2601
+ var handler = createBuildArrayActions('locations', _defineProperty(_defineProperty(_defineProperty({}, ADD_ACTIONS, function (newLocation) {
2602
+ return {
2603
+ action: 'addLocation',
2604
+ location: newLocation
2605
+ };
2606
+ }), REMOVE_ACTIONS, function (oldLocation) {
2607
+ return (
2608
+ // We only add the action if the location is not included in the new object.
2609
+ !hasLocation(newObj.locations, oldLocation) ? {
2610
+ action: 'removeLocation',
2611
+ location: oldLocation
2612
+ } : null
2613
+ );
2614
+ }), CHANGE_ACTIONS, function (oldLocation, newLocation) {
2615
+ var result = [];
2616
+
2617
+ // We only remove the location in case that the oldLocation is not
2618
+ // included in the new object
2619
+ if (!hasLocation(newObj.locations, oldLocation)) result.push({
2620
+ action: 'removeLocation',
2621
+ location: oldLocation
2622
+ });
2623
+
2624
+ // We only add the location in case that the newLocation was not
2625
+ // included in the old object
2626
+ if (!hasLocation(oldObj.locations, newLocation)) result.push({
2627
+ action: 'addLocation',
2628
+ location: newLocation
2629
+ });
2630
+ return result;
2631
+ }));
2632
+ return handler(diff, oldObj, newObj);
2633
+ }
2634
+
2635
+ function createZonesMapActions(mapActionGroup, syncActionConfig) {
2636
+ return function doMapActions(diff, newObj, oldObj) {
2637
+ var allActions = [];
2638
+ allActions.push(mapActionGroup('base', function () {
2639
+ return actionsMapBase$a(diff, oldObj, newObj, syncActionConfig);
2640
+ }));
2641
+ allActions.push(flatten__default["default"](mapActionGroup('locations', function () {
2642
+ return actionsMapLocations(diff, oldObj, newObj);
2643
+ })));
2644
+ return flatten__default["default"](allActions);
2645
+ };
2646
+ }
2647
+ var zones = (function (actionGroupList, syncActionConfig) {
2648
+ // config contains information about which action groups
2649
+ // are allowed or ignored
2650
+
2651
+ // createMapActionGroup returns function 'mapActionGroup' that takes params:
2652
+ // - action group name
2653
+ // - callback function that should return a list of actions that correspond
2654
+ // to the for the action group
2655
+
2656
+ // this resulting function mapActionGroup will call the callback function
2657
+ // for allowed action groups and return the return value of the callback
2658
+ // It will return an empty array for ignored action groups
2659
+ var mapActionGroup = createMapActionGroup(actionGroupList);
2660
+ var doMapActions = createZonesMapActions(mapActionGroup, syncActionConfig);
2661
+ var buildActions = createBuildActions(diff, doMapActions);
2662
+ return {
2663
+ buildActions: buildActions
2664
+ };
2665
+ });
2666
+
2667
+ var baseActionsList$9 = [{
2668
+ action: 'setKey',
2669
+ key: 'key'
2670
+ }, {
2671
+ action: 'changeName',
2672
+ key: 'name'
2673
+ }, {
2674
+ action: 'setLocalizedName',
2675
+ key: 'localizedName'
2676
+ }, {
2677
+ action: 'setDescription',
2678
+ key: 'description'
2679
+ }, {
2680
+ action: 'setLocalizedDescription',
2681
+ key: 'localizedDescription'
2682
+ }, {
2683
+ action: 'changeIsDefault',
2684
+ key: 'isDefault'
2685
+ }, {
2686
+ action: 'setPredicate',
2687
+ key: 'predicate'
2688
+ }, {
2689
+ action: 'changeTaxCategory',
2690
+ key: 'taxCategory'
2691
+ }, {
2692
+ action: 'changeActive',
2693
+ key: 'active'
2694
+ }];
2695
+ function actionsMapBase$9(diff, oldObj, newObj) {
2696
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
2697
+ return buildBaseAttributesActions({
2698
+ actions: baseActionsList$9,
2699
+ diff: diff,
2700
+ oldObj: oldObj,
2701
+ newObj: newObj,
2702
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
2703
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties,
2704
+ shouldPreventUnsettingRequiredFields: config.shouldPreventUnsettingRequiredFields
2705
+ });
2706
+ }
2707
+ var addShippingRates = function addShippingRates(newZoneRate) {
2708
+ return newZoneRate.shippingRates ? newZoneRate.shippingRates.map(function (shippingRate) {
2709
+ return {
2710
+ action: 'addShippingRate',
2711
+ zone: newZoneRate.zone,
2712
+ shippingRate: shippingRate
2713
+ };
2714
+ }) : [];
2715
+ };
2716
+ function actionsMapZoneRatesShippingRates(diff, oldObj, newObj) {
2717
+ var handler = createBuildArrayActions('shippingRates', _defineProperty(_defineProperty(_defineProperty({}, ADD_ACTIONS, function (newShippingRate) {
2718
+ return {
2719
+ action: 'addShippingRate',
2720
+ zone: newObj.zone,
2721
+ shippingRate: newShippingRate
2722
+ };
2723
+ }), REMOVE_ACTIONS, function (oldShippingRate) {
2724
+ return {
2725
+ action: 'removeShippingRate',
2726
+ zone: oldObj.zone,
2727
+ shippingRate: oldShippingRate
2728
+ };
2729
+ }), CHANGE_ACTIONS, function (oldShippingRate, newShippingRate) {
2730
+ return [{
2731
+ action: 'removeShippingRate',
2732
+ zone: oldObj.zone,
2733
+ shippingRate: oldShippingRate
2734
+ }, {
2735
+ action: 'addShippingRate',
2736
+ zone: newObj.zone,
2737
+ shippingRate: newShippingRate
2738
+ }];
2739
+ }));
2740
+ return handler(diff, oldObj, newObj);
2741
+ }
2742
+ function actionsMapZoneRates(diff, oldObj, newObj) {
2743
+ var handler = createBuildArrayActions('zoneRates', _defineProperty(_defineProperty(_defineProperty({}, ADD_ACTIONS, function (newZoneRate) {
2744
+ return [{
2745
+ action: 'addZone',
2746
+ zone: newZoneRate.zone
2747
+ }].concat(_toConsumableArray(addShippingRates(newZoneRate)));
2748
+ }), REMOVE_ACTIONS, function (oldZoneRate) {
2749
+ return {
2750
+ action: 'removeZone',
2751
+ zone: oldZoneRate.zone
2752
+ };
2753
+ }), CHANGE_ACTIONS, function (oldZoneRate, newZoneRate) {
2754
+ var hasZoneActions = false;
2755
+ var shippingRateActions = Object.keys(diff.zoneRates).reduce(function (actions, key) {
2756
+ if (diff.zoneRates[key].zone) hasZoneActions = true;
2757
+ if (diff.zoneRates[key].shippingRates) return [].concat(_toConsumableArray(actions), _toConsumableArray(actionsMapZoneRatesShippingRates(diff.zoneRates[key], oldZoneRate, newZoneRate)));
2758
+ return actions;
2759
+ }, []);
2760
+ return flatten__default["default"](hasZoneActions ? [].concat(_toConsumableArray(shippingRateActions), [{
2761
+ action: 'removeZone',
2762
+ zone: oldZoneRate.zone
2763
+ }, {
2764
+ action: 'addZone',
2765
+ zone: newZoneRate.zone
2766
+ }]) : shippingRateActions);
2767
+ }));
2768
+ return handler(diff, oldObj, newObj);
2769
+ }
2770
+
2771
+ function createShippingMethodsMapActions(mapActionGroup, syncActionConfig) {
2772
+ return function doMapActions(diff, newObj, oldObj) {
2773
+ var allActions = [];
2774
+ allActions.push(mapActionGroup('base', function () {
2775
+ return actionsMapBase$9(diff, oldObj, newObj, syncActionConfig);
2776
+ }));
2777
+ allActions.push(flatten__default["default"](mapActionGroup('zoneRates', function () {
2778
+ return actionsMapZoneRates(diff, oldObj, newObj);
2779
+ })));
2780
+ allActions.push(mapActionGroup('custom', function () {
2781
+ return actionsMapCustom(diff, newObj, oldObj);
2782
+ }));
2783
+ return flatten__default["default"](allActions);
2784
+ };
2785
+ }
2786
+ var shippingMethods = (function (actionGroupList, syncActionConfig) {
2787
+ // actionGroupList contains information about which action groups
2788
+ // are allowed or ignored
2789
+
2790
+ // createMapActionGroup returns function 'mapActionGroup' that takes params:
2791
+ // - action group name
2792
+ // - callback function that should return a list of actions that correspond
2793
+ // to the for the action group
2794
+
2795
+ // this resulting function mapActionGroup will call the callback function
2796
+ // for allowed action groups and return the return value of the callback
2797
+ // It will return an empty array for ignored action groups
2798
+ var mapActionGroup = createMapActionGroup(actionGroupList);
2799
+ var doMapActions = createShippingMethodsMapActions(mapActionGroup, syncActionConfig);
2800
+ var buildActions = createBuildActions(diff, doMapActions);
2801
+ return {
2802
+ buildActions: buildActions
2803
+ };
2804
+ });
2805
+
2806
+ var baseActionsList$8 = [{
2807
+ action: 'changeName',
2808
+ key: 'name'
2809
+ }, {
2810
+ action: 'setKey',
2811
+ key: 'key'
2812
+ }, {
2813
+ action: 'changeDescription',
2814
+ key: 'description'
2815
+ }];
2816
+ function actionsMapBase$8(diff, previous, next) {
2817
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
2818
+ // when `diff` is undefined, then the underlying `buildActions` has returned any diff
2819
+ // which given in product-types would mean that `buildActions` has run with `nestedValuesChanges` applied
2820
+ // To allow continuation of update-action generation, we let this pass..
2821
+ if (!diff) return [];
2822
+ return buildBaseAttributesActions({
2823
+ diff: diff,
2824
+ actions: baseActionsList$8,
2825
+ oldObj: previous,
2826
+ newObj: next,
2827
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
2828
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties
2829
+ });
2830
+ }
2831
+
2832
+ // this is nearly similar to `buildBaseAttributesActions`, however with a significant difference.
2833
+ // `buildBasAttributesActions` generates update-actions with help of `diff`,
2834
+ // which is an object consisting of flags which indicates different operations.
2835
+ // `generateBaseFieldsUpdateActions` only generate based on `previous` and `next`.
2836
+ var generateBaseFieldsUpdateActions = function generateBaseFieldsUpdateActions(previous, next, actionDefinition) {
2837
+ var isEmpty = createIsEmptyValue([undefined, null, '']);
2838
+ return Object.entries(actionDefinition).reduce(function (nextUpdateActions, _ref) {
2839
+ var _ref2 = _slicedToArray(_ref, 2),
2840
+ field = _ref2[0],
2841
+ actionFieldDefinition = _ref2[1];
2842
+ if (isEmpty(previous[field]) && isEmpty(next[field])) return nextUpdateActions;
2843
+ if (!isEmpty(previous[field]) && isEmpty(next[field])) return [].concat(_toConsumableArray(nextUpdateActions), [actionFieldDefinition]);
2844
+ if (!fastEquals.deepEqual(previous[field], next[field])) {
2845
+ switch (field) {
2846
+ // BEWARE that this is generates update-action only for key of enum attribute value,
2847
+ // not key of product type. If we need to re-factor `product-types` sync actions to use
2848
+ // `generateBaseFieldsUpdateActions`, we need to extract the following logic so we could
2849
+ // cover both entity types.
2850
+ case 'key':
2851
+ return [].concat(_toConsumableArray(nextUpdateActions), [
2852
+ // Another option is to have explicit name of `field` e.g `enumKey`, which we could use to
2853
+ // generate appropriate update-action for respective entity type.
2854
+ // An outline of this on the top of my head:
2855
+ // ```js
2856
+ // case 'enumKey':
2857
+ // return [
2858
+ // ...nextUpdateActions,
2859
+ // {
2860
+ // action: actionFieldDefinition.action,
2861
+ // attributeName: actionFieldDefinition.attributeName,
2862
+ // key: previous.key,
2863
+ // newKey: next.key,
2864
+ // },
2865
+ // ]
2866
+ // case 'productTypeKey':
2867
+ // return [
2868
+ // ...nextUpdateActions,
2869
+ // {
2870
+ // action: actionFieldDefinition.action,
2871
+ // key: next.key
2872
+ // },
2873
+ // ]
2874
+ // ```
2875
+ {
2876
+ action: actionFieldDefinition.action,
2877
+ attributeName: actionFieldDefinition.attributeName,
2878
+ key: previous[field],
2879
+ newKey: next[field]
2880
+ }]);
2881
+ // attribute
2882
+ case 'attributeConstraint':
2883
+ case 'inputHint':
2884
+ return [].concat(_toConsumableArray(nextUpdateActions), [{
2885
+ action: actionFieldDefinition.action,
2886
+ attributeName: actionFieldDefinition.attributeName,
2887
+ newValue: next[field]
2888
+ }]);
2889
+ default:
2890
+ return [].concat(_toConsumableArray(nextUpdateActions), [_defineProperty({
2891
+ action: actionFieldDefinition.action,
2892
+ attributeName: actionFieldDefinition.attributeName
2893
+ }, field, next[field])]);
2894
+ }
2895
+ }
2896
+ return nextUpdateActions;
2897
+ }, []);
2898
+ };
2899
+ var generateUpdateActionsForAttributeDefinitions = function generateUpdateActionsForAttributeDefinitions() {
2900
+ var attributeDefinitions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
2901
+ var removedAttributeDefinitions = attributeDefinitions.filter(function (attributeDefinition) {
2902
+ return attributeDefinition.previous && !attributeDefinition.next;
2903
+ });
2904
+ var updatedAttributeDefinitions = attributeDefinitions.filter(function (attributeDefinition) {
2905
+ return attributeDefinition.previous && attributeDefinition.next;
2906
+ });
2907
+ var addedAttributeDefinitions = attributeDefinitions.filter(function (attributeDefinition) {
2908
+ return !attributeDefinition.previous && attributeDefinition.next;
2909
+ });
2910
+ return [].concat(_toConsumableArray(removedAttributeDefinitions.map(function (attributeDef) {
2911
+ return {
2912
+ action: 'removeAttributeDefinition',
2913
+ name: attributeDef.previous.name
2914
+ };
2915
+ })), _toConsumableArray(flatten__default["default"](updatedAttributeDefinitions.map(function (updatedAttributeDefinition) {
2916
+ return generateBaseFieldsUpdateActions(updatedAttributeDefinition.previous, updatedAttributeDefinition.next, {
2917
+ label: {
2918
+ action: 'changeLabel',
2919
+ attributeName: updatedAttributeDefinition.previous.name
2920
+ },
2921
+ inputTip: {
2922
+ action: 'setInputTip',
2923
+ attributeName: updatedAttributeDefinition.previous.name
2924
+ },
2925
+ inputHint: {
2926
+ action: 'changeInputHint',
2927
+ attributeName: updatedAttributeDefinition.previous.name
2928
+ },
2929
+ isSearchable: {
2930
+ action: 'changeIsSearchable',
2931
+ attributeName: updatedAttributeDefinition.previous.name
2932
+ },
2933
+ attributeConstraint: {
2934
+ action: 'changeAttributeConstraint',
2935
+ attributeName: updatedAttributeDefinition.previous.name
2936
+ }
2937
+ });
2938
+ }))), _toConsumableArray(addedAttributeDefinitions.map(function (attributeDef) {
2939
+ return {
2940
+ action: 'addAttributeDefinition',
2941
+ attribute: attributeDef.next
2942
+ };
2943
+ })));
2944
+ };
2945
+ var generateUpdateActionsForAttributeEnumValues = function generateUpdateActionsForAttributeEnumValues() {
2946
+ var attributeEnumValues = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
2947
+ var removedAttributeEnumValues = attributeEnumValues.filter(function (attributeEnumValue) {
2948
+ return attributeEnumValue.previous && !attributeEnumValue.next;
2949
+ });
2950
+ var updatedAttributeEnumValues = attributeEnumValues.filter(function (attributeEnumValue) {
2951
+ return attributeEnumValue.next && attributeEnumValue.previous;
2952
+ });
2953
+ var addedAttributeEnumValues = attributeEnumValues.filter(function (attributeEnumValue) {
2954
+ return !attributeEnumValue.previous && attributeEnumValue.next;
2955
+ });
2956
+ return [].concat(_toConsumableArray(Object.values(removedAttributeEnumValues.reduce(function (nextEnumUpdateActions, removedAttributeEnumValue) {
2957
+ var removedAttributeEnumValueOfSameAttributeName = nextEnumUpdateActions[removedAttributeEnumValue.hint.attributeName] || {
2958
+ keys: [],
2959
+ attributeName: removedAttributeEnumValue.hint.attributeName,
2960
+ action: 'removeEnumValues'
2961
+ };
2962
+ return _objectSpread2(_objectSpread2({}, nextEnumUpdateActions), {}, _defineProperty({}, removedAttributeEnumValue.hint.attributeName, _objectSpread2(_objectSpread2({}, removedAttributeEnumValueOfSameAttributeName), {}, {
2963
+ keys: [].concat(_toConsumableArray(removedAttributeEnumValueOfSameAttributeName.keys), [removedAttributeEnumValue.previous.key])
2964
+ })));
2965
+ }, {}))), _toConsumableArray(flatten__default["default"](updatedAttributeEnumValues.map(function (updatedAttributeEnumValue) {
2966
+ var updateActions = generateBaseFieldsUpdateActions(updatedAttributeEnumValue.previous, updatedAttributeEnumValue.next, {
2967
+ key: {
2968
+ action: 'changeEnumKey',
2969
+ attributeName: updatedAttributeEnumValue.hint.attributeName
2970
+ }
2971
+ });
2972
+ if (!fastEquals.deepEqual(updatedAttributeEnumValue.previous.label, updatedAttributeEnumValue.next.label)) {
2973
+ if (updatedAttributeEnumValue.hint.isLocalized) {
2974
+ return [].concat(_toConsumableArray(updateActions), [{
2975
+ action: 'changeLocalizedEnumValueLabel',
2976
+ attributeName: updatedAttributeEnumValue.hint.attributeName,
2977
+ newValue: updatedAttributeEnumValue.next
2978
+ }]);
2979
+ }
2980
+ return [].concat(_toConsumableArray(updateActions), [{
2981
+ action: 'changePlainEnumValueLabel',
2982
+ attributeName: updatedAttributeEnumValue.hint.attributeName,
2983
+ newValue: updatedAttributeEnumValue.next
2984
+ }]);
2985
+ }
2986
+ return updateActions;
2987
+ }))), _toConsumableArray(addedAttributeEnumValues.map(function (addedAttributeEnumValue) {
2988
+ return {
2989
+ action: addedAttributeEnumValue.hint.isLocalized ? 'addLocalizedEnumValue' : 'addPlainEnumValue',
2990
+ attributeName: addedAttributeEnumValue.hint.attributeName,
2991
+ value: addedAttributeEnumValue.next
2992
+ };
2993
+ })));
2994
+ };
2995
+ var generateChangeAttributeOrderAction = function generateChangeAttributeOrderAction() {
2996
+ var attrsOld = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
2997
+ var attrsNew = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
2998
+ var updateActions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
2999
+ if (!attrsOld.length || !attrsNew.length) return null;
3000
+ var newAttributesOrder = attrsNew.map(function (attribute) {
3001
+ return attribute.name;
3002
+ });
3003
+ var removedAttributeNames = updateActions.filter(function (action) {
3004
+ return action.action === 'removeAttributeDefinition';
3005
+ }).map(function (action) {
3006
+ return action.name;
3007
+ });
3008
+ var addedAttributeNames = updateActions.filter(function (action) {
3009
+ return action.action === 'addAttributeDefinition';
3010
+ }).map(function (action) {
3011
+ return action.attribute.name;
3012
+ });
3013
+
3014
+ // changeAttributeOrder action will be sent to CTP API as the last action so we have to
3015
+ // calculate how the productType will look like after adding/removing attributes
3016
+ var patchedOldAttributesOrder = attrsOld.map(function (attribute) {
3017
+ return attribute.name;
3018
+ }).filter(function (name) {
3019
+ return !removedAttributeNames.includes(name);
3020
+ }).concat(addedAttributeNames);
3021
+ if (newAttributesOrder.join(',') !== patchedOldAttributesOrder.join(',')) return {
3022
+ action: 'changeAttributeOrderByName',
3023
+ attributeNames: newAttributesOrder
3024
+ };
3025
+ return null;
3026
+ };
3027
+ var actionsMapForHints = function actionsMapForHints() {
3028
+ var nestedValuesChanges = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3029
+ var ptOld = arguments.length > 1 ? arguments[1] : undefined;
3030
+ var ptNew = arguments.length > 2 ? arguments[2] : undefined;
3031
+ var updateActions = [].concat(_toConsumableArray(generateUpdateActionsForAttributeDefinitions(nestedValuesChanges.attributeDefinitions)), _toConsumableArray(generateUpdateActionsForAttributeEnumValues(nestedValuesChanges.attributeEnumValues)));
3032
+ var changeAttributeOrderAction = generateChangeAttributeOrderAction(ptOld.attributes, ptNew.attributes, updateActions);
3033
+ if (changeAttributeOrderAction) updateActions.push(changeAttributeOrderAction);
3034
+ return updateActions;
3035
+ };
3036
+
3037
+ function createProductTypeMapActions(mapActionGroup, syncActionConfig) {
3038
+ return function doMapActions(diff, next, previous, options) {
3039
+ return flatten__default["default"]([
3040
+ // we support only base fields for the product type,
3041
+ // for attributes, applying hints would be recommended
3042
+ mapActionGroup('base', function () {
3043
+ return actionsMapBase$8(diff, previous, next, syncActionConfig);
3044
+ }), actionsMapForHints(options.nestedValuesChanges, previous, next)]);
3045
+ };
3046
+ }
3047
+ var productTypes = (function (actionGroupList, syncActionConfig) {
3048
+ var mapActionGroup = createMapActionGroup(actionGroupList);
3049
+ var doMapActions = createProductTypeMapActions(mapActionGroup, syncActionConfig);
3050
+ var onBeforeApplyingDiff = null;
3051
+ var buildActions = createBuildActions(diff, doMapActions, onBeforeApplyingDiff, {
3052
+ withHints: true
3053
+ });
3054
+ return {
3055
+ buildActions: buildActions
3056
+ };
3057
+ });
3058
+
3059
+ var baseActionsList$7 = [{
3060
+ action: 'changeKey',
3061
+ key: 'key'
3062
+ }, {
3063
+ action: 'setName',
3064
+ key: 'name'
3065
+ }, {
3066
+ action: 'setDescription',
3067
+ key: 'description'
3068
+ }, {
3069
+ action: 'changeType',
3070
+ key: 'type'
3071
+ }, {
3072
+ action: 'changeInitial',
3073
+ key: 'initial'
3074
+ }, {
3075
+ action: 'setTransitions',
3076
+ key: 'transitions'
3077
+ }];
3078
+ function actionsMapBase$7(diff, oldObj, newObj) {
3079
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
3080
+ return buildBaseAttributesActions({
3081
+ actions: baseActionsList$7,
3082
+ diff: diff,
3083
+ oldObj: oldObj,
3084
+ newObj: newObj,
3085
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
3086
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties,
3087
+ shouldPreventUnsettingRequiredFields: config.shouldPreventUnsettingRequiredFields
3088
+ });
3089
+ }
3090
+ function actionsMapRoles(diff, oldObj, newObj) {
3091
+ var buildArrayActions = createBuildArrayActions('roles', _defineProperty(_defineProperty({}, ADD_ACTIONS, function (newRole) {
3092
+ return {
3093
+ action: 'addRoles',
3094
+ roles: newRole
3095
+ };
3096
+ }), REMOVE_ACTIONS, function (oldRole) {
3097
+ return {
3098
+ action: 'removeRoles',
3099
+ roles: oldRole
3100
+ };
3101
+ }));
3102
+ return buildArrayActions(diff, oldObj, newObj);
3103
+ }
3104
+
3105
+ // This function groups `addRoles` and `removeRoles` actions to one array
3106
+ function groupRoleActions(_ref) {
3107
+ var _ref2 = _slicedToArray(_ref, 1),
3108
+ actions = _ref2[0];
3109
+ var addActionRoles = [];
3110
+ var removeActionRoles = [];
3111
+ actions.forEach(function (action) {
3112
+ if (action.action === 'removeRoles') removeActionRoles.push(action.roles);
3113
+ if (action.action === 'addRoles') addActionRoles.push(action.roles);
3114
+ });
3115
+ return [{
3116
+ action: 'removeRoles',
3117
+ roles: removeActionRoles
3118
+ }, {
3119
+ action: 'addRoles',
3120
+ roles: addActionRoles
3121
+ }].filter(function (action) {
3122
+ return action.roles.length;
3123
+ });
3124
+ }
3125
+ function createStatesMapActions(mapActionGroup, syncActionConfig) {
3126
+ return function doMapActions(diff, newObj, oldObj) {
3127
+ var baseActions = [];
3128
+ var roleActions = [];
3129
+ baseActions.push(mapActionGroup('base', function () {
3130
+ return actionsMapBase$7(diff, oldObj, newObj, syncActionConfig);
3131
+ }));
3132
+ roleActions.push(mapActionGroup('roles', function () {
3133
+ return actionsMapRoles(diff, oldObj, newObj);
3134
+ }));
3135
+ return flatten__default["default"]([].concat(baseActions, _toConsumableArray(groupRoleActions(roleActions))));
3136
+ };
3137
+ }
3138
+ var states = (function (actionGroupList, syncActionConfig) {
3139
+ var mapActionGroup = createMapActionGroup(actionGroupList);
3140
+ var doMapActions = createStatesMapActions(mapActionGroup, syncActionConfig);
3141
+ var buildActions = createBuildActions(diff, doMapActions);
3142
+ return {
3143
+ buildActions: buildActions
3144
+ };
3145
+ });
3146
+
3147
+ var baseActionsList$6 = [{
3148
+ action: 'changeKey',
3149
+ key: 'key'
3150
+ }, {
3151
+ action: 'changeName',
3152
+ key: 'name'
3153
+ }, {
3154
+ action: 'changeDescription',
3155
+ key: 'description'
3156
+ }, {
3157
+ action: 'setAddress',
3158
+ key: 'address'
3159
+ }, {
3160
+ action: 'setGeoLocation',
3161
+ key: 'geoLocation'
3162
+ }, {
3163
+ action: 'setRoles',
3164
+ key: 'roles'
3165
+ }];
3166
+ function actionsMapBase$6(diff, oldObj, newObj) {
3167
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
3168
+ return buildBaseAttributesActions({
3169
+ actions: baseActionsList$6,
3170
+ diff: diff,
3171
+ oldObj: oldObj,
3172
+ newObj: newObj,
3173
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
3174
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties,
3175
+ shouldPreventUnsettingRequiredFields: config.shouldPreventUnsettingRequiredFields
3176
+ });
3177
+ }
3178
+
3179
+ function createChannelsMapActions$1(mapActionGroup, syncActionConfig) {
3180
+ return function doMapActions(diff, newObj, oldObj) {
3181
+ var allActions = [];
3182
+ allActions.push(mapActionGroup('base', function () {
3183
+ return actionsMapBase$6(diff, oldObj, newObj, syncActionConfig);
3184
+ }));
3185
+ allActions.push(mapActionGroup('custom', function () {
3186
+ return actionsMapCustom(diff, newObj, oldObj);
3187
+ }));
3188
+ return flatten__default["default"](allActions);
3189
+ };
3190
+ }
3191
+ var channels = (function (actionGroupList) {
3192
+ var syncActionConfig = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
3193
+ var mapActionGroup = createMapActionGroup(actionGroupList);
3194
+ var doMapActions = createChannelsMapActions$1(mapActionGroup, syncActionConfig);
3195
+ var buildActions = createBuildActions(diff, doMapActions);
3196
+ return {
3197
+ buildActions: buildActions
3198
+ };
3199
+ });
3200
+
3201
+ var REGEX_NUMBER = new RegExp(/^\d+$/);
3202
+ var REGEX_UNDERSCORE_NUMBER = new RegExp(/^_\d+$/);
3203
+ var getIsChangedOperation = function getIsChangedOperation(key) {
3204
+ return REGEX_NUMBER.test(key);
3205
+ };
3206
+ var getIsRemovedOperation = function getIsRemovedOperation(key) {
3207
+ return REGEX_UNDERSCORE_NUMBER.test(key);
3208
+ };
3209
+ var baseActionsList$5 = [{
3210
+ action: 'changeKey',
3211
+ key: 'key'
3212
+ }, {
3213
+ action: 'changeName',
3214
+ key: 'name'
3215
+ }, {
3216
+ action: 'setDescription',
3217
+ key: 'description'
3218
+ }];
3219
+ function actionsMapBase$5(diff, oldObj, newObj) {
3220
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
3221
+ return buildBaseAttributesActions({
3222
+ actions: baseActionsList$5,
3223
+ diff: diff,
3224
+ oldObj: oldObj,
3225
+ newObj: newObj,
3226
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
3227
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties,
3228
+ shouldPreventUnsettingRequiredFields: config.shouldPreventUnsettingRequiredFields
3229
+ });
3230
+ }
3231
+ function actionsMapEnums(fieldName, attributeType, attributeDiff, previous, next) {
3232
+ var addEnumActionName = attributeType === 'Enum' ? 'addEnumValue' : 'addLocalizedEnumValue';
3233
+ var changeEnumValueLabelActionName = attributeType === 'Enum' ? 'changeEnumValueLabel' : 'changeLocalizedEnumValueLabel';
3234
+ var changeEnumOrderActionName = attributeType === 'Enum' ? 'changeEnumValueOrder' : 'changeLocalizedEnumValueOrder';
3235
+ var buildArrayActions = createBuildArrayActions('values', _defineProperty(_defineProperty({}, ADD_ACTIONS, function (newEnum) {
3236
+ return {
3237
+ fieldName: fieldName,
3238
+ action: addEnumActionName,
3239
+ value: newEnum
3240
+ };
3241
+ }), CHANGE_ACTIONS, function (oldEnum, newEnum) {
3242
+ var oldEnumInNext = next.values.find(function (nextEnum) {
3243
+ return nextEnum.key === oldEnum.key;
3244
+ });
3245
+
3246
+ // These `changeActions` would impose a nested structure among
3247
+ // the accumulated `updateActions` generated by `buildArrayActions`
3248
+ // In the end; we have to flatten the structure before we pass it back
3249
+ // to the client.
3250
+ var changeActions = [];
3251
+ if (oldEnumInNext) {
3252
+ // If the enum value is changed, we need to change the order first
3253
+ var isKeyChanged = oldEnum.key !== newEnum.key;
3254
+
3255
+ // check if the label is changed
3256
+ var foundPreviousEnum = previous.values.find(function (previousEnum) {
3257
+ return previousEnum.key === newEnum.key;
3258
+ });
3259
+ var isLabelEqual = isEqual__default["default"](foundPreviousEnum.label, newEnum.label);
3260
+ if (isKeyChanged) {
3261
+ // these actions is then flatten in the end
3262
+ changeActions.push({
3263
+ fieldName: fieldName,
3264
+ action: changeEnumOrderActionName,
3265
+ value: newEnum
3266
+ });
3267
+ }
3268
+ if (!isLabelEqual) {
3269
+ changeActions.push({
3270
+ fieldName: fieldName,
3271
+ action: changeEnumValueLabelActionName,
3272
+ value: newEnum
3273
+ });
3274
+ }
3275
+ } else {
3276
+ changeActions.push({
3277
+ fieldName: fieldName,
3278
+ action: addEnumActionName,
3279
+ value: newEnum
3280
+ });
3281
+ }
3282
+ return changeActions;
3283
+ }));
3284
+ var actions = [];
3285
+ // following lists are necessary to ensure that when we change the
3286
+ // order of enumValues, we generate one updateAction instead of one at a time.
3287
+ var newEnumValuesOrder = [];
3288
+ flatten__default["default"](buildArrayActions(attributeDiff, previous, next)).forEach(function (updateAction) {
3289
+ if (updateAction.action === changeEnumOrderActionName) {
3290
+ newEnumValuesOrder = next.values.map(function (enumValue) {
3291
+ return enumValue.key;
3292
+ });
3293
+ } else actions.push(updateAction);
3294
+ });
3295
+ return [].concat(actions, _toConsumableArray(newEnumValuesOrder.length > 0 ? [{
3296
+ fieldName: fieldName,
3297
+ action: changeEnumOrderActionName,
3298
+ keys: newEnumValuesOrder
3299
+ }] : []));
3300
+ }
3301
+ function actionsMapFieldDefinitions(fieldDefinitionsDiff, previous, next, diffPaths) {
3302
+ var actions = [];
3303
+ forEach__default["default"](fieldDefinitionsDiff, function (diffValue, diffKey) {
3304
+ var extractedPairs = extractMatchingPairs(diffPaths, diffKey, previous, next);
3305
+ if (getIsChangedOperation(diffKey)) {
3306
+ var _diffValue$type;
3307
+ if (Array.isArray(diffValue)) {
3308
+ var deltaValue = getDeltaValue(diffValue);
3309
+ if (deltaValue.name) {
3310
+ actions.push({
3311
+ action: 'addFieldDefinition',
3312
+ fieldDefinition: deltaValue
3313
+ });
3314
+ }
3315
+ } else if (diffValue.label) {
3316
+ actions.push({
3317
+ action: 'changeLabel',
3318
+ label: extractedPairs.newObj.label,
3319
+ fieldName: extractedPairs.oldObj.name
3320
+ });
3321
+ } else if (diffValue.inputHint) {
3322
+ actions.push({
3323
+ action: 'changeInputHint',
3324
+ inputHint: extractedPairs.newObj.inputHint,
3325
+ fieldName: extractedPairs.oldObj.name
3326
+ });
3327
+ } else if (diffValue !== null && diffValue !== void 0 && (_diffValue$type = diffValue.type) !== null && _diffValue$type !== void 0 && _diffValue$type.values) {
3328
+ actions.push.apply(actions, _toConsumableArray(actionsMapEnums(extractedPairs.oldObj.name, extractedPairs.oldObj.type.name, diffValue.type, extractedPairs.oldObj.type, extractedPairs.newObj.type)));
3329
+ }
3330
+ } else if (getIsRemovedOperation(diffKey)) {
3331
+ if (Array.isArray(diffValue)) {
3332
+ if (diffValue.length === 3 && diffValue[2] === 3) {
3333
+ actions.push({
3334
+ action: 'changeFieldDefinitionOrder',
3335
+ fieldNames: next.map(function (n) {
3336
+ return n.name;
3337
+ })
3338
+ });
3339
+ } else {
3340
+ var _deltaValue = getDeltaValue(diffValue);
3341
+ if (_deltaValue === undefined && diffValue[0].name) actions.push({
3342
+ action: 'removeFieldDefinition',
3343
+ fieldName: diffValue[0].name
3344
+ });
3345
+ }
3346
+ }
3347
+ }
3348
+ });
3349
+
3350
+ // Make sure to execute removeActions before creating new ones
3351
+ // in order to prevent any eventual removal of `addAction`.
3352
+ // List of `removeActions` can be found here
3353
+ // https://docs.commercetools.com/api/projects/types#change-key
3354
+ var sortedActions = sortBy__default["default"](actions, function (action) {
3355
+ return action.action !== 'removeFieldDefinition';
3356
+ });
3357
+ return sortedActions;
3358
+ }
3359
+
3360
+ function createTypeMapActions(mapActionGroup, syncActionConfig) {
3361
+ return function doMapActions(diff, next, previous) {
3362
+ var allActions = [];
3363
+ allActions.push(mapActionGroup('base', function () {
3364
+ return actionsMapBase$5(diff, previous, next, syncActionConfig);
3365
+ }), mapActionGroup('fieldDefinitions', function () {
3366
+ return actionsMapFieldDefinitions(diff.fieldDefinitions, previous.fieldDefinitions, next.fieldDefinitions, findMatchingPairs(diff.fieldDefinitions, previous.fieldDefinitions, next.fieldDefinitions, 'name'));
3367
+ }));
3368
+ return flatten__default["default"](allActions);
3369
+ };
3370
+ }
3371
+ var types = (function (actionGroupList, syncActionConfig) {
3372
+ var mapActionGroup = createMapActionGroup(actionGroupList);
3373
+ var doMapActions = createTypeMapActions(mapActionGroup, syncActionConfig);
3374
+ var buildActions = createBuildActions(diff, doMapActions);
3375
+ return {
3376
+ buildActions: buildActions
3377
+ };
3378
+ });
3379
+
3380
+ var baseActionsList$4 = [{
3381
+ action: 'changeName',
3382
+ key: 'name'
3383
+ }, {
3384
+ action: 'changeCurrencies',
3385
+ key: 'currencies'
3386
+ }, {
3387
+ action: 'changeCountries',
3388
+ key: 'countries'
3389
+ }, {
3390
+ action: 'changeLanguages',
3391
+ key: 'languages'
3392
+ }, {
3393
+ action: 'changeMessagesConfiguration',
3394
+ key: 'messagesConfiguration'
3395
+ }, {
3396
+ action: 'setShippingRateInputType',
3397
+ key: 'shippingRateInputType'
3398
+ }];
3399
+ var myBusinessUnitActionsList = [{
3400
+ action: 'changeMyBusinessUnitStatusOnCreation',
3401
+ key: 'myBusinessUnitStatusOnCreation',
3402
+ actionKey: 'status'
3403
+ }, {
3404
+ action: 'setMyBusinessUnitAssociateRoleOnCreation',
3405
+ key: 'myBusinessUnitAssociateRoleOnCreation',
3406
+ actionKey: 'associateRole'
3407
+ }];
3408
+ var customerSearchActionsList = [{
3409
+ action: 'changeCustomerSearchStatus',
3410
+ key: 'status'
3411
+ }];
3412
+ var businessUnitSearchActionsList = [{
3413
+ action: 'changeBusinessUnitSearchStatus',
3414
+ key: 'status'
3415
+ }];
3416
+ function actionsMapBase$4(diff, oldObj, newObj) {
3417
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
3418
+ return buildBaseAttributesActions({
3419
+ actions: baseActionsList$4,
3420
+ diff: diff,
3421
+ oldObj: oldObj,
3422
+ newObj: newObj,
3423
+ shouldOmitEmptyString: config.shouldOmitEmptyString
3424
+ });
3425
+ }
3426
+ var actionsMapBusinessUnit = function actionsMapBusinessUnit(diff, oldObj, newObj) {
3427
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
3428
+ var businessUnits = diff.businessUnits;
3429
+ if (!businessUnits) {
3430
+ return [];
3431
+ }
3432
+ return buildBaseAttributesActions({
3433
+ actions: myBusinessUnitActionsList,
3434
+ diff: businessUnits,
3435
+ oldObj: oldObj.businessUnits,
3436
+ newObj: newObj.businessUnits,
3437
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
3438
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties
3439
+ });
3440
+ };
3441
+ function actionsMapSearchIndexingConfiguration(diff, oldObj, newObj) {
3442
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
3443
+ var searchIndexing = diff.searchIndexing;
3444
+ if (!searchIndexing) {
3445
+ return [];
3446
+ }
3447
+ var businessUnits = searchIndexing.businessUnits,
3448
+ customers = searchIndexing.customers;
3449
+ if (!customers && !businessUnits) {
3450
+ return [];
3451
+ }
3452
+ var businessUnitsActions = businessUnits ? buildBaseAttributesActions({
3453
+ actions: businessUnitSearchActionsList,
3454
+ diff: diff.searchIndexing.businessUnits,
3455
+ oldObj: oldObj.searchIndexing.businessUnits,
3456
+ newObj: newObj.searchIndexing.businessUnits,
3457
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
3458
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties,
3459
+ shouldPreventUnsettingRequiredFields: config.shouldPreventUnsettingRequiredFields
3460
+ }) : [];
3461
+ var customersActions = customers ? buildBaseAttributesActions({
3462
+ actions: customerSearchActionsList,
3463
+ diff: diff.searchIndexing.customers,
3464
+ oldObj: oldObj.searchIndexing.customers,
3465
+ newObj: newObj.searchIndexing.customers,
3466
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
3467
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties,
3468
+ shouldPreventUnsettingRequiredFields: config.shouldPreventUnsettingRequiredFields
3469
+ }) : [];
3470
+ return [].concat(_toConsumableArray(businessUnitsActions), _toConsumableArray(customersActions));
3471
+ }
3472
+
3473
+ function createChannelsMapActions(mapActionGroup, syncActionConfig) {
3474
+ return function doMapActions(diff, newObj, oldObj) {
3475
+ var allActions = [];
3476
+ allActions.push(mapActionGroup('base', function () {
3477
+ return actionsMapBase$4(diff, oldObj, newObj, syncActionConfig);
3478
+ }));
3479
+ allActions.push(mapActionGroup('businessUnit', function () {
3480
+ return actionsMapBusinessUnit(diff, oldObj, newObj);
3481
+ }));
3482
+ allActions.push(mapActionGroup('searchIndexingConfiguration', function () {
3483
+ return actionsMapSearchIndexingConfiguration(diff, oldObj, newObj);
3484
+ }));
3485
+ return flatten__default["default"](allActions);
3486
+ };
3487
+ }
3488
+ var projects = (function (actionGroupList) {
3489
+ var syncActionConfig = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
3490
+ var mapActionGroup = createMapActionGroup(actionGroupList);
3491
+ var doMapActions = createChannelsMapActions(mapActionGroup, syncActionConfig);
3492
+ var buildActions = createBuildActions(diff, doMapActions);
3493
+ return {
3494
+ buildActions: buildActions
3495
+ };
3496
+ });
3497
+
3498
+ var baseActionsList$3 = [{
3499
+ action: 'setName',
3500
+ key: 'name'
3501
+ }, {
3502
+ action: 'setLanguages',
3503
+ key: 'languages'
3504
+ }, {
3505
+ action: 'setDistributionChannels',
3506
+ key: 'distributionChannels'
3507
+ }, {
3508
+ action: 'setSupplyChannels',
3509
+ key: 'supplyChannels'
3510
+ }];
3511
+ function actionsMapBase$3(diff, oldObj, newObj) {
3512
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
3513
+ return buildBaseAttributesActions({
3514
+ actions: baseActionsList$3,
3515
+ diff: diff,
3516
+ oldObj: oldObj,
3517
+ newObj: newObj,
3518
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
3519
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties,
3520
+ shouldPreventUnsettingRequiredFields: config.shouldPreventUnsettingRequiredFields
3521
+ });
3522
+ }
3523
+
3524
+ function createStoresMapActions(mapActionGroup) {
3525
+ return function doMapActions(diff, next, previous) {
3526
+ var allActions = [];
3527
+ allActions.push(mapActionGroup('base', function () {
3528
+ return actionsMapBase$3(diff, previous, next);
3529
+ }));
3530
+ allActions.push(mapActionGroup('custom', function () {
3531
+ return actionsMapCustom(diff, next, previous);
3532
+ }));
3533
+ return flatten__default["default"](allActions);
3534
+ };
3535
+ }
3536
+ var stores = (function (actionGroupList) {
3537
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
3538
+ var mapActionGroup = createMapActionGroup(actionGroupList);
3539
+ var doMapActions = createStoresMapActions(mapActionGroup);
3540
+ var onBeforeApplyingDiff = null;
3541
+ var buildActions = createBuildActions(diff, doMapActions, onBeforeApplyingDiff, options);
3542
+ return {
3543
+ buildActions: buildActions
3544
+ };
3545
+ });
3546
+
3547
+ var baseActionsList$2 = [{
3548
+ action: 'changeName',
3549
+ key: 'name'
3550
+ }, {
3551
+ action: 'setKey',
3552
+ key: 'key'
3553
+ }];
3554
+ function actionsMapBase$2(diff, oldObj, newObj) {
3555
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
3556
+ return buildBaseAttributesActions({
3557
+ actions: baseActionsList$2,
3558
+ diff: diff,
3559
+ oldObj: oldObj,
3560
+ newObj: newObj,
3561
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
3562
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties,
3563
+ shouldPreventUnsettingRequiredFields: config.shouldPreventUnsettingRequiredFields
3564
+ });
3565
+ }
3566
+
3567
+ function createProductSelectionsMapActions(mapActionGroup) {
3568
+ return function doMapActions(diff, next, previous) {
3569
+ var allActions = [];
3570
+ allActions.push(mapActionGroup('base', function () {
3571
+ return actionsMapBase$2(diff, previous, next);
3572
+ }));
3573
+ allActions.push(mapActionGroup('custom', function () {
3574
+ return actionsMapCustom(diff, next, previous);
3575
+ }));
3576
+ return flatten__default["default"](allActions);
3577
+ };
3578
+ }
3579
+ var productSelections = (function (actionGroupList) {
3580
+ var mapActionGroup = createMapActionGroup(actionGroupList);
3581
+ var doMapActions = createProductSelectionsMapActions(mapActionGroup);
3582
+ var onBeforeApplyingDiff = null;
3583
+ var buildActions = createBuildActions(diff, doMapActions, onBeforeApplyingDiff);
3584
+ return {
3585
+ buildActions: buildActions
3586
+ };
3587
+ });
3588
+
3589
+ var baseActionsList$1 = [{
3590
+ action: 'changeValue',
3591
+ key: 'value'
3592
+ }, {
3593
+ action: 'setDiscountedPrice',
3594
+ key: 'discounted'
3595
+ },
3596
+ // TODO: Later add more accurate actions `addPriceTier`, `removePriceTier`
3597
+ {
3598
+ action: 'setPriceTiers',
3599
+ key: 'tiers'
3600
+ }, {
3601
+ action: 'setKey',
3602
+ key: 'key'
3603
+ }, {
3604
+ action: 'setValidFrom',
3605
+ key: 'validFrom'
3606
+ }, {
3607
+ action: 'setValidUntil',
3608
+ key: 'validUntil'
3609
+ }, {
3610
+ action: 'changeActive',
3611
+ key: 'active'
3612
+ }];
3613
+ function actionsMapBase$1(diff, oldObj, newObj) {
3614
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
3615
+ return buildBaseAttributesActions({
3616
+ actions: baseActionsList$1,
3617
+ diff: diff,
3618
+ oldObj: oldObj,
3619
+ newObj: newObj,
3620
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
3621
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties,
3622
+ shouldPreventUnsettingRequiredFields: config.shouldPreventUnsettingRequiredFields
3623
+ });
3624
+ }
3625
+
3626
+ function createPriceMapActions(mapActionGroup, syncActionConfig) {
3627
+ return function doMapActions(diff, newObj, oldObj) {
3628
+ var baseActions = mapActionGroup('base', function () {
3629
+ return actionsMapBase$1(diff, oldObj, newObj, syncActionConfig);
3630
+ });
3631
+ var customActions = mapActionGroup('custom', function () {
3632
+ return actionsMapCustom(diff, newObj, oldObj);
3633
+ });
3634
+ return combineValidityActions([].concat(_toConsumableArray(baseActions), _toConsumableArray(customActions)));
3635
+ };
3636
+ }
3637
+ var prices = (function (actionGroupList, syncActionConfig) {
3638
+ var mapActionGroup = createMapActionGroup(actionGroupList);
3639
+ var doMapActions = createPriceMapActions(mapActionGroup, syncActionConfig);
3640
+ var buildActions = createBuildActions(diff, doMapActions);
3641
+ return {
3642
+ buildActions: buildActions
3643
+ };
3644
+ });
3645
+
3646
+ var hasAttribute = function hasAttribute(attributes, newValue) {
3647
+ return attributes.some(function (attribute) {
3648
+ return attribute.key === newValue.key;
3649
+ });
3650
+ };
3651
+ var baseActionsList = [{
3652
+ action: 'changeName',
3653
+ key: 'name'
3654
+ }, {
3655
+ action: 'setKey',
3656
+ key: 'key'
3657
+ }, {
3658
+ action: 'setDescription',
3659
+ key: 'description'
3660
+ }];
3661
+ function actionsMapBase(diff, oldObj, newObj) {
3662
+ var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
3663
+ return buildBaseAttributesActions({
3664
+ actions: baseActionsList,
3665
+ diff: diff,
3666
+ oldObj: oldObj,
3667
+ newObj: newObj,
3668
+ shouldOmitEmptyString: config.shouldOmitEmptyString,
3669
+ shouldUnsetOmittedProperties: config.shouldUnsetOmittedProperties,
3670
+ shouldPreventUnsettingRequiredFields: config.shouldPreventUnsettingRequiredFields
3671
+ });
3672
+ }
3673
+ function actionsMapAttributes(diff, oldObj, newObj) {
3674
+ var handler = createBuildArrayActions('attributes', _defineProperty(_defineProperty(_defineProperty({}, ADD_ACTIONS, function (newAttribute) {
3675
+ return {
3676
+ action: 'addAttribute',
3677
+ attribute: newAttribute
3678
+ };
3679
+ }), REMOVE_ACTIONS, function (oldAttribute) {
3680
+ // We only add the action if the attribute is not included in the new object.
3681
+ return !hasAttribute(newObj.attributes, oldAttribute) ? {
3682
+ action: 'removeAttribute',
3683
+ attribute: oldAttribute
3684
+ } : null;
3685
+ }), CHANGE_ACTIONS, function (oldAttribute, newAttribute) {
3686
+ var result = [];
3687
+ // We only remove the attribute in case that the oldAttribute is not
3688
+ // included in the new object
3689
+ if (!hasAttribute(newObj.attributes, oldAttribute)) result.push({
3690
+ action: 'removeAttribute',
3691
+ attribute: oldAttribute
3692
+ });
3693
+
3694
+ // We only add the attribute in case that the newAttribute was not
3695
+ // included in the old object
3696
+ if (!hasAttribute(oldObj.attributes, newAttribute)) result.push({
3697
+ action: 'addAttribute',
3698
+ attribute: newAttribute
3699
+ });
3700
+ return result;
3701
+ }));
3702
+ return handler(diff, oldObj, newObj);
3703
+ }
3704
+
3705
+ function createAttributeGroupsMapActions(mapActionGroup, syncActionConfig) {
3706
+ return function doMapActions(diff, newObj, oldObj) {
3707
+ var allActions = [];
3708
+ allActions.push(mapActionGroup('base', function () {
3709
+ return actionsMapBase(diff, oldObj, newObj, syncActionConfig);
3710
+ }));
3711
+ allActions.push(flatten__default["default"](mapActionGroup('attributes', function () {
3712
+ return actionsMapAttributes(diff, oldObj, newObj);
3713
+ })));
3714
+ return flatten__default["default"](allActions);
3715
+ };
3716
+ }
3717
+ var attributeGroups = (function (actionGroupList, syncActionConfig) {
3718
+ var mapActionGroup = createMapActionGroup(actionGroupList);
3719
+ var doMapActions = createAttributeGroupsMapActions(mapActionGroup, syncActionConfig);
3720
+ var buildActions = createBuildActions(diff, doMapActions);
3721
+ return {
3722
+ buildActions: buildActions
3723
+ };
3724
+ });
3725
+
3726
+ exports.createSyncAttributeGroups = attributeGroups;
3727
+ exports.createSyncCartDiscounts = cartDiscounts;
3728
+ exports.createSyncCategories = categories;
3729
+ exports.createSyncChannels = channels;
3730
+ exports.createSyncCustomerGroup = customerGroup;
3731
+ exports.createSyncCustomers = customers;
3732
+ exports.createSyncDiscountCodes = discountCodes;
3733
+ exports.createSyncInventories = inventories;
3734
+ exports.createSyncOrders = orders;
3735
+ exports.createSyncProductDiscounts = productDiscounts;
3736
+ exports.createSyncProductSelections = productSelections;
3737
+ exports.createSyncProductTypes = productTypes;
3738
+ exports.createSyncProducts = products;
3739
+ exports.createSyncProjects = projects;
3740
+ exports.createSyncRecurringOrders = recurringOrders;
3741
+ exports.createSyncShippingMethods = shippingMethods;
3742
+ exports.createSyncStandalonePrices = prices;
3743
+ exports.createSyncStates = states;
3744
+ exports.createSyncStores = stores;
3745
+ exports.createSyncTaxCategories = taxCategories;
3746
+ exports.createSyncTypes = types;
3747
+ exports.createSyncZones = zones;