From c2b852419958a81ba1c6ba08b440e0517d5cd941 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Tue, 7 Nov 2023 11:21:57 +0100 Subject: [PATCH 01/33] feat(migrate): make compile --- packages/sync-actions/CHANGELOG.md | 155 ++ packages/sync-actions/README.md | 11 + packages/sync-actions/package.json | 51 + packages/sync-actions/src/assets-actions.ts | 41 + .../src/attribute-groups-actions.ts | 70 + packages/sync-actions/src/attribute-groups.ts | 63 + .../src/cart-discounts-actions.ts | 31 + packages/sync-actions/src/cart-discounts.ts | 38 + packages/sync-actions/src/categories.ts | 98 + packages/sync-actions/src/category-actions.ts | 58 + packages/sync-actions/src/channels-actions.ts | 25 + packages/sync-actions/src/channels.ts | 37 + packages/sync-actions/src/customer-actions.ts | 218 ++ .../src/customer-group-actions.ts | 21 + packages/sync-actions/src/customer-group.ts | 37 + packages/sync-actions/src/customers.ts | 133 ++ .../src/discount-codes-actions.ts | 32 + packages/sync-actions/src/discount-codes.ts | 46 + packages/sync-actions/src/index.ts | 21 + packages/sync-actions/src/inventories.ts | 78 + .../sync-actions/src/inventory-actions.ts | 42 + packages/sync-actions/src/order-actions.ts | 226 ++ packages/sync-actions/src/orders.ts | 112 + packages/sync-actions/src/prices-actions.ts | 27 + packages/sync-actions/src/prices.ts | 53 + packages/sync-actions/src/product-actions.ts | 846 ++++++++ .../src/product-discounts-actions.ts | 28 + .../sync-actions/src/product-discounts.ts | 32 + .../src/product-selections-actions.ts | 15 + .../sync-actions/src/product-selections.ts | 57 + .../sync-actions/src/product-types-actions.ts | 325 +++ packages/sync-actions/src/product-types.ts | 73 + packages/sync-actions/src/products.ts | 201 ++ packages/sync-actions/src/projects-actions.ts | 25 + packages/sync-actions/src/projects.ts | 31 + .../src/quote-requests-actions.ts | 21 + packages/sync-actions/src/quote-requests.ts | 67 + packages/sync-actions/src/quotes-actions.ts | 22 + packages/sync-actions/src/quotes.ts | 59 + .../src/shipping-methods-actions.ts | 128 ++ packages/sync-actions/src/shipping-methods.ts | 80 + .../sync-actions/src/staged-quotes-actions.ts | 23 + packages/sync-actions/src/staged-quotes.ts | 67 + packages/sync-actions/src/state-actions.ts | 44 + packages/sync-actions/src/states.ts | 72 + packages/sync-actions/src/stores-actions.ts | 17 + packages/sync-actions/src/stores.ts | 57 + .../src/tax-categories-actions.ts | 48 + packages/sync-actions/src/tax-categories.ts | 74 + packages/sync-actions/src/types-actions.ts | 213 ++ packages/sync-actions/src/types.ts | 50 + .../src/utils/action-map-custom.ts | 82 + packages/sync-actions/src/utils/clone.ts | 3 + .../src/utils/combine-validity-actions.ts | 20 + .../sync-actions/src/utils/common-actions.ts | 125 ++ .../src/utils/copy-empty-array-props.ts | 74 + .../src/utils/create-build-actions.ts | 96 + .../src/utils/create-build-array-actions.ts | 131 ++ .../src/utils/create-map-action-group.ts | 24 + .../sync-actions/src/utils/diffpatcher.ts | 70 + .../src/utils/extract-matching-pairs.ts | 16 + .../src/utils/find-matching-pairs.ts | 47 + packages/sync-actions/src/zones-actions.ts | 70 + packages/sync-actions/src/zones.ts | 68 + ...ct-types-sync-attribute-hints.spec.js.snap | 169 ++ .../test/attribute-groups-sync.spec.ts | 205 ++ .../test/cart-discounts-sync.spec.ts | 449 ++++ .../sync-actions/test/category-sync.spec.ts | 280 +++ .../sync-actions/test/channels-sync-.spec.ts | 215 ++ .../test/customer-group-sync.spec.ts | 136 ++ .../sync-actions/test/customer-sync.spec.ts | 646 ++++++ .../test/discount-codes-sync.spec.ts | 383 ++++ .../sync-actions/test/inventory-sync.spec.ts | 110 + packages/sync-actions/test/order-sync.spec.ts | 906 ++++++++ packages/sync-actions/test/price-sync.spec.ts | 928 +++++++++ .../test/product-discounts-sync.spec.ts | 284 +++ .../test/product-selections-sync.spec.ts | 114 ++ .../test/product-sync-base.spec.ts | 379 ++++ .../test/product-sync-images.spec.ts | 485 +++++ .../test/product-sync-prices.spec.ts | 1118 ++++++++++ .../test/product-sync-variants.spec.ts | 1819 +++++++++++++++++ ...product-types-sync-attribute-hints.spec.ts | 491 +++++ .../test/product-types-sync-base.spec.ts | 360 ++++ .../sync-actions/test/projects-sync.spec.ts | 215 ++ .../test/quote-requests-sync.spec.ts | 129 ++ .../sync-actions/test/quotes-sync.spec.ts | 150 ++ .../test/shipping-methods.spec.ts | 642 ++++++ .../test/staged-quotes-sync.spec.ts | 171 ++ .../sync-actions/test/states-sync.spec.ts | 258 +++ .../sync-actions/test/stores-sync.spec.ts | 175 ++ .../test/tax-categories-sync.spec.ts | 257 +++ .../sync-actions/test/types-sync-base.spec.ts | 118 ++ .../test/types-sync-enums.spec.ts | 616 ++++++ .../test/types-sync-fields.spec.ts | 408 ++++ .../test/utils/action-map-custom.spec.ts | 248 +++ .../utils/combine-validity-actions.spec.ts | 65 + .../test/utils/common-actions.spec.ts | 315 +++ .../test/utils/copy-empty-array-props.spec.ts | 331 +++ .../utils/create-build-array-actions.spec.ts | 155 ++ .../utils/create-map-action-group.spec.ts | 89 + .../test/utils/extract-matching-pairs.spec.ts | 55 + .../test/utils/find-matching-pairs.spec.ts | 34 + packages/sync-actions/test/zones.spec.ts | 214 ++ 103 files changed, 19347 insertions(+) create mode 100644 packages/sync-actions/CHANGELOG.md create mode 100644 packages/sync-actions/README.md create mode 100644 packages/sync-actions/package.json create mode 100644 packages/sync-actions/src/assets-actions.ts create mode 100644 packages/sync-actions/src/attribute-groups-actions.ts create mode 100644 packages/sync-actions/src/attribute-groups.ts create mode 100644 packages/sync-actions/src/cart-discounts-actions.ts create mode 100644 packages/sync-actions/src/cart-discounts.ts create mode 100644 packages/sync-actions/src/categories.ts create mode 100644 packages/sync-actions/src/category-actions.ts create mode 100644 packages/sync-actions/src/channels-actions.ts create mode 100644 packages/sync-actions/src/channels.ts create mode 100644 packages/sync-actions/src/customer-actions.ts create mode 100644 packages/sync-actions/src/customer-group-actions.ts create mode 100644 packages/sync-actions/src/customer-group.ts create mode 100644 packages/sync-actions/src/customers.ts create mode 100644 packages/sync-actions/src/discount-codes-actions.ts create mode 100644 packages/sync-actions/src/discount-codes.ts create mode 100644 packages/sync-actions/src/index.ts create mode 100644 packages/sync-actions/src/inventories.ts create mode 100644 packages/sync-actions/src/inventory-actions.ts create mode 100644 packages/sync-actions/src/order-actions.ts create mode 100644 packages/sync-actions/src/orders.ts create mode 100644 packages/sync-actions/src/prices-actions.ts create mode 100644 packages/sync-actions/src/prices.ts create mode 100644 packages/sync-actions/src/product-actions.ts create mode 100644 packages/sync-actions/src/product-discounts-actions.ts create mode 100644 packages/sync-actions/src/product-discounts.ts create mode 100644 packages/sync-actions/src/product-selections-actions.ts create mode 100644 packages/sync-actions/src/product-selections.ts create mode 100644 packages/sync-actions/src/product-types-actions.ts create mode 100644 packages/sync-actions/src/product-types.ts create mode 100644 packages/sync-actions/src/products.ts create mode 100644 packages/sync-actions/src/projects-actions.ts create mode 100644 packages/sync-actions/src/projects.ts create mode 100644 packages/sync-actions/src/quote-requests-actions.ts create mode 100644 packages/sync-actions/src/quote-requests.ts create mode 100644 packages/sync-actions/src/quotes-actions.ts create mode 100644 packages/sync-actions/src/quotes.ts create mode 100644 packages/sync-actions/src/shipping-methods-actions.ts create mode 100644 packages/sync-actions/src/shipping-methods.ts create mode 100644 packages/sync-actions/src/staged-quotes-actions.ts create mode 100644 packages/sync-actions/src/staged-quotes.ts create mode 100644 packages/sync-actions/src/state-actions.ts create mode 100644 packages/sync-actions/src/states.ts create mode 100644 packages/sync-actions/src/stores-actions.ts create mode 100644 packages/sync-actions/src/stores.ts create mode 100644 packages/sync-actions/src/tax-categories-actions.ts create mode 100644 packages/sync-actions/src/tax-categories.ts create mode 100644 packages/sync-actions/src/types-actions.ts create mode 100644 packages/sync-actions/src/types.ts create mode 100644 packages/sync-actions/src/utils/action-map-custom.ts create mode 100644 packages/sync-actions/src/utils/clone.ts create mode 100644 packages/sync-actions/src/utils/combine-validity-actions.ts create mode 100644 packages/sync-actions/src/utils/common-actions.ts create mode 100644 packages/sync-actions/src/utils/copy-empty-array-props.ts create mode 100644 packages/sync-actions/src/utils/create-build-actions.ts create mode 100644 packages/sync-actions/src/utils/create-build-array-actions.ts create mode 100644 packages/sync-actions/src/utils/create-map-action-group.ts create mode 100644 packages/sync-actions/src/utils/diffpatcher.ts create mode 100644 packages/sync-actions/src/utils/extract-matching-pairs.ts create mode 100644 packages/sync-actions/src/utils/find-matching-pairs.ts create mode 100644 packages/sync-actions/src/zones-actions.ts create mode 100644 packages/sync-actions/src/zones.ts create mode 100644 packages/sync-actions/test/__snapshots__/product-types-sync-attribute-hints.spec.js.snap create mode 100644 packages/sync-actions/test/attribute-groups-sync.spec.ts create mode 100644 packages/sync-actions/test/cart-discounts-sync.spec.ts create mode 100644 packages/sync-actions/test/category-sync.spec.ts create mode 100644 packages/sync-actions/test/channels-sync-.spec.ts create mode 100644 packages/sync-actions/test/customer-group-sync.spec.ts create mode 100644 packages/sync-actions/test/customer-sync.spec.ts create mode 100644 packages/sync-actions/test/discount-codes-sync.spec.ts create mode 100644 packages/sync-actions/test/inventory-sync.spec.ts create mode 100644 packages/sync-actions/test/order-sync.spec.ts create mode 100644 packages/sync-actions/test/price-sync.spec.ts create mode 100644 packages/sync-actions/test/product-discounts-sync.spec.ts create mode 100644 packages/sync-actions/test/product-selections-sync.spec.ts create mode 100644 packages/sync-actions/test/product-sync-base.spec.ts create mode 100644 packages/sync-actions/test/product-sync-images.spec.ts create mode 100644 packages/sync-actions/test/product-sync-prices.spec.ts create mode 100644 packages/sync-actions/test/product-sync-variants.spec.ts create mode 100644 packages/sync-actions/test/product-types-sync-attribute-hints.spec.ts create mode 100644 packages/sync-actions/test/product-types-sync-base.spec.ts create mode 100644 packages/sync-actions/test/projects-sync.spec.ts create mode 100644 packages/sync-actions/test/quote-requests-sync.spec.ts create mode 100644 packages/sync-actions/test/quotes-sync.spec.ts create mode 100644 packages/sync-actions/test/shipping-methods.spec.ts create mode 100644 packages/sync-actions/test/staged-quotes-sync.spec.ts create mode 100644 packages/sync-actions/test/states-sync.spec.ts create mode 100644 packages/sync-actions/test/stores-sync.spec.ts create mode 100644 packages/sync-actions/test/tax-categories-sync.spec.ts create mode 100644 packages/sync-actions/test/types-sync-base.spec.ts create mode 100644 packages/sync-actions/test/types-sync-enums.spec.ts create mode 100644 packages/sync-actions/test/types-sync-fields.spec.ts create mode 100644 packages/sync-actions/test/utils/action-map-custom.spec.ts create mode 100644 packages/sync-actions/test/utils/combine-validity-actions.spec.ts create mode 100644 packages/sync-actions/test/utils/common-actions.spec.ts create mode 100644 packages/sync-actions/test/utils/copy-empty-array-props.spec.ts create mode 100644 packages/sync-actions/test/utils/create-build-array-actions.spec.ts create mode 100644 packages/sync-actions/test/utils/create-map-action-group.spec.ts create mode 100644 packages/sync-actions/test/utils/extract-matching-pairs.spec.ts create mode 100644 packages/sync-actions/test/utils/find-matching-pairs.spec.ts create mode 100644 packages/sync-actions/test/zones.spec.ts diff --git a/packages/sync-actions/CHANGELOG.md b/packages/sync-actions/CHANGELOG.md new file mode 100644 index 000000000..665d3d75e --- /dev/null +++ b/packages/sync-actions/CHANGELOG.md @@ -0,0 +1,155 @@ +# @commercetools/sync-actions + +## 5.15.0 + +### Minor Changes + +- [#1885](https://github.com/commercetools/nodejs/pull/1885) [`d6cb2740`](https://github.com/commercetools/nodejs/commit/d6cb27401279cb42a49366f32802f8ca8c7f01a3) Thanks [@kafis](https://github.com/kafis)! - Add support for 'changeAssetOrder' in (ProductVariants)[https://docs.commercetools.com/api/projects/products#change-asset-order]. + +## 5.14.0 + +### Minor Changes + +- [#1876](https://github.com/commercetools/nodejs/pull/1876) [`27f0d2b6`](https://github.com/commercetools/nodejs/commit/27f0d2b66fefbe082b6a27e7fa940b09e7e6088c) Thanks [@jaikumar-tj](https://github.com/jaikumar-tj)! - Add support for attribute groups `changeName`, `setKey`, `setDescription`, `addAttribute` and `removeAttribute` actions. + +## 5.13.0 + +### Minor Changes + +- [#1874](https://github.com/commercetools/nodejs/pull/1874) [`69f4501d`](https://github.com/commercetools/nodejs/commit/69f4501dc5401ab2b44f4d3096a978094e402c9f) Thanks [@taylor-knapp](https://github.com/taylor-knapp)! - Handle long text values performantly + +## 5.12.2 + +### Patch Changes + +- [#1871](https://github.com/commercetools/nodejs/pull/1871) [`4f8ea39b`](https://github.com/commercetools/nodejs/commit/4f8ea39b66ddd5014ac8f923ed980584bd96290c) Thanks [@ARRIOLALEO](https://github.com/ARRIOLALEO)! - rollback setPriceTiers name change + +## 5.12.1 + +### Patch Changes + +- [#1869](https://github.com/commercetools/nodejs/pull/1869) [`7285a9fb`](https://github.com/commercetools/nodejs/commit/7285a9fbcbcfca6a9460e36ba7b58bb30f34fac6) Thanks [@ARRIOLALEO](https://github.com/ARRIOLALEO)! - Add support for StandalonePrice `setPriceTier` + +## 5.12.0 + +### Minor Changes + +- [#1863](https://github.com/commercetools/nodejs/pull/1863) [`7ed7a663`](https://github.com/commercetools/nodejs/commit/7ed7a663c1cb3aa87bfb4b4c2c008949a66a62e0) Thanks [@ragafus](https://github.com/ragafus)! - Add support for StandalonePrice `setKey`, `setValidFrom`, `setValidUntil`, `setValidFromAndUntil` and `changeActive` actions. + +## 5.11.0 + +### Minor Changes + +- [#1864](https://github.com/commercetools/nodejs/pull/1864) [`91f6b617`](https://github.com/commercetools/nodejs/commit/91f6b61794e7d66766097965e452e14c85e40f14) Thanks [@ARRIOLALEO](https://github.com/ARRIOLALEO)! - Add support for StandalonePrice `setPriceTiers` + +## 5.10.0 + +### Minor Changes + +- [#1856](https://github.com/commercetools/nodejs/pull/1856) [`9a3e3711`](https://github.com/commercetools/nodejs/commit/9a3e3711bf6594deafb5d54a9ce9e32450f9c4d6) Thanks [@qmateub](https://github.com/qmateub)! - orders sync-actions: support action on delivery items `setDeliveryItems` + +## 5.9.0 + +### Minor Changes + +- [#1853](https://github.com/commercetools/nodejs/pull/1853) [`4bb8f979`](https://github.com/commercetools/nodejs/commit/4bb8f979c317bbce1654ca0f1abc9b4717fdda0b) Thanks [@markus-azer](https://github.com/markus-azer)! - types sync-actions: support the following actions `changeInputHint`, `changeEnumValueLabel`, `changeLocalizedEnumValueLabel`. + +## 5.8.0 + +### Minor Changes + +- [#1852](https://github.com/commercetools/nodejs/pull/1852) [`94a376c8`](https://github.com/commercetools/nodejs/commit/94a376c89525b7cee58b710154ddf7cb146cd16c) Thanks [@markus-azer](https://github.com/markus-azer)! - types sync-actions: fix action structure for changeFieldDefinitionOrder + fix internal type sync error by adding optional chaining + +## 5.7.0 + +### Minor Changes + +- [#1850](https://github.com/commercetools/nodejs/pull/1850) [`330cd9a9`](https://github.com/commercetools/nodejs/commit/330cd9a9b4fca045d479d2d220d2a2a2b966b1f4) Thanks [@markus-azer](https://github.com/markus-azer)! - types sync-actions: fix action structure for changeLocalizedEnumValueOrder, changeEnumValueOrder + +## 5.6.0 + +### Minor Changes + +- [#1844](https://github.com/commercetools/nodejs/pull/1844) [`23f0529b`](https://github.com/commercetools/nodejs/commit/23f0529bbf359a11500dbf87bdc9e59cb759c89a) Thanks [@markus-azer](https://github.com/markus-azer)! - Add localizedName action to shipping methods + +## 5.5.0 + +### Minor Changes + +- [#1841](https://github.com/commercetools/nodejs/pull/1841) [`b90c7238`](https://github.com/commercetools/nodejs/commit/b90c7238f0d3d892e1066fd2883cff062b099e66) Thanks [@Rombelirk](https://github.com/Rombelirk)! - Add Custom Fields to Shipping Methods. + +## 5.4.1 + +### Patch Changes + +- [#1839](https://github.com/commercetools/nodejs/pull/1839) [`d6cadcbc`](https://github.com/commercetools/nodejs/commit/d6cadcbc4b850fa6f438b65c3b63b294a32a58ee) Thanks [@tdeekens](https://github.com/tdeekens)! - Fix failing to sync froozen arrays for prices + +## 5.4.0 + +### Minor Changes + +- [#1836](https://github.com/commercetools/nodejs/pull/1836) [`ad34d030`](https://github.com/commercetools/nodejs/commit/ad34d03041e7e6b8284da6224dc968fde537a85a) Thanks [@nicolasnieto92](https://github.com/nicolasnieto92)! - Add setAuthenticationMode sync action + +## 5.3.1 + +### Patch Changes + +- [#1818](https://github.com/commercetools/nodejs/pull/1818) [`856929e3`](https://github.com/commercetools/nodejs/commit/856929e3bc176021a9b52e1ff9c888e51c83cccd) Thanks [@qmateub](https://github.com/qmateub)! - fix(sync-actions/orders): adjust diff calculation of returnInfo items + +## 5.3.0 + +### Minor Changes + +- [#1820](https://github.com/commercetools/nodejs/pull/1820) [`c3964026`](https://github.com/commercetools/nodejs/commit/c3964026b401cb1c8ae8b581a3fcc4ea692ed3b4) Thanks [@danrleyt](https://github.com/danrleyt)! - Adding support to quote requests and staged quotes + +## 5.2.0 + +### Minor Changes + +- [`cad54c42`](https://github.com/commercetools/nodejs/commit/cad54c421e18464ae03fb283a30f2ba2f3f6e46a) Thanks [@qmateub](https://github.com/qmateub)! - feat(sync-actions): improve performance for large arrays comparisons" + +## 5.1.0 + +### Minor Changes + +- [#1803](https://github.com/commercetools/nodejs/pull/1803) [`823985ae`](https://github.com/commercetools/nodejs/commit/823985ae67465673c26f296b68681f255230d571) Thanks [@nicolasnieto92](https://github.com/nicolasnieto92)! - Add createSyncStandalonePrices export to index for supporting prices sync actions + +## 5.0.0 + +### Major Changes + +- [#1775](https://github.com/commercetools/nodejs/pull/1775) [`35669f30`](https://github.com/commercetools/nodejs/commit/35669f30dbc4b24d59ec3df3f38417b1f2a77837) Thanks [@ajimae](https://github.com/ajimae)! - Drop support for Node `v10` and `v12`. Supported versions now are `v14`, `v16` and `v18`. + +## 4.13.0 + +### Minor Changes + +- [#1798](https://github.com/commercetools/nodejs/pull/1798) [`850325d0`](https://github.com/commercetools/nodejs/commit/850325d08603764787c387b2341e4009d0c4f788) Thanks [@markus-azer](https://github.com/markus-azer)! - support standalone prices + +## 4.12.0 + +### Minor Changes + +- [#1796](https://github.com/commercetools/nodejs/pull/1796) [`7aaf91cd`](https://github.com/commercetools/nodejs/commit/7aaf91cdecb7c844943369fc137a5356becdba36) Thanks [@VineetKumarKushwaha](https://github.com/VineetKumarKushwaha)! - Fix custom types sync actions to detect addEnumValue action correctly + +## 4.11.0 + +### Minor Changes + +- [#1788](https://github.com/commercetools/nodejs/pull/1788) [`f1acfb67`](https://github.com/commercetools/nodejs/commit/f1acfb67708d8253f551481fd65097add48c6686) Thanks [@nicolasnieto92](https://github.com/nicolasnieto92)! - Add setPriceMode sync action for commercetools-importer project + +## 4.10.1 + +### Patch Changes + +- [#1770](https://github.com/commercetools/nodejs/pull/1770) [`381d1e1f`](https://github.com/commercetools/nodejs/commit/381d1e1f07cc2705962973e3a48934bf7884e309) Thanks [@mohib0306](https://github.com/mohib0306)! - Fix product selection's name update action. `setName` => `changeName` + Expose `createSyncProductSelections` from `sync-actions` package + +## 4.10.0 + +### Minor Changes + +- [#1767](https://github.com/commercetools/nodejs/pull/1767) [`1aef3423`](https://github.com/commercetools/nodejs/commit/1aef3423e96da7f5df20fd5f66ec29146cacee83) Thanks [@mohib0306](https://github.com/mohib0306)! - feat(sync-actions/product-selections): add sync action support for product selections + + As product selections are available via the API, the sync-actions package is updated to support generating update actions for product selections. diff --git a/packages/sync-actions/README.md b/packages/sync-actions/README.md new file mode 100644 index 000000000..3d0c0ea96 --- /dev/null +++ b/packages/sync-actions/README.md @@ -0,0 +1,11 @@ +# commercetools-sync-actions + +Construct API update actions, for usage with `@commercetools/sdk-client`. + +https://commercetools.github.io/nodejs/sdk/api/syncActions.html + +## Install + +```bash +npm install --save @commercetools/sync-actions +``` diff --git a/packages/sync-actions/package.json b/packages/sync-actions/package.json new file mode 100644 index 000000000..ead2f182a --- /dev/null +++ b/packages/sync-actions/package.json @@ -0,0 +1,51 @@ +{ + "name": "@commercetools/sync-actions", + "version": "1.0.0", + "engines": { + "node": ">=14" + }, + "description": "Build API update actions for the commercetools platform.", + "keywords": ["commercetools", "sync", "actions"], + "homepage": "https://commercetools.github.io/nodejs/", + "license": "MIT", + "directories": { + "lib": "lib", + "test": "test" + }, + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/commercetools/commercetools-sdk-typescript.git" + }, + "bugs": { + "url": "https://github.com/commercetools/commercetools-sdk-typescript/issues" + }, + "dependencies": { + "fast-equals": "^2.0.0", + "jsondiffpatch": "^0.4.0", + "lodash.flatten": "^4.4.0", + "lodash.foreach": "^4.5.0", + "lodash.intersection": "^4.4.0", + "lodash.isequal": "^4.5.0", + "lodash.isnil": "^4.0.0", + "lodash.shuffle": "^4.2.0", + "lodash.sortby": "^4.7.0", + "lodash.uniqwith": "^4.5.0", + "lodash.without": "^4.4.0" + }, + "files": ["dist", "CHANGELOG.md"], + "author": "Nicola Molinari (https://github.com/emmenko)", + "main": "dist/commercetools-sync-actions.cjs.js", + "module": "dist/commercetools-sync-actions.esm.js", + "browser": { + "./dist/commercetools-sync-actions.cjs.js": "./dist/commercetools-sync-actions.browser.cjs.js", + "./dist/commercetools-sync-actions.esm.js": "./dist/commercetools-sync-actions.browser.esm.js" + }, + "scripts": { + "organize_imports": "find src -type f -name '*.ts' | xargs organize-imports-cli", + "postbuild": "yarn organize_imports", + "post_process_generate": "yarn organize_imports" + } +} diff --git a/packages/sync-actions/src/assets-actions.ts b/packages/sync-actions/src/assets-actions.ts new file mode 100644 index 000000000..3f08c4ccd --- /dev/null +++ b/packages/sync-actions/src/assets-actions.ts @@ -0,0 +1,41 @@ +import createBuildArrayActions, { + ADD_ACTIONS, + REMOVE_ACTIONS, + CHANGE_ACTIONS, +} from './utils/create-build-array-actions' + +function toAssetIdentifier(asset) { + const assetIdentifier = asset.id + ? { assetId: asset.id } + : { assetKey: asset.key } + return assetIdentifier +} + +export default function actionsMapAssets(diff, oldObj, newObj) { + const handler = createBuildArrayActions('assets', { + [ADD_ACTIONS]: (newAsset) => ({ + action: 'addAsset', + asset: newAsset, + }), + [REMOVE_ACTIONS]: (oldAsset) => ({ + action: 'removeAsset', + ...toAssetIdentifier(oldAsset), + }), + [CHANGE_ACTIONS]: (oldAsset, newAsset) => + // here we could use more atomic update actions (e.g. changeAssetName) + // but for now we use the simpler approach to first remove and then + // re-add the asset - which reduces the code complexity + [ + { + action: 'removeAsset', + ...toAssetIdentifier(oldAsset), + }, + { + action: 'addAsset', + asset: newAsset, + }, + ], + }) + + return handler(diff, oldObj, newObj) +} diff --git a/packages/sync-actions/src/attribute-groups-actions.ts b/packages/sync-actions/src/attribute-groups-actions.ts new file mode 100644 index 000000000..7f3d8dbb6 --- /dev/null +++ b/packages/sync-actions/src/attribute-groups-actions.ts @@ -0,0 +1,70 @@ +import { buildBaseAttributesActions } from './utils/common-actions' +import createBuildArrayActions, { + ADD_ACTIONS, + REMOVE_ACTIONS, + CHANGE_ACTIONS, +} from './utils/create-build-array-actions' + +const hasAttribute = (attributes, newValue) => + attributes.some((attribute) => attribute.key === newValue.key) + +export const baseActionsList = [ + { action: 'changeName', key: 'name' }, + { action: 'setKey', key: 'key' }, + { action: 'setDescription', key: 'description' }, +] + +export function actionsMapBase( + diff, + oldObj, + newObj, + config: { shouldOmitEmptyString?: boolean } = {} +) { + return buildBaseAttributesActions({ + actions: baseActionsList, + diff, + oldObj, + newObj, + shouldOmitEmptyString: config.shouldOmitEmptyString, + }) +} + +export function actionsMapAttributes(diff, oldObj, newObj) { + const handler = createBuildArrayActions('attributes', { + [ADD_ACTIONS]: (newAttribute) => ({ + action: 'addAttribute', + attribute: newAttribute, + }), + [REMOVE_ACTIONS]: (oldAttribute) => { + // We only add the action if the attribute is not included in the new object. + return !hasAttribute(newObj.attributes, oldAttribute) + ? { + action: 'removeAttribute', + attribute: oldAttribute, + } + : null + }, + [CHANGE_ACTIONS]: (oldAttribute, newAttribute) => { + const result = [] + // We only remove the attribute in case that the oldAttribute is not + // included in the new object + if (!hasAttribute(newObj.attributes, oldAttribute)) + result.push({ + action: 'removeAttribute', + attribute: oldAttribute, + }) + + // We only add the attribute in case that the newAttribute was not + // included in the old object + if (!hasAttribute(oldObj.attributes, newAttribute)) + result.push({ + action: 'addAttribute', + attribute: newAttribute, + }) + + return result + }, + }) + + return handler(diff, oldObj, newObj) +} diff --git a/packages/sync-actions/src/attribute-groups.ts b/packages/sync-actions/src/attribute-groups.ts new file mode 100644 index 000000000..a193f76c5 --- /dev/null +++ b/packages/sync-actions/src/attribute-groups.ts @@ -0,0 +1,63 @@ +/* @flow */ +import flatten from 'lodash.flatten' +import type { + SyncAction, + ActionGroup, + UpdateAction, + SyncActionConfig, +} from '@commercetools/sdk-client-v2' +import * as attributeGroupsActions from './attribute-groups-actions' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import * as diffpatcher from './utils/diffpatcher' + +function createAttributeGroupsMapActions( + mapActionGroup: ( + type: string, + fn: () => Array + ) => Array, + syncActionConfig?: SyncActionConfig +): (diff: any, newObj: any, oldObj: any) => Array { + return function doMapActions( + diff: any, + newObj: any, + oldObj: any + ): Array { + const allActions = [] + allActions.push( + mapActionGroup( + 'base', + (): Array => + attributeGroupsActions.actionsMapBase( + diff, + oldObj, + newObj, + syncActionConfig + ) + ) + ) + allActions.push( + flatten( + mapActionGroup( + 'attributes', + (): Array => + attributeGroupsActions.actionsMapAttributes(diff, oldObj, newObj) + ) + ) + ) + return flatten(allActions) + } +} + +export default ( + actionGroupList?: Array, + syncActionConfig?: SyncActionConfig +): SyncAction => { + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createAttributeGroupsMapActions( + mapActionGroup, + syncActionConfig + ) + const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + return { buildActions } +} diff --git a/packages/sync-actions/src/cart-discounts-actions.ts b/packages/sync-actions/src/cart-discounts-actions.ts new file mode 100644 index 000000000..7ef4e27be --- /dev/null +++ b/packages/sync-actions/src/cart-discounts-actions.ts @@ -0,0 +1,31 @@ +import { buildBaseAttributesActions } from './utils/common-actions' + +export const baseActionsList = [ + { action: 'changeIsActive', key: 'isActive' }, + { action: 'changeName', key: 'name' }, + { action: 'changeCartPredicate', key: 'cartPredicate' }, + { action: 'changeSortOrder', key: 'sortOrder' }, + { action: 'changeValue', key: 'value' }, + { action: 'changeRequiresDiscountCode', key: 'requiresDiscountCode' }, + { action: 'changeTarget', key: 'target' }, + { action: 'setDescription', key: 'description' }, + { action: 'setValidFrom', key: 'validFrom' }, + { action: 'setValidUntil', key: 'validUntil' }, + { action: 'changeStackingMode', key: 'stackingMode' }, + { action: 'setKey', key: 'key' }, +] + +export function actionsMapBase( + diff, + oldObj, + newObj, + config: { shouldOmitEmptyString?: boolean } = {} +) { + return buildBaseAttributesActions({ + actions: baseActionsList, + diff, + oldObj, + newObj, + shouldOmitEmptyString: config.shouldOmitEmptyString, + }) +} diff --git a/packages/sync-actions/src/cart-discounts.ts b/packages/sync-actions/src/cart-discounts.ts new file mode 100644 index 000000000..3c7c2b941 --- /dev/null +++ b/packages/sync-actions/src/cart-discounts.ts @@ -0,0 +1,38 @@ +import flatten from 'lodash.flatten' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import actionsMapCustom from './utils/action-map-custom' +import { actionsMapBase } from './cart-discounts-actions' +import combineValidityActions from './utils/combine-validity-actions' +import * as diffpatcher from './utils/diffpatcher' +import { SyncActionConfig } from '@commercetools/sdk-client-v2' + +export const actionGroups = ['base', 'custom'] + +function createCartDiscountsMapActions(mapActionGroup, syncActionConfig) { + return function doMapActions(diff, newObj, oldObj) { + const allActions = [] + + allActions.push( + mapActionGroup('base', () => + actionsMapBase(diff, oldObj, newObj, syncActionConfig) + ) + ) + + allActions.push( + mapActionGroup('custom', () => actionsMapCustom(diff, newObj, oldObj)) + ) + + return combineValidityActions(flatten(allActions)) + } +} + +export default (actionGroupList?, syncActionConfig?: SyncActionConfig) => { + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createCartDiscountsMapActions( + mapActionGroup, + syncActionConfig + ) + const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + return { buildActions } +} diff --git a/packages/sync-actions/src/categories.ts b/packages/sync-actions/src/categories.ts new file mode 100644 index 000000000..92d71f098 --- /dev/null +++ b/packages/sync-actions/src/categories.ts @@ -0,0 +1,98 @@ +/* @flow */ +import flatten from 'lodash.flatten' +import type { + SyncAction, + SyncActionConfig, + UpdateAction, + ActionGroup, +} from '@commercetools/sdk-client-v2' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import actionsMapCustom from './utils/action-map-custom' +import actionsMapAssets from './assets-actions' +import * as categoryActions from './category-actions' +import * as diffpatcher from './utils/diffpatcher' +import copyEmptyArrayProps from './utils/copy-empty-array-props' + +export const actionGroups = ['base', 'references', 'meta', 'custom', 'assets'] + +function createCategoryMapActions( + mapActionGroup: Function, + syncActionConfig?: SyncActionConfig +): (diff: any, newObj: any, oldObj: any) => Array { + return function doMapActions( + diff: any, + newObj: any, + oldObj: any /* , options */ + ): Array { + const allActions = [] + + allActions.push( + mapActionGroup( + 'base', + (): Array => + categoryActions.actionsMapBase(diff, oldObj, newObj, syncActionConfig) + ) + ) + + allActions.push( + mapActionGroup( + 'references', + (): Array => + categoryActions.actionsMapReferences(diff, oldObj, newObj) + ) + ) + + allActions.push( + mapActionGroup( + 'meta', + (): Array => + categoryActions.actionsMapMeta(diff, oldObj, newObj) + ) + ) + + allActions.push( + mapActionGroup( + 'custom', + (): Array => actionsMapCustom(diff, newObj, oldObj) + ) + ) + + allActions.push( + mapActionGroup( + 'assets', + (): Array => actionsMapAssets(diff, oldObj, newObj) + ) + ) + + return flatten(allActions) + } +} + +export default ( + actionGroupList?: Array, + syncActionConfig?: SyncActionConfig +): SyncAction => { + // actionGroupList contains information about which action groups + // are allowed or ignored + + // createMapActionGroup returns function 'mapActionGroup' that takes params: + // - action group name + // - callback function that should return a list of actions that correspond + // to the for the action group + + // this resulting function mapActionGroup will call the callback function + // for allowed action groups and return the return value of the callback + // It will return an empty array for ignored action groups + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createCategoryMapActions( + mapActionGroup, + syncActionConfig + ) + const buildActions = createBuildActions( + diffpatcher.diff, + doMapActions, + copyEmptyArrayProps + ) + return { buildActions } +} diff --git a/packages/sync-actions/src/category-actions.ts b/packages/sync-actions/src/category-actions.ts new file mode 100644 index 000000000..0e23ee5fd --- /dev/null +++ b/packages/sync-actions/src/category-actions.ts @@ -0,0 +1,58 @@ +import { + buildBaseAttributesActions, + buildReferenceActions, +} from './utils/common-actions' + +export const baseActionsList = [ + { action: 'changeName', key: 'name' }, + { action: 'changeSlug', key: 'slug' }, + { action: 'setDescription', key: 'description' }, + { action: 'changeOrderHint', key: 'orderHint' }, + { action: 'setExternalId', key: 'externalId' }, + { action: 'setKey', key: 'key' }, +] + +export const metaActionsList = [ + { action: 'setMetaTitle', key: 'metaTitle' }, + { action: 'setMetaKeywords', key: 'metaKeywords' }, + { action: 'setMetaDescription', key: 'metaDescription' }, +] + +export const referenceActionsList = [{ action: 'changeParent', key: 'parent' }] + +/** + * SYNC FUNCTIONS + */ + +export function actionsMapBase( + diff, + oldObj, + newObj, + config: { shouldOmitEmptyString?: boolean } = {} +) { + return buildBaseAttributesActions({ + actions: baseActionsList, + diff, + oldObj, + newObj, + shouldOmitEmptyString: config.shouldOmitEmptyString, + }) +} + +export function actionsMapReferences(diff, oldObj, newObj) { + return buildReferenceActions({ + actions: referenceActionsList, + diff, + oldObj, + newObj, + }) +} + +export function actionsMapMeta(diff, oldObj, newObj) { + return buildBaseAttributesActions({ + actions: metaActionsList, + diff, + oldObj, + newObj, + }) +} diff --git a/packages/sync-actions/src/channels-actions.ts b/packages/sync-actions/src/channels-actions.ts new file mode 100644 index 000000000..2459c4e02 --- /dev/null +++ b/packages/sync-actions/src/channels-actions.ts @@ -0,0 +1,25 @@ +import { buildBaseAttributesActions } from './utils/common-actions' + +export const baseActionsList = [ + { action: 'changeKey', key: 'key' }, + { action: 'changeName', key: 'name' }, + { action: 'changeDescription', key: 'description' }, + { action: 'setAddress', key: 'address' }, + { action: 'setGeoLocation', key: 'geoLocation' }, + { action: 'setRoles', key: 'roles' }, +] + +export function actionsMapBase( + diff, + oldObj, + newObj, + config: { shouldOmitEmptyString?: boolean } = {} +) { + return buildBaseAttributesActions({ + actions: baseActionsList, + diff, + oldObj, + newObj, + shouldOmitEmptyString: config.shouldOmitEmptyString, + }) +} diff --git a/packages/sync-actions/src/channels.ts b/packages/sync-actions/src/channels.ts new file mode 100644 index 000000000..a59a86077 --- /dev/null +++ b/packages/sync-actions/src/channels.ts @@ -0,0 +1,37 @@ +import flatten from 'lodash.flatten' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import actionsMapCustom from './utils/action-map-custom' +import { actionsMapBase } from './channels-actions' +import * as diffpatcher from './utils/diffpatcher' +import { SyncActionConfig } from '@commercetools/sdk-client-v2' + +export const actionGroups = ['base', 'custom'] + +function createChannelsMapActions(mapActionGroup, syncActionConfig) { + return function doMapActions(diff, newObj, oldObj) { + const allActions = [] + + allActions.push( + mapActionGroup('base', () => + actionsMapBase(diff, oldObj, newObj, syncActionConfig) + ) + ) + + allActions.push( + mapActionGroup('custom', () => actionsMapCustom(diff, newObj, oldObj)) + ) + + return flatten(allActions) + } +} + +export default (actionGroupList?, syncActionConfig?: SyncActionConfig) => { + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createChannelsMapActions( + mapActionGroup, + syncActionConfig + ) + const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + return { buildActions } +} diff --git a/packages/sync-actions/src/customer-actions.ts b/packages/sync-actions/src/customer-actions.ts new file mode 100644 index 000000000..4582a7760 --- /dev/null +++ b/packages/sync-actions/src/customer-actions.ts @@ -0,0 +1,218 @@ +import isNil from 'lodash.isnil' +import { + buildBaseAttributesActions, + buildReferenceActions, + createIsEmptyValue, +} from './utils/common-actions' +import createBuildArrayActions, { + ADD_ACTIONS, + REMOVE_ACTIONS, + CHANGE_ACTIONS, +} from './utils/create-build-array-actions' +import * as diffpatcher from './utils/diffpatcher' +import clone from './utils/clone' + +const isEmptyValue = createIsEmptyValue([undefined, null, '']) + +export const baseActionsList = [ + { action: 'setSalutation', key: 'salutation' }, + { action: 'changeEmail', key: 'email' }, + { action: 'setFirstName', key: 'firstName' }, + { action: 'setLastName', key: 'lastName' }, + { action: 'setMiddleName', key: 'middleName' }, + { action: 'setTitle', key: 'title' }, + { action: 'setCustomerNumber', key: 'customerNumber' }, + { action: 'setExternalId', key: 'externalId' }, + { action: 'setCompanyName', key: 'companyName' }, + { action: 'setDateOfBirth', key: 'dateOfBirth' }, + { action: 'setLocale', key: 'locale' }, + { action: 'setVatId', key: 'vatId' }, + { + action: 'setStores', + key: 'stores', + }, + { action: 'setKey', key: 'key' }, +] + +export const setDefaultBaseActionsList = [ + { + action: 'setDefaultBillingAddress', + key: 'defaultBillingAddressId', + actionKey: 'addressId', + }, + { + action: 'setDefaultShippingAddress', + key: 'defaultShippingAddressId', + actionKey: 'addressId', + }, +] + +export const referenceActionsList = [ + { action: 'setCustomerGroup', key: 'customerGroup' }, +] + +export const authenticationModeActionsList = [ + { + action: 'setAuthenticationMode', + key: 'authenticationMode', + value: 'password', + }, +] + +/** + * SYNC FUNCTIONS + */ + +export function actionsMapBase( + diff, + oldObj, + newObj, + config: { shouldOmitEmptyString?: boolean } = {} +) { + return buildBaseAttributesActions({ + actions: baseActionsList, + diff, + oldObj, + newObj, + shouldOmitEmptyString: config.shouldOmitEmptyString, + }) +} + +export function actionsMapSetDefaultBase( + diff, + oldObj, + newObj, + config: { shouldOmitEmptyString?: boolean } = {} +) { + return buildBaseAttributesActions({ + actions: setDefaultBaseActionsList, + diff, + oldObj, + newObj, + shouldOmitEmptyString: config.shouldOmitEmptyString, + }) +} + +export function actionsMapReferences(diff, oldObj, newObj) { + return buildReferenceActions({ + actions: referenceActionsList, + diff, + oldObj, + newObj, + }) +} + +export function actionsMapAddresses(diff, oldObj, newObj) { + const handler = createBuildArrayActions('addresses', { + [ADD_ACTIONS]: (newObject) => ({ + action: 'addAddress', + address: newObject, + }), + [REMOVE_ACTIONS]: (objectToRemove) => ({ + action: 'removeAddress', + addressId: objectToRemove.id, + }), + [CHANGE_ACTIONS]: (oldObject, updatedObject) => ({ + action: 'changeAddress', + addressId: oldObject.id, + address: updatedObject, + }), + }) + + return handler(diff, oldObj, newObj) +} + +export function actionsMapBillingAddresses(diff, oldObj, newObj) { + const handler = createBuildArrayActions('billingAddressIds', { + [ADD_ACTIONS]: (addressId) => ({ + action: 'addBillingAddressId', + addressId, + }), + [REMOVE_ACTIONS]: (addressId) => ({ + action: 'removeBillingAddressId', + addressId, + }), + }) + + return handler(diff, oldObj, newObj) +} + +export function actionsMapShippingAddresses(diff, oldObj, newObj) { + const handler = createBuildArrayActions('shippingAddressIds', { + [ADD_ACTIONS]: (addressId) => ({ + action: 'addShippingAddressId', + addressId, + }), + [REMOVE_ACTIONS]: (addressId) => ({ + action: 'removeShippingAddressId', + addressId, + }), + }) + + return handler(diff, oldObj, newObj) +} + +export function actionsMapAuthenticationModes(diff, oldObj, newObj) { + // eslint-disable-next-line no-use-before-define + return buildAuthenticationModeActions({ + actions: authenticationModeActionsList, + diff, + oldObj, + newObj, + }) +} + +function buildAuthenticationModeActions({ actions, diff, oldObj, newObj }) { + return actions + .map((item) => { + const key = item.key + const value = item.value || item.key + const delta = diff[key] + const before = oldObj[key] + const now = newObj[key] + const isNotDefinedBefore = isEmptyValue(oldObj[key]) + const isNotDefinedNow = isEmptyValue(newObj[key]) + const authenticationModes = ['Password', 'ExternalAuth'] + + if (!delta) return undefined + + if (isNotDefinedNow && isNotDefinedBefore) return undefined + + if (newObj.authenticationMode === 'Password' && !newObj.password) + throw new Error( + 'Cannot set to Password authentication mode without password' + ) + + if ( + 'authenticationMode' in newObj && + !authenticationModes.includes(newObj.authenticationMode) + ) + throw new Error('Invalid Authentication Mode') + + if (!isNotDefinedNow && isNotDefinedBefore) { + // no value previously set + if (newObj.authenticationMode === 'ExternalAuth') + return { action: item.action, authMode: now } + return { action: item.action, authMode: now, [value]: newObj.password } + } + + /* no new value */ + if (isNotDefinedNow && !{}.hasOwnProperty.call(newObj, key)) + return undefined + + if (isNotDefinedNow && {}.hasOwnProperty.call(newObj, key)) + // value unset + return undefined + + // We need to clone `before` as `patch` will mutate it + const patched = diffpatcher.patch(clone(before), delta) + if (newObj.authenticationMode === 'ExternalAuth') + return { action: item.action, authMode: patched } + return { + action: item.action, + authMode: patched, + [value]: newObj.password, + } + }) + .filter((action) => !isNil(action)) +} diff --git a/packages/sync-actions/src/customer-group-actions.ts b/packages/sync-actions/src/customer-group-actions.ts new file mode 100644 index 000000000..7e687e580 --- /dev/null +++ b/packages/sync-actions/src/customer-group-actions.ts @@ -0,0 +1,21 @@ +import { buildBaseAttributesActions } from './utils/common-actions' + +export const baseActionsList = [ + { action: 'changeName', key: 'name' }, + { action: 'setKey', key: 'key' }, +] + +export function actionsMapBase( + diff, + oldObj, + newObj, + config: { shouldOmitEmptyString?: boolean } = {} +) { + return buildBaseAttributesActions({ + actions: baseActionsList, + diff, + oldObj, + newObj, + shouldOmitEmptyString: config.shouldOmitEmptyString, + }) +} diff --git a/packages/sync-actions/src/customer-group.ts b/packages/sync-actions/src/customer-group.ts new file mode 100644 index 000000000..3ea3949d2 --- /dev/null +++ b/packages/sync-actions/src/customer-group.ts @@ -0,0 +1,37 @@ +import flatten from 'lodash.flatten' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import actionsMapCustom from './utils/action-map-custom' +import { actionsMapBase } from './customer-group-actions' +import * as diffpatcher from './utils/diffpatcher' +import { SyncActionConfig } from '@commercetools/sdk-client-v2' + +export const actionGroups = ['base', 'custom'] + +function createCustomerGroupMapActions(mapActionGroup, syncActionConfig) { + return function doMapActions(diff, newObj, oldObj) { + const allActions = [] + + allActions.push( + mapActionGroup('base', () => + actionsMapBase(diff, oldObj, newObj, syncActionConfig) + ) + ) + + allActions.push( + mapActionGroup('custom', () => actionsMapCustom(diff, newObj, oldObj)) + ) + + return flatten(allActions) + } +} + +export default (actionGroupList?, syncActionConfig?: SyncActionConfig) => { + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createCustomerGroupMapActions( + mapActionGroup, + syncActionConfig + ) + const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + return { buildActions } +} diff --git a/packages/sync-actions/src/customers.ts b/packages/sync-actions/src/customers.ts new file mode 100644 index 000000000..5e91f6bb1 --- /dev/null +++ b/packages/sync-actions/src/customers.ts @@ -0,0 +1,133 @@ +/* @flow */ +import flatten from 'lodash.flatten' +import type { + SyncAction, + SyncActionConfig, + UpdateAction, + ActionGroup, +} from '@commercetools/sdk-client-v2' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import actionsMapCustom from './utils/action-map-custom' +import * as customerActions from './customer-actions' +import * as diffpatcher from './utils/diffpatcher' +import copyEmptyArrayProps from './utils/copy-empty-array-props' + +export const actionGroups = [ + 'base', + 'references', + 'addresses', + 'custom', + 'authenticationModes', +] + +function createCustomerMapActions( + mapActionGroup: Function, + syncActionConfig?: SyncActionConfig +): (diff: any, newObj: any, oldObj: any) => Array { + return function doMapActions( + diff: any, + newObj: any, + oldObj: any /* , options */ + ): Array { + const allActions = [] + + allActions.push( + mapActionGroup( + 'base', + (): Array => + customerActions.actionsMapBase(diff, oldObj, newObj, syncActionConfig) + ) + ) + + allActions.push( + mapActionGroup( + 'references', + (): Array => + customerActions.actionsMapReferences(diff, oldObj, newObj) + ) + ) + + allActions.push( + mapActionGroup( + 'addresses', + (): Array => + customerActions.actionsMapAddresses(diff, oldObj, newObj) + ) + ) + + allActions.push( + mapActionGroup( + 'base', + (): Array => + customerActions.actionsMapSetDefaultBase( + diff, + oldObj, + newObj, + syncActionConfig + ) + ) + ) + + allActions.push( + mapActionGroup( + 'billingAddressIds', + (): Array => + customerActions.actionsMapBillingAddresses(diff, oldObj, newObj) + ) + ) + + allActions.push( + mapActionGroup( + 'shippingAddressIds', + (): Array => + customerActions.actionsMapShippingAddresses(diff, oldObj, newObj) + ) + ) + + allActions.push( + mapActionGroup( + 'custom', + (): Array => actionsMapCustom(diff, newObj, oldObj) + ) + ) + + allActions.push( + mapActionGroup( + 'authenticationModes', + (): Array => + customerActions.actionsMapAuthenticationModes(diff, oldObj, newObj) + ) + ) + + return flatten(allActions) + } +} + +export default ( + actionGroupList?: Array, + syncActionConfig?: SyncActionConfig +): SyncAction => { + // actionGroupList contains information about which action groups + // are allowed or ignored + + // createMapActionGroup returns function 'mapActionGroup' that takes params: + // - action group name + // - callback function that should return a list of actions that correspond + // to the for the action group + + // this resulting function mapActionGroup will call the callback function + // for allowed action groups and return the return value of the callback + // It will return an empty array for ignored action groups + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createCustomerMapActions( + mapActionGroup, + syncActionConfig + ) + const buildActions = createBuildActions( + diffpatcher.diff, + doMapActions, + copyEmptyArrayProps + ) + return { buildActions } +} diff --git a/packages/sync-actions/src/discount-codes-actions.ts b/packages/sync-actions/src/discount-codes-actions.ts new file mode 100644 index 000000000..ba39d2565 --- /dev/null +++ b/packages/sync-actions/src/discount-codes-actions.ts @@ -0,0 +1,32 @@ +import { buildBaseAttributesActions } from './utils/common-actions' + +export const baseActionsList = [ + { action: 'changeIsActive', key: 'isActive' }, + { action: 'setName', key: 'name' }, + { action: 'setDescription', key: 'description' }, + { action: 'setCartPredicate', key: 'cartPredicate' }, + { action: 'setMaxApplications', key: 'maxApplications' }, + { + action: 'setMaxApplicationsPerCustomer', + key: 'maxApplicationsPerCustomer', + }, + { action: 'changeCartDiscounts', key: 'cartDiscounts' }, + { action: 'setValidFrom', key: 'validFrom' }, + { action: 'setValidUntil', key: 'validUntil' }, + { action: 'changeGroups', key: 'groups' }, +] + +export function actionsMapBase( + diff, + oldObj, + newObj, + config: { shouldOmitEmptyString?: boolean } = {} +) { + return buildBaseAttributesActions({ + actions: baseActionsList, + diff, + oldObj, + newObj, + shouldOmitEmptyString: config.shouldOmitEmptyString, + }) +} diff --git a/packages/sync-actions/src/discount-codes.ts b/packages/sync-actions/src/discount-codes.ts new file mode 100644 index 000000000..d864de17a --- /dev/null +++ b/packages/sync-actions/src/discount-codes.ts @@ -0,0 +1,46 @@ +import flatten from 'lodash.flatten' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import actionsMapCustom from './utils/action-map-custom' +import { actionsMapBase } from './discount-codes-actions' +import combineValidityActions from './utils/combine-validity-actions' +import * as diffpatcher from './utils/diffpatcher' +import { SyncActionConfig } from '@commercetools/sdk-client-v2' + +export const actionGroups = ['base', 'custom'] + +function createDiscountCodesMapActions(mapActionGroup, syncActionConfig) { + return function doMapActions(diff, newObj, oldObj) { + const allActions = [] + allActions.push( + mapActionGroup('base', () => + actionsMapBase(diff, oldObj, newObj, syncActionConfig) + ) + ) + allActions.push( + mapActionGroup('custom', () => actionsMapCustom(diff, newObj, oldObj)) + ) + return combineValidityActions(flatten(allActions)) + } +} + +export default (actionGroupList?, syncActionConfig?: SyncActionConfig) => { + // actionGroupList contains information about which action groups + // are allowed or ignored + + // createMapActionGroup returns function 'mapActionGroup' that takes params: + // - action group name + // - callback function that should return a list of actions that correspond + // to the for the action group + + // this resulting function mapActionGroup will call the callback function + // for allowed action groups and return the return value of the callback + // It will return an empty array for ignored action groups + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createDiscountCodesMapActions( + mapActionGroup, + syncActionConfig + ) + const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + return { buildActions } +} diff --git a/packages/sync-actions/src/index.ts b/packages/sync-actions/src/index.ts new file mode 100644 index 000000000..348e1d398 --- /dev/null +++ b/packages/sync-actions/src/index.ts @@ -0,0 +1,21 @@ +export { default as createSyncCategories } from './categories' +export { default as createSyncCustomers } from './customers' +export { default as createSyncInventories } from './inventories' +export { default as createSyncProducts } from './products' +export { default as createSyncOrders } from './orders' +export { default as createSyncProductDiscounts } from './product-discounts' +export { default as createSyncDiscountCodes } from './discount-codes' +export { default as createSyncCustomerGroup } from './customer-group' +export { default as createSyncCartDiscounts } from './cart-discounts' +export { default as createSyncTaxCategories } from './tax-categories' +export { default as createSyncZones } from './zones' +export { default as createSyncShippingMethods } from './shipping-methods' +export { default as createSyncProductTypes } from './product-types' +export { default as createSyncStates } from './states' +export { default as createSyncChannels } from './channels' +export { default as createSyncTypes } from './types' +export { default as createSyncProjects } from './projects' +export { default as createSyncStores } from './stores' +export { default as createSyncProductSelections } from './product-selections' +export { default as createSyncStandalonePrices } from './prices' +export { default as createSyncAttributeGroups } from './attribute-groups' diff --git a/packages/sync-actions/src/inventories.ts b/packages/sync-actions/src/inventories.ts new file mode 100644 index 000000000..1ed7edf38 --- /dev/null +++ b/packages/sync-actions/src/inventories.ts @@ -0,0 +1,78 @@ +/* @flow */ +import flatten from 'lodash.flatten' +import type { + SyncAction, + SyncActionConfig, + UpdateAction, + ActionGroup, +} from '@commercetools/sdk-client-v2' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import actionsMapCustom from './utils/action-map-custom' +import * as inventoryActions from './inventory-actions' +import * as diffpatcher from './utils/diffpatcher' + +export const actionGroups = ['base', 'references'] + +function createInventoryMapActions( + mapActionGroup: Function, + syncActionConfig?: SyncActionConfig +): (diff: any, newObj: any, oldObj: any) => Array { + return function doMapActions( + diff: any, + newObj: any, + oldObj: any /* , options */ + ): Array { + const allActions = [] + allActions.push( + mapActionGroup( + 'base', + (): Array => + inventoryActions.actionsMapBase( + diff, + oldObj, + newObj, + syncActionConfig + ) + ) + ) + allActions.push( + mapActionGroup( + 'references', + (): Array => + inventoryActions.actionsMapReferences(diff, oldObj, newObj) + ) + ) + allActions.push( + mapActionGroup( + 'custom', + (): Array => actionsMapCustom(diff, newObj, oldObj) + ) + ) + return flatten(allActions) + } +} + +export default ( + actionGroupList?: Array, + syncActionConfig?: SyncActionConfig +): SyncAction => { + // actionGroupList contains information about which action groups + // are allowed or ignored + + // createMapActionGroup returns function 'mapActionGroup' that takes params: + // - action group name + // - callback function that should return a list of actions that correspond + // to the for the action group + + // this resulting function mapActionGroup will call the callback function + // for allowed action groups and return the return value of the callback + // It will return an empty array for ignored action groups + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createInventoryMapActions( + mapActionGroup, + syncActionConfig + ) + const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + return { buildActions } +} diff --git a/packages/sync-actions/src/inventory-actions.ts b/packages/sync-actions/src/inventory-actions.ts new file mode 100644 index 000000000..2c200cf2c --- /dev/null +++ b/packages/sync-actions/src/inventory-actions.ts @@ -0,0 +1,42 @@ +import { + buildBaseAttributesActions, + buildReferenceActions, +} from './utils/common-actions' + +export const baseActionsList = [ + { action: 'changeQuantity', key: 'quantityOnStock', actionKey: 'quantity' }, + { action: 'setRestockableInDays', key: 'restockableInDays' }, + { action: 'setExpectedDelivery', key: 'expectedDelivery' }, +] + +export const referenceActionsList = [ + { action: 'setSupplyChannel', key: 'supplyChannel' }, +] + +/** + * SYNC FUNCTIONS + */ + +export function actionsMapBase( + diff, + oldObj, + newObj, + config: { shouldOmitEmptyString?: boolean } = {} +) { + return buildBaseAttributesActions({ + actions: baseActionsList, + diff, + oldObj, + newObj, + shouldOmitEmptyString: config.shouldOmitEmptyString, + }) +} + +export function actionsMapReferences(diff, oldObj, newObj) { + return buildReferenceActions({ + actions: referenceActionsList, + diff, + oldObj, + newObj, + }) +} diff --git a/packages/sync-actions/src/order-actions.ts b/packages/sync-actions/src/order-actions.ts new file mode 100644 index 000000000..6d9a9fe15 --- /dev/null +++ b/packages/sync-actions/src/order-actions.ts @@ -0,0 +1,226 @@ +import forEach from 'lodash.foreach' +import * as diffpatcher from './utils/diffpatcher' +import { buildBaseAttributesActions } from './utils/common-actions' +import createBuildArrayActions, { + ADD_ACTIONS, + CHANGE_ACTIONS, +} from './utils/create-build-array-actions' +import extractMatchingPairs from './utils/extract-matching-pairs' +import findMatchingPairs from './utils/find-matching-pairs' + +const REGEX_NUMBER = new RegExp(/^\d+$/) +const REGEX_UNDERSCORE_NUMBER = new RegExp(/^_\d+$/) + +const isAddAction = (key, resource) => + REGEX_NUMBER.test(key) && Array.isArray(resource) && resource.length + +const isRemoveAction = (key, resource) => + REGEX_UNDERSCORE_NUMBER.test(key) && Number(resource[2]) === 0 + +export const baseActionsList = [ + { action: 'changeOrderState', key: 'orderState' }, + { action: 'changePaymentState', key: 'paymentState' }, + { action: 'changeShipmentState', key: 'shipmentState' }, +] + +/** + * SYNC FUNCTIONS + */ + +export function actionsMapBase( + diff, + oldObj, + newObj, + config: { shouldOmitEmptyString?: boolean } = {} +) { + return buildBaseAttributesActions({ + actions: baseActionsList, + diff, + oldObj, + newObj, + shouldOmitEmptyString: config.shouldOmitEmptyString, + }) +} + +export function actionsMapDeliveries(diff, oldObj, newObj) { + const deliveriesDiff = diff.shippingInfo + if (!deliveriesDiff) return [] + + const handler = createBuildArrayActions('deliveries', { + [ADD_ACTIONS]: (newObject) => ({ + action: 'addDelivery', + items: newObject.items, + parcels: newObject.parcels, + }), + }) + + return handler(deliveriesDiff, oldObj.shippingInfo, newObj.shippingInfo) +} + +function _buildDeliveryParcelsAction( + diffedParcels, + oldDelivery: any = {}, + newDelivery: any = {} +) { + const addParcelActions = [] + const removeParcelActions = [] + + // generate a hashMap to be able to reference the right image from both ends + const matchingParcelPairs = findMatchingPairs( + diffedParcels, + oldDelivery.parcels, + newDelivery.parcels + ) + forEach(diffedParcels, (parcel, key) => { + const { oldObj } = extractMatchingPairs( + matchingParcelPairs, + key, + oldDelivery.parcels, + newDelivery.parcels + ) + + if (isAddAction(key, parcel)) { + addParcelActions.push({ + action: 'addParcelToDelivery', + deliveryId: oldDelivery.id, + ...diffpatcher.getDeltaValue(parcel), + }) + return + } + + if (isRemoveAction(key, parcel)) { + removeParcelActions.push({ + action: 'removeParcelFromDelivery', + parcelId: oldObj.id, + }) + } + }) + + return [addParcelActions, removeParcelActions] +} + +function _buildDeliveryItemsAction(diffedItems, newDelivery: any = {}) { + const setDeliveryItemsAction: Array = [] + // If there is a diff it means that there were changes (update, adds or removes) + // over the items, which means that `setDeliveryItems` change has happened over + // the delivery + if (diffedItems && Object.keys(diffedItems).length > 0) { + setDeliveryItemsAction.push({ + action: 'setDeliveryItems', + deliveryId: newDelivery.id, + deliveryKey: newDelivery.key, + items: newDelivery.items, + }) + } + + return [setDeliveryItemsAction] +} + +export function actionsMapParcels(diff, oldObj, newObj, deliveryHashMap) { + const shippingInfo = diff.shippingInfo + if (!shippingInfo) return [] + + const deliveries = shippingInfo.deliveries + if (!deliveries) return [] + + let addParcelActions = [] + let removeParcelActions = [] + + if (deliveries) + forEach(deliveries, (delivery, key) => { + const { oldObj: oldDelivery, newObj: newDelivery } = extractMatchingPairs( + deliveryHashMap, + key, + oldObj.shippingInfo.deliveries, + newObj.shippingInfo.deliveries + ) + if (REGEX_UNDERSCORE_NUMBER.test(key) || REGEX_NUMBER.test(key)) { + const [addParcelAction, removeParcelAction] = + _buildDeliveryParcelsAction( + delivery.parcels, + oldDelivery, + newDelivery + ) + + addParcelActions = addParcelActions.concat(addParcelAction) + removeParcelActions = removeParcelActions.concat(removeParcelAction) + } + }) + + return removeParcelActions.concat(addParcelActions) +} + +export function actionsMapDeliveryItems(diff, oldObj, newObj, deliveryHashMap) { + const shippingInfo = diff.shippingInfo + if (!shippingInfo) return [] + + const deliveries = shippingInfo.deliveries + if (!deliveries) return [] + + let setDeliveryItemsActions = [] + + forEach(deliveries, (delivery, key) => { + const { newObj: newDelivery } = extractMatchingPairs( + deliveryHashMap, + key, + oldObj.shippingInfo.deliveries, + newObj.shippingInfo.deliveries + ) + if (REGEX_UNDERSCORE_NUMBER.test(key) || REGEX_NUMBER.test(key)) { + const [setDeliveryItemsAction] = _buildDeliveryItemsAction( + delivery.items, + newDelivery + ) + setDeliveryItemsActions = setDeliveryItemsActions.concat( + setDeliveryItemsAction + ) + } + }) + + return setDeliveryItemsActions +} + +export function actionsMapReturnsInfo(diff, oldObj, newObj) { + const returnInfoDiff = diff.returnInfo + if (!returnInfoDiff) return [] + + const handler = createBuildArrayActions('returnInfo', { + [ADD_ACTIONS]: (newReturnInfo) => { + if (newReturnInfo.items) { + return [ + { + action: 'addReturnInfo', + ...newReturnInfo, + }, + ] + } + return [] + }, + [CHANGE_ACTIONS]: (oldSReturnInfo, newReturnInfo, key) => { + const { items = {} } = returnInfoDiff[key] + if (Object.keys(items).length === 0) { + return [] + } + return Object.keys(items).reduce((actions, index) => { + const item = newReturnInfo.items[index] + if (items[index].shipmentState) { + actions.push({ + action: 'setReturnShipmentState', + returnItemId: item.id, + shipmentState: item.shipmentState, + }) + } + if (items[index].paymentState) { + actions.push({ + action: 'setReturnPaymentState', + returnItemId: item.id, + paymentState: item.paymentState, + }) + } + return actions + }, []) + }, + }) + + return handler(diff, oldObj, newObj) +} diff --git a/packages/sync-actions/src/orders.ts b/packages/sync-actions/src/orders.ts new file mode 100644 index 000000000..01a22a7d1 --- /dev/null +++ b/packages/sync-actions/src/orders.ts @@ -0,0 +1,112 @@ +/* @flow */ +import flatten from 'lodash.flatten' +import type { + SyncAction, + SyncActionConfig, + ActionGroup, + UpdateAction, +} from '@commercetools/sdk-client-v2' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import actionsMapCustom from './utils/action-map-custom' +import * as orderActions from './order-actions' +import * as diffpatcher from './utils/diffpatcher' +import findMatchingPairs from './utils/find-matching-pairs' + +export const actionGroups = ['base', 'deliveries'] + +function createOrderMapActions( + mapActionGroup: Function, + syncActionConfig?: SyncActionConfig +): (diff: any, newObj: any, oldObj: any) => Array { + return function doMapActions( + diff: any, + newObj: any, + oldObj: any /* , options */ + ): Array { + const allActions = [] + let deliveryHashMap + + if (diff.shippingInfo && diff.shippingInfo.deliveries) { + deliveryHashMap = findMatchingPairs( + diff.shippingInfo.deliveries, + oldObj.shippingInfo.deliveries, + newObj.shippingInfo.deliveries + ) + } + + allActions.push( + mapActionGroup( + 'base', + (): Array => + orderActions.actionsMapBase(diff, oldObj, newObj, syncActionConfig) + ) + ) + + allActions.push( + mapActionGroup( + 'deliveries', + (): Array => + orderActions.actionsMapDeliveries(diff, oldObj, newObj) + ) + ) + + allActions.push( + mapActionGroup( + 'parcels', + (): Array => + orderActions.actionsMapParcels(diff, oldObj, newObj, deliveryHashMap) + ) + ) + + allActions.push( + mapActionGroup( + 'items', + (): Array => + orderActions.actionsMapDeliveryItems( + diff, + oldObj, + newObj, + deliveryHashMap + ) + ) + ) + + allActions.push( + flatten( + mapActionGroup( + 'returnInfo', + (): Array => + orderActions.actionsMapReturnsInfo(diff, oldObj, newObj) + ) + ) + ) + + allActions.push( + mapActionGroup('custom', () => actionsMapCustom(diff, newObj, oldObj)) + ) + + return flatten(allActions) + } +} + +export default ( + actionGroupList?: Array, + syncActionConfig?: SyncActionConfig +): SyncAction => { + // actionGroupList contains information about which action groups + // are allowed or ignored + + // createMapActionGroup returns function 'mapActionGroup' that takes params: + // - action group name + // - callback function that should return a list of actions that correspond + // to the for the action group + + // this resulting function mapActionGroup will call the callback function + // for allowed action groups and return the return value of the callback + // It will return an empty array for ignored action groups + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createOrderMapActions(mapActionGroup, syncActionConfig) + const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + return { buildActions } +} diff --git a/packages/sync-actions/src/prices-actions.ts b/packages/sync-actions/src/prices-actions.ts new file mode 100644 index 000000000..5d2b61b38 --- /dev/null +++ b/packages/sync-actions/src/prices-actions.ts @@ -0,0 +1,27 @@ +import { buildBaseAttributesActions } from './utils/common-actions' + +export const baseActionsList = [ + { action: 'changeValue', key: 'value' }, + { action: 'setDiscountedPrice', key: 'discounted' }, + // TODO: Later add more accurate actions `addPriceTier`, `removePriceTier` + { action: 'setPriceTiers', key: 'tiers' }, + { action: 'setKey', key: 'key' }, + { action: 'setValidFrom', key: 'validFrom' }, + { action: 'setValidUntil', key: 'validUntil' }, + { action: 'changeActive', key: 'active' }, +] + +export function actionsMapBase( + diff, + oldObj, + newObj, + config: { shouldOmitEmptyString?: boolean } = {} +) { + return buildBaseAttributesActions({ + actions: baseActionsList, + diff, + oldObj, + newObj, + shouldOmitEmptyString: config.shouldOmitEmptyString, + }) +} diff --git a/packages/sync-actions/src/prices.ts b/packages/sync-actions/src/prices.ts new file mode 100644 index 000000000..ce4b7928c --- /dev/null +++ b/packages/sync-actions/src/prices.ts @@ -0,0 +1,53 @@ +/* @flow */ +import type { + SyncAction, + SyncActionConfig, + ActionGroup, + UpdateAction, +} from '@commercetools/sdk-client-v2' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import actionsMapCustom from './utils/action-map-custom' +import * as pricesActions from './prices-actions' +import * as diffpatcher from './utils/diffpatcher' +import combineValidityActions from './utils/combine-validity-actions' + +const actionGroups = ['base', 'custom'] + +function createPriceMapActions( + mapActionGroup: Function, + syncActionConfig?: SyncActionConfig +): (diff: any, newObj: any, oldObj: any, options: any) => Array { + return function doMapActions( + diff: any, + newObj: any, + oldObj: any + ): Array { + const baseActions = mapActionGroup( + 'base', + (): Array => + pricesActions.actionsMapBase(diff, oldObj, newObj, syncActionConfig) + ) + + const customActions = mapActionGroup( + 'custom', + (): Array => actionsMapCustom(diff, newObj, oldObj) + ) + + return combineValidityActions([...baseActions, ...customActions]) + } +} + +export default ( + actionGroupList?: Array, + syncActionConfig?: SyncActionConfig +): SyncAction => { + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createPriceMapActions(mapActionGroup, syncActionConfig) + + const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + + return { buildActions } +} + +export { actionGroups } diff --git a/packages/sync-actions/src/product-actions.ts b/packages/sync-actions/src/product-actions.ts new file mode 100644 index 000000000..4f5de1a05 --- /dev/null +++ b/packages/sync-actions/src/product-actions.ts @@ -0,0 +1,846 @@ +/* eslint-disable max-len */ +import forEach from 'lodash.foreach' +import uniqWith from 'lodash.uniqwith' +import intersection from 'lodash.intersection' +import without from 'lodash.without' +import * as diffpatcher from './utils/diffpatcher' +import extractMatchingPairs from './utils/extract-matching-pairs' +import actionsMapCustom from './utils/action-map-custom' +import { + buildBaseAttributesActions, + buildReferenceActions, +} from './utils/common-actions' +import createBuildArrayActions, { + ADD_ACTIONS, + REMOVE_ACTIONS, +} from './utils/create-build-array-actions' +import findMatchingPairs from './utils/find-matching-pairs' + +const REGEX_NUMBER = new RegExp(/^\d+$/) +const REGEX_UNDERSCORE_NUMBER = new RegExp(/^_\d+$/) + +export const baseActionsList = [ + { action: 'changeName', key: 'name' }, + { action: 'changeSlug', key: 'slug' }, + { action: 'setDescription', key: 'description' }, + { action: 'setSearchKeywords', key: 'searchKeywords' }, + { action: 'setKey', key: 'key' }, + { action: 'setPriceMode', key: 'priceMode' }, +] + +export const baseAssetActionsList = [ + { action: 'setAssetKey', key: 'key', actionKey: 'assetKey' }, + { action: 'changeAssetName', key: 'name' }, + { action: 'setAssetDescription', key: 'description' }, + { action: 'setAssetTags', key: 'tags' }, + { action: 'setAssetSources', key: 'sources' }, +] + +export const metaActionsList = [ + { action: 'setMetaTitle', key: 'metaTitle' }, + { action: 'setMetaDescription', key: 'metaDescription' }, + { action: 'setMetaKeywords', key: 'metaKeywords' }, +] + +export const referenceActionsList = [ + { action: 'setTaxCategory', key: 'taxCategory' }, + { action: 'transitionState', key: 'state' }, +] + +/** + * HELPER FUNCTIONS + */ + +const getIsAddAction = (key, resource) => + REGEX_NUMBER.test(key) && Array.isArray(resource) && resource.length + +const getIsUpdateAction = (key, resource) => + REGEX_NUMBER.test(key) && Object.keys(resource).length + +const getIsRemoveAction = (key, resource) => + REGEX_UNDERSCORE_NUMBER.test(key) && Number(resource[2]) === 0 + +const getIsItemMovedAction = (key, resource) => + REGEX_UNDERSCORE_NUMBER.test(key) && Number(resource[2]) === 3 + +function _buildSkuActions(variantDiff, oldVariant) { + if ({}.hasOwnProperty.call(variantDiff, 'sku')) { + const newValue = diffpatcher.getDeltaValue(variantDiff.sku) + if (!newValue && !oldVariant.sku) return null + + return { + action: 'setSku', + variantId: oldVariant.id, + sku: newValue || null, + } + } + return null +} + +function _buildKeyActions(variantDiff, oldVariant) { + if ({}.hasOwnProperty.call(variantDiff, 'key')) { + const newValue = diffpatcher.getDeltaValue(variantDiff.key) + if (!newValue && !oldVariant.key) return null + + return { + action: 'setProductVariantKey', + variantId: oldVariant.id, + key: newValue || null, + } + } + return null +} + +function _buildNewSetAttributeAction(id, el, sameForAllAttributeNames) { + const attributeName = el && el.name + if (!attributeName) return undefined + + let action = { + action: 'setAttribute', + variantId: id, + name: attributeName, + value: el.value, + } + + if (sameForAllAttributeNames.indexOf(attributeName) !== -1) { + action = { ...action, action: 'setAttributeInAllVariants' } + delete action.variantId + } + + return action +} + +function _buildSetAttributeAction( + diffedValue, + oldVariant, + attribute, + sameForAllAttributeNames +) { + if (!attribute) return undefined + + let action: any = { + action: 'setAttribute', + variantId: oldVariant.id, + name: attribute.name, + } + + // Used as original object for patching long diff text + const oldAttribute = + oldVariant.attributes.find((a) => a.name === attribute.name) || {} + + if (sameForAllAttributeNames.indexOf(attribute.name) !== -1) { + action = { ...action, action: 'setAttributeInAllVariants' } + delete action.variantId + } + + if (Array.isArray(diffedValue)) + action.value = diffpatcher.getDeltaValue(diffedValue, oldAttribute.value) + else if (typeof diffedValue === 'string') + // LText: value: {en: "", de: ""} + // Enum: value: {key: "foo", label: "Foo"} + // LEnum: value: {key: "foo", label: {en: "Foo", de: "Foo"}} + // Money: value: {centAmount: 123, currencyCode: ""} + // *: value: "" + + // normal + action.value = diffpatcher.getDeltaValue(diffedValue, oldAttribute.value) + else if (diffedValue.centAmount || diffedValue.currencyCode) + // Money + action.value = { + centAmount: diffedValue.centAmount + ? diffpatcher.getDeltaValue(diffedValue.centAmount) + : attribute.value.centAmount, + currencyCode: diffedValue.currencyCode + ? diffpatcher.getDeltaValue(diffedValue.currencyCode) + : attribute.value.currencyCode, + } + else if (diffedValue.key) + // Enum / LEnum (use only the key) + action.value = diffpatcher.getDeltaValue(diffedValue.key) + else if (typeof diffedValue === 'object') + if ({}.hasOwnProperty.call(diffedValue, '_t') && diffedValue._t === 'a') { + // set-typed attribute + action = { ...action, value: attribute.value } + } else { + // LText + + const updatedValue = Object.keys(diffedValue).reduce( + (acc, lang) => { + const patchedValue = diffpatcher.getDeltaValue( + diffedValue[lang], + acc[lang] + ) + return Object.assign(acc, { [lang]: patchedValue }) + }, + { ...oldAttribute.value } + ) + + action.value = updatedValue + } + + return action +} + +function _buildVariantImagesAction( + diffedImages, + oldVariant: any = {}, + newVariant: any = {} +) { + const actions = [] + // generate a hashMap to be able to reference the right image from both ends + const matchingImagePairs = findMatchingPairs( + diffedImages, + oldVariant.images, + newVariant.images, + 'url' + ) + forEach(diffedImages, (image, key) => { + const { oldObj, newObj } = extractMatchingPairs( + matchingImagePairs, + key, + oldVariant.images, + newVariant.images + ) + if (REGEX_NUMBER.test(key)) { + // New image + if (Array.isArray(image) && image.length) + actions.push({ + action: 'addExternalImage', + variantId: oldVariant.id, + image: diffpatcher.getDeltaValue(image), + }) + else if (typeof image === 'object') + if ({}.hasOwnProperty.call(image, 'url') && image.url.length === 2) { + // There is a new image, remove the old one first. + actions.push({ + action: 'removeImage', + variantId: oldVariant.id, + imageUrl: oldObj.url, + }) + actions.push({ + action: 'addExternalImage', + variantId: oldVariant.id, + image: newObj, + }) + } else if ( + {}.hasOwnProperty.call(image, 'label') && + (image.label.length === 1 || image.label.length === 2) + ) + actions.push({ + action: 'setImageLabel', + variantId: oldVariant.id, + imageUrl: oldObj.url, + label: diffpatcher.getDeltaValue(image.label), + }) + } else if (REGEX_UNDERSCORE_NUMBER.test(key)) + if (Array.isArray(image) && image.length === 3) { + if (Number(image[2]) === 3) + // image position changed + actions.push({ + action: 'moveImageToPosition', + variantId: oldVariant.id, + imageUrl: oldObj.url, + position: Number(image[1]), + }) + else if (Number(image[2]) === 0) + // image removed + actions.push({ + action: 'removeImage', + variantId: oldVariant.id, + imageUrl: oldObj.url, + }) + } + }) + + return actions +} + +function _buildVariantPricesAction( + diffedPrices, + oldVariant: any = {}, + newVariant: any = {}, + enableDiscounted = false +) { + const addPriceActions = [] + const changePriceActions = [] + const removePriceActions = [] + + // generate a hashMap to be able to reference the right image from both ends + const matchingPricePairs = findMatchingPairs( + diffedPrices, + oldVariant.prices, + newVariant.prices + ) + forEach(diffedPrices, (price, key) => { + const { oldObj, newObj } = extractMatchingPairs( + matchingPricePairs, + key, + oldVariant.prices, + newVariant.prices + ) + if (getIsAddAction(key, price)) { + // Remove read-only fields + const patchedPrice = price.map((p) => { + const shallowClone = { ...p } + if (enableDiscounted !== true) delete shallowClone.discounted + return shallowClone + }) + + addPriceActions.push({ + action: 'addPrice', + variantId: oldVariant.id, + price: diffpatcher.getDeltaValue(patchedPrice), + }) + return + } + + if (getIsUpdateAction(key, price)) { + // Remove the discounted field and make sure that the price + // still has other values, otherwise simply return + const filteredPrice = { ...price } + if (enableDiscounted !== true) delete filteredPrice.discounted + if (Object.keys(filteredPrice).length) { + // At this point price should have changed, simply pick the new one + const newPrice = { ...newObj } + if (enableDiscounted !== true) delete newPrice.discounted + + changePriceActions.push({ + action: 'changePrice', + priceId: oldObj.id, + price: newPrice, + }) + } + return + } + + if (getIsRemoveAction(key, price)) { + // price removed + removePriceActions.push({ + action: 'removePrice', + priceId: oldObj.id, + }) + } + }) + + return [addPriceActions, changePriceActions, removePriceActions] +} + +function _buildVariantAttributesActions( + attributes, + oldVariant, + newVariant, + sameForAllAttributeNames +) { + const actions = [] + + if (!attributes) return actions + + forEach(attributes, (value, key) => { + if (REGEX_NUMBER.test(key)) { + if (Array.isArray(value)) { + const { id } = oldVariant + const deltaValue = diffpatcher.getDeltaValue(value) + const setAction = _buildNewSetAttributeAction( + id, + deltaValue, + sameForAllAttributeNames + ) + + if (setAction) actions.push(setAction) + } else if (newVariant.attributes) { + const setAction = _buildSetAttributeAction( + value.value, + oldVariant, + newVariant.attributes[key], + sameForAllAttributeNames + ) + if (setAction) actions.push(setAction) + } + } else if (REGEX_UNDERSCORE_NUMBER.test(key)) + if (Array.isArray(value)) { + // Ignore pure array moves! + if (value.length === 3 && value[2] === 3) return + + const { id } = oldVariant + + let deltaValue = diffpatcher.getDeltaValue(value) + if (!deltaValue) + if (value[0] && value[0].name) + // unset attribute if + deltaValue = { name: value[0].name } + else deltaValue = undefined + + const setAction = _buildNewSetAttributeAction( + id, + deltaValue, + sameForAllAttributeNames + ) + + if (setAction) actions.push(setAction) + } else { + const index = key.substring(1) + if (newVariant.attributes) { + const setAction = _buildSetAttributeAction( + value.value, + oldVariant, + newVariant.attributes[index], + sameForAllAttributeNames + ) + if (setAction) actions.push(setAction) + } + } + }) + + return actions +} + +function toAssetIdentifier(asset) { + const assetIdentifier = asset.id + ? { assetId: asset.id } + : { assetKey: asset.key } + return assetIdentifier +} + +function toVariantIdentifier(variant) { + const { id, sku } = variant + return id ? { variantId: id } : { sku } +} + +function _buildVariantChangeAssetOrderAction( + diffAssets, + oldVariant, + newVariant +) { + const isAssetOrderChanged = Object.entries(diffAssets).find((entry) => + getIsItemMovedAction(entry[0], entry[1]) + ) + if (!isAssetOrderChanged) { + return [] + } + const assetIdsBefore = oldVariant.assets.map((_) => _.id) + const assetIdsCurrent = newVariant.assets + .map((_) => _.id) + .filter((_) => _ !== undefined) + const assetIdsToKeep = intersection(assetIdsCurrent, assetIdsBefore) + const assetIdsToRemove = without(assetIdsBefore, ...assetIdsToKeep) + const changeAssetOrderAction = { + action: 'changeAssetOrder', + assetOrder: assetIdsToKeep.concat(assetIdsToRemove), + ...toVariantIdentifier(oldVariant), + } + return [changeAssetOrderAction] +} +function _buildVariantAssetsActions(diffAssets, oldVariant, newVariant) { + const assetActions = [] + + // generate a hashMap to be able to reference the right asset from both ends + const matchingAssetPairs = findMatchingPairs( + diffAssets, + oldVariant.assets, + newVariant.assets + ) + + forEach(diffAssets, (asset, key) => { + const { oldObj: oldAsset, newObj: newAsset } = extractMatchingPairs( + matchingAssetPairs, + key, + oldVariant.assets, + newVariant.assets + ) + + if (getIsAddAction(key, asset)) { + assetActions.push({ + action: 'addAsset', + asset: diffpatcher.getDeltaValue(asset), + ...toVariantIdentifier(newVariant), + position: Number(key), + }) + return + } + + if (getIsUpdateAction(key, asset)) { + // todo add changeAssetOrder + const basicActions = buildBaseAttributesActions({ + actions: baseAssetActionsList, + diff: asset, + oldObj: oldAsset, + newObj: newAsset, + }).map((action) => { + // in case of 'setAssetKey' then the identifier will be only 'assetId' + if (action.action === 'setAssetKey') { + return { + ...action, + ...toVariantIdentifier(oldVariant), + assetId: oldAsset.id, + } + } + + return { + ...action, + ...toVariantIdentifier(oldVariant), + ...toAssetIdentifier(oldAsset), + } + }) + assetActions.push(...basicActions) + + if (asset.custom) { + const customActions = actionsMapCustom(asset, newAsset, oldAsset, { + actions: { + setCustomType: 'setAssetCustomType', + setCustomField: 'setAssetCustomField', + }, + ...toVariantIdentifier(oldVariant), + ...toAssetIdentifier(oldAsset), + }) + assetActions.push(...customActions) + } + + return + } + + if (getIsRemoveAction(key, asset)) { + assetActions.push({ + action: 'removeAsset', + ...toAssetIdentifier(oldAsset), + ...toVariantIdentifier(oldVariant), + }) + } + }) + + const changedAssetOrderAction = _buildVariantChangeAssetOrderAction( + diffAssets, + oldVariant, + newVariant + ) + return [...changedAssetOrderAction, ...assetActions] +} + +/** + * SYNC FUNCTIONS + */ + +export function actionsMapBase( + diff, + oldObj, + newObj, + config: { shouldOmitEmptyString?: boolean } = {} +) { + return buildBaseAttributesActions({ + actions: baseActionsList, + diff, + oldObj, + newObj, + shouldOmitEmptyString: config.shouldOmitEmptyString, + }) +} + +export function actionsMapMeta(diff, oldObj, newObj) { + return buildBaseAttributesActions({ + actions: metaActionsList, + diff, + oldObj, + newObj, + }) +} + +export function actionsMapAddVariants(diff, oldObj, newObj) { + const handler = createBuildArrayActions('variants', { + [ADD_ACTIONS]: (newObject) => ({ + ...newObject, + action: 'addVariant', + }), + }) + return handler(diff, oldObj, newObj) +} + +export function actionsMapRemoveVariants(diff, oldObj, newObj) { + const handler = createBuildArrayActions('variants', { + [REMOVE_ACTIONS]: ({ id }) => ({ + action: 'removeVariant', + id, + }), + }) + return handler(diff, oldObj, newObj) +} + +export function actionsMapReferences(diff, oldObj, newObj) { + return buildReferenceActions({ + actions: referenceActionsList, + diff, + oldObj, + newObj, + }) +} + +export function actionsMapCategories(diff) { + const actions = [] + if (!diff.categories) return actions + + const addToCategoryActions = [] + const removeFromCategoryActions = [] + + forEach(diff.categories, (category) => { + if (Array.isArray(category)) { + const action: any = { category: category[0] } + + if (category.length === 3) { + // Ignore pure array moves! + if (category[2] !== 3) { + action.action = 'removeFromCategory' + removeFromCategoryActions.push(action) + } + } else if (category.length === 1) { + action.action = 'addToCategory' + addToCategoryActions.push(action) + } + } + }) + + // Make sure `removeFromCategory` actions come first + return removeFromCategoryActions.concat(addToCategoryActions) +} + +export function actionsMapCategoryOrderHints(diff) { + if (!diff.categoryOrderHints) return [] + // Ignore this pattern as its means no changes happened [{},0,0] + if (Array.isArray(diff.categoryOrderHints)) return [] + + return Object.keys(diff.categoryOrderHints).map((categoryId) => { + const hintChange = diff.categoryOrderHints[categoryId] + + const action: any = { + action: 'setCategoryOrderHint', + categoryId, + } + + if (hintChange.length === 1) + // item was added + action.orderHint = hintChange[0] + else if (hintChange.length === 2 && hintChange[1] !== 0) + // item was changed + action.orderHint = hintChange[1] + + // else item was removed -> do not set 'orderHint' property + + return action + }) +} + +export function actionsMapAssets(diff, oldObj, newObj, variantHashMap) { + let allAssetsActions = [] + + const { variants } = diff + + if (variants) + forEach(variants, (variant, key) => { + const { oldObj: oldVariant, newObj: newVariant } = extractMatchingPairs( + variantHashMap, + key, + oldObj.variants, + newObj.variants + ) + if ( + variant.assets && + (REGEX_UNDERSCORE_NUMBER.test(key) || REGEX_NUMBER.test(key)) + ) { + const assetActions = _buildVariantAssetsActions( + variant.assets, + oldVariant, + newVariant + ) + + allAssetsActions = allAssetsActions.concat(assetActions) + } + }) + + return allAssetsActions +} + +export function actionsMapAttributes( + diff, + oldObj, + newObj, + sameForAllAttributeNames = [], + variantHashMap +) { + let actions = [] + const { variants } = diff + + if (variants) + forEach(variants, (variant, key) => { + const { oldObj: oldVariant, newObj: newVariant } = extractMatchingPairs( + variantHashMap, + key, + oldObj.variants, + newObj.variants + ) + if (REGEX_NUMBER.test(key) && !Array.isArray(variant)) { + const skuAction = _buildSkuActions(variant, oldVariant) + const keyAction = _buildKeyActions(variant, oldVariant) + if (skuAction) actions.push(skuAction) + if (keyAction) actions.push(keyAction) + + const { attributes } = variant + + const attrActions = _buildVariantAttributesActions( + attributes, + oldVariant, + newVariant, + sameForAllAttributeNames + ) + actions = actions.concat(attrActions) + } + }) + + // Ensure that an action is unique. + // This is especially necessary for SFA attributes. + return uniqWith( + actions, + (a, b) => + a.action === b.action && a.name === b.name && a.variantId === b.variantId + ) +} + +export function actionsMapImages(diff, oldObj, newObj, variantHashMap) { + let actions = [] + const { variants } = diff + if (variants) + forEach(variants, (variant, key) => { + const { oldObj: oldVariant, newObj: newVariant } = extractMatchingPairs( + variantHashMap, + key, + oldObj.variants, + newObj.variants + ) + if (REGEX_UNDERSCORE_NUMBER.test(key) || REGEX_NUMBER.test(key)) { + const vActions = _buildVariantImagesAction( + variant.images, + oldVariant, + newVariant + ) + actions = actions.concat(vActions) + } + }) + + return actions +} + +export function actionsMapPrices( + diff, + oldObj, + newObj, + variantHashMap, + enableDiscounted +) { + let addPriceActions = [] + let changePriceActions = [] + let removePriceActions = [] + + const { variants } = diff + + if (variants) + forEach(variants, (variant, key) => { + const { oldObj: oldVariant, newObj: newVariant } = extractMatchingPairs( + variantHashMap, + key, + oldObj.variants, + newObj.variants + ) + if (REGEX_UNDERSCORE_NUMBER.test(key) || REGEX_NUMBER.test(key)) { + const [addPriceAction, changePriceAction, removePriceAction] = + _buildVariantPricesAction( + variant.prices, + oldVariant, + newVariant, + enableDiscounted + ) + + addPriceActions = addPriceActions.concat(addPriceAction) + changePriceActions = changePriceActions.concat(changePriceAction) + removePriceActions = removePriceActions.concat(removePriceAction) + } + }) + + // price actions need to be in this below order + return changePriceActions.concat(removePriceActions).concat(addPriceActions) +} + +export function actionsMapPricesCustom(diff, oldObj, newObj, variantHashMap) { + let actions = [] + + const { variants } = diff + + if (variants) + forEach(variants, (variant, key) => { + const { oldObj: oldVariant, newObj: newVariant } = extractMatchingPairs( + variantHashMap, + key, + oldObj.variants, + newObj.variants + ) + + if ( + variant && + variant.prices && + (REGEX_UNDERSCORE_NUMBER.test(key) || REGEX_NUMBER.test(key)) + ) { + const priceHashMap = findMatchingPairs( + variant.prices, + oldVariant.prices, + newVariant.prices + ) + + forEach(variant.prices, (price, index) => { + const { oldObj: oldPrice, newObj: newPrice } = extractMatchingPairs( + priceHashMap, + index, + oldVariant.prices, + newVariant.prices + ) + + if ( + price.custom && + (REGEX_UNDERSCORE_NUMBER.test(index) || REGEX_NUMBER.test(index)) + ) { + const generatedActions = actionsMapCustom( + price, + newPrice, + oldPrice, + { + actions: { + setCustomType: 'setProductPriceCustomType', + setCustomField: 'setProductPriceCustomField', + }, + priceId: oldPrice.id, + } + ) + + actions = actions.concat(generatedActions) + } + }) + } + }) + + return actions +} + +export function actionsMapMasterVariant(oldObj, newObj) { + const createChangeMasterVariantAction = (variantId) => ({ + action: 'changeMasterVariant', + variantId, + }) + const extractMasterVariantId = (fromObj) => { + const variants = Array.isArray(fromObj.variants) ? fromObj.variants : [] + + return variants[0] ? variants[0].id : undefined + } + + const newMasterVariantId = extractMasterVariantId(newObj) + const oldMasterVariantId = extractMasterVariantId(oldObj) + + // Old and new master master variant differ and a new master variant id exists + if (newMasterVariantId && oldMasterVariantId !== newMasterVariantId) + return [createChangeMasterVariantAction(newMasterVariantId)] + + return [] +} diff --git a/packages/sync-actions/src/product-discounts-actions.ts b/packages/sync-actions/src/product-discounts-actions.ts new file mode 100644 index 000000000..38f7fd72c --- /dev/null +++ b/packages/sync-actions/src/product-discounts-actions.ts @@ -0,0 +1,28 @@ +import { buildBaseAttributesActions } from './utils/common-actions' + +export const baseActionsList = [ + { action: 'changeIsActive', key: 'isActive' }, + { action: 'changeName', key: 'name' }, + { action: 'changePredicate', key: 'predicate' }, + { action: 'changeSortOrder', key: 'sortOrder' }, + { action: 'changeValue', key: 'value' }, + { action: 'setDescription', key: 'description' }, + { action: 'setValidFrom', key: 'validFrom' }, + { action: 'setValidUntil', key: 'validUntil' }, + { action: 'setKey', key: 'key' }, +] + +export function actionsMapBase( + diff, + oldObj, + newObj, + config: { shouldOmitEmptyString?: boolean } = {} +) { + return buildBaseAttributesActions({ + actions: baseActionsList, + diff, + oldObj, + newObj, + shouldOmitEmptyString: config.shouldOmitEmptyString, + }) +} diff --git a/packages/sync-actions/src/product-discounts.ts b/packages/sync-actions/src/product-discounts.ts new file mode 100644 index 000000000..3bfd17574 --- /dev/null +++ b/packages/sync-actions/src/product-discounts.ts @@ -0,0 +1,32 @@ +import flatten from 'lodash.flatten' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import { actionsMapBase } from './product-discounts-actions' +import combineValidityActions from './utils/combine-validity-actions' +import * as diffpatcher from './utils/diffpatcher' +import { SyncActionConfig } from '@commercetools/sdk-client-v2' + +export const actionGroups = ['base'] + +function createProductDiscountsMapActions(mapActionGroup, syncActionConfig) { + return function doMapActions(diff, newObj, oldObj) { + const allActions = [] + + allActions.push( + mapActionGroup('base', () => + actionsMapBase(diff, oldObj, newObj, syncActionConfig) + ) + ) + return combineValidityActions(flatten(allActions)) + } +} + +export default (actionGroupList?, syncActionConfig?: SyncActionConfig) => { + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createProductDiscountsMapActions( + mapActionGroup, + syncActionConfig + ) + const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + return { buildActions } +} diff --git a/packages/sync-actions/src/product-selections-actions.ts b/packages/sync-actions/src/product-selections-actions.ts new file mode 100644 index 000000000..abeae9464 --- /dev/null +++ b/packages/sync-actions/src/product-selections-actions.ts @@ -0,0 +1,15 @@ +import { buildBaseAttributesActions } from './utils/common-actions' + +export const baseActionsList = [ + { action: 'changeName', key: 'name' }, + { action: 'setKey', key: 'key' }, +] + +export function actionsMapBase(diff, oldObj, newObj) { + return buildBaseAttributesActions({ + actions: baseActionsList, + diff, + oldObj, + newObj, + }) +} diff --git a/packages/sync-actions/src/product-selections.ts b/packages/sync-actions/src/product-selections.ts new file mode 100644 index 000000000..1969eaf12 --- /dev/null +++ b/packages/sync-actions/src/product-selections.ts @@ -0,0 +1,57 @@ +/* @flow */ +import flatten from 'lodash.flatten' +import type { + SyncAction, + UpdateAction, + ActionGroup, +} from '@commercetools/sdk-client-v2' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import actionsMapCustom from './utils/action-map-custom' +import * as productSelectionsActions from './product-selections-actions' +import * as diffpatcher from './utils/diffpatcher' + +export const actionGroups = ['base'] + +function createProductSelectionsMapActions( + mapActionGroup: ( + type: string, + fn: () => Array + ) => Array +): (diff: any, next: any, previous: any, options: any) => Array { + return function doMapActions( + diff: any, + next: any, + previous: any + ): Array { + const allActions = [] + allActions.push( + mapActionGroup( + 'base', + (): Array => + productSelectionsActions.actionsMapBase(diff, previous, next) + ) + ) + allActions.push( + mapActionGroup( + 'custom', + (): Array => actionsMapCustom(diff, next, previous) + ) + ) + + return flatten(allActions) + } +} + +export default (actionGroupList?: Array): SyncAction => { + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createProductSelectionsMapActions(mapActionGroup) + const onBeforeApplyingDiff = null + const buildActions = createBuildActions( + diffpatcher.diff, + doMapActions, + onBeforeApplyingDiff + ) + + return { buildActions } +} diff --git a/packages/sync-actions/src/product-types-actions.ts b/packages/sync-actions/src/product-types-actions.ts new file mode 100644 index 000000000..afb926e1d --- /dev/null +++ b/packages/sync-actions/src/product-types-actions.ts @@ -0,0 +1,325 @@ +import flatten from 'lodash.flatten' +import { deepEqual } from 'fast-equals' +import { + createIsEmptyValue, + buildBaseAttributesActions, +} from './utils/common-actions' + +export const baseActionsList = [ + { action: 'changeName', key: 'name' }, + { action: 'setKey', key: 'key' }, + { action: 'changeDescription', key: 'description' }, +] + +export function actionsMapBase( + diff, + previous, + next, + config: { shouldOmitEmptyString?: boolean } = {} +) { + // when `diff` is undefined, then the underlying `buildActions` has returned any diff + // which given in product-types would mean that `buildActions` has run with `nestedValuesChanges` applied + // To allow continuation of update-action generation, we let this pass.. + if (!diff) return [] + return buildBaseAttributesActions({ + diff, + actions: baseActionsList, + oldObj: previous, + newObj: next, + shouldOmitEmptyString: config.shouldOmitEmptyString, + }) +} + +// this is nearly similar to `buildBaseAttributesActions`, however with a significant difference. +// `buildBasAttributesActions` generates update-actions with help of `diff`, +// which is an object consisting of flags which indicates different operations. +// `generateBaseFieldsUpdateActions` only generate based on `previous` and `next`. +export const generateBaseFieldsUpdateActions = ( + previous, + next, + actionDefinition: { [s: string]: { action: string; attributeName?: string } } +) => { + const isEmpty = createIsEmptyValue([undefined, null, '']) + return Object.entries(actionDefinition).reduce( + (nextUpdateActions, [field, actionFieldDefinition]) => { + if (isEmpty(previous[field]) && isEmpty(next[field])) + return nextUpdateActions + if (!isEmpty(previous[field]) && isEmpty(next[field])) + return [...nextUpdateActions, actionFieldDefinition] + if (!deepEqual(previous[field], next[field])) { + switch (field) { + // BEWARE that this is generates update-action only for key of enum attribute value, + // not key of product type. If we need to re-factor `product-types` sync actions to use + // `generateBaseFieldsUpdateActions`, we need to extract the following logic so we could + // cover both entity types. + case 'key': + return [ + ...nextUpdateActions, + // Another option is to have explicit name of `field` e.g `enumKey`, which we could use to + // generate appropriate update-action for respective entity type. + // An outline of this on the top of my head: + // ```js + // case 'enumKey': + // return [ + // ...nextUpdateActions, + // { + // action: actionFieldDefinition.action, + // attributeName: actionFieldDefinition.attributeName, + // key: previous.key, + // newKey: next.key, + // }, + // ] + // case 'productTypeKey': + // return [ + // ...nextUpdateActions, + // { + // action: actionFieldDefinition.action, + // key: next.key + // }, + // ] + // ``` + { + action: actionFieldDefinition.action, + attributeName: actionFieldDefinition.attributeName, + key: previous[field], + newKey: next[field], + }, + ] + // attribute + case 'attributeConstraint': + case 'inputHint': + return [ + ...nextUpdateActions, + { + action: actionFieldDefinition.action, + attributeName: actionFieldDefinition.attributeName, + newValue: next[field], + }, + ] + default: + return [ + ...nextUpdateActions, + { + action: actionFieldDefinition.action, + attributeName: actionFieldDefinition.attributeName, + [field]: next[field], + }, + ] + } + } + return nextUpdateActions + }, + [] + ) +} + +const generateUpdateActionsForAttributeDefinitions = ( + attributeDefinitions = [] +) => { + const removedAttributeDefinitions = attributeDefinitions.filter( + (attributeDefinition) => + attributeDefinition.previous && !attributeDefinition.next + ) + const updatedAttributeDefinitions = attributeDefinitions.filter( + (attributeDefinition) => + attributeDefinition.previous && attributeDefinition.next + ) + + const addedAttributeDefinitions = attributeDefinitions.filter( + (attributeDefinition) => + !attributeDefinition.previous && attributeDefinition.next + ) + + return [ + ...removedAttributeDefinitions.map((attributeDef) => ({ + action: 'removeAttributeDefinition', + name: attributeDef.previous.name, + })), + ...flatten( + updatedAttributeDefinitions.map((updatedAttributeDefinition) => + generateBaseFieldsUpdateActions( + updatedAttributeDefinition.previous, + updatedAttributeDefinition.next, + { + label: { + action: 'changeLabel', + attributeName: updatedAttributeDefinition.previous.name, + }, + inputTip: { + action: 'setInputTip', + attributeName: updatedAttributeDefinition.previous.name, + }, + inputHint: { + action: 'changeInputHint', + attributeName: updatedAttributeDefinition.previous.name, + }, + isSearchable: { + action: 'changeIsSearchable', + attributeName: updatedAttributeDefinition.previous.name, + }, + attributeConstraint: { + action: 'changeAttributeConstraint', + attributeName: updatedAttributeDefinition.previous.name, + }, + } + ) + ) + ), + ...addedAttributeDefinitions.map((attributeDef) => ({ + action: 'addAttributeDefinition', + attribute: attributeDef.next, + })), + ] +} +const generateUpdateActionsForAttributeEnumValues = ( + attributeEnumValues = [] +) => { + const removedAttributeEnumValues = attributeEnumValues.filter( + (attributeEnumValue) => + attributeEnumValue.previous && !attributeEnumValue.next + ) + const updatedAttributeEnumValues = attributeEnumValues.filter( + (attributeEnumValue) => + attributeEnumValue.next && attributeEnumValue.previous + ) + const addedAttributeEnumValues = attributeEnumValues.filter( + (attributeEnumValue) => + !attributeEnumValue.previous && attributeEnumValue.next + ) + + return [ + ...Object.values( + removedAttributeEnumValues.reduce( + (nextEnumUpdateActions, removedAttributeEnumValue) => { + const removedAttributeEnumValueOfSameAttributeName = + nextEnumUpdateActions[ + removedAttributeEnumValue.hint.attributeName + ] || { + keys: [], + attributeName: removedAttributeEnumValue.hint.attributeName, + action: 'removeEnumValues', + } + return { + ...nextEnumUpdateActions, + [removedAttributeEnumValue.hint.attributeName]: { + ...removedAttributeEnumValueOfSameAttributeName, + keys: [ + ...removedAttributeEnumValueOfSameAttributeName.keys, + removedAttributeEnumValue.previous.key, + ], + }, + } + }, + {} + ) + ), + ...flatten( + updatedAttributeEnumValues.map((updatedAttributeEnumValue) => { + const updateActions = generateBaseFieldsUpdateActions( + updatedAttributeEnumValue.previous, + updatedAttributeEnumValue.next, + { + key: { + action: 'changeEnumKey', + attributeName: updatedAttributeEnumValue.hint.attributeName, + }, + } + ) + if ( + !deepEqual( + updatedAttributeEnumValue.previous.label, + updatedAttributeEnumValue.next.label + ) + ) { + if (updatedAttributeEnumValue.hint.isLocalized) { + return [ + ...updateActions, + { + action: 'changeLocalizedEnumValueLabel', + attributeName: updatedAttributeEnumValue.hint.attributeName, + newValue: updatedAttributeEnumValue.next, + }, + ] + } + return [ + ...updateActions, + { + action: 'changePlainEnumValueLabel', + attributeName: updatedAttributeEnumValue.hint.attributeName, + newValue: updatedAttributeEnumValue.next, + }, + ] + } + return updateActions + }) + ), + ...addedAttributeEnumValues.map((addedAttributeEnumValue) => ({ + action: addedAttributeEnumValue.hint.isLocalized + ? 'addLocalizedEnumValue' + : 'addPlainEnumValue', + attributeName: addedAttributeEnumValue.hint.attributeName, + value: addedAttributeEnumValue.next, + })), + ] +} + +const generateChangeAttributeOrderAction = ( + attrsOld = [], + attrsNew = [], + updateActions = [] +) => { + if (!attrsOld.length || !attrsNew.length) return null + + const newAttributesOrder = attrsNew.map((attribute) => attribute.name) + + const removedAttributeNames = updateActions + .filter((action) => action.action === 'removeAttributeDefinition') + .map((action) => action.name) + + const addedAttributeNames = updateActions + .filter((action) => action.action === 'addAttributeDefinition') + .map((action) => action.attribute.name) + + // changeAttributeOrder action will be sent to CTP API as the last action so we have to + // calculate how the productType will look like after adding/removing attributes + const patchedOldAttributesOrder = attrsOld + .map((attribute) => attribute.name) + .filter((name) => !removedAttributeNames.includes(name)) + .concat(addedAttributeNames) + + if (newAttributesOrder.join(',') !== patchedOldAttributesOrder.join(',')) + return { + action: 'changeAttributeOrderByName', + attributeNames: newAttributesOrder, + } + + return null +} + +export const actionsMapForHints = ( + nestedValuesChanges: { + attributeDefinitions: Array + attributeEnumValues: Array + } = { attributeDefinitions: [], attributeEnumValues: [] }, + ptOld, + ptNew +) => { + const updateActions = [ + ...generateUpdateActionsForAttributeDefinitions( + nestedValuesChanges.attributeDefinitions + ), + ...generateUpdateActionsForAttributeEnumValues( + nestedValuesChanges.attributeEnumValues + ), + ] + + const changeAttributeOrderAction = generateChangeAttributeOrderAction( + ptOld.attributes, + ptNew.attributes, + updateActions + ) + + if (changeAttributeOrderAction) updateActions.push(changeAttributeOrderAction) + + return updateActions +} diff --git a/packages/sync-actions/src/product-types.ts b/packages/sync-actions/src/product-types.ts new file mode 100644 index 000000000..b5ca614f9 --- /dev/null +++ b/packages/sync-actions/src/product-types.ts @@ -0,0 +1,73 @@ +/* @flow */ +import flatten from 'lodash.flatten' +import type { + SyncAction, + UpdateAction, + ActionGroup, + SyncActionConfig as BaseSyncActionConfig, +} from '@commercetools/sdk-client-v2' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import * as productTypeActions from './product-types-actions' +import * as diffpatcher from './utils/diffpatcher' + +type SyncActionConfig = { withHints?: boolean } & BaseSyncActionConfig + +const actionGroups = ['base'] + +function createProductTypeMapActions( + mapActionGroup: ( + type: string, + fn: () => Array + ) => Array, + syncActionConfig?: SyncActionConfig +): (diff: any, next: any, previous: any, options: any) => Array { + return function doMapActions( + diff: any, + next: any, + previous: any, + options: any + ): Array { + return flatten([ + // we support only base fields for the product type, + // for attributes, applying hints would be recommended + mapActionGroup( + 'base', + (): Array => + productTypeActions.actionsMapBase( + diff, + previous, + next, + syncActionConfig + ) + ), + productTypeActions.actionsMapForHints( + options.nestedValuesChanges, + previous, + next + ), + ]) + } +} + +export default ( + actionGroupList?: Array, + syncActionConfig?: SyncActionConfig +): SyncAction => { + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createProductTypeMapActions( + mapActionGroup, + syncActionConfig + ) + const onBeforeApplyingDiff = null + const buildActions = createBuildActions( + diffpatcher.diff, + doMapActions, + onBeforeApplyingDiff, + { withHints: true } + ) + + return { buildActions } +} + +export { actionGroups } diff --git a/packages/sync-actions/src/products.ts b/packages/sync-actions/src/products.ts new file mode 100644 index 000000000..b1d504be6 --- /dev/null +++ b/packages/sync-actions/src/products.ts @@ -0,0 +1,201 @@ +/* @flow */ +import flatten from 'lodash.flatten' +import type { + SyncAction, + SyncActionConfig, + ActionGroup, + UpdateAction, +} from '@commercetools/sdk-client-v2' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import * as productActions from './product-actions' +import * as diffpatcher from './utils/diffpatcher' +import findMatchingPairs from './utils/find-matching-pairs' +import copyEmptyArrayProps from './utils/copy-empty-array-props' + +const actionGroups = [ + 'base', + 'meta', + 'references', + 'prices', + 'pricesCustom', + 'attributes', + 'images', + 'variants', + 'categories', + 'categoryOrderHints', +] + +function createProductMapActions( + mapActionGroup: Function, + syncActionConfig?: SyncActionConfig +): (diff: any, newObj: any, oldObj: any, options: any) => Array { + return function doMapActions( + diff: any, + newObj: any, + oldObj: any, + options: any = {} + ): Array { + const allActions = [] + const { sameForAllAttributeNames, enableDiscounted } = options + const { publish, staged } = newObj + + const variantHashMap = findMatchingPairs( + diff.variants, + oldObj.variants, + newObj.variants + ) + + allActions.push( + mapActionGroup( + 'attributes', + (): Array => + productActions.actionsMapAttributes( + diff, + oldObj, + newObj, + sameForAllAttributeNames || [], + variantHashMap + ) + ) + ) + + allActions.push( + mapActionGroup( + 'variants', + (): Array => + productActions.actionsMapAddVariants(diff, oldObj, newObj) + ) + ) + + allActions.push(productActions.actionsMapMasterVariant(oldObj, newObj)) + + allActions.push( + mapActionGroup( + 'variants', + (): Array => + productActions.actionsMapRemoveVariants(diff, oldObj, newObj) + ) + ) + + allActions.push( + mapActionGroup( + 'base', + (): Array => + productActions.actionsMapBase(diff, oldObj, newObj, syncActionConfig) + ) + ) + + allActions.push( + mapActionGroup( + 'meta', + (): Array => + productActions.actionsMapMeta(diff, oldObj, newObj) + ) + ) + + allActions.push( + mapActionGroup( + 'references', + (): Array => + productActions.actionsMapReferences(diff, oldObj, newObj) + ) + ) + + allActions.push( + mapActionGroup( + 'images', + (): Array => + productActions.actionsMapImages(diff, oldObj, newObj, variantHashMap) + ) + ) + + allActions.push( + mapActionGroup( + 'pricesCustom', + (): Array => + productActions.actionsMapPricesCustom( + diff, + oldObj, + newObj, + variantHashMap + ) + ) + ) + + allActions.push( + mapActionGroup( + 'prices', + (): Array => + productActions.actionsMapPrices( + diff, + oldObj, + newObj, + variantHashMap, + enableDiscounted + ) + ) + ) + + allActions.push( + mapActionGroup( + 'categories', + (): Array => productActions.actionsMapCategories(diff) + ) + ) + + allActions.push( + mapActionGroup( + 'categories', + (): Array => + productActions.actionsMapCategoryOrderHints(diff) + ) + ) + + allActions.push( + mapActionGroup( + 'assets', + (): Array => + productActions.actionsMapAssets(diff, oldObj, newObj, variantHashMap) + ) + ) + + if (publish === true || staged === false) + return flatten(allActions).map((action) => ({ ...action, staged: false })) + + return flatten(allActions) + } +} + +function moveMasterVariantsIntoVariants(before: any, now: any): Array { + const [beforeCopy, nowCopy] = copyEmptyArrayProps(before, now) + const move = (obj: any): any => ({ + ...obj, + masterVariant: undefined, + variants: [obj.masterVariant, ...(obj.variants || [])], + }) + const hasMasterVariant = (obj: any): any => obj && obj.masterVariant + + return [ + hasMasterVariant(beforeCopy) ? move(beforeCopy) : beforeCopy, + hasMasterVariant(nowCopy) ? move(nowCopy) : nowCopy, + ] +} + +export default ( + actionGroupList?: Array, + syncActionConfig?: SyncActionConfig +): SyncAction => { + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createProductMapActions(mapActionGroup, syncActionConfig) + + const buildActions = createBuildActions( + diffpatcher.diff, + doMapActions, + moveMasterVariantsIntoVariants + ) + + return { buildActions } +} + +export { actionGroups } diff --git a/packages/sync-actions/src/projects-actions.ts b/packages/sync-actions/src/projects-actions.ts new file mode 100644 index 000000000..aa7423351 --- /dev/null +++ b/packages/sync-actions/src/projects-actions.ts @@ -0,0 +1,25 @@ +import { buildBaseAttributesActions } from './utils/common-actions' + +export const baseActionsList = [ + { action: 'changeName', key: 'name' }, + { action: 'changeCurrencies', key: 'currencies' }, + { action: 'changeCountries', key: 'countries' }, + { action: 'changeLanguages', key: 'languages' }, + { action: 'changeMessagesConfiguration', key: 'messagesConfiguration' }, + { action: 'setShippingRateInputType', key: 'shippingRateInputType' }, +] + +export function actionsMapBase( + diff, + oldObj, + newObj, + config: { shouldOmitEmptyString?: boolean } = {} +) { + return buildBaseAttributesActions({ + actions: baseActionsList, + diff, + oldObj, + newObj, + shouldOmitEmptyString: config.shouldOmitEmptyString, + }) +} diff --git a/packages/sync-actions/src/projects.ts b/packages/sync-actions/src/projects.ts new file mode 100644 index 000000000..848de9de9 --- /dev/null +++ b/packages/sync-actions/src/projects.ts @@ -0,0 +1,31 @@ +import flatten from 'lodash.flatten' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import { actionsMapBase } from './projects-actions' +import * as diffpatcher from './utils/diffpatcher' + +export const actionGroups = ['base'] + +function createChannelsMapActions(mapActionGroup, syncActionConfig) { + return function doMapActions(diff, newObj, oldObj) { + const allActions = [] + + allActions.push( + mapActionGroup('base', () => + actionsMapBase(diff, oldObj, newObj, syncActionConfig) + ) + ) + + return flatten(allActions) + } +} + +export default (actionGroupList?, syncActionConfig?) => { + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createChannelsMapActions( + mapActionGroup, + syncActionConfig + ) + const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + return { buildActions } +} diff --git a/packages/sync-actions/src/quote-requests-actions.ts b/packages/sync-actions/src/quote-requests-actions.ts new file mode 100644 index 000000000..045bb1d2a --- /dev/null +++ b/packages/sync-actions/src/quote-requests-actions.ts @@ -0,0 +1,21 @@ +import { buildBaseAttributesActions } from './utils/common-actions' + +export const baseActionsList = [ + { action: 'changeQuoteRequestState', key: 'quoteRequestState' }, + { action: 'transitionState', key: 'state' }, +] + +export function actionsMapBase( + diff, + oldObj, + newObj, + config: { shouldOmitEmptyString?: boolean } = {} +) { + return buildBaseAttributesActions({ + actions: baseActionsList, + diff, + oldObj, + newObj, + shouldOmitEmptyString: config.shouldOmitEmptyString, + }) +} diff --git a/packages/sync-actions/src/quote-requests.ts b/packages/sync-actions/src/quote-requests.ts new file mode 100644 index 000000000..2a1f13ce0 --- /dev/null +++ b/packages/sync-actions/src/quote-requests.ts @@ -0,0 +1,67 @@ +/* @flow */ +import flatten from 'lodash.flatten' +import type { + SyncAction, + SyncActionConfig, + ActionGroup, + UpdateAction, +} from '@commercetools/sdk-client-v2' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import actionsMapCustom from './utils/action-map-custom' +import * as QuoteRequestsActions from './quote-requests-actions' +import * as diffpatcher from './utils/diffpatcher' + +const actionGroups = ['base', 'custom'] + +function createQuoteRequestsMapActions( + mapActionGroup: Function, + syncActionConfig?: SyncActionConfig +): (diff: any, newObj: any, oldObj: any, options: any) => Array { + return function doMapActions( + diff: any, + newObj: any, + oldObj: any + ): Array { + const allActions = [] + + allActions.push( + mapActionGroup( + 'base', + (): Array => + QuoteRequestsActions.actionsMapBase( + diff, + oldObj, + newObj, + syncActionConfig + ) + ) + ) + + allActions.push( + mapActionGroup( + 'custom', + (): Array => actionsMapCustom(diff, newObj, oldObj) + ) + ) + + return flatten(allActions) + } +} + +export default ( + actionGroupList?: Array, + syncActionConfig?: SyncActionConfig +): SyncAction => { + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createQuoteRequestsMapActions( + mapActionGroup, + syncActionConfig + ) + + const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + + return { buildActions } +} + +export { actionGroups } diff --git a/packages/sync-actions/src/quotes-actions.ts b/packages/sync-actions/src/quotes-actions.ts new file mode 100644 index 000000000..a6881cc64 --- /dev/null +++ b/packages/sync-actions/src/quotes-actions.ts @@ -0,0 +1,22 @@ +import { buildBaseAttributesActions } from './utils/common-actions' + +export const baseActionsList = [ + { action: 'changeQuoteState', key: 'quoteState' }, + { action: 'requestQuoteRenegotiation', key: 'buyerComment' }, + { action: 'transitionState', key: 'state' }, +] + +export function actionsMapBase( + diff, + oldObj, + newObj, + config: { shouldOmitEmptyString?: boolean } = {} +) { + return buildBaseAttributesActions({ + actions: baseActionsList, + diff, + oldObj, + newObj, + shouldOmitEmptyString: config.shouldOmitEmptyString, + }) +} diff --git a/packages/sync-actions/src/quotes.ts b/packages/sync-actions/src/quotes.ts new file mode 100644 index 000000000..1eedeb6d8 --- /dev/null +++ b/packages/sync-actions/src/quotes.ts @@ -0,0 +1,59 @@ +/* @flow */ +import flatten from 'lodash.flatten' +import type { + SyncAction, + SyncActionConfig, + ActionGroup, + UpdateAction, +} from '@commercetools/sdk-client-v2' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import actionsMapCustom from './utils/action-map-custom' +import * as QuotesActions from './quotes-actions' +import * as diffpatcher from './utils/diffpatcher' + +const actionGroups = ['base', 'custom'] + +function createQuotesMapActions( + mapActionGroup: Function, + syncActionConfig?: SyncActionConfig +): (diff: any, newObj: any, oldObj: any, options: any) => Array { + return function doMapActions( + diff: any, + newObj: any, + oldObj: any + ): Array { + const allActions = [] + + allActions.push( + mapActionGroup( + 'base', + (): Array => + QuotesActions.actionsMapBase(diff, oldObj, newObj, syncActionConfig) + ) + ) + + allActions.push( + mapActionGroup( + 'custom', + (): Array => actionsMapCustom(diff, newObj, oldObj) + ) + ) + + return flatten(allActions) + } +} + +export default ( + actionGroupList?: Array, + syncActionConfig?: SyncActionConfig +): SyncAction => { + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createQuotesMapActions(mapActionGroup, syncActionConfig) + + const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + + return { buildActions } +} + +export { actionGroups } diff --git a/packages/sync-actions/src/shipping-methods-actions.ts b/packages/sync-actions/src/shipping-methods-actions.ts new file mode 100644 index 000000000..57cea1fc8 --- /dev/null +++ b/packages/sync-actions/src/shipping-methods-actions.ts @@ -0,0 +1,128 @@ +import flatten from 'lodash.flatten' +import createBuildArrayActions, { + ADD_ACTIONS, + REMOVE_ACTIONS, + CHANGE_ACTIONS, +} from './utils/create-build-array-actions' +import { buildBaseAttributesActions } from './utils/common-actions' + +export const baseActionsList = [ + { action: 'setKey', key: 'key' }, + { action: 'changeName', key: 'name' }, + { action: 'setLocalizedName', key: 'localizedName' }, + { action: 'setDescription', key: 'description' }, + { action: 'setLocalizedDescription', key: 'localizedDescription' }, + { action: 'changeIsDefault', key: 'isDefault' }, + { action: 'setPredicate', key: 'predicate' }, + { action: 'changeTaxCategory', key: 'taxCategory' }, +] + +export function actionsMapBase( + diff, + oldObj, + newObj, + config: { shouldOmitEmptyString?: boolean } = {} +) { + return buildBaseAttributesActions({ + actions: baseActionsList, + diff, + oldObj, + newObj, + shouldOmitEmptyString: config.shouldOmitEmptyString, + }) +} + +const addShippingRates = (newZoneRate) => + newZoneRate.shippingRates + ? newZoneRate.shippingRates.map((shippingRate) => ({ + action: 'addShippingRate', + zone: newZoneRate.zone, + shippingRate, + })) + : [] + +function actionsMapZoneRatesShippingRates(diff, oldObj, newObj) { + const handler = createBuildArrayActions('shippingRates', { + [ADD_ACTIONS]: (newShippingRate) => ({ + action: 'addShippingRate', + zone: newObj.zone, + shippingRate: newShippingRate, + }), + [REMOVE_ACTIONS]: (oldShippingRate) => ({ + action: 'removeShippingRate', + zone: oldObj.zone, + shippingRate: oldShippingRate, + }), + [CHANGE_ACTIONS]: (oldShippingRate, newShippingRate) => [ + { + action: 'removeShippingRate', + zone: oldObj.zone, + shippingRate: oldShippingRate, + }, + { + action: 'addShippingRate', + zone: newObj.zone, + shippingRate: newShippingRate, + }, + ], + }) + + return handler(diff, oldObj, newObj) +} + +export function actionsMapZoneRates(diff, oldObj, newObj) { + const handler = createBuildArrayActions('zoneRates', { + [ADD_ACTIONS]: (newZoneRate) => [ + { + action: 'addZone', + zone: newZoneRate.zone, + }, + ...addShippingRates(newZoneRate), + ], + [REMOVE_ACTIONS]: (oldZoneRate) => ({ + action: 'removeZone', + zone: oldZoneRate.zone, + }), + [CHANGE_ACTIONS]: (oldZoneRate, newZoneRate) => { + let hasZoneActions = false + + const shippingRateActions = Object.keys(diff.zoneRates).reduce( + (actions, key) => { + if (diff.zoneRates[key].zone) hasZoneActions = true + + if (diff.zoneRates[key].shippingRates) + return [ + ...actions, + ...actionsMapZoneRatesShippingRates( + diff.zoneRates[key], + oldZoneRate, + newZoneRate + ), + ] + return actions + }, + [] + ) + + return flatten( + hasZoneActions + ? [ + ...shippingRateActions, + ...[ + { + action: 'removeZone', + zone: oldZoneRate.zone, + }, + { + action: 'addZone', + zone: newZoneRate.zone, + }, + ], + ] + : shippingRateActions + ) + }, + }) + + return handler(diff, oldObj, newObj) +} diff --git a/packages/sync-actions/src/shipping-methods.ts b/packages/sync-actions/src/shipping-methods.ts new file mode 100644 index 000000000..f94aec3c0 --- /dev/null +++ b/packages/sync-actions/src/shipping-methods.ts @@ -0,0 +1,80 @@ +/* @flow */ +import flatten from 'lodash.flatten' +import type { + SyncAction, + SyncActionConfig, + ActionGroup, + UpdateAction, +} from '@commercetools/sdk-client-v2' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import actionsMapCustom from './utils/action-map-custom' +import * as shippingMethodsActions from './shipping-methods-actions' +import * as diffpatcher from './utils/diffpatcher' + +export const actionGroups = ['base', 'zoneRates', 'custom'] + +function createShippingMethodsMapActions( + mapActionGroup: Function, + syncActionConfig?: SyncActionConfig +): (diff: any, newObj: any, oldObj: any) => Array { + return function doMapActions( + diff: any, + newObj: any, + oldObj: any + ): Array { + const allActions = [] + allActions.push( + mapActionGroup( + 'base', + (): Array => + shippingMethodsActions.actionsMapBase( + diff, + oldObj, + newObj, + syncActionConfig + ) + ) + ) + allActions.push( + flatten( + mapActionGroup( + 'zoneRates', + (): Array => + shippingMethodsActions.actionsMapZoneRates(diff, oldObj, newObj) + ) + ) + ) + allActions.push( + mapActionGroup( + 'custom', + (): Array => actionsMapCustom(diff, newObj, oldObj) + ) + ) + return flatten(allActions) + } +} + +export default ( + actionGroupList?: Array, + syncActionConfig?: SyncActionConfig +): SyncAction => { + // actionGroupList contains information about which action groups + // are allowed or ignored + + // createMapActionGroup returns function 'mapActionGroup' that takes params: + // - action group name + // - callback function that should return a list of actions that correspond + // to the for the action group + + // this resulting function mapActionGroup will call the callback function + // for allowed action groups and return the return value of the callback + // It will return an empty array for ignored action groups + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createShippingMethodsMapActions( + mapActionGroup, + syncActionConfig + ) + const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + return { buildActions } +} diff --git a/packages/sync-actions/src/staged-quotes-actions.ts b/packages/sync-actions/src/staged-quotes-actions.ts new file mode 100644 index 000000000..b454b7708 --- /dev/null +++ b/packages/sync-actions/src/staged-quotes-actions.ts @@ -0,0 +1,23 @@ +import { buildBaseAttributesActions } from './utils/common-actions' + +export const baseActionsList = [ + { action: 'changeStagedQuoteState', key: 'stagedQuoteState' }, + { action: 'setSellerComment', key: 'sellerComment' }, + { action: 'setValidTo', key: 'validTo' }, + { action: 'transitionState', key: 'state' }, +] + +export function actionsMapBase( + diff, + oldObj, + newObj, + config: { shouldOmitEmptyString?: boolean } = {} +) { + return buildBaseAttributesActions({ + actions: baseActionsList, + diff, + oldObj, + newObj, + shouldOmitEmptyString: config.shouldOmitEmptyString, + }) +} diff --git a/packages/sync-actions/src/staged-quotes.ts b/packages/sync-actions/src/staged-quotes.ts new file mode 100644 index 000000000..fb98232e4 --- /dev/null +++ b/packages/sync-actions/src/staged-quotes.ts @@ -0,0 +1,67 @@ +/* @flow */ +import flatten from 'lodash.flatten' +import type { + SyncAction, + SyncActionConfig, + ActionGroup, + UpdateAction, +} from '@commercetools/sdk-client-v2' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import actionsMapCustom from './utils/action-map-custom' +import * as StagedQuotesActions from './staged-quotes-actions' +import * as diffpatcher from './utils/diffpatcher' + +const actionGroups = ['base', 'custom'] + +function createStagedQuotesMapActions( + mapActionGroup: Function, + syncActionConfig?: SyncActionConfig +): (diff: any, newObj: any, oldObj: any, options: any) => Array { + return function doMapActions( + diff: any, + newObj: any, + oldObj: any + ): Array { + const allActions = [] + + allActions.push( + mapActionGroup( + 'base', + (): Array => + StagedQuotesActions.actionsMapBase( + diff, + oldObj, + newObj, + syncActionConfig + ) + ) + ) + + allActions.push( + mapActionGroup( + 'custom', + (): Array => actionsMapCustom(diff, newObj, oldObj) + ) + ) + + return flatten(allActions) + } +} + +export default ( + actionGroupList?: Array, + syncActionConfig?: SyncActionConfig +): SyncAction => { + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createStagedQuotesMapActions( + mapActionGroup, + syncActionConfig + ) + + const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + + return { buildActions } +} + +export { actionGroups } diff --git a/packages/sync-actions/src/state-actions.ts b/packages/sync-actions/src/state-actions.ts new file mode 100644 index 000000000..809f64bf3 --- /dev/null +++ b/packages/sync-actions/src/state-actions.ts @@ -0,0 +1,44 @@ +import { buildBaseAttributesActions } from './utils/common-actions' +import createBuildArrayActions, { + ADD_ACTIONS, + REMOVE_ACTIONS, +} from './utils/create-build-array-actions' + +export const baseActionsList = [ + { action: 'changeKey', key: 'key' }, + { action: 'setName', key: 'name' }, + { action: 'setDescription', key: 'description' }, + { action: 'changeType', key: 'type' }, + { action: 'changeInitial', key: 'initial' }, + { action: 'setTransitions', key: 'transitions' }, +] + +export function actionsMapBase( + diff, + oldObj, + newObj, + config: { shouldOmitEmptyString?: boolean } = {} +) { + return buildBaseAttributesActions({ + actions: baseActionsList, + diff, + oldObj, + newObj, + shouldOmitEmptyString: config.shouldOmitEmptyString, + }) +} + +export function actionsMapRoles(diff, oldObj, newObj) { + const buildArrayActions = createBuildArrayActions('roles', { + [ADD_ACTIONS]: (newRole) => ({ + action: 'addRoles', + roles: newRole, + }), + [REMOVE_ACTIONS]: (oldRole) => ({ + action: 'removeRoles', + roles: oldRole, + }), + }) + + return buildArrayActions(diff, oldObj, newObj) +} diff --git a/packages/sync-actions/src/states.ts b/packages/sync-actions/src/states.ts new file mode 100644 index 000000000..c18e26fc5 --- /dev/null +++ b/packages/sync-actions/src/states.ts @@ -0,0 +1,72 @@ +/* @flow */ +import flatten from 'lodash.flatten' +import type { + UpdateAction, + SyncAction, + ActionGroup, + SyncActionConfig, +} from '@commercetools/sdk-client-v2' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import * as stateActions from './state-actions' +import * as diffpatcher from './utils/diffpatcher' + +type RoleUpdate = { + action: string + roles: string +} + +export const actionGroups = ['base'] + +// This function groups `addRoles` and `removeRoles` actions to one array +function groupRoleActions([actions]: Array): Array { + const addActionRoles = [] + const removeActionRoles = [] + actions.forEach((action: UpdateAction) => { + if (action.action === 'removeRoles') removeActionRoles.push(action.roles) + if (action.action === 'addRoles') addActionRoles.push(action.roles) + }) + return [ + { action: 'removeRoles', roles: removeActionRoles }, + { action: 'addRoles', roles: addActionRoles }, + ].filter((action: UpdateAction): number => action.roles.length) +} + +function createStatesMapActions( + mapActionGroup: Function, + syncActionConfig?: SyncActionConfig +): (diff: any, newObj: any, oldObj: any) => Array { + return function doMapActions( + diff: any, + newObj: any, + oldObj: any + ): Array { + const baseActions = [] + const roleActions = [] + baseActions.push( + mapActionGroup( + 'base', + (): Array => + stateActions.actionsMapBase(diff, oldObj, newObj, syncActionConfig) + ) + ) + roleActions.push( + mapActionGroup( + 'roles', + (): Array => + stateActions.actionsMapRoles(diff, oldObj, newObj) + ) + ) + return flatten([...baseActions, ...groupRoleActions(roleActions)]) + } +} + +export default ( + actionGroupList?: Array, + syncActionConfig?: SyncActionConfig +): SyncAction => { + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createStatesMapActions(mapActionGroup, syncActionConfig) + const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + return { buildActions } +} diff --git a/packages/sync-actions/src/stores-actions.ts b/packages/sync-actions/src/stores-actions.ts new file mode 100644 index 000000000..7e1ad8a6a --- /dev/null +++ b/packages/sync-actions/src/stores-actions.ts @@ -0,0 +1,17 @@ +import { buildBaseAttributesActions } from './utils/common-actions' + +export const baseActionsList = [ + { action: 'setName', key: 'name' }, + { action: 'setLanguages', key: 'languages' }, + { action: 'setDistributionChannels', key: 'distributionChannels' }, + { action: 'setSupplyChannels', key: 'supplyChannels' }, +] + +export function actionsMapBase(diff, oldObj, newObj) { + return buildBaseAttributesActions({ + actions: baseActionsList, + diff, + oldObj, + newObj, + }) +} diff --git a/packages/sync-actions/src/stores.ts b/packages/sync-actions/src/stores.ts new file mode 100644 index 000000000..de9df04c1 --- /dev/null +++ b/packages/sync-actions/src/stores.ts @@ -0,0 +1,57 @@ +/* @flow */ +import flatten from 'lodash.flatten' +import type { + SyncAction, + UpdateAction, + ActionGroup, +} from '@commercetools/sdk-client-v2' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import actionsMapCustom from './utils/action-map-custom' +import * as storesActions from './stores-actions' +import * as diffpatcher from './utils/diffpatcher' + +export const actionGroups = ['base'] + +function createStoresMapActions( + mapActionGroup: ( + type: string, + fn: () => Array + ) => Array +): (diff: any, next: any, previous: any, options: any) => Array { + return function doMapActions( + diff: any, + next: any, + previous: any + ): Array { + const allActions = [] + allActions.push( + mapActionGroup( + 'base', + (): Array => + storesActions.actionsMapBase(diff, previous, next) + ) + ) + allActions.push( + mapActionGroup( + 'custom', + (): Array => actionsMapCustom(diff, next, previous) + ) + ) + + return flatten(allActions) + } +} + +export default (actionGroupList?: Array): SyncAction => { + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createStoresMapActions(mapActionGroup) + const onBeforeApplyingDiff = null + const buildActions = createBuildActions( + diffpatcher.diff, + doMapActions, + onBeforeApplyingDiff + ) + + return { buildActions } +} diff --git a/packages/sync-actions/src/tax-categories-actions.ts b/packages/sync-actions/src/tax-categories-actions.ts new file mode 100644 index 000000000..a62b869d5 --- /dev/null +++ b/packages/sync-actions/src/tax-categories-actions.ts @@ -0,0 +1,48 @@ +import { buildBaseAttributesActions } from './utils/common-actions' +import createBuildArrayActions, { + ADD_ACTIONS, + REMOVE_ACTIONS, + CHANGE_ACTIONS, +} from './utils/create-build-array-actions' + +export const baseActionsList = [ + { action: 'changeName', key: 'name' }, + { action: 'setKey', key: 'key' }, + { action: 'setDescription', key: 'description' }, +] + +export function actionsMapBase( + diff, + oldObj, + newObj, + config: { shouldOmitEmptyString?: boolean } = {} +) { + return buildBaseAttributesActions({ + actions: baseActionsList, + diff, + oldObj, + newObj, + shouldOmitEmptyString: config.shouldOmitEmptyString, + }) +} + +export function actionsMapRates(diff, oldObj, newObj) { + const handler = createBuildArrayActions('rates', { + [ADD_ACTIONS]: (newObject) => ({ + action: 'addTaxRate', + taxRate: newObject, + }), + [REMOVE_ACTIONS]: (objectToRemove) => ({ + action: 'removeTaxRate', + taxRateId: objectToRemove.id, + }), + [CHANGE_ACTIONS]: (oldObject, updatedObject) => ({ + action: 'replaceTaxRate', + taxRateId: + oldObject.id === updatedObject.id ? oldObject.id : updatedObject.id, + taxRate: updatedObject, + }), + }) + + return handler(diff, oldObj, newObj) +} diff --git a/packages/sync-actions/src/tax-categories.ts b/packages/sync-actions/src/tax-categories.ts new file mode 100644 index 000000000..f5b2e5bbe --- /dev/null +++ b/packages/sync-actions/src/tax-categories.ts @@ -0,0 +1,74 @@ +/* @flow */ +import flatten from 'lodash.flatten' +import type { + SyncAction, + ActionGroup, + UpdateAction, + SyncActionConfig, +} from '@commercetools/sdk-client-v2' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import * as taxCategoriesActions from './tax-categories-actions' +import * as diffpatcher from './utils/diffpatcher' + +export const actionGroups = ['base', 'rates'] + +function createTaxCategoriesMapActions( + mapActionGroup: ( + type: string, + fn: () => Array + ) => Array, + syncActionConfig?: SyncActionConfig +): (diff: any, newObj: any, oldObj: any) => Array { + return function doMapActions( + diff: any, + newObj: any, + oldObj: any + ): Array { + const allActions = [] + allActions.push( + mapActionGroup( + 'base', + (): Array => + taxCategoriesActions.actionsMapBase( + diff, + oldObj, + newObj, + syncActionConfig + ) + ) + ) + allActions.push( + mapActionGroup( + 'rates', + (): Array => + taxCategoriesActions.actionsMapRates(diff, oldObj, newObj) + ) + ) + return flatten(allActions) + } +} + +export default ( + actionGroupList?: Array, + syncActionConfig?: SyncActionConfig +): SyncAction => { + // config contains information about which action groups + // are allowed or ignored + + // createMapActionGroup returns function 'mapActionGroup' that takes params: + // - action group name + // - callback function that should return a list of actions that correspond + // to the for the action group + + // this resulting function mapActionGroup will call the callback function + // for allowed action groups and return the return value of the callback + // It will return an empty array for ignored action groups + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createTaxCategoriesMapActions( + mapActionGroup, + syncActionConfig + ) + const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + return { buildActions } +} diff --git a/packages/sync-actions/src/types-actions.ts b/packages/sync-actions/src/types-actions.ts new file mode 100644 index 000000000..1b8f9bd43 --- /dev/null +++ b/packages/sync-actions/src/types-actions.ts @@ -0,0 +1,213 @@ +import forEach from 'lodash.foreach' +import flatten from 'lodash.flatten' +import sortBy from 'lodash.sortby' + +import isEqual from 'lodash.isequal' +import createBuildArrayActions, { + ADD_ACTIONS, + CHANGE_ACTIONS, +} from './utils/create-build-array-actions' +import { buildBaseAttributesActions } from './utils/common-actions' +import * as diffPatcher from './utils/diffpatcher' +import extractMatchingPairs from './utils/extract-matching-pairs' + +const REGEX_NUMBER = new RegExp(/^\d+$/) +const REGEX_UNDERSCORE_NUMBER = new RegExp(/^_\d+$/) +const getIsChangedOperation = (key) => REGEX_NUMBER.test(key) +const getIsRemovedOperation = (key) => REGEX_UNDERSCORE_NUMBER.test(key) + +export const baseActionsList = [ + { action: 'changeKey', key: 'key' }, + { action: 'changeName', key: 'name' }, + { action: 'setDescription', key: 'description' }, +] + +export function actionsMapBase( + diff, + oldObj, + newObj, + config: { shouldOmitEmptyString?: boolean } = {} +) { + return buildBaseAttributesActions({ + actions: baseActionsList, + diff, + oldObj, + newObj, + shouldOmitEmptyString: config.shouldOmitEmptyString, + }) +} + +function actionsMapEnums( + fieldName, + attributeType, + attributeDiff, + previous, + next +) { + const addEnumActionName = + attributeType === 'Enum' ? 'addEnumValue' : 'addLocalizedEnumValue' + const changeEnumValueLabelActionName = + attributeType === 'Enum' + ? 'changeEnumValueLabel' + : 'changeLocalizedEnumValueLabel' + const changeEnumOrderActionName = + attributeType === 'Enum' + ? 'changeEnumValueOrder' + : 'changeLocalizedEnumValueOrder' + const buildArrayActions = createBuildArrayActions('values', { + [ADD_ACTIONS]: (newEnum) => ({ + fieldName, + action: addEnumActionName, + value: newEnum, + }), + [CHANGE_ACTIONS]: (oldEnum, newEnum) => { + const oldEnumInNext = next.values.find( + (nextEnum) => nextEnum.key === oldEnum.key + ) + + // These `changeActions` would impose a nested structure among + // the accumulated `updateActions` generated by `buildArrayActions` + // In the end; we have to flatten the structure before we pass it back + // to the client. + const changeActions = [] + if (oldEnumInNext) { + // If the enum value is changed, we need to change the order first + const isKeyChanged = oldEnum.key !== newEnum.key + + // check if the label is changed + const foundPreviousEnum = previous.values.find( + (previousEnum) => previousEnum.key === newEnum.key + ) + const isLabelEqual = isEqual(foundPreviousEnum.label, newEnum.label) + + if (isKeyChanged) { + // these actions is then flatten in the end + changeActions.push({ + fieldName, + action: changeEnumOrderActionName, + value: newEnum, + }) + } + + if (!isLabelEqual) { + changeActions.push({ + fieldName, + action: changeEnumValueLabelActionName, + value: newEnum, + }) + } + } else { + changeActions.push({ + fieldName, + action: addEnumActionName, + value: newEnum, + }) + } + return changeActions + }, + }) + + const actions = [] + // following lists are necessary to ensure that when we change the + // order of enumValues, we generate one updateAction instead of one at a time. + let newEnumValuesOrder = [] + + flatten(buildArrayActions(attributeDiff, previous, next)).forEach( + (updateAction) => { + if (updateAction.action === changeEnumOrderActionName) { + newEnumValuesOrder = next.values.map((enumValue) => enumValue.key) + } else actions.push(updateAction) + } + ) + + return [ + ...actions, + ...(newEnumValuesOrder.length > 0 + ? [ + { + fieldName, + action: changeEnumOrderActionName, + keys: newEnumValuesOrder, + }, + ] + : []), + ] +} + +export function actionsMapFieldDefinitions( + fieldDefinitionsDiff, + previous, + next, + diffPaths +) { + const actions = [] + forEach(fieldDefinitionsDiff, (diffValue, diffKey) => { + const extractedPairs = extractMatchingPairs( + diffPaths, + diffKey, + previous, + next + ) + + if (getIsChangedOperation(diffKey)) { + if (Array.isArray(diffValue)) { + const deltaValue = diffPatcher.getDeltaValue(diffValue) + if (deltaValue.name) { + actions.push({ + action: 'addFieldDefinition', + fieldDefinition: deltaValue, + }) + } + } else if (diffValue.label) { + actions.push({ + action: 'changeLabel', + label: extractedPairs.newObj.label, + fieldName: extractedPairs.oldObj.name, + }) + } else if (diffValue.inputHint) { + actions.push({ + action: 'changeInputHint', + inputHint: extractedPairs.newObj.inputHint, + fieldName: extractedPairs.oldObj.name, + }) + } else if (diffValue?.type?.values) { + actions.push( + ...actionsMapEnums( + extractedPairs.oldObj.name, + extractedPairs.oldObj.type.name, + diffValue.type, + extractedPairs.oldObj.type, + extractedPairs.newObj.type + ) + ) + } + } else if (getIsRemovedOperation(diffKey)) { + if (Array.isArray(diffValue)) { + if (diffValue.length === 3 && diffValue[2] === 3) { + actions.push({ + action: 'changeFieldDefinitionOrder', + fieldNames: next.map((n) => n.name), + }) + } else { + const deltaValue = diffPatcher.getDeltaValue(diffValue) + if (deltaValue === undefined && diffValue[0].name) + actions.push({ + action: 'removeFieldDefinition', + fieldName: diffValue[0].name, + }) + } + } + } + }) + + // Make sure to execute removeActions before creating new ones + // in order to prevent any eventual removal of `addAction`. + // List of `removeActions` can be found here + // https://docs.commercetools.com/http-api-projects-types.html#change-key + const sortedActions = sortBy( + actions, + (action) => action.action !== 'removeFieldDefinition' + ) + + return sortedActions +} diff --git a/packages/sync-actions/src/types.ts b/packages/sync-actions/src/types.ts new file mode 100644 index 000000000..9627e80d1 --- /dev/null +++ b/packages/sync-actions/src/types.ts @@ -0,0 +1,50 @@ +import flatten from 'lodash.flatten' + +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import * as typeActions from './types-actions' +import * as diffPatcher from './utils/diffpatcher' +import findMatchingPairs from './utils/find-matching-pairs' +import { SyncActionConfig } from '@commercetools/sdk-client-v2' + +const actionGroups = ['base', 'fieldDefinitions'] + +function createTypeMapActions( + mapActionGroup, + syncActionConfig: { shouldOmitEmptyString?: boolean } +) { + return function doMapActions(diff, next, previous) { + const allActions = [] + allActions.push( + mapActionGroup('base', () => + typeActions.actionsMapBase(diff, previous, next, syncActionConfig) + ), + mapActionGroup('fieldDefinitions', () => + typeActions.actionsMapFieldDefinitions( + diff.fieldDefinitions, + previous.fieldDefinitions, + next.fieldDefinitions, + findMatchingPairs( + diff.fieldDefinitions, + previous.fieldDefinitions, + next.fieldDefinitions, + 'name' + ) + ) + ) + ) + return flatten(allActions) + } +} + +export default ( + actionGroupList?: Array, + syncActionConfig?: SyncActionConfig +) => { + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createTypeMapActions(mapActionGroup, syncActionConfig) + const buildActions = createBuildActions(diffPatcher.diff, doMapActions) + return { buildActions } +} + +export { actionGroups } diff --git a/packages/sync-actions/src/utils/action-map-custom.ts b/packages/sync-actions/src/utils/action-map-custom.ts new file mode 100644 index 000000000..ba6b303be --- /dev/null +++ b/packages/sync-actions/src/utils/action-map-custom.ts @@ -0,0 +1,82 @@ +import * as diffpatcher from './diffpatcher' + +const Actions = { + setCustomType: 'setCustomType', + setCustomField: 'setCustomField', +} + +const hasSingleCustomFieldChanged = (diff) => Array.isArray(diff.custom) +const haveMultipleCustomFieldsChanged = (diff) => Boolean(diff.custom.fields) +const hasCustomTypeChanged = (diff) => Boolean(diff.custom.type) +const extractCustomType = (diff, previousObject) => + Array.isArray(diff.custom.type) + ? diffpatcher.getDeltaValue(diff.custom.type, previousObject) + : diff.custom.type +const extractTypeId = (type, nextObject) => + Array.isArray(type.id) + ? diffpatcher.getDeltaValue(type.id) + : nextObject.custom.type.id +const extractTypeKey = (type, nextObject) => + Array.isArray(type.key) + ? diffpatcher.getDeltaValue(type.key) + : nextObject.custom.type.key +const extractTypeFields = (diffedFields, nextFields) => + Array.isArray(diffedFields) + ? diffpatcher.getDeltaValue(diffedFields) + : nextFields +const extractFieldValue = (newFields, fieldName) => newFields[fieldName] + +export default function actionsMapCustom( + diff: any, + newObj: any, + oldObj: any, + customProps: { actions: any; priceId?: string } = { + actions: {}, + } +) { + const actions = [] + const { actions: customPropsActions, ...options } = customProps + const actionGroup = { ...Actions, ...customPropsActions } + + if (!diff.custom) return actions + if (hasSingleCustomFieldChanged(diff)) { + // If custom is not defined on the new or old category + const custom = diffpatcher.getDeltaValue(diff.custom, oldObj) + actions.push({ action: actionGroup.setCustomType, ...options, ...custom }) + } else if (hasCustomTypeChanged(diff)) { + // If custom is set to an empty object on the new or old category + const type = extractCustomType(diff, oldObj) + + if (!type) actions.push({ action: actionGroup.setCustomType, ...options }) + else if (type.id) + actions.push({ + action: actionGroup.setCustomType, + ...options, + type: { + typeId: 'type', + id: extractTypeId(type, newObj), + }, + fields: extractTypeFields(diff.custom.fields, newObj.custom.fields), + }) + else if (type.key) + actions.push({ + action: actionGroup.setCustomType, + ...options, + type: { + typeId: 'type', + key: extractTypeKey(type, newObj), + }, + fields: extractTypeFields(diff.custom.fields, newObj.custom.fields), + }) + } else if (haveMultipleCustomFieldsChanged(diff)) { + const customFieldsActions = Object.keys(diff.custom.fields).map((name) => ({ + action: actionGroup.setCustomField, + ...options, + name, + value: extractFieldValue(newObj.custom.fields, name), + })) + actions.push(...customFieldsActions) + } + + return actions +} diff --git a/packages/sync-actions/src/utils/clone.ts b/packages/sync-actions/src/utils/clone.ts new file mode 100644 index 000000000..96a7ef9e7 --- /dev/null +++ b/packages/sync-actions/src/utils/clone.ts @@ -0,0 +1,3 @@ +export default function clone(obj) { + return JSON.parse(JSON.stringify(obj)) +} diff --git a/packages/sync-actions/src/utils/combine-validity-actions.ts b/packages/sync-actions/src/utils/combine-validity-actions.ts new file mode 100644 index 000000000..4cb6b7222 --- /dev/null +++ b/packages/sync-actions/src/utils/combine-validity-actions.ts @@ -0,0 +1,20 @@ +const validityActions = ['setValidFrom', 'setValidUntil'] + +const isValidityActions = (actionName) => validityActions.includes(actionName) + +export default function combineValidityActions(actions = []) { + const [setValidFromAction, setValidUntilAction] = actions.filter((item) => + isValidityActions(item.action) + ) + if (setValidFromAction && setValidUntilAction) { + return [ + ...actions.filter((item) => !isValidityActions(item.action)), + { + action: 'setValidFromAndUntil', + validFrom: setValidFromAction.validFrom, + validUntil: setValidUntilAction.validUntil, + }, + ] + } + return actions +} diff --git a/packages/sync-actions/src/utils/common-actions.ts b/packages/sync-actions/src/utils/common-actions.ts new file mode 100644 index 000000000..fe7ed7fa5 --- /dev/null +++ b/packages/sync-actions/src/utils/common-actions.ts @@ -0,0 +1,125 @@ +import isNil from 'lodash.isnil' +import clone from './clone' +import * as diffpatcher from './diffpatcher' + +const normalizeValue = (value) => + typeof value === 'string' ? value.trim() : value + +export const createIsEmptyValue = (emptyValues) => (value) => + emptyValues.some((emptyValue) => emptyValue === normalizeValue(value)) + +/** + * Builds actions for simple object properties, given a list of actions + * E.g. [{ action: `changeName`, key: 'name' }] + * + * @param {Array} options.actions - a list of actions to be built + * based on the given property + * @param {Object} options.diff - the diff object + * @param {Object} options.oldObj - the object that needs to be updated + * @param {Object} options.newObj - the new representation of the object + * @param {Boolean} options.shouldOmitEmptyString - a flag to determine if we should treat an empty string a NON-value + */ +export function buildBaseAttributesActions({ + actions, + diff, + oldObj, + newObj, + shouldOmitEmptyString, +}: { + actions: Array + diff: any + oldObj: any + newObj: any + shouldOmitEmptyString?: boolean +}) { + const isEmptyValue = createIsEmptyValue( + shouldOmitEmptyString ? [undefined, null, ''] : [undefined, null] + ) + return actions + .map((item) => { + const key = item.key // e.g.: name, description, ... + const actionKey = item.actionKey || item.key + const delta = diff[key] + const before = oldObj[key] + const now = newObj[key] + const isNotDefinedBefore = isEmptyValue(oldObj[key]) + const isNotDefinedNow = isEmptyValue(newObj[key]) + if (!delta) return undefined + + if (isNotDefinedNow && isNotDefinedBefore) return undefined + + if (!isNotDefinedNow && isNotDefinedBefore) + // no value previously set + return { action: item.action, [actionKey]: now } + + /* no new value */ + if (isNotDefinedNow && !{}.hasOwnProperty.call(newObj, key)) + return undefined + + if (isNotDefinedNow && {}.hasOwnProperty.call(newObj, key)) + // value unset + return { action: item.action } + + // We need to clone `before` as `patch` will mutate it + const patched = diffpatcher.patch(clone(before), delta) + return { action: item.action, [actionKey]: patched } + }) + .filter((action) => !isNil(action)) +} + +/** + * Builds actions for simple reference objects, given a list of actions + * E.g. [{ action: `setTaxCategory`, key: 'taxCategory' }] + * + * @param {Array} options.actions - a list of actions to be built + * based on the given property + * @param {Object} options.diff - the diff object + * @param {Object} options.oldObj - the object that needs to be updated + * @param {Object} options.newObj - the new representation of the object + */ +export function buildReferenceActions({ actions, diff, oldObj, newObj }) { + return actions + .map((item) => { + const action = item.action + const key = item.key + + if ( + diff[key] && + // The `key` value was added or removed + (Array.isArray(diff[key]) || + // The `key` value id changed + diff[key].id) + ) { + const newValue = Array.isArray(diff[key]) + ? diffpatcher.getDeltaValue(diff[key]) + : newObj[key] + + if (!newValue) return { action } + + // When the `id` of the object is undefined + if (!newValue.id) { + return { + action, + [key]: { + typeId: newValue.typeId, + key: newValue.key, + }, + } + } + + return { + action, + // We only need to pass a reference to the object. + // This prevents accidentally sending the expanded (`obj`) + // over the wire. + [key]: { + typeId: newValue.typeId, + id: newValue.id, + }, + } + } + + return undefined + }) + .filter((action) => action) +} diff --git a/packages/sync-actions/src/utils/copy-empty-array-props.ts b/packages/sync-actions/src/utils/copy-empty-array-props.ts new file mode 100644 index 000000000..d6767cdae --- /dev/null +++ b/packages/sync-actions/src/utils/copy-empty-array-props.ts @@ -0,0 +1,74 @@ +import isNil from 'lodash.isnil' + +const CUSTOM = 'custom' + +/** + * @function copyEmptyArrayProps + * @description Create new key with empty array value on `newobj` for the arrays exist on `oldObj` and doesnt exist on `newobj` + * One use case is to easily compare two object without generating this error `Cannot read property '0' of undefined` + * @param {Object} oldObj + * @param {Object} newObj + * @returns {Array} Ordered Array [oldObj, newObj] + */ +export default function copyEmptyArrayProps(oldObj = {}, newObj = {}) { + if (!isNil(oldObj) && !isNil(newObj)) { + const nextObjectWithEmptyArray = Object.entries(oldObj).reduce( + (merged, [key, value]) => { + // Ignore CUSTOM key as this object is dynamic and its up to the user to dynamically change it + // todo, it would be better if we pass it as ignored keys param + if (key === CUSTOM) return merged + + if (Array.isArray(value) && newObj[key] && newObj[key].length >= 1) { + /* eslint-disable no-plusplus */ + const hashMapValue = value.reduce((acc, val) => { + acc[val.id] = val + return acc + }, {}) + for (let i = 0; i < newObj[key].length; i++) { + if ( + !isNil(newObj[key][i]) && + typeof newObj[key][i] === 'object' && + !isNil(newObj[key][i].id) + ) { + // Since its unordered array elements then check if the element on `oldObj` exists by id + const foundObject = hashMapValue[newObj[key][i].id] + if (!isNil(foundObject)) { + const [, nestedObject] = copyEmptyArrayProps( + foundObject, + newObj[key][i] + ) + if (Object.isFrozen(merged[key])) { + /* eslint-disable no-param-reassign */ + merged[key] = merged[key].slice() + } + /* eslint-disable no-param-reassign */ + merged[key][i] = nestedObject + } + } + } + + return merged + } + if (Array.isArray(value)) { + merged[key] = isNil(newObj[key]) ? [] : newObj[key] + return merged + } + if ( + !isNil(newObj[key]) && + typeof value === 'object' && + // Ignore Date as this will create invalid object since typeof date === 'object' return true + // ex: {date: new Date()} will result {date: {}} + !(value instanceof Date) + ) { + const [, nestedObject] = copyEmptyArrayProps(value, newObj[key]) + merged[key] = nestedObject + return merged + } + return merged + }, + { ...newObj } + ) + return [oldObj, nextObjectWithEmptyArray] + } + return [oldObj, newObj] +} diff --git a/packages/sync-actions/src/utils/create-build-actions.ts b/packages/sync-actions/src/utils/create-build-actions.ts new file mode 100644 index 000000000..a3ee4c7af --- /dev/null +++ b/packages/sync-actions/src/utils/create-build-actions.ts @@ -0,0 +1,96 @@ +import isEqual from 'lodash.isequal' +import isNil from 'lodash.isnil' + +function applyOnBeforeDiff(before, now, fn?: (before, now) => Array) { + return fn && typeof fn === 'function' ? fn(before, now) : [before, now] +} + +const createPriceComparator = (price) => ({ + value: { currencyCode: price.value.currencyCode }, + channel: price.channel, + country: price.country, + customerGroup: price.customerGroup, + validFrom: price.validFrom, + validUntil: price.validUntil, +}) + +function arePricesStructurallyEqual(oldPrice, newPrice) { + const oldPriceComparison = createPriceComparator(oldPrice) + const newPriceComparison = createPriceComparator(newPrice) + return isEqual(newPriceComparison, oldPriceComparison) +} + +function extractPriceFromPreviousVariant(newPrice, previousVariant) { + if (!previousVariant) return null + const price = previousVariant.prices.find((oldPrice) => + arePricesStructurallyEqual(oldPrice, newPrice) + ) + return price || null +} + +function injectMissingPriceIds(nextVariants, previousVariants) { + return nextVariants.map((newVariant) => { + const { prices, ...restOfVariant } = newVariant + + if (!prices) return restOfVariant + const oldVariant = previousVariants.find( + (previousVariant) => + (!isNil(previousVariant.id) && previousVariant.id === newVariant.id) || + (!isNil(previousVariant.key) && + previousVariant.key === newVariant.key) || + (!isNil(previousVariant.sku) && previousVariant.sku === newVariant.sku) + ) + + return { + ...restOfVariant, + prices: prices.map((price) => { + const newPrice = { ...price } + const oldPrice = extractPriceFromPreviousVariant(price, oldVariant) + + if (oldPrice) { + // copy ID if not provided + if (!newPrice.id) newPrice.id = oldPrice.id + + if (isNil(newPrice.value.type)) + newPrice.value.type = oldPrice.value.type + + if (isNil(newPrice.value.fractionDigits)) + newPrice.value.fractionDigits = oldPrice.value.fractionDigits + } + + return newPrice + }), + } + }) +} + +export default function createBuildActions( + differ, + doMapActions, + onBeforeDiff?: (before, now) => Array, + buildActionsConfig: any = {} +) { + return function buildActions(now, before, options = {}) { + if (!now || !before) + throw new Error( + 'Missing either `newObj` or `oldObj` ' + + 'in order to build update actions' + ) + + const [processedBefore, processedNow] = applyOnBeforeDiff( + before, + now, + onBeforeDiff + ) + + if (processedNow.variants && processedBefore.variants) + processedNow.variants = injectMissingPriceIds( + processedNow.variants, + processedBefore.variants + ) + + const diffed = differ(processedBefore, processedNow) + if (!buildActionsConfig.withHints && !diffed) return [] + return doMapActions(diffed, processedNow, processedBefore, options) + } +} diff --git a/packages/sync-actions/src/utils/create-build-array-actions.ts b/packages/sync-actions/src/utils/create-build-array-actions.ts new file mode 100644 index 000000000..b752b630c --- /dev/null +++ b/packages/sync-actions/src/utils/create-build-array-actions.ts @@ -0,0 +1,131 @@ +const REGEX_NUMBER = new RegExp(/^\d+$/) +const REGEX_UNDERSCORE_NUMBER = new RegExp(/^_\d+$/) + +export const ADD_ACTIONS = 'create' +export const REMOVE_ACTIONS = 'remove' +export const CHANGE_ACTIONS = 'change' + +/** + * Tests a delta to see if it represents a create action. + * eg. delta: + * { + * 0: [ { foo: 'bar' } ] + * } + * + * @param {object} obj The delta generated by the diffpatcher + * @param {string} key key of generated delta to examine + * @return {Boolean} Returns true if delta represents a create action, + * false otherwise + */ +function isCreateAction(obj, key) { + return ( + REGEX_NUMBER.test(key) && Array.isArray(obj[key]) && obj[key].length === 1 + ) +} + +/** + * Tests a delta to see if it represents a change action. + * eg. delta: + * + * { + * 0: { + * foo: ['bar', 'baz'] + * } + * } + * @param {object} obj The delta generated by the diffpatcher + * @param {string} key key of generated delta to examine + * @return {Boolean} Returns true if delta represents a change action, + * false otherwise + */ +function isChangeAction(obj, key) { + return ( + REGEX_NUMBER.test(key) && + (typeof obj[key] === 'object' || typeof obj[key] === 'string') + ) +} + +/** + * Tests a delta to see if it represents a remove action. + * eg. delta: + * + * { + * _0: [ 'foo', 0, 0 ] + * } + * @param {object} obj The delta generated by the diffpatcher + * @param {string} key key of generated delta to examine + * @return {Boolean} Returns true if delta represents a remove action, + * false otherwise + */ +function isRemoveAction(obj, key) { + return ( + REGEX_UNDERSCORE_NUMBER.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 + ) +} + +/** + * Generate + configure a function to build actions for nested objects + * @param {string} key key of the attribute containing the array of + * nested objects + * @param {object} config configuration object that can contain the keys + * [ADD_ACTIONS, REMOVE_ACTIONS, CHANGE_ACTIONS], each of + * which is a function. The function should accept the old + new arrays and + * return an action object. + * @return {Array} The generated array of actions + */ +export default function createBuildArrayActions(key, config) { + return function buildArrayActions(diff, oldObj, newObj) { + const addActions = [] + const removeActions = [] + const changeActions = [] + + if (diff[key]) { + const arrayDelta = diff[key] + + Object.keys(arrayDelta).forEach((index) => { + if (config[ADD_ACTIONS] && isCreateAction(arrayDelta, index)) { + const actionGenerator = config[ADD_ACTIONS] + // When adding a new element you don't need the oldObj + const action = actionGenerator( + newObj[key][index], + parseInt(index, 10) + ) + + if (action) addActions.push(action) + } else if ( + config[CHANGE_ACTIONS] && + isChangeAction(arrayDelta, index) + ) { + const actionGenerator = config[CHANGE_ACTIONS] + // When changing an existing element you need both old + new + const action = actionGenerator( + oldObj[key][index], + newObj[key][index], + parseInt(index, 10) + ) + + if (action) changeActions.push(action) + } else if ( + config[REMOVE_ACTIONS] && + isRemoveAction(arrayDelta, index) + ) { + const realIndex = index.replace('_', '') + const actionGenerator = config[REMOVE_ACTIONS] + // When removing an existing element you don't need the newObj + const action = actionGenerator( + oldObj[key][realIndex], + parseInt(realIndex, 10) + ) + + if (action) removeActions.push(action) + } + }) + } + + return changeActions.concat(removeActions, addActions) + } +} diff --git a/packages/sync-actions/src/utils/create-map-action-group.ts b/packages/sync-actions/src/utils/create-map-action-group.ts new file mode 100644 index 000000000..f42940091 --- /dev/null +++ b/packages/sync-actions/src/utils/create-map-action-group.ts @@ -0,0 +1,24 @@ +// Array of action groups which need to be allowed or ignored. +// Example: +// [ +// { type: 'base', group: 'ignore' }, +// { type: 'prices', group: 'allow' }, +// { type: 'variants', group: 'ignore' }, +// ] +export default function createMapActionGroup(actionGroups = []) { + return function mapActionGroup(type, fn) { + if (!Object.keys(actionGroups).length) return fn() + + const found = actionGroups.find((c) => c.type === type) + if (!found) return [] + + // Keep `black` for backwards compatibility. + if (found.group === 'ignore' || found.group === 'black') return [] + // Keep `white` for backwards compatibility. + if (found.group === 'allow' || found.group === 'white') return fn() + + throw new Error( + `Action group '${found.group}' not supported. Use either "allow" or "ignore".` + ) + } +} diff --git a/packages/sync-actions/src/utils/diffpatcher.ts b/packages/sync-actions/src/utils/diffpatcher.ts new file mode 100644 index 000000000..42dabb8ee --- /dev/null +++ b/packages/sync-actions/src/utils/diffpatcher.ts @@ -0,0 +1,70 @@ +// jsondiffpatch does not yet handle minified UMD builds +// with es6 modules so we use require instead below +// TODO create an issue here https://github.com/benjamine/jsondiffpatch/issues/new +const DiffPatcher = require('jsondiffpatch').DiffPatcher + +export function objectHash(obj, index) { + const objIndex = `$$index:${index}` + return typeof obj === 'object' && obj !== null + ? obj.id || obj.name || obj.url || objIndex + : objIndex +} + +const diffpatcher = new DiffPatcher({ + objectHash, + arrays: { + // detect items moved inside the array + detectMove: true, + + // value of items moved is not included in deltas + includeValueOnMove: false, + }, + textDiff: { + /** + * jsondiffpatch uses a very fine-grained diffing algorithm for long strings to easily identify + * what changed between strings. However, we don't actually care about what changed, just + * if the string changed at all. So we set the minimum length to diff to a very large number to avoid + * using the very slow algorithm. + * See https://github.com/benjamine/jsondiffpatch/blob/master/docs/deltas.md#text-diffs. + */ + minLength: Number.MAX_SAFE_INTEGER, + }, +}) + +export function diff(oldObj, newObj) { + return diffpatcher.diff(oldObj, newObj) +} + +export function patch(obj, delta) { + return diffpatcher.patch(obj, delta) +} + +export function getDeltaValue(arr, originalObject?: any) { + if (!Array.isArray(arr)) + throw new Error('Expected array to extract delta value') + + if (arr.length === 1) return arr[0] // new + + if (arr.length === 2) return arr[1] // update + + if (arr.length === 3 && arr[2] === 0) return undefined // delete + + if (arr.length === 3 && arr[2] === 2) { + // text diff + if (!originalObject) + throw new Error( + 'Cannot apply patch to long text diff. Missing original object.' + ) + // try to apply patch to given object based on delta value + return patch(originalObject, arr) + } + + if (arr.length === 3 && arr[2] === 3) + // array move + throw new Error( + 'Detected an array move, it should not happen as ' + + '`includeValueOnMove` should be set to false' + ) + + throw new Error(`Got unsupported number ${arr[2]} in delta value`) +} diff --git a/packages/sync-actions/src/utils/extract-matching-pairs.ts b/packages/sync-actions/src/utils/extract-matching-pairs.ts new file mode 100644 index 000000000..2818eb54a --- /dev/null +++ b/packages/sync-actions/src/utils/extract-matching-pairs.ts @@ -0,0 +1,16 @@ +export default function extractMatchingPairs(hashMap, key, before, now) { + let oldObjPos + let newObjPos + let oldObj + let newObj + + if (hashMap[key]) { + oldObjPos = hashMap[key][0] + newObjPos = hashMap[key][1] + if (before && before[oldObjPos]) oldObj = before[oldObjPos] + + if (now && now[newObjPos]) newObj = now[newObjPos] + } + + return { oldObj, newObj } +} diff --git a/packages/sync-actions/src/utils/find-matching-pairs.ts b/packages/sync-actions/src/utils/find-matching-pairs.ts new file mode 100644 index 000000000..05149138b --- /dev/null +++ b/packages/sync-actions/src/utils/find-matching-pairs.ts @@ -0,0 +1,47 @@ +import forEach from 'lodash.foreach' + +const REGEX_NUMBER = new RegExp(/^\d+$/) +const REGEX_UNDERSCORE_NUMBER = new RegExp(/^_\d+$/) + +function preProcessCollection(collection = [], identifier = 'id') { + return collection.reduce( + (acc, currentValue, currentIndex) => { + acc.refByIndex[String(currentIndex)] = currentValue[identifier] + acc.refByIdentifier[currentValue[identifier]] = String(currentIndex) + return acc + }, + { + refByIndex: {}, + refByIdentifier: {}, + } + ) +} + +// creates a hash of a location of an item in collection1 and collection2 +export default function findMatchingPairs( + diff, + before = [], + now = [], + identifier = 'id' +) { + const result = {} + const { + refByIdentifier: beforeObjRefByIdentifier, + refByIndex: beforeObjRefByIndex, + } = preProcessCollection(before, identifier) + const { + refByIdentifier: nowObjRefByIdentifier, + refByIndex: nowObjRefByIndex, + } = preProcessCollection(now, identifier) + forEach(diff, (item, key) => { + if (REGEX_NUMBER.test(key)) { + const matchingIdentifier = nowObjRefByIndex[key] + result[key] = [beforeObjRefByIdentifier[matchingIdentifier], key] + } else if (REGEX_UNDERSCORE_NUMBER.test(key)) { + const index = key.substring(1) + const matchingIdentifier = beforeObjRefByIndex[index] + result[key] = [index, nowObjRefByIdentifier[matchingIdentifier]] + } + }) + return result +} diff --git a/packages/sync-actions/src/zones-actions.ts b/packages/sync-actions/src/zones-actions.ts new file mode 100644 index 000000000..44616f9bf --- /dev/null +++ b/packages/sync-actions/src/zones-actions.ts @@ -0,0 +1,70 @@ +import createBuildArrayActions, { + ADD_ACTIONS, + REMOVE_ACTIONS, + CHANGE_ACTIONS, +} from './utils/create-build-array-actions' +import { buildBaseAttributesActions } from './utils/common-actions' + +export const baseActionsList = [ + { action: 'changeName', key: 'name' }, + { action: 'setDescription', key: 'description' }, + { action: 'setKey', key: 'key' }, +] + +const hasLocation = (locations, otherLocation) => + locations.some((location) => location.country === otherLocation.country) + +export function actionsMapBase( + diff, + oldObj, + newObj, + config: { shouldOmitEmptyString?: boolean } = {} +) { + return buildBaseAttributesActions({ + actions: baseActionsList, + diff, + oldObj, + newObj, + shouldOmitEmptyString: config.shouldOmitEmptyString, + }) +} + +export function actionsMapLocations(diff, oldObj, newObj) { + const handler = createBuildArrayActions('locations', { + [ADD_ACTIONS]: (newLocation) => ({ + action: 'addLocation', + location: newLocation, + }), + [REMOVE_ACTIONS]: (oldLocation) => + // We only add the action if the location is not included in the new object. + !hasLocation(newObj.locations, oldLocation) + ? { + action: 'removeLocation', + location: oldLocation, + } + : null, + [CHANGE_ACTIONS]: (oldLocation, newLocation) => { + const result = [] + + // We only remove the location in case that the oldLocation is not + // included in the new object + if (!hasLocation(newObj.locations, oldLocation)) + result.push({ + action: 'removeLocation', + location: oldLocation, + }) + + // We only add the location in case that the newLocation was not + // included in the old object + if (!hasLocation(oldObj.locations, newLocation)) + result.push({ + action: 'addLocation', + location: newLocation, + }) + + return result + }, + }) + + return handler(diff, oldObj, newObj) +} diff --git a/packages/sync-actions/src/zones.ts b/packages/sync-actions/src/zones.ts new file mode 100644 index 000000000..e2aad4a9f --- /dev/null +++ b/packages/sync-actions/src/zones.ts @@ -0,0 +1,68 @@ +/* @flow */ +import flatten from 'lodash.flatten' +import type { + SyncAction, + ActionGroup, + SyncActionConfig, + UpdateAction, +} from '@commercetools/sdk-client-v2' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' +import * as zonesActions from './zones-actions' +import * as diffpatcher from './utils/diffpatcher' + +export const actionGroups = ['base', 'locations'] + +function createZonesMapActions( + mapActionGroup: ( + type: string, + fn: () => Array + ) => Array, + syncActionConfig?: SyncActionConfig +): (diff: any, next: any, previous: any) => Array { + return function doMapActions( + diff: any, + newObj: any, + oldObj: any + ): Array { + const allActions = [] + allActions.push( + mapActionGroup( + 'base', + (): Array => + zonesActions.actionsMapBase(diff, oldObj, newObj, syncActionConfig) + ) + ) + allActions.push( + flatten( + mapActionGroup( + 'locations', + (): Array => + zonesActions.actionsMapLocations(diff, oldObj, newObj) + ) + ) + ) + return flatten(allActions) + } +} + +export default ( + actionGroupList?: Array, + syncActionConfig?: SyncActionConfig +): SyncAction => { + // config contains information about which action groups + // are allowed or ignored + + // createMapActionGroup returns function 'mapActionGroup' that takes params: + // - action group name + // - callback function that should return a list of actions that correspond + // to the for the action group + + // this resulting function mapActionGroup will call the callback function + // for allowed action groups and return the return value of the callback + // It will return an empty array for ignored action groups + const mapActionGroup = createMapActionGroup(actionGroupList) + const doMapActions = createZonesMapActions(mapActionGroup, syncActionConfig) + const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + return { buildActions } +} diff --git a/packages/sync-actions/test/__snapshots__/product-types-sync-attribute-hints.spec.js.snap b/packages/sync-actions/test/__snapshots__/product-types-sync-attribute-hints.spec.js.snap new file mode 100644 index 000000000..008887c01 --- /dev/null +++ b/packages/sync-actions/test/__snapshots__/product-types-sync-attribute-hints.spec.js.snap @@ -0,0 +1,169 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`product type hints attribute enum values with previous with changes when is localized should match snapshot 1`] = ` +Array [ + Object { + "action": "changeEnumKey", + "attributeName": "attribute-name", + "key": "enum-key", + "newKey": "next-key", + }, + Object { + "action": "changeLocalizedEnumValueLabel", + "attributeName": "attribute-name", + "newValue": Object { + "key": "next-key", + "label": "next-label", + }, + }, +] +`; + +exports[`product type hints attribute enum values with previous with changes when is not localized should match snapshot 1`] = ` +Array [ + Object { + "action": "changeEnumKey", + "attributeName": "attribute-name", + "key": "enum-key", + "newKey": "next-key", + }, + Object { + "action": "changePlainEnumValueLabel", + "attributeName": "attribute-name", + "newValue": Object { + "key": "next-key", + "label": "next-label", + }, + }, +] +`; + +exports[`product type hints attribute enum values with previous with changes when removing, adding, and editing (in a single batch of actions) should match snapshot 1`] = ` +Array [ + Object { + "action": "removeEnumValues", + "attributeName": "attribute-enum-with-2-enum-values-to-remove", + "keys": Array [ + "enum-key-1", + "enum-key-2", + ], + }, + Object { + "action": "changeEnumKey", + "attributeName": "attribute-name", + "key": "enum-key", + "newKey": "next-enum-draft-item", + }, + Object { + "action": "changePlainEnumValueLabel", + "attributeName": "attribute-name", + "newValue": Object { + "key": "next-enum-draft-item", + "label": undefined, + }, + }, + Object { + "action": "addPlainEnumValue", + "attributeName": "attribute-name", + "value": Object { + "key": "new-enum-draft-item", + "label": "new-enum-draft-item", + }, + }, +] +`; + +exports[`product type hints attribute enum values without previous should match snapshot 1`] = ` +Array [ + Object { + "action": "addPlainEnumValue", + "attributeName": "attribute-name", + "value": Object { + "key": "enum-key", + "label": "enum-label", + }, + }, +] +`; + +exports[`product type hints attribute enum values without previous when is localized should match snapshot 1`] = ` +Array [ + Object { + "action": "addLocalizedEnumValue", + "attributeName": "attribute-name", + "value": Object { + "key": "enum-key", + "label": "enum-label", + }, + }, +] +`; + +exports[`product type hints attribute hints with previous with next with changes should match snapshot 1`] = ` +Array [ + Object { + "action": "changeLabel", + "attributeName": "attribute-name", + "label": Object { + "en": "next-attribute-label", + }, + }, + Object { + "action": "setInputTip", + "attributeName": "attribute-name", + "inputTip": Object { + "en": "next-input-tip", + }, + }, + Object { + "action": "changeInputHint", + "attributeName": "attribute-name", + "newValue": "MultiLine", + }, + Object { + "action": "changeIsSearchable", + "attributeName": "attribute-name", + "isSearchable": true, + }, + Object { + "action": "changeAttributeConstraint", + "attributeName": "attribute-name", + "newValue": "None", + }, +] +`; + +exports[`product type hints attribute hints with previous with next with no changes should match snapshot 1`] = `Array []`; + +exports[`product type hints attribute hints with previous without next should match snapshot 1`] = ` +Array [ + Object { + "action": "removeAttributeDefinition", + "name": "attribute-name", + }, +] +`; + +exports[`product type hints attribute hints without previous should match snapshot 1`] = ` +Array [ + Object { + "action": "addAttributeDefinition", + "attribute": Object { + "attributeConstraint": "SameForAll", + "inputHint": "SingleLine", + "inputTip": Object { + "en": "input-hint", + }, + "isRequired": false, + "isSearchable": false, + "label": Object { + "en": "attribute-label", + }, + "name": "attribute-name", + "type": Object { + "name": "text", + }, + }, + }, +] +`; diff --git a/packages/sync-actions/test/attribute-groups-sync.spec.ts b/packages/sync-actions/test/attribute-groups-sync.spec.ts new file mode 100644 index 000000000..57766d0bc --- /dev/null +++ b/packages/sync-actions/test/attribute-groups-sync.spec.ts @@ -0,0 +1,205 @@ +import attributeGroupSyncFn from '../src/attribute-groups' +import { baseActionsList } from '../src/attribute-groups-actions' + +describe('Exports', () => { + test('correctly define base actions list', () => { + expect(baseActionsList).toEqual([ + { action: 'changeName', key: 'name' }, + { action: 'setKey', key: 'key' }, + { action: 'setDescription', key: 'description' }, + ]) + }) +}) + +describe('Actions', () => { + let attributeGroupSync + beforeEach(() => { + attributeGroupSync = attributeGroupSyncFn() + }) + + test('should build `changeName` action', () => { + const before = { + name: 'John', + } + const now = { + name: 'Robert', + } + + const actual = attributeGroupSync.buildActions(now, before) + const expected = [{ action: 'changeName', name: now.name }] + expect(actual).toEqual(expected) + }) + + test('should build `setDescription` action', () => { + const before = { + description: 'some description', + } + const now = { + description: 'some updated description', + } + + const actual = attributeGroupSync.buildActions(now, before) + const expected = [ + { + action: 'setDescription', + description: now.description, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setKey` action', () => { + const before = { + key: 'some-key', + } + const now = { + key: 'new-key', + } + + const actual = attributeGroupSync.buildActions(now, before) + const expected = [ + { + action: 'setKey', + key: now.key, + }, + ] + expect(actual).toEqual(expected) + }) + + describe('`addAttribute`', () => { + test('should build `addAttribute` action with one attribute', () => { + const before = { + attributes: [], + } + const now = { attributes: [{ key: 'Size' }] } + + const actual = attributeGroupSync.buildActions(now, before) + const expected = [ + { action: 'addAttribute', attribute: now.attributes[0] }, + ] + expect(actual).toEqual(expected) + }) + test('should build `addAttribute` action with two attributes', () => { + const before = { attributes: [] } + const now = { attributes: [{ key: 'Size' }, { key: 'Brand' }] } + + const actual = attributeGroupSync.buildActions(now, before) + const expected = [ + { action: 'addAttribute', attribute: now.attributes[0] }, + { action: 'addAttribute', attribute: now.attributes[1] }, + ] + expect(actual).toEqual(expected) + }) + }) + + describe('`removeAttribute`', () => { + test('should build `removeAttribute` action removing one attribute', () => { + const before = { + attributes: [{ key: 'Size' }, { key: 'Brand' }], + } + const now = { attributes: [{ key: 'Size' }] } + + const actual = attributeGroupSync.buildActions(now, before) + const expected = [ + { action: 'removeAttribute', attribute: before.attributes[1] }, + ] + expect(actual).toEqual(expected) + }) + test('should build `removeAttribute` action removing two attributes', () => { + const before = { + attributes: [{ key: 'Size' }, { key: 'Brand' }], + } + const now = { attributes: [] } + + const actual = attributeGroupSync.buildActions(now, before) + const expected = [ + { action: 'removeAttribute', attribute: before.attributes[0] }, + { action: 'removeAttribute', attribute: before.attributes[1] }, + ] + expect(actual).toEqual(expected) + }) + }) + + describe('Swap attributes (create one + delete one)', () => { + test('should build `removeAttribute` and `addAttribute`', () => { + const before = { attributes: [{ key: 'Size' }] } + const now = { attributes: [{ key: 'Brand' }] } + + const actual = attributeGroupSync.buildActions(now, before) + const expected = [ + { action: 'removeAttribute', attribute: before.attributes[0] }, + { action: 'addAttribute', attribute: now.attributes[0] }, + ] + expect(actual).toEqual(expected) + }) + }) + + describe('Multiple actions', () => { + test('should build multiple actions for required changes', () => { + const before = { + attributes: [{ key: 'Size' }, { key: 'Brand' }], + } + const now = { + attributes: [{ key: 'Quality' }, { key: 'Brand' }, { key: 'color' }], + } + + const actual = attributeGroupSync.buildActions(now, before) + const expected = [ + { action: 'removeAttribute', attribute: before.attributes[0] }, + { action: 'addAttribute', attribute: now.attributes[0] }, + { action: 'addAttribute', attribute: now.attributes[2] }, + ] + expect(actual).toEqual(expected) + }) + }) + + describe('Delete first attributes', () => { + test('should build multiple actions for required changes', () => { + const before = { + attributes: [{ key: 'Size' }, { key: 'Brand' }, { key: 'Color' }], + } + const now = { + attributes: [{ key: 'Color' }], + } + + const actual = attributeGroupSync.buildActions(now, before) + const expected = [ + { action: 'removeAttribute', attribute: before.attributes[0] }, + { action: 'removeAttribute', attribute: before.attributes[1] }, + ] + expect(actual).toEqual(expected) + }) + }) + + describe('Delete multiple attributes', () => { + test('should build multiple actions for required changes', () => { + const before = { + attributes: [ + { key: 'Size' }, + { key: 'Brand' }, + { key: 'Quality' }, + { key: 'Color' }, + { key: 'Model' }, + { key: 'attr-1' }, + ], + } + const now = { + attributes: [ + { key: 'Brand' }, + { key: 'Quality' }, + { key: 'Model' }, + { key: 'attr-2' }, + ], + } + + const actual = attributeGroupSync.buildActions(now, before) + const expected = [ + { action: 'removeAttribute', attribute: before.attributes[0] }, + { action: 'removeAttribute', attribute: before.attributes[3] }, + { action: 'addAttribute', attribute: now.attributes[3] }, + { action: 'removeAttribute', attribute: before.attributes[5] }, + ] + expect(actual).toEqual(expected) + }) + }) +}) diff --git a/packages/sync-actions/test/cart-discounts-sync.spec.ts b/packages/sync-actions/test/cart-discounts-sync.spec.ts new file mode 100644 index 000000000..340f86723 --- /dev/null +++ b/packages/sync-actions/test/cart-discounts-sync.spec.ts @@ -0,0 +1,449 @@ +import cartDiscountsSyncFn, { actionGroups } from '../src/cart-discounts' +import { baseActionsList } from '../src/cart-discounts-actions' + +describe('Cart Discounts Exports', () => { + test('action group list', () => { + expect(actionGroups).toEqual(['base', 'custom']) + }) + + describe('action list', () => { + test('should contain `changeIsActive` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'changeIsActive', key: 'isActive' }]) + ) + }) + + test('should contain `changeName` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'changeName', key: 'name' }]) + ) + }) + + test('should contain `changeCartPredicate` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'changeCartPredicate', + key: 'cartPredicate', + }, + ]) + ) + }) + + test('should contain `changeSortOrder` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { action: 'changeSortOrder', key: 'sortOrder' }, + ]) + ) + }) + + test('should contain `changeValue` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'changeValue', key: 'value' }]) + ) + }) + + test('should contain `changeRequiresDiscountCode` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'changeRequiresDiscountCode', + key: 'requiresDiscountCode', + }, + ]) + ) + }) + + test('should contain `changeTarget` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'changeTarget', key: 'target' }]) + ) + }) + + test('should contain `setDescription` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'setDescription', + key: 'description', + }, + ]) + ) + }) + + test('should contain `setValidFrom` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'setValidFrom', key: 'validFrom' }]) + ) + }) + + test('should contain `setValidUntil` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'setValidUntil', key: 'validUntil' }]) + ) + }) + + test('should contain `changeStackingMode` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'changeStackingMode', + key: 'stackingMode', + }, + ]) + ) + }) + + test('should contain `setKey` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'setKey', + key: 'key', + }, + ]) + ) + }) + }) +}) + +describe('Cart Discounts Actions', () => { + let cartDiscountsSync + beforeEach(() => { + cartDiscountsSync = cartDiscountsSyncFn() + }) + + test('should build the `changeIsActive` action', () => { + const before = { + isActive: false, + } + + const now = { + isActive: true, + } + + const expected = [ + { + action: 'changeIsActive', + isActive: true, + }, + ] + const actual = cartDiscountsSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + + test('should build the `changeName` action', () => { + const before = { + name: { en: 'en-name-before', de: 'de-name-before' }, + } + + const now = { + name: { en: 'en-name-now', de: 'de-name-now' }, + } + + const expected = [ + { + action: 'changeName', + name: { en: 'en-name-now', de: 'de-name-now' }, + }, + ] + const actual = cartDiscountsSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + + test('should build the `changeCartPredicate` action', () => { + const before = { + cartPredicate: '1=1', + } + + const now = { + cartPredicate: 'sku="test-sku"', + } + + const expected = [ + { + action: 'changeCartPredicate', + cartPredicate: 'sku="test-sku"', + }, + ] + const actual = cartDiscountsSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + + test('should build the `changeSortOrder` action', () => { + const before = { + sortOrder: '0.1', + } + + const now = { + sortOrder: '0.2', + } + + const expected = [ + { + action: 'changeSortOrder', + sortOrder: '0.2', + }, + ] + const actual = cartDiscountsSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + + test('should build the `changeValue` action', () => { + const before = { + value: { + type: 'relative', + permyriad: 100, + }, + } + + const now = { + value: { + type: 'relative', + permyriad: 200, + }, + } + + const expected = [ + { + action: 'changeValue', + value: { + type: 'relative', + permyriad: 200, + }, + }, + ] + const actual = cartDiscountsSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + + test('should build the `changeRequiresDiscountCode` action', () => { + const before = { + requiresDiscountCode: false, + } + + const now = { + requiresDiscountCode: true, + } + + const expected = [ + { + action: 'changeRequiresDiscountCode', + requiresDiscountCode: true, + }, + ] + const actual = cartDiscountsSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + + test('should build the `changeTarget` action', () => { + const before = { + target: { + type: 'customLineItems', + predicate: 'sku="sku-a"', + }, + } + + const now = { + target: { + type: 'lineItems', + predicate: 'sku="sku-b"', + }, + } + + const expected = [ + { + action: 'changeTarget', + target: { + type: 'lineItems', + predicate: 'sku="sku-b"', + }, + }, + ] + const actual = cartDiscountsSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + + test('should build the `setDescription` action', () => { + const before = { + description: { + en: 'en-description-before', + de: 'de-description-before', + }, + } + + const now = { + description: { en: 'en-description-now', de: 'de-description-now' }, + } + + const expected = [ + { + action: 'setDescription', + description: { en: 'en-description-now', de: 'de-description-now' }, + }, + ] + const actual = cartDiscountsSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + + test('should build the `setValidFrom` action', () => { + const before = { + validFrom: 'date1', + } + + const now = { + validFrom: 'date2', + } + + const expected = [ + { + action: 'setValidFrom', + validFrom: 'date2', + }, + ] + const actual = cartDiscountsSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + + test('should build the `setValidUntil` action', () => { + const before = { + validUntil: 'date1', + } + + const now = { + validUntil: 'date2', + } + + const expected = [ + { + action: 'setValidUntil', + validUntil: 'date2', + }, + ] + const actual = cartDiscountsSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + test('should build the `setValidFromAndUntil` action when both `validFrom` and `validUntil` exist', () => { + const before = { + validFrom: 'date-1-From', + validUntil: 'date-1-Until', + } + + const now = { + validFrom: 'date-2-From', + validUntil: 'date-2-Until', + } + + const expected = [ + { + action: 'setValidFromAndUntil', + validFrom: 'date-2-From', + validUntil: 'date-2-Until', + }, + ] + const actual = cartDiscountsSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + test('should build the `changeStackingMode` action', () => { + const before = { + stackingMode: 'Stacking', + } + + const now = { + stackingMode: 'StopAfterThisDiscount', + } + + const expected = [ + { + action: 'changeStackingMode', + stackingMode: 'StopAfterThisDiscount', + }, + ] + const actual = cartDiscountsSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + + describe('custom fields', () => { + test('should build `setCustomType` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType2', + }, + fields: { + customField1: true, + }, + }, + } + const actual = cartDiscountsSync.buildActions(now, before) + const expected = [{ action: 'setCustomType', ...now.custom }] + expect(actual).toEqual(expected) + }) + }) + + test('should build `setCustomField` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: false, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const actual = cartDiscountsSync.buildActions(now, before) + const expected = [ + { + action: 'setCustomField', + name: 'customField1', + value: true, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build the `setKey` action', () => { + const before = { + key: 'key-before', + } + + const now = { + key: 'key-now', + } + + const expected = [ + { + action: 'setKey', + key: 'key-now', + }, + ] + const actual = cartDiscountsSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) +}) diff --git a/packages/sync-actions/test/category-sync.spec.ts b/packages/sync-actions/test/category-sync.spec.ts new file mode 100644 index 000000000..52401979e --- /dev/null +++ b/packages/sync-actions/test/category-sync.spec.ts @@ -0,0 +1,280 @@ +import categorySyncFn, { actionGroups } from '../src/categories' +import { + baseActionsList, + metaActionsList, + referenceActionsList, +} from '../src/category-actions' + +describe('Exports', () => { + test('action group list', () => { + expect(actionGroups).toEqual([ + 'base', + 'references', + 'meta', + 'custom', + 'assets', + ]) + }) + + test('correctly define base actions list', () => { + expect(baseActionsList).toEqual([ + { action: 'changeName', key: 'name' }, + { action: 'changeSlug', key: 'slug' }, + { action: 'setDescription', key: 'description' }, + { action: 'changeOrderHint', key: 'orderHint' }, + { action: 'setExternalId', key: 'externalId' }, + { action: 'setKey', key: 'key' }, + ]) + }) + + test('correctly define meta actions list', () => { + expect(metaActionsList).toEqual([ + { action: 'setMetaTitle', key: 'metaTitle' }, + { action: 'setMetaKeywords', key: 'metaKeywords' }, + { action: 'setMetaDescription', key: 'metaDescription' }, + ]) + }) + + test('correctly define reference actions list', () => { + expect(referenceActionsList).toEqual([ + { action: 'changeParent', key: 'parent' }, + ]) + }) +}) + +describe('Actions', () => { + let categorySync + beforeEach(() => { + categorySync = categorySyncFn() + }) + + describe('custom fields', () => { + test('should build `setCustomType` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType2', + }, + fields: { + customField1: true, + }, + }, + } + const actual = categorySync.buildActions(now, before) + const expected = [{ action: 'setCustomType', ...now.custom }] + expect(actual).toEqual(expected) + }) + }) + + test('should build `setCustomField` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: false, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const actual = categorySync.buildActions(now, before) + const expected = [ + { + action: 'setCustomField', + name: 'customField1', + value: true, + }, + ] + expect(actual).toEqual(expected) + }) + + describe('assets', () => { + test('should build "addAsset" action with empty assets', () => { + const before = { + assets: [], + } + const now = { + assets: [ + { + key: 'asset-key', + name: { + en: 'asset name ', + }, + sources: [ + { + uri: 'http://example.org/content/product-manual.pdf', + }, + ], + }, + ], + } + const actual = categorySync.buildActions(now, before) + const expected = [ + { + action: 'addAsset', + asset: now.assets[0], + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build "addAsset" action with existing assets', () => { + const existingAsset = { + key: 'existing', + sources: [ + { + uri: 'http://example.org/content/product-manual.pdf', + }, + ], + } + const newAsset = { + key: 'new', + sources: [ + { + uri: 'http://example.org/content/product-manual.gif', + }, + ], + } + const before = { + assets: [existingAsset], + } + const now = { + assets: [existingAsset, newAsset], + } + const actual = categorySync.buildActions(now, before) + const expected = [ + { + action: 'addAsset', + asset: newAsset, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build "removeAsset" action with assetId prop', () => { + const before = { + assets: [ + { + id: 'c136c9dc-51e8-40fe-8e2e-2a4c159f3358', + name: { + en: 'asset name ', + }, + sources: [ + { + uri: 'http://example.org/content/product-manual.pdf', + }, + ], + }, + ], + } + const now = { + assets: [], + } + const actual = categorySync.buildActions(now, before) + const expected = [ + { + action: 'removeAsset', + assetId: before.assets[0].id, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build "removeAsset" action with assetKey prop', () => { + const before = { + assets: [ + { + key: 'asset-key', + name: { + en: 'asset name ', + }, + sources: [ + { + uri: 'http://example.org/content/product-manual.pdf', + }, + ], + }, + ], + } + const now = { + assets: [], + } + const actual = categorySync.buildActions(now, before) + const expected = [ + { + action: 'removeAsset', + assetKey: before.assets[0].key, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should throw no exception on missing assets', () => { + const before = { + assets: [], + } + const now = {} + const actual = categorySync.buildActions(now, before) + const expected = [] + expect(actual).toEqual(expected) + }) + }) + + test('should build "removeAsset" and "addAsset" action when asset is changed', () => { + const initialAsset = { + key: 'asset-key', + name: { + en: 'asset name ', + }, + } + const changedName = { + name: { + en: 'asset name ', + de: 'Asset Name', + }, + } + const changedAsset = { ...initialAsset, ...changedName } + const before = { + assets: [initialAsset], + } + const now = { + assets: [changedAsset], + } + const actual = categorySync.buildActions(now, before) + const expected = [ + { + action: 'removeAsset', + assetKey: before.assets[0].key, + }, + { + action: 'addAsset', + asset: changedAsset, + }, + ] + expect(actual).toEqual(expected) + }) +}) diff --git a/packages/sync-actions/test/channels-sync-.spec.ts b/packages/sync-actions/test/channels-sync-.spec.ts new file mode 100644 index 000000000..9061c4490 --- /dev/null +++ b/packages/sync-actions/test/channels-sync-.spec.ts @@ -0,0 +1,215 @@ +import createChannelsSync, { actionGroups } from '../src/channels' +import { baseActionsList } from '../src/channels-actions' + +describe('Exports', () => { + test('action group list', () => { + expect(actionGroups).toEqual(['base', 'custom']) + }) + + describe('action list', () => { + test('should contain `changeKey` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'changeKey', key: 'key' }]) + ) + }) + + test('should contain `changeName` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'changeName', key: 'name' }]) + ) + }) + + test('should contain `changeDescription` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'changeDescription', + key: 'description', + }, + ]) + ) + }) + + test('should contain `setAddress` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'setAddress', + key: 'address', + }, + ]) + ) + }) + + test('should contain `setGeoLocation` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'setGeoLocation', + key: 'geoLocation', + }, + ]) + ) + }) + + test('should contain `setRoles` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'setRoles', + key: 'roles', + }, + ]) + ) + }) + }) +}) + +describe('Actions', () => { + let channelsSync + beforeEach(() => { + channelsSync = createChannelsSync() + }) + + test('should build `changeKey` action', () => { + const before = { key: 'keyBefore' } + const now = { key: 'keyAfter' } + const actual = channelsSync.buildActions(now, before) + const expected = [ + { + action: 'changeKey', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `changeName` action', () => { + const before = { name: 'nameBefore' } + const now = { name: 'nameAfter' } + const actual = channelsSync.buildActions(now, before) + const expected = [ + { + action: 'changeName', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `changeDescription` action', () => { + const before = { description: 'descriptionBefore' } + const now = { description: 'descriptionAfter' } + const actual = channelsSync.buildActions(now, before) + const expected = [ + { + action: 'changeDescription', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setAddress` action', () => { + const before = { address: 'addressBefore' } + const now = { address: 'addressAfter' } + const actual = channelsSync.buildActions(now, before) + const expected = [ + { + action: 'setAddress', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setGeoLocation` action', () => { + const before = { geoLocation: 'geoLocationBefore' } + const now = { geoLocation: 'geoLocationAfter' } + const actual = channelsSync.buildActions(now, before) + const expected = [ + { + action: 'setGeoLocation', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setRoles` action', () => { + const before = { roles: ['exists'] } + const now = { roles: ['exists', 'new'] } + const actual = channelsSync.buildActions(now, before) + const expected = [ + { + action: 'setRoles', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + + describe('custom fields', () => { + test('should build `setCustomType` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType2', + }, + fields: { + customField1: true, + }, + }, + } + const actual = channelsSync.buildActions(now, before) + const expected = [{ action: 'setCustomType', ...now.custom }] + expect(actual).toEqual(expected) + }) + }) + + test('should build `setCustomField` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: false, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const actual = channelsSync.buildActions(now, before) + const expected = [ + { + action: 'setCustomField', + name: 'customField1', + value: true, + }, + ] + expect(actual).toEqual(expected) + }) +}) diff --git a/packages/sync-actions/test/customer-group-sync.spec.ts b/packages/sync-actions/test/customer-group-sync.spec.ts new file mode 100644 index 000000000..1213fe173 --- /dev/null +++ b/packages/sync-actions/test/customer-group-sync.spec.ts @@ -0,0 +1,136 @@ +import customerGroupSyncFn, { actionGroups } from '../src/customer-group' +import { baseActionsList } from '../src/customer-group-actions' + +describe('Customer Groups Exports', () => { + test('action group list', () => { + expect(actionGroups).toEqual(['base', 'custom']) + }) + + describe('action list', () => { + test('should contain `changeName` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'changeName', key: 'name' }]) + ) + }) + + test('should contain `setKey` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'setKey', + key: 'key', + }, + ]) + ) + }) + }) +}) + +describe('Customer Groups Actions', () => { + let customerGroupSync + beforeEach(() => { + customerGroupSync = customerGroupSyncFn() + }) + + test('should build the `changeName` action', () => { + const before = { + name: { en: 'en-name-before', de: 'de-name-before' }, + } + + const now = { + name: { en: 'en-name-now', de: 'de-name-now' }, + } + + const expected = [ + { + action: 'changeName', + name: { en: 'en-name-now', de: 'de-name-now' }, + }, + ] + const actual = customerGroupSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + + test('should build the `setKey` action', () => { + const before = { + key: 'foo-key', + } + + const now = { + key: 'bar-key', + } + + const expected = [ + { + action: 'setKey', + key: 'bar-key', + }, + ] + const actual = customerGroupSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + + describe('custom fields', () => { + test('should build `setCustomType` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType2', + }, + fields: { + customField1: true, + }, + }, + } + const actual = customerGroupSync.buildActions(now, before) + const expected = [{ action: 'setCustomType', ...now.custom }] + expect(actual).toEqual(expected) + }) + }) + + test('should build `setCustomField` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: false, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const actual = customerGroupSync.buildActions(now, before) + const expected = [ + { + action: 'setCustomField', + name: 'customField1', + value: true, + }, + ] + expect(actual).toEqual(expected) + }) +}) diff --git a/packages/sync-actions/test/customer-sync.spec.ts b/packages/sync-actions/test/customer-sync.spec.ts new file mode 100644 index 000000000..ec5bbe1ad --- /dev/null +++ b/packages/sync-actions/test/customer-sync.spec.ts @@ -0,0 +1,646 @@ +import customerSyncFn, { actionGroups } from '../src/customers' +import { + baseActionsList, + setDefaultBaseActionsList, + referenceActionsList, +} from '../src/customer-actions' + +describe('Exports', () => { + test('action group list', () => { + expect(actionGroups).toEqual([ + 'base', + 'references', + 'addresses', + 'custom', + 'authenticationModes', + ]) + }) + + test('correctly define base actions list', () => { + expect(baseActionsList).toEqual([ + { action: 'setSalutation', key: 'salutation' }, + { action: 'changeEmail', key: 'email' }, + { action: 'setFirstName', key: 'firstName' }, + { action: 'setLastName', key: 'lastName' }, + { action: 'setMiddleName', key: 'middleName' }, + { action: 'setTitle', key: 'title' }, + { action: 'setCustomerNumber', key: 'customerNumber' }, + { action: 'setExternalId', key: 'externalId' }, + { action: 'setCompanyName', key: 'companyName' }, + { action: 'setDateOfBirth', key: 'dateOfBirth' }, + { action: 'setLocale', key: 'locale' }, + { action: 'setVatId', key: 'vatId' }, + { + action: 'setStores', + key: 'stores', + }, + { + action: 'setKey', + key: 'key', + }, + ]) + }) + + test('correctly define base set default actions list', () => { + expect(setDefaultBaseActionsList).toEqual([ + { + action: 'setDefaultBillingAddress', + key: 'defaultBillingAddressId', + actionKey: 'addressId', + }, + { + action: 'setDefaultShippingAddress', + key: 'defaultShippingAddressId', + actionKey: 'addressId', + }, + ]) + }) + + test('correctly define reference actions list', () => { + expect(referenceActionsList).toEqual([ + { action: 'setCustomerGroup', key: 'customerGroup' }, + ]) + }) +}) + +describe('Actions', () => { + let customerSync + beforeEach(() => { + customerSync = customerSyncFn() + }) + + test('should build `setSalutation` action', () => { + const before = { + salutation: 'Best', + } + const now = { + salutation: 'Dear', + } + + const actual = customerSync.buildActions(now, before) + const expected = [{ action: 'setSalutation', salutation: now.salutation }] + expect(actual).toEqual(expected) + }) + + test('should build `changeEmail` action', () => { + const before = { + email: 'john@doe.com', + } + const now = { + email: 'jessy@jones.com', + } + + const actual = customerSync.buildActions(now, before) + const expected = [{ action: 'changeEmail', email: now.email }] + expect(actual).toEqual(expected) + }) + + test('should build `setDefaultBillingAddress` action', () => { + const before = { + defaultBillingAddressId: 'abc123', + } + const now = { + defaultBillingAddressId: 'def456', + } + + const actual = customerSync.buildActions(now, before) + const expected = [ + { + action: 'setDefaultBillingAddress', + addressId: now.defaultBillingAddressId, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setDefaultShippingAddress` action', () => { + const before = { + defaultShippingAddressId: 'abc123', + } + const now = { + defaultShippingAddressId: 'def456', + } + + const actual = customerSync.buildActions(now, before) + const expected = [ + { + action: 'setDefaultShippingAddress', + addressId: now.defaultShippingAddressId, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `addAddress` action', () => { + const before = { addresses: [] } + const now = { + addresses: [{ streetName: 'some name', streetNumber: '5' }], + } + + const actual = customerSync.buildActions(now, before) + const expected = [{ action: 'addAddress', address: now.addresses[0] }] + expect(actual).toEqual(expected) + }) + + test('should build `addAddress` action before `setDefaultShippingAddress`', () => { + const before = { addresses: [] } + const now = { + addresses: [{ streetName: 'some name', streetNumber: '5' }], + defaultShippingAddressId: 'def456', + } + + const actual = customerSync.buildActions(now, before) + const expected = [ + { action: 'addAddress', address: now.addresses[0] }, + { + action: 'setDefaultShippingAddress', + addressId: now.defaultShippingAddressId, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `changeAddress` action', () => { + const before = { + addresses: [ + { + id: 'somelongidgoeshere199191', + streetName: 'some name', + streetNumber: '5', + }, + ], + } + const now = { + addresses: [ + { + id: 'somelongidgoeshere199191', + streetName: 'some different name', + streetNumber: '5', + }, + ], + } + + const actual = customerSync.buildActions(now, before) + const expected = [ + { + action: 'changeAddress', + addressId: before.addresses[0].id, + address: now.addresses[0], + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `removeAddress` action', () => { + const before = { + addresses: [{ id: 'somelongidgoeshere199191' }], + } + const now = { addresses: [] } + + const actual = customerSync.buildActions(now, before) + const expected = [ + { + action: 'removeAddress', + addressId: before.addresses[0].id, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build complex mixed actions', () => { + const before = { + addresses: [ + { + id: 'addressId1', + title: 'mr', + streetName: 'address 1 street', + postalCode: 'postal code 1', + }, + { + id: 'addressId2', + title: 'mr', + streetName: 'address 2 street', + postalCode: 'postal code 2', + }, + { + id: 'addressId4', + title: 'mr', + streetName: 'address 4 street', + postalCode: 'postal code 4', + }, + ], + } + const now = { + addresses: [ + { + id: 'addressId1', + title: 'mr', + streetName: 'address 1 street changed', // CHANGED + postalCode: 'postal code 1', + }, + // REMOVED ADDRESS 2 + { + // UNCHANGED ADDRESS 4 + id: 'addressId4', + title: 'mr', + streetName: 'address 4 street', + postalCode: 'postal code 4', + }, + { + // ADD NEW ADDRESS + id: 'addressId3', + title: 'mr', + streetName: 'address 3 street', + postalCode: 'postal code 3', + }, + ], + } + + const actual = customerSync.buildActions(now, before) + const expected = [ + { + // CHANGE ACTIONS FIRST + action: 'changeAddress', + addressId: 'addressId1', + address: now.addresses[0], + }, + { + // REMOVE ACTIONS NEXT + action: 'removeAddress', + addressId: 'addressId2', + }, + { + // CREATE ACTIONS LAST + action: 'addAddress', + address: now.addresses[2], + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `addBillingAddressId` action', () => { + const addressId = 'addressId' + const before = { billingAddressIds: [] } + const now = { + billingAddressIds: [addressId], + } + + const actual = customerSync.buildActions(now, before) + const expected = [{ action: 'addBillingAddressId', addressId }] + expect(actual).toEqual(expected) + }) + + test('should build `removeBillingAddressId` action', () => { + const addressId = 'addressId' + const before = { + billingAddressIds: [addressId], + } + const now = { billingAddressIds: [] } + + const actual = customerSync.buildActions(now, before) + const expected = [{ action: 'removeBillingAddressId', addressId }] + expect(actual).toEqual(expected) + }) + + test('should build both `add-` and `removeBillingAddressId` actions', () => { + const before = { + billingAddressIds: ['remove', 'keep', 'remove2'], + } + const now = { + billingAddressIds: ['keep', 'new'], + } + + const actual = customerSync.buildActions(now, before) + const expected = [ + { + action: 'removeBillingAddressId', + addressId: 'remove', + }, + { + action: 'removeBillingAddressId', + addressId: 'remove2', + }, + { + action: 'addBillingAddressId', + addressId: 'new', + }, + ] + expect(actual).toEqual(expected) + }) + test('should build `addShippingAddressId` action', () => { + const addressId = 'addressId' + const before = { shippingAddressIds: [] } + const now = { + shippingAddressIds: [addressId], + } + + const actual = customerSync.buildActions(now, before) + const expected = [{ action: 'addShippingAddressId', addressId }] + expect(actual).toEqual(expected) + }) + + test('should build `removeShippingAddressId` action', () => { + const addressId = 'addressId' + const before = { + shippingAddressIds: [addressId], + } + const now = { shippingAddressIds: [] } + + const actual = customerSync.buildActions(now, before) + const expected = [{ action: 'removeShippingAddressId', addressId }] + expect(actual).toEqual(expected) + }) + + test('should build both `add-` and `removeShippingAddressId` actions', () => { + const before = { + shippingAddressIds: ['remove', 'keep', 'remove2'], + } + const now = { + shippingAddressIds: ['keep', 'new'], + } + + const actual = customerSync.buildActions(now, before) + const expected = [ + { + action: 'removeShippingAddressId', + addressId: 'remove', + }, + { + action: 'removeShippingAddressId', + addressId: 'remove2', + }, + { + action: 'addShippingAddressId', + addressId: 'new', + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setCustomerGroup` action with key', () => { + const before = {} + const now = { + customerGroup: { + typeId: 'customer-group', + key: 'foo-customer-group', + }, + } + const actual = customerSync.buildActions(now, before) + const expected = [ + { + action: 'setCustomerGroup', + customerGroup: now.customerGroup, + }, + ] + expect(actual).toEqual(expected) + }) + + describe('custom fields', () => { + test('should build `setCustomType` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType2', + }, + fields: { + customField1: true, + }, + }, + } + const actual = customerSync.buildActions(now, before) + const expected = [{ action: 'setCustomType', ...now.custom }] + expect(actual).toEqual(expected) + }) + }) + + test('should build `setCustomField` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: false, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const actual = customerSync.buildActions(now, before) + const expected = [ + { + action: 'setCustomField', + name: 'customField1', + value: true, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setStores` action', () => { + const before = { + stores: [ + { + typeId: 'store', + key: 'canada', + }, + ], + } + const now = { + stores: [ + { + typeId: 'store', + key: 'canada', + }, + { + typeId: 'store', + key: 'usa', + }, + ], + } + const actual = customerSync.buildActions(now, before) + expect(actual).toEqual([ + { + action: 'setStores', + stores: [ + { + typeId: 'store', + key: 'canada', + }, + { + typeId: 'store', + key: 'usa', + }, + ], + }, + ]) + }) + + test('should build `setKey` action', () => { + const before = { + key: 'key-before', + } + + const now = { + key: 'key-now', + } + const actual = customerSync.buildActions(now, before) + expect(actual).toEqual([ + { + action: 'setKey', + key: 'key-now', + }, + ]) + }) + + test('should build not throw error for empty array', () => { + const before = { + stores: [ + { + typeId: 'store', + key: 'canada', + }, + { + typeId: 'store', + key: 'usa', + }, + ], + } + + const now = {} + + const actual = customerSync.buildActions(now, before) + expect(actual).toEqual([ + { + action: 'setStores', + stores: [], + }, + ]) + }) + + test('should build setAuthenticationMode sync action', () => { + let before + let now + let actual + let expected + + before = { + authenticationMode: 'Password', + } + now = { + authenticationMode: 'ExternalAuth', + } + + actual = customerSync.buildActions(now, before) + + expected = [ + { + action: 'setAuthenticationMode', + authMode: now.authenticationMode, + }, + ] + expect(actual).toEqual(expected) + + before = { + authenticationMode: 'ExternalAuth', + } + now = { + authenticationMode: 'Password', + password: 'abc123', + } + + actual = customerSync.buildActions(now, before) + expected = [ + { + action: 'setAuthenticationMode', + authMode: now.authenticationMode, + password: now.password, + }, + ] + + expect(actual).toEqual(expected) + + before = {} + now = { + authenticationMode: 'ExternalAuth', + } + + actual = customerSync.buildActions(now, before) + expected = [ + { + action: 'setAuthenticationMode', + authMode: now.authenticationMode, + }, + ] + expect(actual).toEqual(expected) + + before = { + authenticationMode: 'ExternalAuth', + } + now = {} + + actual = customerSync.buildActions(now, before) + + expected = [] + expect(actual).toEqual(expected) + + before = { + authenticationMode: 'ExternalAuth', + } + now = { + authenticationMode: '', + } + + expect(() => { + customerSync.buildActions(now, before) + }).toThrow('Invalid Authentication Mode') + }) + + test('should throw error if password not specified while setting authenticationMode to password', () => { + const before = { + authenticationMode: 'ExternalAuth', + } + const now = { + authenticationMode: 'Password', + } + + expect(() => { + customerSync.buildActions(now, before) + }).toThrow('Cannot set to Password authentication mode without password') + }) + + test('should throw error if user specifies invalid authentication mode', () => { + const before = { + authenticationMode: 'ExternalAuth', + } + const now = { + authenticationMode: 'xyz', + } + + expect(() => { + customerSync.buildActions(now, before) + }).toThrow('Invalid Authentication Mode') + }) +}) diff --git a/packages/sync-actions/test/discount-codes-sync.spec.ts b/packages/sync-actions/test/discount-codes-sync.spec.ts new file mode 100644 index 000000000..a2bfd2e94 --- /dev/null +++ b/packages/sync-actions/test/discount-codes-sync.spec.ts @@ -0,0 +1,383 @@ +import discountCodesSyncFn, { actionGroups } from '../src/discount-codes' +import { baseActionsList } from '../src/discount-codes-actions' + +describe('Exports', () => { + test('action group list', () => { + expect(actionGroups).toEqual(['base', 'custom']) + }) + + describe('action list', () => { + test('should contain `changeIsActive` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'changeIsActive', key: 'isActive' }]) + ) + }) + + test('should contain `setName` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'setName', key: 'name' }]) + ) + }) + + test('should contain `setDescription` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'setDescription', + key: 'description', + }, + ]) + ) + }) + + test('should contain `setMaxApplications` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'setMaxApplications', + key: 'maxApplications', + }, + ]) + ) + }) + + test('should contain `setMaxApplicationsPerCustomer` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'setMaxApplicationsPerCustomer', + key: 'maxApplicationsPerCustomer', + }, + ]) + ) + }) + + test('should contain `changeCartDiscounts` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'changeCartDiscounts', + key: 'cartDiscounts', + }, + ]) + ) + }) + + test('should contain `setValidFrom` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'setValidFrom', key: 'validFrom' }]) + ) + }) + + test('should contain `setValidUntil` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'setValidUntil', key: 'validUntil' }]) + ) + }) + + test('should contain `changeGroups` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'changeGroups', key: 'groups' }]) + ) + }) + }) +}) + +describe('Actions', () => { + let discountCodesSync + beforeEach(() => { + discountCodesSync = discountCodesSyncFn() + }) + + test('should build `changeIsActive` action', () => { + const before = { isActive: false } + const now = { isActive: true } + const actual = discountCodesSync.buildActions(now, before) + const expected = [ + { + action: 'changeIsActive', + isActive: true, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setName` action', () => { + const before = { + name: { en: 'previous-en-name', de: 'previous-de-name' }, + } + const now = { + name: { en: 'current-en-name', de: 'current-de-name' }, + } + + const actual = discountCodesSync.buildActions(now, before) + const expected = [ + { + action: 'setName', + name: { en: 'current-en-name', de: 'current-de-name' }, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setDescription` action', () => { + const before = { + description: { en: 'old-en-description', de: 'old-de-description' }, + } + const now = { + description: { en: 'new-en-description', de: 'new-de-description' }, + } + + const actual = discountCodesSync.buildActions(now, before) + const expected = [ + { + action: 'setDescription', + description: { en: 'new-en-description', de: 'new-de-description' }, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setCartPredicate` action', () => { + const before = { cartPredicate: 'old-cart-predicate' } + const now = { cartPredicate: 'new-cart-predicate' } + const actual = discountCodesSync.buildActions(now, before) + const expected = [ + { + action: 'setCartPredicate', + cartPredicate: 'new-cart-predicate', + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setMaxApplications` action', () => { + const before = { maxApplications: 5 } + const now = { maxApplications: 10 } + const actual = discountCodesSync.buildActions(now, before) + const expected = [ + { + action: 'setMaxApplications', + maxApplications: 10, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setMaxApplicationsPerCustomer` action', () => { + const before = { maxApplicationsPerCustomer: 1 } + const now = { maxApplicationsPerCustomer: 3 } + const actual = discountCodesSync.buildActions(now, before) + const expected = [ + { + action: 'setMaxApplicationsPerCustomer', + maxApplicationsPerCustomer: 3, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `changeCartDiscounts` action', () => { + const before = { + cartDiscounts: [ + { + typeId: 'previous-cart-discount', + id: 'previous-cart-discount-id', + }, + { + typeId: 'another-previous-cart-discount', + id: 'another-previous-cart-discount-id', + }, + ], + } + const now = { + cartDiscounts: [ + { + typeId: 'previous-cart-discount', + id: 'previous-cart-discount-id', + }, + { + typeId: 'new-cart-discount-1', + id: 'new-cart-discount-id-1', + }, + { + typeId: 'new-cart-discount-2', + id: 'new-cart-discount-id-2', + }, + { + typeId: 'another-new-cart-discount-2', + id: 'another-new-cart-discount-id-2', + }, + ], + } + + const actual = discountCodesSync.buildActions(now, before) + const expected = [ + { + action: 'changeCartDiscounts', + cartDiscounts: [ + { + typeId: 'previous-cart-discount', + id: 'previous-cart-discount-id', + }, + { + typeId: 'new-cart-discount-1', + id: 'new-cart-discount-id-1', + }, + { + typeId: 'new-cart-discount-2', + id: 'new-cart-discount-id-2', + }, + { + typeId: 'another-new-cart-discount-2', + id: 'another-new-cart-discount-id-2', + }, + ], + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build the `setValidFrom` action', () => { + const before = { + validFrom: 'date1', + } + + const now = { + validFrom: 'date2', + } + + const expected = [ + { + action: 'setValidFrom', + validFrom: 'date2', + }, + ] + const actual = discountCodesSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + + test('should build the `setValidUntil` action', () => { + const before = { + validUntil: 'date1', + } + + const now = { + validUntil: 'date2', + } + + const expected = [ + { + action: 'setValidUntil', + validUntil: 'date2', + }, + ] + const actual = discountCodesSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + + test('should build the `setValidFromAndUntil` action when both `validFrom` and `validUntil` exist', () => { + const before = { + validFrom: 'date-1-From', + validUntil: 'date-1-Until', + } + + const now = { + validFrom: 'date-2-From', + validUntil: 'date-2-Until', + } + + const expected = [ + { + action: 'setValidFromAndUntil', + validFrom: 'date-2-From', + validUntil: 'date-2-Until', + }, + ] + const actual = discountCodesSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + + test('should build the `changeGroups` action', () => { + const before = { + groups: ['A'], + } + + const now = { + groups: ['A', 'B'], + } + + const expected = [ + { + action: 'changeGroups', + groups: ['A', 'B'], + }, + ] + const actual = discountCodesSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + + describe('custom fields', () => { + test('should build `setCustomType` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType2', + }, + fields: { + customField1: true, + }, + }, + } + const actual = discountCodesSync.buildActions(now, before) + const expected = [{ action: 'setCustomType', ...now.custom }] + expect(actual).toEqual(expected) + }) + }) + + test('should build `setCustomField` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: false, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const actual = discountCodesSync.buildActions(now, before) + const expected = [ + { + action: 'setCustomField', + name: 'customField1', + value: true, + }, + ] + expect(actual).toEqual(expected) + }) +}) diff --git a/packages/sync-actions/test/inventory-sync.spec.ts b/packages/sync-actions/test/inventory-sync.spec.ts new file mode 100644 index 000000000..df114f1f8 --- /dev/null +++ b/packages/sync-actions/test/inventory-sync.spec.ts @@ -0,0 +1,110 @@ +import inventorySyncFn, { actionGroups } from '../src/inventories' +import { baseActionsList, referenceActionsList } from '../src/inventory-actions' + +describe('Exports', () => { + test('action group list', () => { + expect(actionGroups).toEqual(['base', 'references']) + }) + + test('correctly define base actions list', () => { + expect(baseActionsList).toEqual([ + { + action: 'changeQuantity', + key: 'quantityOnStock', + actionKey: 'quantity', + }, + { action: 'setRestockableInDays', key: 'restockableInDays' }, + { action: 'setExpectedDelivery', key: 'expectedDelivery' }, + ]) + }) + + test('correctly define reference actions list', () => { + expect(referenceActionsList).toEqual([ + { action: 'setSupplyChannel', key: 'supplyChannel' }, + ]) + }) +}) + +describe('Actions', () => { + let inventorySync + beforeEach(() => { + inventorySync = inventorySyncFn() + }) + + test('should build `changeQuantity` action', () => { + const before = { + quantityOnStock: 1, + } + const now = { + quantityOnStock: 2, + } + + const actual = inventorySync.buildActions(now, before) + const expected = [{ action: 'changeQuantity', quantity: 2 }] + expect(actual).toEqual(expected) + }) + + describe('custom fields', () => { + test('should build `setCustomType` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType2', + }, + fields: { + customField1: true, + }, + }, + } + const actual = inventorySync.buildActions(now, before) + const expected = [{ action: 'setCustomType', ...now.custom }] + expect(actual).toEqual(expected) + }) + }) + + test('should build `setCustomField` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: false, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const actual = inventorySync.buildActions(now, before) + const expected = [ + { + action: 'setCustomField', + name: 'customField1', + value: true, + }, + ] + expect(actual).toEqual(expected) + }) +}) diff --git a/packages/sync-actions/test/order-sync.spec.ts b/packages/sync-actions/test/order-sync.spec.ts new file mode 100644 index 000000000..0e7d66592 --- /dev/null +++ b/packages/sync-actions/test/order-sync.spec.ts @@ -0,0 +1,906 @@ +import { performance } from 'perf_hooks' +import orderSyncFn, { actionGroups } from '../src/orders' +import { baseActionsList } from '../src/order-actions' + +describe('Exports', () => { + test('action group list', () => { + expect(actionGroups).toEqual(['base', 'deliveries']) + }) + + test('correctly define base actions list', () => { + expect(baseActionsList).toEqual([ + { action: 'changeOrderState', key: 'orderState' }, + { action: 'changePaymentState', key: 'paymentState' }, + { action: 'changeShipmentState', key: 'shipmentState' }, + ]) + }) +}) + +describe('Actions', () => { + let orderSync + beforeEach(() => { + orderSync = orderSyncFn() + }) + + describe('base', () => { + test('should build *state actions', () => { + const before = { + orderState: 'Open', + paymentState: 'Pending', + shipmentState: 'Ready', + } + const now = { + orderState: 'Complete', + paymentState: 'Paid', + shipmentState: 'Shipped', + } + + const actual = orderSync.buildActions(now, before) + const expected = [ + { action: 'changeOrderState', orderState: 'Complete' }, + { action: 'changePaymentState', paymentState: 'Paid' }, + { action: 'changeShipmentState', shipmentState: 'Shipped' }, + ] + expect(actual).toEqual(expected) + }) + }) + + describe('deliveries', () => { + test('should build `addDelivery` action', () => { + const before = { + shippingInfo: { + deliveries: [], + }, + } + const now = { + shippingInfo: { + deliveries: [ + { + items: [ + { id: 'li-1', qty: 1 }, + { id: 'li-2', qty: 2 }, + ], + parcels: [ + { + measurements: { + heightInMillimeter: 1, + lengthInMillimeter: 1, + widthInMillimeter: 1, + weightInGram: 1, + }, + trackingData: { + trackingId: '111', + }, + }, + ], + }, + ], + }, + } + + const actual = orderSync.buildActions(now, before) + const expected = [ + { + action: 'addDelivery', + items: now.shippingInfo.deliveries[0].items, + parcels: now.shippingInfo.deliveries[0].parcels, + }, + ] + expect(actual).toEqual(expected) + }) + test('should build `setDeliveryItems` action', () => { + const before = { + shippingInfo: { + deliveries: [ + { + id: 'delivery-1', + items: [ + { id: 'li-1', qty: 1 }, + { id: 'li-2', qty: 2 }, + ], + parcels: [], + }, + ], + }, + } + const now = { + shippingInfo: { + deliveries: [ + { + id: 'delivery-1', + items: [{ id: 'li-2', qty: 2 }], + parcels: [], + }, + ], + }, + } + + const actual = orderSync.buildActions(now, before) + const expected = [ + { + action: 'setDeliveryItems', + items: now.shippingInfo.deliveries[0].items, + deliveryId: now.shippingInfo.deliveries[0].id, + deliveryKey: undefined, + }, + ] + expect(actual).toEqual(expected) + }) + test('should build multiple `setDeliveryItems` action', () => { + const before = { + shippingInfo: { + deliveries: [ + { + id: 'delivery-1', + items: [ + { id: 'li-1', qty: 1 }, + { id: 'li-2', qty: 2 }, + ], + parcels: [], + }, + { + id: 'delivery-2', + items: [], + parcels: [], + }, + ], + }, + } + const now = { + shippingInfo: { + deliveries: [ + { + id: 'delivery-1', + items: [{ id: 'li-2', qty: 2 }], + parcels: [], + }, + { + id: 'delivery-2', + items: [ + { id: 'li-1', qty: 1 }, + { id: 'li-2', qty: 2 }, + ], + parcels: [], + }, + ], + }, + } + + const actual = orderSync.buildActions(now, before) + const expected = [ + { + action: 'setDeliveryItems', + items: now.shippingInfo.deliveries[0].items, + deliveryId: now.shippingInfo.deliveries[0].id, + deliveryKey: undefined, + }, + { + action: 'setDeliveryItems', + items: now.shippingInfo.deliveries[1].items, + deliveryId: now.shippingInfo.deliveries[1].id, + deliveryKey: undefined, + }, + ] + expect(actual).toEqual(expected) + }) + describe('performance test', () => { + it('should be performant for large arrays', () => { + const before = { + shippingInfo: { + deliveries: Array(100) + .fill(null) + .map((a, index) => ({ + parcels: [], + items: Array(50) + .fill(null) + .map((b, index2) => { + return { + id: `id-${index}-${index2}`, + qty: 1, + } + }), + })), + }, + } + const now = { + shippingInfo: { + deliveries: Array(100) + .fill(null) + .map((a, index) => ({ + parcels: [], + items: Array(50) + .fill(null) + .map((b, index2) => { + return { + id: `id-${index}-${index2}`, + qty: 2, + } + }), + })), + }, + } + + const start = performance.now() + orderSync.buildActions(now, before) + const end = performance.now() + + expect(end - start).toBeLessThan(500) + }) + }) + }) + + describe('parcels', () => { + test('should add `parcel` action', () => { + const before = { + shippingInfo: { + deliveries: [ + { + id: 'id-1', + parcels: [ + { + id: 'unique-id-1', + measurements: { + heightInMillimeter: 20, + lengthInMillimeter: 40, + widthInMillimeter: 5, + weightInGram: 10, + }, + trackingData: { + trackingId: 'tracking-id-1', + }, + }, + ], + }, + ], + }, + } + + const now = { + shippingInfo: { + deliveries: [ + { + id: 'id-1', + parcels: [ + { + id: 'unique-id-1', + measurements: { + heightInMillimeter: 20, + lengthInMillimeter: 40, + widthInMillimeter: 5, + weightInGram: 10, + }, + trackingData: { + trackingId: 'tracking-id-1', + }, + }, + { + measurements: { + heightInMillimeter: 10, + lengthInMillimeter: 20, + widthInMillimeter: 2, + weightInGram: 5, + }, + trackingData: { + trackingId: 'tracking-id-2', + }, + }, + ], + }, + ], + }, + } + + const actual = orderSync.buildActions(now, before) + const expected = [ + { + action: 'addParcelToDelivery', + deliveryId: now.shippingInfo.deliveries[0].id, + measurements: now.shippingInfo.deliveries[0].parcels[1].measurements, + trackingData: now.shippingInfo.deliveries[0].parcels[1].trackingData, + }, + ] + + expect(actual).toEqual(expected) + }) + + test('should create remove `parcel` action', () => { + const before = { + shippingInfo: { + deliveries: [ + { + id: 'id-1', + parcels: [ + { + id: 'unique-id-1', + measurements: { + heightInMillimeter: 20, + lengthInMillimeter: 40, + widthInMillimeter: 5, + weightInGram: 10, + }, + trackingData: { + trackingId: 'tracking-id-1', + }, + }, + ], + }, + ], + }, + } + + const now = { + shippingInfo: { + deliveries: [ + { + id: 'id-1', + parcels: [], + }, + ], + }, + } + + const actual = orderSync.buildActions(now, before) + const expected = [ + { + action: 'removeParcelFromDelivery', + parcelId: before.shippingInfo.deliveries[0].parcels[0].id, + }, + ] + + expect(actual).toEqual(expected) + }) + }) + + describe('returnInfo', () => { + test('should not build `returnInfo` action if items are not set', () => { + const before = { + returnInfo: [], + } + + const now = { + returnInfo: [ + { + returnTrackingId: 'tracking-id-1', + returnDate: '21-04-30T09:21:15.003Z', + }, + ], + } + + const actual = orderSync.buildActions(now, before) + const expected = [] + expect(actual).toEqual(expected) + }) + + test('should add `returnInfo` action', () => { + const before = { + returnInfo: [], + } + + const now = { + returnInfo: [ + { + returnTrackingId: 'tracking-id-1', + items: [ + { + id: 'test-1', + type: 'LineItemReturnItem', + quantity: 1, + lineItemId: '1', + shipmentState: 'Advised', + paymentState: 'Initial', + }, + { + id: 'test-2', + type: 'LineItemReturnItem', + quantity: 1, + lineItemId: '1', + shipmentState: 'Advised', + paymentState: 'Initial', + }, + ], + }, + { + returnTrackingId: 'tracking-id-2', + items: [ + { + id: 'test-3', + type: 'LineItemReturnItem', + quantity: 2, + lineItemId: '2', + shipmentState: 'Advised', + paymentState: 'Initial', + }, + ], + }, + ], + } + + const actual = orderSync.buildActions(now, before) + const expected = [ + { + action: 'addReturnInfo', + returnTrackingId: now.returnInfo[0].returnTrackingId, + items: now.returnInfo[0].items, + }, + { + action: 'addReturnInfo', + returnTrackingId: now.returnInfo[1].returnTrackingId, + items: now.returnInfo[1].items, + }, + ] + + expect(actual).toEqual(expected) + }) + + test('should build `setReturnShipmentState` action', () => { + const before = { + returnInfo: [ + { + returnTrackingId: 'touched-item', + items: [ + { + id: 'test-1', + shipmentState: 'returned', + paymentState: 'initial', + }, + { + id: 'test-2', + shipmentState: 'returned', + paymentState: 'initial', + }, + ], + }, + { + returnTrackingId: 'not-touched-item', + items: [ + { + id: 'test-3', + shipmentState: 'returned', + paymentState: 'initial', + }, + { + id: 'test-4', + shipmentState: 'returned', + paymentState: 'initial', + }, + ], + }, + ], + } + + const now = { + returnInfo: [ + { + returnTrackingId: 'touched-item', + items: [ + { + id: 'test-1', + // This have changed + shipmentState: 'backInStock', + paymentState: 'initial', + }, + { + id: 'test-2', + shipmentState: 'returned', + paymentState: 'initial', + }, + ], + }, + { + returnTrackingId: 'not-touched-item', + items: [ + { + id: 'test-3', + shipmentState: 'returned', + paymentState: 'initial', + }, + { + id: 'test-4', + shipmentState: 'returned', + paymentState: 'initial', + }, + ], + }, + ], + } + + const actual = orderSync.buildActions(now, before) + const expected = [ + { + action: 'setReturnShipmentState', + returnItemId: now.returnInfo[0].items[0].id, + shipmentState: now.returnInfo[0].items[0].shipmentState, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setReturnPaymentState` action', () => { + const before = { + returnInfo: [ + { + returnTrackingId: 'touched-item', + items: [ + { + id: 'test-1', + shipmentState: 'returned', + paymentState: 'initial', + }, + { + id: 'test-2', + shipmentState: 'returned', + paymentState: 'initial', + }, + ], + }, + { + returnTrackingId: 'not-touched-item', + items: [ + { + id: 'test-3', + shipmentState: 'returned', + paymentState: 'initial', + }, + { + id: 'test-4', + shipmentState: 'returned', + paymentState: 'initial', + }, + ], + }, + ], + } + + const now = { + returnInfo: [ + { + returnTrackingId: 'touched-item', + items: [ + { + id: 'test-1', + shipmentState: 'returned', + paymentState: 'initial', + }, + { + id: 'test-2', + shipmentState: 'returned', + // This have changed + paymentState: 'refunded', + }, + ], + }, + { + returnTrackingId: 'not-touched-item', + items: [ + { + id: 'test-3', + shipmentState: 'returned', + paymentState: 'initial', + }, + { + id: 'test-4', + shipmentState: 'returned', + paymentState: 'initial', + }, + ], + }, + ], + } + + const actual = orderSync.buildActions(now, before) + const expected = [ + { + action: 'setReturnPaymentState', + returnItemId: now.returnInfo[0].items[1].id, + paymentState: now.returnInfo[0].items[1].paymentState, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setReturnShipmentState` and `setReturnPaymentState` action', () => { + const before = { + returnInfo: [ + { + returnTrackingId: 'touched-item', + items: [ + { + id: 'test-1', + shipmentState: 'returned', + paymentState: 'initial', + }, + { + id: 'test-2', + shipmentState: 'returned', + paymentState: 'initial', + }, + ], + }, + { + returnTrackingId: 'not-touched-item', + items: [ + { + id: 'test-3', + shipmentState: 'returned', + paymentState: 'initial', + }, + { + id: 'test-4', + shipmentState: 'returned', + paymentState: 'initial', + }, + ], + }, + ], + } + + const now = { + returnInfo: [ + { + returnTrackingId: 'touched-item', + items: [ + { + id: 'test-1', + // This have changed + shipmentState: 'backInStock', + // This have changed + paymentState: 'refunded', + }, + { + id: 'test-2', + shipmentState: 'returned', + paymentState: 'initial', + }, + ], + }, + { + returnTrackingId: 'not-touched-item', + items: [ + { + id: 'test-3', + shipmentState: 'returned', + paymentState: 'initial', + }, + { + id: 'test-4', + shipmentState: 'returned', + paymentState: 'initial', + }, + ], + }, + ], + } + + const actual = orderSync.buildActions(now, before) + const expected = [ + { + action: 'setReturnShipmentState', + returnItemId: now.returnInfo[0].items[0].id, + shipmentState: now.returnInfo[0].items[0].shipmentState, + }, + { + action: 'setReturnPaymentState', + returnItemId: now.returnInfo[0].items[0].id, + paymentState: now.returnInfo[0].items[0].paymentState, + }, + ] + expect(actual).toEqual(expected) + }) + describe('when all items have changed its `paymentState`', () => { + test('should build `returnInfoPaymentState` action', () => { + const before = { + returnInfo: [ + { + items: [ + { + id: 'id1', + shipmentState: 'Returned', + paymentState: 'Initial', + }, + ], + }, + { + items: [ + { + id: 'id2', + shipmentState: 'Returned', + paymentState: 'Initial', + }, + { + id: 'id3', + shipmentState: 'Returned', + paymentState: 'Initial', + }, + { + id: 'id4', + shipmentState: 'Returned', + paymentState: 'Initial', + }, + { + id: 'id5', + shipmentState: 'Returned', + paymentState: 'Initial', + }, + ], + returnDate: '2022-10-24T00:00:00.000Z', + }, + ], + } + const now = { + returnInfo: [ + { + items: [ + { + id: 'id1', + shipmentState: 'Returned', + paymentState: 'NotRefunded', + }, + ], + }, + { + items: [ + { + id: 'id2', + shipmentState: 'Returned', + paymentState: 'Refunded', + }, + { + id: 'id3', + shipmentState: 'Returned', + paymentState: 'Refunded', + }, + { + id: 'id4', + shipmentState: 'Returned', + paymentState: 'Refunded', + }, + { + id: 'id5', + shipmentState: 'Returned', + paymentState: 'Refunded', + }, + ], + returnDate: '2022-10-24T00:00:00.000Z', + }, + ], + } + const actual = orderSync.buildActions(now, before) + const expected = [ + { + action: 'setReturnPaymentState', + returnItemId: now.returnInfo[0].items[0].id, + paymentState: now.returnInfo[0].items[0].paymentState, + }, + { + action: 'setReturnPaymentState', + returnItemId: now.returnInfo[1].items[0].id, + paymentState: now.returnInfo[1].items[0].paymentState, + }, + { + action: 'setReturnPaymentState', + returnItemId: now.returnInfo[1].items[1].id, + paymentState: now.returnInfo[1].items[1].paymentState, + }, + { + action: 'setReturnPaymentState', + returnItemId: now.returnInfo[1].items[2].id, + paymentState: now.returnInfo[1].items[2].paymentState, + }, + { + action: 'setReturnPaymentState', + returnItemId: now.returnInfo[1].items[3].id, + paymentState: now.returnInfo[1].items[3].paymentState, + }, + ] + expect(actual).toEqual(expected) + }) + describe('performance test', () => { + it('should be performant for large arrays', () => { + const before = { + returnInfo: Array(100) + .fill(null) + .map((a, index) => ({ + items: Array(50) + .fill(null) + .map((b, index2) => { + return { + id: `id-${index}-${index2}`, + shipmentState: 'Returned', + paymentState: 'Initial', + } + }), + })), + } + const now = { + returnInfo: Array(100) + .fill(null) + .map((a, index) => ({ + items: Array(50) + .fill(null) + .map((b, index2) => { + return { + id: `id-${index}-${index2}`, + shipmentState: 'Returned', + paymentState: 'Refunded', + } + }), + })), + } + + const start = performance.now() + orderSync.buildActions(now, before) + const end = performance.now() + + expect(end - start).toBeLessThan(500) + }) + }) + }) + }) +}) + +describe('custom fields', () => { + let orderSync + beforeEach(() => { + orderSync = orderSyncFn() + }) + test('should build `setCustomType` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType2', + }, + fields: { + customField1: true, + }, + }, + } + const actual = orderSync.buildActions(now, before) + const expected = [{ action: 'setCustomType', ...now.custom }] + expect(actual).toEqual(expected) + }) + test('should build `setCustomField` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: false, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const actual = orderSync.buildActions(now, before) + const expected = [ + { + action: 'setCustomField', + name: 'customField1', + value: true, + }, + ] + expect(actual).toEqual(expected) + }) +}) diff --git a/packages/sync-actions/test/price-sync.spec.ts b/packages/sync-actions/test/price-sync.spec.ts new file mode 100644 index 000000000..66e4572d5 --- /dev/null +++ b/packages/sync-actions/test/price-sync.spec.ts @@ -0,0 +1,928 @@ +import pricesSyncFn, { actionGroups } from '../src/prices' + +const pricesSync = pricesSyncFn() + +const dateNow = new Date() +const twoWeeksFromNow = new Date(Date.now() + 12096e5) + +/* eslint-disable max-len */ +describe('price actions', () => { + test('action group list', () => { + expect(actionGroups).toEqual(['base', 'custom']) + }) + + test('should not build actions if prices are not set', () => { + const before = {} + const now = {} + const actions = pricesSync.buildActions(now, before) + expect(actions).toEqual([]) + }) + + test('should not build actions if now price is not set', () => { + const before = { + id: '9fe6610f', + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + } + const now = {} + const actions = pricesSync.buildActions(now, before) + expect(actions).toEqual([]) + }) + + test('should not build actions if there is no change', () => { + const before = { + id: '9fe6610f', + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + discounted: { + value: { centAmount: 4000, currencyCode: 'EGP' }, + discount: { typeId: 'product-discount', id: 'pd1' }, + }, + custom: { + type: { + typeId: 'type', + id: '5678', + }, + fields: { + source: 'shop', + }, + }, + } + + const now = { + id: '9fe6610f', + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + discounted: { + value: { centAmount: 4000, currencyCode: 'EGP' }, + discount: { typeId: 'product-discount', id: 'pd1' }, + }, + custom: { + type: { + typeId: 'type', + id: '5678', + }, + fields: { + source: 'shop', + }, + }, + } + const actions = pricesSync.buildActions(now, before) + expect(actions).toEqual([]) + }) + + describe('changeValue', () => { + test('should generate changeValue action', () => { + const before = { + id: '9fe6610f', + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + } + + const now = { + id: '9fe6610f', + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 5678, + fractionDigits: 2, + }, + } + + const actions = pricesSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'changeValue', + value: { + centAmount: 5678, + currencyCode: 'EUR', + fractionDigits: 2, + type: 'centPrecision', + }, + }, + ]) + }) + }) + + describe('setDiscountedPrice', () => { + test('should build `setDiscountedPrice` action for newly discounted', () => { + const before = { + id: '1010', + value: { currencyCode: 'EGP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + } + + const now = { + id: '1010', + value: { currencyCode: 'EGP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + discounted: { + value: { centAmount: 4000, currencyCode: 'EGP' }, + discount: { typeId: 'product-discount', id: 'pd1' }, + }, + } + + const actions = pricesSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'setDiscountedPrice', + discounted: { + value: { centAmount: 4000, currencyCode: 'EGP' }, + discount: { + typeId: 'product-discount', + id: 'pd1', + }, + }, + }, + ]) + }) + + test('should build `setDiscountedPrice` action for removed discounted', () => { + const before = { + id: '1010', + value: { currencyCode: 'EGP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + discounted: { + value: { centAmount: 4000, currencyCode: 'EGP' }, + discount: { typeId: 'product-discount', id: 'pd1' }, + }, + } + + const now = { + id: '1010', + value: { currencyCode: 'EGP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + // TODO: check this + discounted: null, + } + + const actions = pricesSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'setDiscountedPrice', + discounted: undefined, + }, + ]) + }) + + test('should build `setDiscountedPrice` action for changed value centAmount', () => { + const before = { + id: '1010', + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + discounted: { + value: { centAmount: 4000, currencyCode: 'EUR' }, + discount: { typeId: 'product-discount', id: 'pd1' }, + }, + } + + const now = { + id: '1010', + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + discounted: { + value: { centAmount: 3000, currencyCode: 'EUR' }, + discount: { typeId: 'product-discount', id: 'pd1' }, + }, + } + + const actions = pricesSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'setDiscountedPrice', + discounted: { + value: { centAmount: 3000, currencyCode: 'EUR' }, + discount: { + typeId: 'product-discount', + id: 'pd1', + }, + }, + }, + ]) + }) + }) + + describe('setPriceTiers', () => { + test('should build `setPriceTiers` action if price tier are set', () => { + const before = {} + const now = { + id: '9fe6610f', + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + tiers: [ + { + minimumQuantity: 5, + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + }, + ], + } + const actions = pricesSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'changeValue', + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + }, + { + action: 'setPriceTiers', + tiers: [ + { + minimumQuantity: 5, + value: { + centAmount: 1900, + currencyCode: 'EUR', + fractionDigits: 2, + type: 'centPrecision', + }, + }, + ], + }, + ]) + }) + + test('should build `setPriceTiers` action for price tier change', () => { + const before = { + id: '9fe6610f', + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + tiers: [ + { + minimumQuantity: 5, + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + }, + ], + } + const now = { + id: '9fe6610f', + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + tiers: [ + { + minimumQuantity: 5, + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 900, + fractionDigits: 2, + }, + }, + ], + } + const actions = pricesSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'setPriceTiers', + tiers: [ + { + minimumQuantity: 5, + value: { + centAmount: 900, + currencyCode: 'EUR', + fractionDigits: 2, + type: 'centPrecision', + }, + }, + ], + }, + ]) + }) + + test('should build `setPriceTiers` action for removed price tier', () => { + const before = { + id: '9fe6610f', + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + tiers: [ + { + minimumQuantity: 5, + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + }, + { + minimumQuantity: 25, + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 2900, + fractionDigits: 2, + }, + }, + ], + } + + const now = { + id: '9fe6610f', + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + tiers: [ + { + minimumQuantity: 5, + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + }, + ], + } + + const actions = pricesSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'setPriceTiers', + tiers: [ + { + minimumQuantity: 5, + value: { + centAmount: 1900, + currencyCode: 'EUR', + fractionDigits: 2, + type: 'centPrecision', + }, + }, + ], + }, + ]) + }) + + test('should build `setPriceTiers` action when removed all price tier', () => { + const before = { + id: '9fe6610f', + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + tiers: [ + { + minimumQuantity: 5, + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + }, + { + minimumQuantity: 25, + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 2900, + fractionDigits: 2, + }, + }, + ], + } + + const now = { + id: '9fe6610f', + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + tiers: null, + } + + const actions = pricesSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'setPriceTiers', + tiers: undefined, + }, + ]) + }) + + test('should not build `setPriceTiers` action when price tiers on now and then are equal', () => { + const before = { + id: '9fe6610f', + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + tiers: [ + { + minimumQuantity: 5, + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + }, + { + minimumQuantity: 25, + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 2900, + fractionDigits: 2, + }, + }, + ], + } + + const now = { + id: '9fe6610f', + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + tiers: [ + { + minimumQuantity: 5, + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + }, + { + minimumQuantity: 25, + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 2900, + fractionDigits: 2, + }, + }, + ], + } + + const actions = pricesSync.buildActions(now, before) + expect(actions).toEqual([]) + }) + }) + + describe('setKey', () => { + test('should build `setKey` action', () => { + const key = 'test-key' + + const before = { + id: '1010', + key: undefined, + } + + const now = { + id: '1010', + key, + } + + const actions = pricesSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'setKey', + key, + }, + ]) + }) + }) + + describe('setValidFrom', () => { + test('should build `setValidFrom` action', () => { + const before = { + id: '1010', + validFrom: dateNow, + validUntil: dateNow, + } + + const now = { + id: '1010', + validFrom: twoWeeksFromNow, + validUntil: dateNow, + } + + const actions = pricesSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'setValidFrom', + validFrom: twoWeeksFromNow, + }, + ]) + }) + }) + + describe('setValidUntil', () => { + test('should build `setValidUntil` action', () => { + const before = { + id: '1010', + validFrom: dateNow, + validUntil: dateNow, + } + + const now = { + id: '1010', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + } + + const actions = pricesSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'setValidUntil', + validUntil: twoWeeksFromNow, + }, + ]) + }) + }) + + describe('setValidFromAndUntil', () => { + it('should build `setValidFromAndUntil` action', () => { + const before = { + id: '1010', + validFrom: dateNow, + validUntil: dateNow, + } + + const now = { + id: '1010', + validFrom: twoWeeksFromNow, + validUntil: twoWeeksFromNow, + } + + const actions = pricesSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'setValidFromAndUntil', + validFrom: twoWeeksFromNow, + validUntil: twoWeeksFromNow, + }, + ]) + }) + }) + + describe('changeActive', () => { + test('should build `changeActive` action', () => { + const before = { + id: '1010', + active: false, + } + + const now = { + id: '1010', + active: true, + } + + const actions = pricesSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'changeActive', + active: true, + }, + ]) + }) + }) + + describe('setCustomType', () => { + test('should build `setCustomType` action without fields', () => { + const before = { + id: '888', + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + } + + const now = { + id: '888', + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + custom: { + type: { + typeId: 'type', + id: '5678', + }, + }, + } + + const actions = pricesSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'setCustomType', + type: { + id: '5678', + typeId: 'type', + }, + }, + ]) + }) + + test('should build `setCustomType` action', () => { + const before = { + id: '999', + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + } + + const now = { + // set price custom type and field + id: '999', + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + custom: { + type: { + typeId: 'type', + id: '5678', + }, + fields: { + source: 'shop', + }, + }, + } + + const actions = pricesSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'setCustomType', + type: { + id: '5678', + typeId: 'type', + }, + fields: { + source: 'shop', + }, + }, + ]) + }) + + test('should build `setCustomType` action which delete custom type', () => { + const before = { + id: '1111', + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + custom: { + type: { + typeId: 'type', + id: '5678', + }, + fields: { + source: 'shop', + }, + }, + } + + const now = { + // remove price custom field and type + id: '1111', + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + } + + const actions = pricesSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'setCustomType', + }, + ]) + }) + }) + + describe('setCustomField', () => { + test('should generate `setCustomField` actions', () => { + const before = { + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + id: '9fe6610f', + country: 'DE', + custom: { + type: { + typeId: 'type', + id: '218d8068', + }, + fields: { + touchpoints: ['value'], + }, + }, + } + + const now = { + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + id: '9fe6610f', + country: 'DE', + custom: { + type: { + typeId: 'type', + id: '218d8068', + }, + fields: { + published: false, + }, + }, + } + + const actions = pricesSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'setCustomField', + name: 'touchpoints', + value: undefined, + }, + { + action: 'setCustomField', + name: 'published', + value: false, + }, + ]) + }) + + test('should build `setCustomField` action', () => { + const before = { + id: '1010', + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + custom: { + type: { + typeId: 'type', + id: '5678', + }, + fields: { + source: 'shop', + }, + }, + } + + const now = { + id: '1010', + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + custom: { + type: { + typeId: 'type', + id: '5678', + }, + fields: { + source: 'random', + }, + }, + } + + const actions = pricesSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'setCustomField', + name: 'source', + value: 'random', + }, + ]) + }) + + test('should build three `setCustomField` action', () => { + const before = { + id: '1010', + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + custom: { + type: { + typeId: 'type', + id: '5678', + }, + fields: { + source: 'shop', + source2: 'shop2', + source3: 'shop3', + source4: 'shop4', + }, + }, + } + + const now = { + id: '1010', + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + custom: { + type: { + typeId: 'type', + id: '5678', + }, + fields: { + source: 'random', + source2: 'random2', + source3: 'random3', + source4: 'shop4', + }, + }, + } + + const actions = pricesSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'setCustomField', + name: 'source', + value: 'random', + }, + { + action: 'setCustomField', + name: 'source2', + value: 'random2', + }, + { + action: 'setCustomField', + name: 'source3', + value: 'random3', + }, + ]) + }) + }) +}) diff --git a/packages/sync-actions/test/product-discounts-sync.spec.ts b/packages/sync-actions/test/product-discounts-sync.spec.ts new file mode 100644 index 000000000..0932a1b01 --- /dev/null +++ b/packages/sync-actions/test/product-discounts-sync.spec.ts @@ -0,0 +1,284 @@ +import productDiscountsSyncFn, { actionGroups } from '../src/product-discounts' +import { baseActionsList } from '../src/product-discounts-actions' + +describe('Exports', () => { + test('action group list', () => { + expect(actionGroups).toEqual(['base']) + }) + + describe('Exports', () => { + test('should contain `changeIsActive` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'changeIsActive', key: 'isActive' }]) + ) + }) + + test('should contain `changeName` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'changeName', key: 'name' }]) + ) + }) + + test('should contain `changePredicate` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'changePredicate', + key: 'predicate', + }, + ]) + ) + }) + + test('should contain `changeSortOrder` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { action: 'changeSortOrder', key: 'sortOrder' }, + ]) + ) + }) + + test('should contain `changeValue` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'changeValue', key: 'value' }]) + ) + }) + + test('should contain `setDescription` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'setDescription', + key: 'description', + }, + ]) + ) + }) + + test('should contain `setValidFrom` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'setValidFrom', key: 'validFrom' }]) + ) + }) + + test('should contain `setValidUntil` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'setValidUntil', key: 'validUntil' }]) + ) + }) + + test('should contain `setKey` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'setKey', key: 'key' }]) + ) + }) + }) +}) + +describe('Actions', () => { + let productDiscountsSync + beforeEach(() => { + productDiscountsSync = productDiscountsSyncFn() + }) + + test('should build the `changeIsActive` action', () => { + const before = { + isActive: false, + } + + const now = { + isActive: true, + } + + const expected = [ + { + action: 'changeIsActive', + isActive: true, + }, + ] + const actual = productDiscountsSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + + test('should build "changeName" action', () => { + const before = { + name: { en: 'en-name-before', de: 'de-name-before' }, + } + + const now = { + name: { en: 'en-name-now', de: 'de-name-now' }, + } + + const expected = [ + { + action: 'changeName', + name: { en: 'en-name-now', de: 'de-name-now' }, + }, + ] + const actual = productDiscountsSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + + test('should build the `changePredicate` action', () => { + const before = { + predicate: '1=1', + } + + const now = { + predicate: 'sku="test-sku"', + } + + const expected = [ + { + action: 'changePredicate', + predicate: 'sku="test-sku"', + }, + ] + const actual = productDiscountsSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + + test('should build the `changeSortOrder` action', () => { + const before = { + sortOrder: '0.1', + } + + const now = { + sortOrder: '0.2', + } + + const expected = [ + { + action: 'changeSortOrder', + sortOrder: '0.2', + }, + ] + const actual = productDiscountsSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + + test('should build the `changeValue` action', () => { + const before = { + value: { + type: 'relative', + permyriad: 100, + }, + } + + const now = { + value: { + type: 'relative', + permyriad: 200, + }, + } + + const expected = [ + { + action: 'changeValue', + value: { + type: 'relative', + permyriad: 200, + }, + }, + ] + const actual = productDiscountsSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + test('should build the `setDescription` action', () => { + const before = { + description: { + en: 'en-description-before', + de: 'de-description-before', + }, + } + const now = { + description: { en: 'en-description-now', de: 'de-description-now' }, + } + const expected = [ + { + action: 'setDescription', + description: { en: 'en-description-now', de: 'de-description-now' }, + }, + ] + const actual = productDiscountsSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + + test('should build the `setValidFrom` action', () => { + const before = { + validFrom: 'date1', + } + + const now = { + validFrom: 'date2', + } + + const expected = [ + { + action: 'setValidFrom', + validFrom: 'date2', + }, + ] + const actual = productDiscountsSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + + test('should build the `setValidUntil` action', () => { + const before = { + validUntil: 'date1', + } + + const now = { + validUntil: 'date2', + } + + const expected = [ + { + action: 'setValidUntil', + validUntil: 'date2', + }, + ] + const actual = productDiscountsSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + test('should build the `setValidFromAndUntil` action when both `validFrom` and `validUntil` exist', () => { + const before = { + validFrom: 'date-1-From', + validUntil: 'date-1-Until', + } + + const now = { + validFrom: 'date-2-From', + validUntil: 'date-2-Until', + } + + const expected = [ + { + action: 'setValidFromAndUntil', + validFrom: 'date-2-From', + validUntil: 'date-2-Until', + }, + ] + const actual = productDiscountsSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) + + test('should build the `setKey` action', () => { + const before = { + key: 'key-before', + } + + const now = { + key: 'key-now', + } + + const expected = [ + { + action: 'setKey', + key: 'key-now', + }, + ] + const actual = productDiscountsSync.buildActions(now, before) + expect(actual).toEqual(expected) + }) +}) diff --git a/packages/sync-actions/test/product-selections-sync.spec.ts b/packages/sync-actions/test/product-selections-sync.spec.ts new file mode 100644 index 000000000..e9c9164f0 --- /dev/null +++ b/packages/sync-actions/test/product-selections-sync.spec.ts @@ -0,0 +1,114 @@ +import { baseActionsList } from '../src/product-selections-actions' +import productSelectionsSyncFn, { + actionGroups, +} from '../src/product-selections' + +describe('Exports', () => { + test('action group list', () => { + expect(actionGroups).toEqual(['base']) + }) + + test('correctly define base actions list', () => { + expect(baseActionsList).toEqual([ + { action: 'changeName', key: 'name' }, + { action: 'setKey', key: 'key' }, + ]) + }) +}) + +describe('Actions', () => { + let productSelectionsSync + beforeEach(() => { + productSelectionsSync = productSelectionsSyncFn() + }) + + test('should build `changeName` action', () => { + const before = { + name: { en: 'Algeria' }, + } + const now = { + name: { en: 'Algeria', de: 'Algerian' }, + } + + const actual = productSelectionsSync.buildActions(now, before) + const expected = [{ action: 'changeName', name: now.name }] + expect(actual).toEqual(expected) + }) + + test('should build `setKey` action', () => { + const before = { + key: '', + } + const now = { + key: 'new-key', + } + + const actual = productSelectionsSync.buildActions(now, before) + const expected = [{ action: 'setKey', key: now.key }] + expect(actual).toEqual(expected) + }) + + describe('custom fields', () => { + test('should build `setCustomType` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType2', + }, + fields: { + customField1: true, + }, + }, + } + const actual = productSelectionsSync.buildActions(now, before) + const expected = [{ action: 'setCustomType', ...now.custom }] + expect(actual).toEqual(expected) + }) + }) + + test('should build `setCustomField` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: false, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const actual = productSelectionsSync.buildActions(now, before) + const expected = [ + { + action: 'setCustomField', + name: 'customField1', + value: true, + }, + ] + expect(actual).toEqual(expected) + }) +}) diff --git a/packages/sync-actions/test/product-sync-base.spec.ts b/packages/sync-actions/test/product-sync-base.spec.ts new file mode 100644 index 000000000..959b91ed7 --- /dev/null +++ b/packages/sync-actions/test/product-sync-base.spec.ts @@ -0,0 +1,379 @@ +import clone from '../src/utils/clone' +import productsSyncFn, { actionGroups } from '../src/products' +import { + baseActionsList, + metaActionsList, + referenceActionsList, +} from '../src/product-actions' + +describe('Exports', () => { + test('action group list', () => { + expect(actionGroups).toEqual([ + 'base', + 'meta', + 'references', + 'prices', + 'pricesCustom', + 'attributes', + 'images', + 'variants', + 'categories', + 'categoryOrderHints', + ]) + }) + + test('correctly define base actions list', () => { + expect(baseActionsList).toEqual([ + { action: 'changeName', key: 'name' }, + { action: 'changeSlug', key: 'slug' }, + { action: 'setDescription', key: 'description' }, + { action: 'setSearchKeywords', key: 'searchKeywords' }, + { action: 'setKey', key: 'key' }, + { action: 'setPriceMode', key: 'priceMode' }, + ]) + }) + + test('correctly define meta actions list', () => { + expect(metaActionsList).toEqual([ + { action: 'setMetaTitle', key: 'metaTitle' }, + { action: 'setMetaDescription', key: 'metaDescription' }, + { action: 'setMetaKeywords', key: 'metaKeywords' }, + ]) + }) + + test('correctly define reference actions list', () => { + expect(referenceActionsList).toEqual([ + { action: 'setTaxCategory', key: 'taxCategory' }, + { action: 'transitionState', key: 'state' }, + ]) + }) +}) + +describe('Actions', () => { + let productsSync + beforeEach(() => { + productsSync = productsSyncFn() + }) + + test('should ensure given objects are not mutated', () => { + const before = { + name: { en: 'Car', de: 'Auto' }, + key: 'unique-key', + masterVariant: { + id: 1, + sku: '001', + attributes: [{ name: 'a1', value: 1 }], + }, + variants: [ + { id: 2, sku: '002', attributes: [{ name: 'a2', value: 2 }] }, + { id: 3, sku: '003', attributes: [{ name: 'a3', value: 3 }] }, + ], + } + const now = { + name: { en: 'Sport car' }, + key: 'unique-key-2', + masterVariant: { + id: 1, + sku: '100', + attributes: [{ name: 'a1', value: 100 }], + }, + variants: [ + { id: 2, sku: '200', attributes: [{ name: 'a2', value: 200 }] }, + { id: 3, sku: '300', attributes: [{ name: 'a3', value: 300 }] }, + ], + } + productsSync.buildActions(now, before) + expect(before).toEqual(clone(before)) + expect(now).toEqual(clone(now)) + }) + + test('should build `setKey` action', () => { + const before = { key: 'unique-key-1' } + const now = { key: 'unique-key-2' } + const actions = productsSync.buildActions(now, before) + + expect(actions).toEqual([{ action: 'setKey', ...now }]) + }) + + test('should build `changeName` action', () => { + const before = { name: { en: 'Car', de: 'Auto' } } + const now = { name: { en: 'Sport car' } } + const actions = productsSync.buildActions(now, before) + + expect(actions).toEqual([{ action: 'changeName', ...now }]) + }) + + test('should build action with `staged` flag as false', () => { + const before = { name: { en: 'Car', de: 'Auto' } } + const now = { name: { en: 'Sport car' }, publish: true } + const actions = productsSync.buildActions(now, before) + + expect(actions).toEqual([ + { action: 'changeName', name: { en: 'Sport car' }, staged: false }, + ]) + }) + + test('should build action with `staged` flag as false when `staged` is set to false', () => { + const before = { name: { en: 'Car', de: 'Auto' } } + const now = { name: { en: 'New sport car' }, staged: false } + const actions = productsSync.buildActions(now, before) + + expect(actions).toEqual([ + { action: 'changeName', name: { en: 'New sport car' }, staged: false }, + ]) + }) + + test('should build action without `staged` flag', () => { + const before = { name: { en: 'Car', de: 'Auto' } } + const now = { name: { en: 'Sport car' }, publish: false } + const actions = productsSync.buildActions(now, before) + + expect(actions).toEqual([ + { action: 'changeName', name: { en: 'Sport car' } }, + ]) + }) + + test('should build `setSearchKeywords` action', () => { + /* eslint-disable max-len */ + const before = { + searchKeywords: { + en: [ + { text: 'Multi tool' }, + { + text: 'Swiss Army Knife', + suggestTokenizer: { type: 'whitespace' }, + }, + ], + de: [ + { + text: 'Schweizer Messer', + suggestTokenizer: { + type: 'custom', + inputs: ['schweizer messer', 'offiziersmesser', 'sackmesser'], + }, + }, + ], + }, + } + const now = { + searchKeywords: { + en: [ + { + text: 'Swiss Army Knife', + suggestTokenizer: { type: 'whitespace' }, + }, + ], + de: [ + { + text: 'Schweizer Messer', + suggestTokenizer: { + type: 'custom', + inputs: [ + 'schweizer messer', + 'offiziersmesser', + 'sackmesser', + 'messer', + ], + }, + }, + ], + it: [{ text: 'Coltello svizzero' }], + }, + } + /* eslint-enable max-len */ + const actions = productsSync.buildActions(now, before) + expect(actions).toEqual([{ action: 'setSearchKeywords', ...now }]) + }) + + test('should build no actions if searchKeywords did not change', () => { + /* eslint-disable max-len */ + const before = { + name: { en: 'Car', de: 'Auto' }, + searchKeywords: { + en: [ + { text: 'Multi tool' }, + { + text: 'Swiss Army Knife', + suggestTokenizer: { type: 'whitespace' }, + }, + ], + de: [ + { + text: 'Schweizer Messer', + suggestTokenizer: { + type: 'custom', + inputs: ['schweizer messer', 'offiziersmesser', 'sackmesser'], + }, + }, + ], + }, + } + /* eslint-enable max-len */ + const actions = productsSync.buildActions(before, before) + expect(actions).toEqual([]) + }) + + test('should build `add/remove Category` actions', () => { + const before = { + categories: [ + { id: 'aebe844e-0616-420a-8397-a22c48d5e99f' }, + { id: '34cae6ad-5898-4f94-973b-ae9ceb7464ce' }, + ], + } + const now = { + categories: [ + { id: 'aebe844e-0616-420a-8397-a22c48d5e99f' }, + { id: '4f278964-48c0-4f2c-8b61-09310d1de60a' }, + { id: 'cca7a250-d8cf-4b8a-9d47-60fcc093b86b' }, + ], + } + const actions = productsSync.buildActions(now, before) + + expect(actions).toEqual([ + { + action: 'removeFromCategory', + category: { id: '34cae6ad-5898-4f94-973b-ae9ceb7464ce' }, + }, + { + action: 'addToCategory', + category: { id: '4f278964-48c0-4f2c-8b61-09310d1de60a' }, + }, + { + action: 'addToCategory', + category: { id: 'cca7a250-d8cf-4b8a-9d47-60fcc093b86b' }, + }, + ]) + }) + + test('should add/remove category and categoryOrderHints', () => { + const before = { + categories: [ + { id: '123e844e-0616-420a-8397-a22c48d5e99f' }, + { id: 'aebe844e-0616-420a-8397-a22c48d5e99f' }, + { id: '34cae6ad-5898-4f94-973b-ae9ceb7464ce' }, + ], + categoryOrderHints: { + '123e844e-0616-420a-8397-a22c48d5e99f': '0.1', // will be preserved + 'aebe844e-0616-420a-8397-a22c48d5e99f': '0.2', // will be changed to 0.5 + '34cae6ad-5898-4f94-973b-ae9ceb7464ce': '0.5', // will be removed + }, + } + + const now = { + categories: [ + { id: '123e844e-0616-420a-8397-a22c48d5e99f' }, + { id: 'aebe844e-0616-420a-8397-a22c48d5e99f' }, + { id: 'cca7a250-d8cf-4b8a-9d47-60fcc093b86b' }, + ], + categoryOrderHints: { + '123e844e-0616-420a-8397-a22c48d5e99f': '0.1', + 'aebe844e-0616-420a-8397-a22c48d5e99f': '0.5', + 'cca7a250-d8cf-4b8a-9d47-60fcc093b86b': '0.999', + }, + } + const actions = productsSync.buildActions(now, before) + + expect(actions).toEqual([ + { + action: 'removeFromCategory', + category: { id: '34cae6ad-5898-4f94-973b-ae9ceb7464ce' }, + }, + { + action: 'addToCategory', + category: { id: 'cca7a250-d8cf-4b8a-9d47-60fcc093b86b' }, + }, + { + action: 'setCategoryOrderHint', + categoryId: 'aebe844e-0616-420a-8397-a22c48d5e99f', + orderHint: '0.5', + }, + { + action: 'setCategoryOrderHint', + categoryId: '34cae6ad-5898-4f94-973b-ae9ceb7464ce', + }, + { + action: 'setCategoryOrderHint', + categoryId: 'cca7a250-d8cf-4b8a-9d47-60fcc093b86b', + orderHint: '0.999', + }, + ]) + }) + + test('shouldnt generate any categoryOrderHints actions', () => { + const before = { + categoryOrderHints: {}, + } + + const now = {} + + const actions = productsSync.buildActions(now, before) + + expect(actions).toEqual([]) + }) + + test('shouldnt generate any searchKeywords actions', () => { + const before = { + searchKeywords: {}, + } + + const now = {} + + const actions = productsSync.buildActions(now, before) + + expect(actions).toEqual([]) + }) + + test('should build base actions for long diff text', () => { + const longText = ` + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + Nunc ultricies fringilla tortor eu egestas. + Praesent rhoncus molestie libero, eu tempor sapien placerat id. + Donec commodo nunc sed nulla scelerisque, eu pulvinar augue egestas. + Donec at leo dolor. Cras at molestie arcu. + Sed non fringilla quam, sit amet ultricies massa. + Donec luctus tempus erat, ut suscipit elit varius nec. + Mauris dolor enim, aliquet sed nulla et, dignissim lobortis augue. + Proin pharetra magna eu neque semper tristique sed. + ` + + /* eslint-disable max-len */ + const before = { + name: { + en: longText, + }, + slug: { + en: longText, + }, + description: { + en: longText, + }, + } + const now = { + name: { + en: `Hello, ${longText}`, + }, + slug: { + en: `Hello, ${longText}`, + }, + description: { + en: `Hello, ${longText}`, + }, + } + /* eslint-enable max-len */ + const actions = productsSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'changeName', + name: now.name, + }, + { + action: 'changeSlug', + slug: now.slug, + }, + { + action: 'setDescription', + description: now.description, + }, + ]) + }) +}) diff --git a/packages/sync-actions/test/product-sync-images.spec.ts b/packages/sync-actions/test/product-sync-images.spec.ts new file mode 100644 index 000000000..727e6acd6 --- /dev/null +++ b/packages/sync-actions/test/product-sync-images.spec.ts @@ -0,0 +1,485 @@ +import productsSyncFn from '../src/products' + +/* eslint-disable max-len */ +describe('Actions', () => { + let productsSync + beforeEach(() => { + productsSync = productsSyncFn() + }) + + describe('with matching variant order', () => { + test('should build actions for images', () => { + const before = { + id: '123', + masterVariant: { + id: 1, + images: [], + }, + variants: [ + { + id: 2, + images: [ + { + url: '//example.com/image2.png', + label: 'foo', + dimensions: { h: 1024, w: 768 }, + }, + ], + }, + { + id: 3, + images: [ + { + url: '//example.com/image3.png', + label: 'foo', + dimensions: { h: 1024, w: 768 }, + }, + { + url: '//example.com/image4.png', + dimensions: { h: 1024, w: 768 }, + }, + { + url: '//example.com/image5.png', + label: 'foo', + dimensions: { h: 1024, w: 768 }, + }, + ], + }, + { + id: 4, + images: [ + // Order is important! + { + url: '//example.com/old-remove.png', + dimensions: { h: 400, w: 600 }, + }, + { + url: '//example.com/old-keep.png', + dimensions: { h: 608, w: 1000 }, + }, + ], + }, + ], + } + + const now = { + id: '123', + masterVariant: { + id: 1, + images: [ + // new image + { url: 'http://cat.com', label: 'A cat' }, + ], + }, + variants: [ + { + id: 2, + images: [ + // no changes + { + url: '//example.com/image2.png', + label: 'foo', + dimensions: { h: 1024, w: 768 }, + }, + ], + }, + { + id: 3, + images: [ + // label added + { + url: '//example.com/image4.png', + label: 'ADDED', + dimensions: { h: 400, w: 300 }, + }, + // label changed + { + url: '//example.com/image3.png', + label: 'CHANGED', + dimensions: { h: 1024, w: 768 }, + }, + // url changed (new image) + { + url: '//example.com/CHANGED.jpg', + label: 'foo', + dimensions: { h: 400, w: 300 }, + }, + ], + }, + // images removed + { + id: 4, + images: [ + { + url: '//example.com/old-keep.png', + dimensions: { h: 608, w: 1000 }, + }, + ], + }, + ], + } + + const actions = productsSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'addExternalImage', + variantId: 1, + image: { url: 'http://cat.com', label: 'A cat' }, + }, + { + action: 'setImageLabel', + variantId: 3, + imageUrl: '//example.com/image4.png', + label: 'ADDED', + }, + { + action: 'setImageLabel', + variantId: 3, + imageUrl: '//example.com/image3.png', + label: 'CHANGED', + }, + { + action: 'addExternalImage', + variantId: 3, + image: { + url: '//example.com/CHANGED.jpg', + label: 'foo', + dimensions: { h: 400, w: 300 }, + }, + }, + { + action: 'moveImageToPosition', + variantId: 3, + imageUrl: '//example.com/image4.png', + position: 0, + }, + { + action: 'removeImage', + variantId: 3, + imageUrl: '//example.com/image5.png', + }, + { + action: 'removeImage', + variantId: 4, + imageUrl: '//example.com/old-remove.png', + }, + ]) + }) + }) + + describe('with non-matching variant order', () => { + test('should detect image movement', () => { + const before = { + key: 'foo-key', + published: true, + hasStagedChanges: true, + masterVariant: { + assets: [], + images: [], + prices: [], + sku: 'third-variant', + id: 3, + }, + variants: [ + { + assets: [], + images: [], + prices: [], + id: 4, + }, + { + assets: [], + images: [], + prices: [], + sku: 'testing-animation', + id: 5, + }, + { + assets: [], + images: [ + { + url: 'https://95bc80c3c245100a18cc-04fc5bec7ec901344d7cbd57f9a2fab3.ssl.cf3.rackcdn.com/Screen+Shot+2017-04--LOx1OrZZ.png', + dimensions: { + w: 1456, + h: 1078, + }, + }, + { + url: 'https://95bc80c3c245100a18cc-04fc5bec7ec901344d7cbd57f9a2fab3.ssl.cf3.rackcdn.com/cactus-with-surfboar-BmOeVZEZ.jpg', + label: 'cactus', + dimensions: { + w: 602, + h: 600, + }, + }, + ], + sku: '89978FRU', + id: 1, + }, + { + assets: [], + images: [], + prices: [], + sku: 'vid6', + id: 10, + }, + { + availability: { + isOnStock: true, + availableQuantity: 5678, + }, + assets: [], + images: [], + key: 'test', + sku: 'secondary-variant', + id: 2, + }, + ], + } + + const now = { + masterVariant: { + id: 1, + sku: '89978FRU', + images: [ + { + url: 'https://95bc80c3c245100a18cc-04fc5bec7ec901344d7cbd57f9a2fab3.ssl.cf3.rackcdn.com/cactus-with-surfboar-BmOeVZEZ.jpg', + label: 'cactus', + dimensions: { + w: 602, + h: 600, + }, + }, + { + url: 'https://95bc80c3c245100a18cc-04fc5bec7ec901344d7cbd57f9a2fab3.ssl.cf3.rackcdn.com/Screen+Shot+2017-04--LOx1OrZZ.png', + dimensions: { + w: 1456, + h: 1078, + }, + }, + ], + assets: [], + }, + variants: [ + { + id: 2, + sku: 'secondary-variant', + key: 'test', + prices: [], + images: [], + assets: [], + availability: { + isOnStock: true, + availableQuantity: 5678, + }, + }, + { + id: 3, + sku: 'third-variant', + prices: [], + images: [], + assets: [], + }, + { + id: 4, + prices: [], + images: [], + assets: [], + }, + { + id: 5, + sku: 'testing-animation', + prices: [], + images: [], + assets: [], + }, + ], + hasStagedChanges: true, + published: true, + key: 'foo-key', + } + const actions = productsSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'changeMasterVariant', + variantId: 1, + }, + { + action: 'removeVariant', + id: 10, + }, + { + action: 'moveImageToPosition', + variantId: 1, + imageUrl: + 'https://95bc80c3c245100a18cc-04fc5bec7ec901344d7cbd57f9a2fab3.ssl.cf3.rackcdn.com/cactus-with-surfboar-BmOeVZEZ.jpg', + position: 0, + }, + ]) + }) + + test('should build actions for image removal', () => { + const before = { + key: 'foo-key', + published: true, + hasStagedChanges: true, + masterVariant: { + assets: [], + images: [], + prices: [], + sku: 'third-variant', + id: 3, + }, + variants: [ + { + assets: [], + images: [], + prices: [], + id: 4, + }, + { + assets: [], + images: [], + prices: [], + sku: 'testing-animation', + id: 5, + }, + { + assets: [], + prices: [], + images: [ + { + url: 'https://95bc80c3c245100a18cc-04fc5bec7ec901344d7cbd57f9a2fab3.ssl.cf3.rackcdn.com/Screen+Shot+2017-04--LOx1OrZZ.png', + dimensions: { + w: 1456, + h: 1078, + }, + }, + { + url: 'https://95bc80c3c245100a18cc-04fc5bec7ec901344d7cbd57f9a2fab3.ssl.cf3.rackcdn.com/cactus-with-surfboar-BmOeVZEZ.jpg', + label: 'cactus', + dimensions: { + w: 602, + h: 600, + }, + }, + ], + sku: '89978FRU', + id: 1, + }, + { + assets: [], + images: [], + prices: [], + sku: 'vid6', + id: 10, + }, + { + availability: { + isOnStock: true, + availableQuantity: 5678, + }, + assets: [], + prices: [], + images: [], + key: 'test', + sku: 'secondary-variant', + id: 2, + }, + ], + } + + const now = { + masterVariant: { + id: 1, + sku: '89978FRU', + prices: [], + images: [ + { + url: 'https://95bc80c3c245100a18cc-04fc5bec7ec901344d7cbd57f9a2fab3.ssl.cf3.rackcdn.com/cactus-with-surfboar-BmOeVZEZ.jpg', + label: 'cactus', + dimensions: { + w: 602, + h: 600, + }, + }, + ], + assets: [], + }, + variants: [ + { + id: 2, + sku: 'secondary-variant', + key: 'test', + prices: [], + images: [], + assets: [], + availability: { + isOnStock: true, + availableQuantity: 5678, + }, + }, + { + id: 3, + sku: 'third-variant', + prices: [], + images: [], + assets: [], + }, + { + id: 4, + prices: [], + images: [], + assets: [], + }, + { + id: 5, + sku: 'testing-animation', + prices: [], + images: [], + assets: [], + }, + ], + hasStagedChanges: true, + published: true, + key: 'foo-key', + } + + const actions = productsSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'changeMasterVariant', + variantId: 1, + }, + { + action: 'removeVariant', + id: 10, + }, + { + action: 'removeImage', + imageUrl: + 'https://95bc80c3c245100a18cc-04fc5bec7ec901344d7cbd57f9a2fab3.ssl.cf3.rackcdn.com/Screen+Shot+2017-04--LOx1OrZZ.png', + variantId: 1, + }, + ]) + }) + }) + + describe('without images', () => { + test('should not build actions if images are not set', () => { + const before = { + id: '123-abc', + masterVariant: { id: 1, images: [] }, + variants: [], + } + const now = { + id: '456-def', + masterVariant: { id: 1 }, + variants: [], + } + + const actions = productsSync.buildActions(now, before) + expect(actions).toEqual([]) + }) + }) +}) diff --git a/packages/sync-actions/test/product-sync-prices.spec.ts b/packages/sync-actions/test/product-sync-prices.spec.ts new file mode 100644 index 000000000..e2b3a2942 --- /dev/null +++ b/packages/sync-actions/test/product-sync-prices.spec.ts @@ -0,0 +1,1118 @@ +import shuffle from 'lodash.shuffle' +import productsSyncFn from '../src/products' + +/* eslint-disable max-len */ +describe('Actions', () => { + let productsSync + beforeEach(() => { + productsSync = productsSyncFn() + }) + + describe('with `priceID`', () => { + const discounted = { + value: { centAmount: 4000, currencyCode: 'EUR' }, + discount: { typeId: 'product-discount', id: 'pd1' }, + } + const validFrom = new Date().toISOString() + + const before = { + id: '123', + masterVariant: { + id: 1, + prices: [ + { + id: '111', + value: { currencyCode: 'EUR', centAmount: 1000 }, + discounted, + }, + ], + }, + variants: [ + { + id: 3, + prices: [], + }, + { + id: 2, + prices: [ + { + id: '222', + value: { currencyCode: 'EUR', centAmount: 1000 }, + customerGroup: { typeId: 'customer-group', id: 'cg1' }, + discounted, + }, + ], + }, + { + id: 4, + prices: [ + { + id: '223', + value: { currencyCode: 'USD', centAmount: 1200 }, + customerGroup: { typeId: 'customer-group', id: 'cg1' }, + discounted, + }, + { + id: '444', + value: { currencyCode: 'EUR', centAmount: 1000 }, + country: 'DE', + customerGroup: { typeId: 'customer-group', id: 'cg1' }, + channel: { typeId: 'channel', id: 'ch1' }, + discounted, + }, + ], + }, + ], + } + + const now = { + id: '123', + masterVariant: { + id: 1, + prices: [ + // Changed + { + id: '111', + value: { currencyCode: 'EUR', centAmount: 2000 }, + country: 'US', + discounted, + }, + ], + }, + variants: [ + { + id: 2, + // Removed + prices: [], + }, + { + id: 3, + prices: [ + // New + { + value: { currencyCode: 'USD', centAmount: 5000 }, + country: 'US', + customerGroup: { typeId: 'customer-group', id: 'cg1' }, + channel: { typeId: 'channel', id: 'ch1' }, + validFrom, + }, + ], + }, + { + id: 4, + prices: [ + // No change + { + id: '444', + value: { currencyCode: 'EUR', centAmount: 1000 }, + country: 'DE', + customerGroup: { typeId: 'customer-group', id: 'cg1' }, + channel: { typeId: 'channel', id: 'ch1' }, + }, + { + id: '223', + value: { currencyCode: 'USD', centAmount: 1200 }, + customerGroup: { typeId: 'customer-group', id: 'cg1' }, + discounted, + }, + ], + }, + ], + } + + test('should build actions for prices', () => { + const actions = productsSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'changePrice', + priceId: '111', + price: { + id: '111', + value: { currencyCode: 'EUR', centAmount: 2000 }, + country: 'US', + }, + }, + { action: 'removePrice', priceId: '222' }, + { + action: 'addPrice', + variantId: 3, + price: { + value: { currencyCode: 'USD', centAmount: 5000 }, + country: 'US', + customerGroup: { typeId: 'customer-group', id: 'cg1' }, + channel: { typeId: 'channel', id: 'ch1' }, + validFrom, + }, + }, + ]) + }) + + test('should build actions for prices with discounted when enableDiscounted is set to true', () => { + const actions = productsSync.buildActions(now, before, { + enableDiscounted: true, + }) + expect(actions).toEqual([ + { + action: 'changePrice', + priceId: '111', + price: { + country: 'US', + id: '111', + value: { currencyCode: 'EUR', centAmount: 2000 }, + discounted: { + value: { centAmount: 4000, currencyCode: 'EUR' }, + discount: { typeId: 'product-discount', id: 'pd1' }, + }, + }, + }, + { + action: 'changePrice', + price: { + channel: { + id: 'ch1', + typeId: 'channel', + }, + country: 'DE', + customerGroup: { + id: 'cg1', + typeId: 'customer-group', + }, + id: '444', + value: { + centAmount: 1000, + currencyCode: 'EUR', + fractionDigits: undefined, + type: undefined, + }, + }, + priceId: '444', + }, + { action: 'removePrice', priceId: '222' }, + { + action: 'addPrice', + variantId: 3, + price: { + value: { currencyCode: 'USD', centAmount: 5000 }, + country: 'US', + customerGroup: { typeId: 'customer-group', id: 'cg1' }, + channel: { typeId: 'channel', id: 'ch1' }, + validFrom, + }, + }, + ]) + }) + + test('should not delete the discounted field from the original object', () => { + expect('discounted' in before.masterVariant.prices[0]).toBeTruthy() + expect('discounted' in now.masterVariant.prices[0]).toBeTruthy() + }) + }) + + test('should not build actions if prices are not set', () => { + const before = { + id: '123-abc', + masterVariant: { id: 1, prices: [] }, + variants: [], + } + const now = { + id: '456-def', + masterVariant: { id: 1, prices: [] }, + variants: [], + } + + const actions = productsSync.buildActions(now, before) + expect(actions).toEqual([]) + }) + + test('should generate PriceCustom actions before changePrice action', () => { + const before = { + id: '123', + masterVariant: { + prices: [ + { + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1900, + fractionDigits: 2, + }, + id: '9fe6610f', + country: 'DE', + custom: { + type: { + typeId: 'type', + id: '218d8068', + }, + fields: { + touchpoints: ['value'], + }, + }, + }, + ], + }, + } + + const now = { + id: '123', + masterVariant: { + prices: [ + { + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 5678, + fractionDigits: 2, + }, + id: '9fe6610f', + country: 'DE', + custom: { + type: { + typeId: 'type', + id: '218d8068', + }, + fields: { + published: false, + }, + }, + }, + ], + }, + } + + const actions = productsSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'setProductPriceCustomField', + name: 'touchpoints', + priceId: '9fe6610f', + value: undefined, + }, + { + action: 'setProductPriceCustomField', + name: 'published', + priceId: '9fe6610f', + value: false, + }, + { + action: 'changePrice', + price: { + country: 'DE', + custom: { + fields: { + published: false, + }, + type: { + id: '218d8068', + typeId: 'type', + }, + }, + id: '9fe6610f', + value: { + centAmount: 5678, + currencyCode: 'EUR', + fractionDigits: 2, + type: 'centPrecision', + }, + }, + priceId: '9fe6610f', + }, + ]) + }) + + describe('without `priceID`', () => { + let actions + const dateNow = new Date() + const twoWeeksFromNow = new Date(Date.now() + 12096e5) // two weeks from now + const threeWeeksFromNow = new Date(Date.now() + 12096e5 * 1.5) + + const before = { + id: '123-abc', + masterVariant: { + id: 1, + prices: [ + { + // change + id: '111', + value: { currencyCode: 'EUR', centAmount: 3000 }, + country: 'US', + customerGroup: { typeId: 'customer-group', id: 'cg1' }, + channel: { typeId: 'channel', id: 'ch1' }, + }, + { + // change + id: '333', + value: { currencyCode: 'SEK', centAmount: 10000 }, + country: 'US', + channel: { typeId: 'channel', id: 'ch1' }, + }, + { + // keep + id: '444', + value: { currencyCode: 'SEK', centAmount: 25000 }, + country: 'SE', + }, + { + // remove + id: '666', + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'UK', + validFrom: twoWeeksFromNow, + validUntil: threeWeeksFromNow, + }, + { + // change + id: '777', + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + }, + { + // set price custom type + id: '888', + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + }, + { + // set price custom type and field + id: '999', + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + }, + { + // change price custom field + id: '1010', + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + custom: { + type: { + typeId: 'type', + id: '5678', + }, + fields: { + source: 'shop', + }, + }, + }, + { + // remove price custom field + id: '1111', + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + custom: { + type: { + typeId: 'type', + id: '5678', + }, + fields: { + source: 'shop', + }, + }, + }, + { + // action `changePrice` should contian custom object + id: '2222', + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + custom: { + type: { + typeId: 'type', + id: '5678', + }, + fields: { + source: 'shop', + }, + }, + }, + ], + }, + } + const now = { + id: '456-def', + masterVariant: { + id: 1, + prices: [ + { + // change + value: { currencyCode: 'EUR', centAmount: 4000 }, + country: 'US', + customerGroup: { typeId: 'customer-group', id: 'cg1' }, + channel: { typeId: 'channel', id: 'ch1' }, + }, + { + // change + value: { currencyCode: 'SEK', centAmount: 15000 }, + country: 'US', + channel: { typeId: 'channel', id: 'ch1' }, + }, + { + // change + value: { currencyCode: 'GBP', centAmount: 10000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + }, + { + // keep + value: { currencyCode: 'SEK', centAmount: 25000 }, + country: 'SE', + }, + { + // add + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'US', + validFrom: twoWeeksFromNow, + validUntil: threeWeeksFromNow, + }, + { + // set price custom type + id: '888', + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + custom: { + type: { + typeId: 'type', + id: '5678', + }, + }, + }, + { + // set price custom type and field + id: '999', + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + custom: { + type: { + typeId: 'type', + id: '5678', + }, + fields: { + source: 'shop', + }, + }, + }, + { + // change price custom field + id: '1010', + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + custom: { + type: { + typeId: 'type', + id: '5678', + }, + fields: { + source: 'random', + }, + }, + }, + { + // remove price custom field and type + id: '1111', + value: { currencyCode: 'GBP', centAmount: 1000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + }, + { + // action `changePrice` should contian custom object + id: '2222', + value: { currencyCode: 'GBP', centAmount: 2000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + custom: { + type: { + typeId: 'type', + id: '5678', + }, + fields: { + source: 'shop', + }, + }, + }, + ], + }, + } + + beforeEach(() => { + now.masterVariant.prices = shuffle(now.masterVariant.prices) + actions = productsSync.buildActions(now, before) + }) + + test('should build five update actions', () => { + expect(actions).toHaveLength(14) + }) + + test('should build `changePrice` actions', () => { + expect(actions).toEqual( + expect.arrayContaining([ + { + action: 'changePrice', + priceId: '111', + price: { + id: '111', + value: { currencyCode: 'EUR', centAmount: 4000 }, + country: 'US', + customerGroup: { typeId: 'customer-group', id: 'cg1' }, + channel: { typeId: 'channel', id: 'ch1' }, + }, + }, + { + action: 'changePrice', + priceId: '333', + price: { + id: '333', + value: { currencyCode: 'SEK', centAmount: 15000 }, + country: 'US', + channel: { typeId: 'channel', id: 'ch1' }, + }, + }, + { + action: 'changePrice', + priceId: '777', + price: { + id: '777', + value: { currencyCode: 'GBP', centAmount: 10000 }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + }, + }, + ]) + ) + }) + + test('should build `removePrice` action', () => { + expect(actions).toEqual( + expect.arrayContaining([ + { + action: 'removePrice', + priceId: '666', + }, + ]) + ) + }) + + test('should build `addPrice` action', () => { + expect(actions).toEqual( + expect.arrayContaining([ + { + action: 'addPrice', + price: { + value: { + currencyCode: 'GBP', + centAmount: 1000, + }, + country: 'US', + validFrom: twoWeeksFromNow, + validUntil: threeWeeksFromNow, + }, + variantId: 1, + }, + ]) + ) + }) + + test('should build `changePrice` action without deleting `custom` prop', () => { + expect(actions).toEqual( + expect.arrayContaining([ + { + action: 'changePrice', + price: { + id: '2222', + value: { + currencyCode: 'GBP', + centAmount: 2000, + fractionDigits: undefined, + type: undefined, + }, + country: 'UK', + validFrom: dateNow, + validUntil: twoWeeksFromNow, + custom: { + type: { + typeId: 'type', + id: '5678', + }, + fields: { + source: 'shop', + }, + }, + }, + priceId: '2222', + }, + ]) + ) + }) + + test('should build `setProductPriceCustomType` action without fields', () => { + expect(actions).toEqual( + expect.arrayContaining([ + { + action: 'setProductPriceCustomType', + priceId: '888', + type: { + id: '5678', + typeId: 'type', + }, + }, + ]) + ) + }) + + test('should build `setProductPriceCustomType` action', () => { + expect(actions).toEqual( + expect.arrayContaining([ + { + action: 'setProductPriceCustomType', + priceId: '999', + type: { + id: '5678', + typeId: 'type', + }, + fields: { + source: 'shop', + }, + }, + ]) + ) + }) + + test('should build `setProductPriceCustomType` action which delete custom type', () => { + expect(actions).toEqual( + expect.arrayContaining([ + { + action: 'setProductPriceCustomType', + priceId: '1111', + }, + ]) + ) + }) + + test('should build `setProductPriceCustomField` action', () => { + expect(actions).toEqual( + expect.arrayContaining([ + { + action: 'setProductPriceCustomField', + name: 'source', + priceId: '1010', + value: 'random', + }, + ]) + ) + }) + + test('should remove a price without id', () => { + const oldProduct = { + id: '123', + version: 1, + masterVariant: { + id: 1, + sku: 'v1', + prices: [ + { + country: 'DE', + id: 'DE_PRICE', + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1111, + fractionDigits: 2, + }, + }, + { + country: 'LT', + id: 'LT_PRICE', + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 2222, + fractionDigits: 2, + }, + }, + { + country: 'IT', + id: 'IT_PRICE', + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 3333, + fractionDigits: 2, + }, + }, + ], + attributes: [], + }, + variants: [], + } + const newProduct = { + id: '123', + version: 1, + masterVariant: { + id: 1, + sku: 'v1', + prices: [ + { + country: 'DE', + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1111, + fractionDigits: 2, + }, + }, + { + country: 'IT', + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 3333, + fractionDigits: 2, + }, + }, + ], + attributes: [], + }, + variants: [], + } + const updateActions = productsSync.buildActions(newProduct, oldProduct) + expect(updateActions).toHaveLength(1) + expect(updateActions).toEqual([ + { + action: 'removePrice', + priceId: 'LT_PRICE', + }, + ]) + }) + + test('should handle missing optional fields', () => { + const oldProduct = { + id: '123', + version: 1, + masterVariant: { + id: 1, + sku: 'v1', + prices: [ + { + country: 'DE', + id: 'DE_PRICE', + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1111, + fractionDigits: 2, + }, + }, + ], + attributes: [], + }, + variants: [], + } + const newProduct = { + id: '123', + version: 1, + masterVariant: { + id: 1, + sku: 'v1', + prices: [ + { + country: 'DE', + value: { + currencyCode: 'EUR', + centAmount: 1111, + // optional fields are missing here + }, + }, + ], + attributes: [], + }, + variants: [], + } + const updateActions = productsSync.buildActions(newProduct, oldProduct) + expect(updateActions).toHaveLength(0) + }) + + test('should sync when optional fields are different', () => { + const oldProduct = { + id: '123', + version: 1, + masterVariant: { + id: 1, + sku: 'v1', + prices: [ + { + country: 'DE', + id: 'DE_PRICE', + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 1111, + fractionDigits: 2, + }, + }, + ], + attributes: [], + }, + variants: [], + } + const newProduct = { + id: '123', + version: 1, + masterVariant: { + id: 1, + sku: 'v1', + prices: [ + { + country: 'DE', + value: { + type: 'highPrecision', + currencyCode: 'EUR', + centAmount: 1111, + fractionDigits: 4, + }, + }, + ], + attributes: [], + }, + variants: [], + } + const updateActions = productsSync.buildActions(newProduct, oldProduct) + expect(updateActions).toHaveLength(1) + expect(updateActions).toEqual([ + { + action: 'changePrice', + price: { + country: 'DE', + id: 'DE_PRICE', + value: { + centAmount: 1111, + currencyCode: 'EUR', + fractionDigits: 4, + type: 'highPrecision', + }, + }, + priceId: 'DE_PRICE', + }, + ]) + }) + }) + + describe('without `country`', () => { + let actions + const before = { + id: '81400c95-1de9-4431-9abd-a3eb8e0884d5', + version: 1, + productType: { + typeId: 'product-type', + id: 'c538376f-b565-4cb7-ac29-49b88b7f2acf', + }, + name: { + de: 'abcd', + }, + description: { + de: 'abcd', + }, + categories: [], + categoryOrderHints: {}, + slug: { + de: 'abcd', + }, + masterVariant: { + id: 1, + sku: '1111111111111', + prices: [ + { + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 8995, + fractionDigits: 2, + }, + id: '7960b455-ab04-4722-a8b2-431460d60012', + custom: { + type: { + typeId: 'type', + id: 'aada6bfb-2df1-4877-90f3-6efae0fbefa8', + }, + fields: { + promotionDiscountType: 'VerlaengerungHZArtikel', + promotionValidToExclusive: '2018-09-30T23:59:35.570Z', + promotionValidFromInclusive: '2018-09-24T00:00:35.570Z', + promotionRegularPrice: 9995, + }, + }, + }, + ], + }, + variants: [ + { + id: 2, + sku: '22222222222', + prices: [ + { + value: { + type: 'centPrecision', + currencyCode: 'EUR', + centAmount: 8995, + fractionDigits: 2, + }, + id: '38a9667a-976d-4bcc-8d2a-b04701e41f18', + custom: { + type: { + typeId: 'type', + id: 'aada6bfb-2df1-4877-90f3-6efae0fbefa8', + }, + fields: { + promotionDiscountType: 'VerlaengerungHZArtikel', + promotionValidToExclusive: '2018-09-30T23:59:35.570Z', + promotionValidFromInclusive: '2018-09-24T00:00:35.570Z', + promotionRegularPrice: 9995, + }, + }, + }, + ], + }, + ], + } + + const now = { + id: '81400c95-1de9-4431-9abd-a3eb8e0884d5', + version: 1, + productType: { + typeId: 'product-type', + id: 'c538376f-b565-4cb7-ac29-49b88b7f2acf', + }, + name: { + de: 'abcd', + }, + description: { + de: 'abcd', + }, + categories: [], + categoryOrderHints: {}, + slug: { + de: 'abcd', + }, + masterVariant: { + id: 1, + sku: '1111111111111', + prices: [ + { + value: { + centAmount: 6495, + currencyCode: 'EUR', + }, + custom: { + type: { + id: 'aada6bfb-2df1-4877-90f3-6efae0fbefa8', + }, + fields: { + promotionDiscountType: 'Tiefpreis', + promotionRegularPrice: 8995, + promotionValidToExclusive: 'SKU-1111111111111', + promotionValidFromInclusive: '2018-10-02T00:00:35.570Z', + }, + }, + }, + ], + }, + variants: [ + { + id: 2, + sku: '22222222222', + prices: [ + { + value: { + centAmount: 8995, + currencyCode: 'EUR', + }, + custom: { + type: { + id: 'aada6bfb-2df1-4877-90f3-6efae0fbefa8', + }, + fields: { + promotionDiscountType: 'Tiefpreis', + promotionRegularPrice: 9995, + promotionValidToExclusive: 'SKU-2222222222222', + promotionValidFromInclusive: '2018-10-02T00:00:35.570Z', + }, + }, + }, + ], + }, + ], + } + + beforeEach(() => { + actions = productsSync.buildActions(now, before) + }) + + test('should sync when optional fields are different', () => { + const actionNames = actions.map((action) => action.action) + + expect(actions).toHaveLength(2) + expect(actionNames).toEqual(['changePrice', 'changePrice']) + }) + }) + + describe('with read only prices', () => { + const before = { + id: '123', + masterVariant: { + id: 1, + prices: Object.freeze([ + { + id: '111', + value: { currencyCode: 'EUR', centAmount: 1000 }, + }, + ]), + }, + } + + const now = { + id: '123', + masterVariant: { + id: 1, + prices: Object.freeze([ + { + id: '111', + value: { currencyCode: 'EUR', centAmount: 2000 }, + country: 'US', + }, + ]), + }, + } + + test('should build actions for prices', () => { + const actions = productsSync.buildActions(now, before) + expect(actions).toEqual([ + { + action: 'changePrice', + priceId: '111', + price: { + id: '111', + value: { currencyCode: 'EUR', centAmount: 2000 }, + country: 'US', + }, + }, + ]) + }) + }) +}) diff --git a/packages/sync-actions/test/product-sync-variants.spec.ts b/packages/sync-actions/test/product-sync-variants.spec.ts new file mode 100644 index 000000000..a4129f3a8 --- /dev/null +++ b/packages/sync-actions/test/product-sync-variants.spec.ts @@ -0,0 +1,1819 @@ +import productsSyncFn from '../src/products' + +/* eslint-disable max-len */ +describe('Actions', () => { + let productsSync + beforeEach(() => { + productsSync = productsSyncFn() + }) + + test('should build attribute actions', () => { + const before = { + id: '123', + masterVariant: { + id: 1, + attributes: [ + { name: 'uid', value: '20063672' }, + { name: 'length', value: 160 }, + { name: 'wide', value: 85 }, + { name: 'bulkygoods', value: { label: 'Ja', key: 'YES' } }, + { name: 'ean', value: '20063672' }, + ], + }, + variants: [ + { id: 3, attributes: [] }, + { + id: 2, + attributes: [ + { name: 'uid', value: '20063672' }, + { name: 'length', value: 160 }, + { name: 'wide', value: 85 }, + { name: 'bulkygoods', value: { label: 'Ja', key: 'YES' } }, + { name: 'ean', value: '20063672' }, + ], + }, + { + id: 4, + attributes: [ + { name: 'uid', value: '1234567' }, + { name: 'length', value: 123 }, + { name: 'bulkygoods', value: { label: 'Si', key: 'SI' } }, + ], + }, + ], + } + + const now = { + id: '123', + masterVariant: { + id: 1, + attributes: [ + { name: 'uid', value: '20063675' }, // changed + { name: 'length', value: 160 }, + { name: 'wide', value: 10 }, // changed + { name: 'bulkygoods', value: 'NO' }, // changed + { name: 'ean', value: '20063672' }, + ], + }, + variants: [ + { + id: 2, + attributes: [ + { name: 'uid', value: '20055572' }, // changed + { name: 'length', value: 333 }, // changed + { name: 'wide', value: 33 }, // changed + { name: 'bulkygoods', value: 'YES' }, // changed + { name: 'ean', value: '20063672' }, + ], + }, + { + id: 3, + attributes: [ + // new + { name: 'uid', value: '00001' }, + { name: 'length', value: 500 }, + { name: 'bulkygoods', value: 'SI' }, + ], + }, + { id: 4, attributes: [] }, // removed + ], + } + + const actions = productsSync.buildActions(now, before) + + expect(actions).toEqual([ + { action: 'setAttribute', variantId: 1, name: 'uid', value: '20063675' }, + { action: 'setAttribute', variantId: 1, name: 'wide', value: 10 }, + { action: 'setAttribute', variantId: 1, name: 'bulkygoods', value: 'NO' }, + + { action: 'setAttribute', variantId: 2, name: 'uid', value: '20055572' }, + { action: 'setAttribute', variantId: 2, name: 'length', value: 333 }, + { action: 'setAttribute', variantId: 2, name: 'wide', value: 33 }, + { + action: 'setAttribute', + variantId: 2, + name: 'bulkygoods', + value: 'YES', + }, + + { action: 'setAttribute', variantId: 3, name: 'uid', value: '00001' }, + { action: 'setAttribute', variantId: 3, name: 'length', value: 500 }, + { action: 'setAttribute', variantId: 3, name: 'bulkygoods', value: 'SI' }, + + { action: 'setAttribute', variantId: 4, name: 'uid', value: undefined }, + { + action: 'setAttribute', + variantId: 4, + name: 'length', + value: undefined, + }, + { + action: 'setAttribute', + variantId: 4, + name: 'bulkygoods', + value: undefined, + }, + ]) + }) + + test('should handle long text values performantly', () => { + const longText = 'a'.repeat(10_000) + const longText2 = 'b'.repeat(10_000) + const before = { + id: '123', + masterVariant: { + id: 1, + attributes: [ + { name: 'color', value: longText }, + { name: 'size', value: longText }, + { name: 'weight', value: longText }, + ], + }, + variants: [ + { + id: 2, + attributes: [ + { name: 'color', value: longText }, + { name: 'size', value: longText }, + { name: 'weight', value: longText }, + ], + }, + ], + } + + const now = { + id: '123', + masterVariant: { + id: 1, + attributes: [ + { name: 'color', value: longText2 }, + { name: 'size', value: longText2 }, + { name: 'weight', value: longText2 }, + ], + }, + variants: [ + { + id: 2, + attributes: [ + { name: 'color', value: longText2 }, + { name: 'size', value: longText2 }, + { name: 'weight', value: longText2 }, + ], + }, + ], + } + + const startTime = Date.now() + const actions = productsSync.buildActions(now, before) + + // Should take less than 100ms. + expect(Date.now() - startTime).toBeLessThan(100) + expect(actions).toEqual([ + { action: 'setAttribute', variantId: 1, name: 'color', value: longText2 }, + { action: 'setAttribute', variantId: 1, name: 'size', value: longText2 }, + { + action: 'setAttribute', + variantId: 1, + name: 'weight', + value: longText2, + }, + { action: 'setAttribute', variantId: 2, name: 'color', value: longText2 }, + { action: 'setAttribute', variantId: 2, name: 'size', value: longText2 }, + { + action: 'setAttribute', + variantId: 2, + name: 'weight', + value: longText2, + }, + ]) + }) + + test('should build SameForAll attribute actions', () => { + const before = { + id: '123', + masterVariant: { + id: 1, + attributes: [ + { name: 'color', value: 'red' }, + { name: 'size', value: 'M' }, + { name: 'weigth', value: '1' }, + ], + }, + variants: [ + { id: 3, attributes: [] }, + { + id: 2, + attributes: [ + { name: 'color', value: 'red' }, + { name: 'size', value: 'M' }, + { name: 'weigth', value: '2' }, + ], + }, + ], + } + + const now = { + id: '123', + masterVariant: { + id: 1, + attributes: [ + // new + { name: 'vendor', value: 'ferrari' }, + // changed + { name: 'color', value: 'yellow' }, + // removed + { name: 'size', value: undefined }, + // normal attribute + { name: 'weigth', value: '3' }, + ], + }, + variants: [ + { + id: 2, + attributes: [ + // new + { name: 'vendor', value: 'ferrari' }, + // changed + { name: 'color', value: 'yellow' }, + // removed + { name: 'size', value: undefined }, + // normal attribute + { name: 'weigth', value: '4' }, + ], + }, + { id: 3, attributes: [] }, + ], + } + + const actions = productsSync.buildActions(now, before, { + sameForAllAttributeNames: ['vendor', 'color', 'size'], + }) + + expect(actions).toEqual([ + { action: 'setAttributeInAllVariants', name: 'vendor', value: 'ferrari' }, + { action: 'setAttributeInAllVariants', name: 'color', value: 'yellow' }, + { action: 'setAttributeInAllVariants', name: 'size', value: undefined }, + { action: 'setAttribute', variantId: 1, name: 'weigth', value: '3' }, + { action: 'setAttribute', variantId: 2, name: 'weigth', value: '4' }, + ]) + }) + + test('should build SameForAll attribute actions for a SET of object values', () => { + const before = { + masterVariant: { + attributes: [ + { + name: 'set-attribute-reference-type', + value: [ + { id: '123', referenceTypeId: 'reference-example' }, + { id: '234', referenceTypeId: 'reference-example' }, + ], + }, + ], + }, + } + + const now = { + masterVariant: { + attributes: [ + { + name: 'set-attribute-reference-type', + value: [ + { id: '444', referenceTypeId: 'reference-example' }, + // Test setting null, to test and ensure that objectHash + // takes this type into account when calculating a correct + // hash for array diff with object values + // github.com/benjamine/jsondiffpatch/blob/master/docs/arrays.md + null, + ], + }, + ], + }, + } + + const actions = productsSync.buildActions(now, before, { + sameForAllAttributeNames: ['set-attribute-reference-type'], + }) + + expect(actions).toEqual([ + { + action: 'setAttributeInAllVariants', + name: 'set-attribute-reference-type', + value: [ + { id: '444', referenceTypeId: 'reference-example' }, + // Since objectHash gives the diffpatcher an index, + // we expect a null to be given here + null, + ], + }, + ]) + }) + + test('should build `addVariant` action', () => { + const newVariant: any = { + key: 'ddd', + sku: 'ccc', + attributes: [{ name: 'color', value: 'red' }], + images: [{ url: 'http://foo.com', label: 'foo' }], + prices: [{ value: { centAmount: 300, currencyCode: 'USD' } }], + } + + const before = { + variants: [ + { + id: 2, + key: 'eee', + sku: 'aaa', + attributes: [{ name: 'color', value: 'green' }], + prices: [{ value: { centAmount: 100, currencyCode: 'EUR' } }], + }, + { + id: 3, + key: 'fff', + sku: 'bbb', + attributes: [{ name: 'color', value: 'yellow' }], + prices: [{ value: { centAmount: 200, currencyCode: 'GBP' } }], + }, + ], + } + const now = { variants: before.variants.slice(0, 1).concat(newVariant) } + + const actions = productsSync.buildActions(now, before) + + expect(actions).toEqual([ + { action: 'addVariant', ...newVariant }, + { action: 'removeVariant', id: 3 }, + ]) + }) + + test('should handle mapping actions for new variants without ids', () => { + const before = { + id: '123', + masterVariant: { + id: 1, + sku: 'v1', + key: 'v1', + attributes: [{ name: 'foo', value: 'bar' }], + }, + variants: [ + { + id: 2, + sku: 'v2', + key: 'v2', + attributes: [{ name: 'foo', value: 'qux' }], + }, + { + id: 3, + sku: 'v3', + key: 'v3', + attributes: [{ name: 'foo', value: 'baz' }], + }, + ], + } + + const now = { + id: '123', + masterVariant: { + id: 1, + sku: 'v1', + key: 'v2', + attributes: [{ name: 'foo', value: 'new value' }], + }, + variants: [ + { + id: 3, + sku: 'v4', + key: 'v4', + attributes: [{ name: 'foo', value: 'i dont care' }], + }, + { + id: 2, + sku: 'v2', + key: 'v2', + attributes: [{ name: 'foo', value: 'another value' }], + }, + { + sku: 'v3', + key: 'v3', + attributes: [{ name: 'foo', value: 'yet another' }], + }, + ], + } + + const actions = productsSync.buildActions(now, before) + expect(actions).toEqual([ + { action: 'setProductVariantKey', key: 'v2', variantId: 1 }, + { action: 'setAttribute', variantId: 1, name: 'foo', value: 'new value' }, + { action: 'setSku', sku: 'v4', variantId: 3 }, + { action: 'setProductVariantKey', key: 'v4', variantId: 3 }, + { + action: 'setAttribute', + variantId: 3, + name: 'foo', + value: 'i dont care', + }, + { + action: 'setAttribute', + variantId: 2, + name: 'foo', + value: 'another value', + }, + { + action: 'addVariant', + sku: 'v3', + key: 'v3', + attributes: [{ name: 'foo', value: 'yet another' }], + }, + ]) + }) + + describe('without master variant in `now`', () => { + describe('with master variant in `before`', () => { + const before = { + id: '123', + version: 1, + masterVariant: { + id: 1, + sku: 'v1', + attributes: [{ name: 'foo', value: 'bar' }], + }, + variants: [], + } + + const now = { + id: '123', + // <-- no masterVariant + variants: [], + } + + test('should generate update action to remove variant', () => { + const actions = productsSync.buildActions(now, before) + expect(actions).toEqual([{ action: 'removeVariant', id: 1 }]) + }) + }) + + describe('with variants in `now`', () => { + const before = { + id: '123', + version: 1, + variants: [ + { + id: 2, + sku: 'v2', + key: 'v2', + attributes: [{ name: 'foo', value: 'qux' }], + }, + { + id: 3, + sku: 'v3', + key: 'v3', + attributes: [{ name: 'foo', value: 'baz' }], + }, + ], + } + + const now = { + id: '123', + variants: [ + // changed + { + id: 2, + sku: 'v2', + key: 'v2', + attributes: [{ name: 'foo', value: 'another value' }], + }, + // changed + { + id: 3, + sku: 'v3', + key: 'v3', + attributes: [{ name: 'foo', value: 'i dont care' }], + }, + // new + { + sku: 'v4', + key: 'v4', + attributes: [{ name: 'foo', value: 'yet another' }], + }, + ], + } + + test('should generate `addVariant` and `setAttribute` actions', () => { + const actions = productsSync.buildActions(now, before) + + expect(actions).toEqual([ + { + action: 'setAttribute', + variantId: 2, + name: 'foo', + value: 'another value', + }, + { + action: 'setAttribute', + variantId: 3, + name: 'foo', + value: 'i dont care', + }, + { + action: 'addVariant', + sku: 'v4', + key: 'v4', + attributes: [{ name: 'foo', value: 'yet another' }], + }, + ]) + }) + }) + + describe('when changing master variant', () => { + describe('when moving master variant to variants', () => { + const before = { + id: '123', + version: 1, + masterVariant: { + id: 1, + sku: 'v1', + attributes: [{ name: 'foo', value: 'bar' }], + }, + variants: [], + } + + const now = { + id: '123', + version: 1, + masterVariant: { + id: 2, + sku: 'v1', + attributes: [{ name: 'foo', value: 'bar' }], + }, + variants: [ + { + id: 1, + sku: 'v1', + attributes: [{ name: 'foo', value: 'bar' }], + }, + ], + } + + test('should generate `changeMasterVariant` and `addVariant` action', () => { + const actions = productsSync.buildActions(now, before) + + expect(actions).toEqual([ + { + action: 'addVariant', + attributes: [{ name: 'foo', value: 'bar' }], + id: 2, + sku: 'v1', + }, + { action: 'changeMasterVariant', variantId: 2 }, + ]) + }) + }) + + describe('when adding new master variant (without moving)', () => { + const before = { + id: '123', + version: 1, + masterVariant: { + id: 1, + sku: 'v1', + attributes: [{ name: 'foo', value: 'bar' }], + }, + variants: [], + } + + const now = { + id: '123', + version: 1, + masterVariant: { + id: 2, + sku: 'v1', + attributes: [{ name: 'foo', value: 'bar' }], + }, + variants: [], + } + + test('should generate `changeMasterVariant`, `addVariant` and `removeVariant` action', () => { + const actions = productsSync.buildActions(now, before) + + expect(actions).toEqual([ + { + action: 'addVariant', + attributes: [{ name: 'foo', value: 'bar' }], + id: 2, + sku: 'v1', + }, + { action: 'changeMasterVariant', variantId: 2 }, + { action: 'removeVariant', id: 1 }, + ]) + }) + }) + + describe('with existing variant in `now` and `before`', () => { + describe('without changes to attributes', () => { + const before = { + id: '123', + version: 1, + masterVariant: { + id: 2, + sku: 'v1', + attributes: [{ name: 'foo', value: 'bar' }], + }, + variants: [ + { + id: 1, + sku: 'v1', + attributes: [{ name: 'foo-2', value: 'bar-2' }], + }, + ], + } + + const now = { + id: '123', + version: 1, + masterVariant: { + id: 1, + sku: 'v1', + attributes: [{ name: 'foo-2', value: 'bar-2' }], + }, + variants: [ + { + id: 2, + sku: 'v1', + attributes: [{ name: 'foo', value: 'bar' }], + }, + ], + } + + test('should generate `changeMasterVariant` action', () => { + const actions = productsSync.buildActions(now, before) + + expect(actions).toEqual([ + { action: 'changeMasterVariant', variantId: 1 }, + ]) + }) + }) + + describe('with changes to attributes', () => { + const before = { + id: '123', + version: 1, + masterVariant: { + id: 2, + sku: 'v1', + attributes: [{ name: 'foo', value: 'bar' }], + }, + variants: [ + { + id: 1, + sku: 'v1', + attributes: [{ name: 'foo-2', value: 'bar-2' }], + }, + ], + } + + const now = { + id: '123', + version: 1, + masterVariant: { + id: 1, + sku: 'v1', + attributes: [{ name: 'foo-2', value: 'bar-3' }], + }, + variants: [ + { + id: 2, + sku: 'v1', + attributes: [{ name: 'foo', value: 'bar' }], + }, + ], + } + + test('should generate `changeMasterVariant` and `setAttribute` actions', () => { + const actions = productsSync.buildActions(now, before) + + expect(actions).toEqual([ + { + action: 'setAttribute', + name: 'foo-2', + value: 'bar-3', + variantId: 1, + }, + { action: 'changeMasterVariant', variantId: 1 }, + ]) + }) + }) + }) + }) + }) + + test('should handle unsetting the sku of a variant', () => { + const before = { + id: '123', + masterVariant: { + id: 1, + sku: 'v1', + attributes: [{ name: 'foo', value: 'bar' }], + }, + } + + const now = { + id: '123', + masterVariant: { + id: 1, + sku: '', + attributes: [{ name: 'foo', value: 'bar' }], + }, + } + + const actions = productsSync.buildActions(now, before) + expect(actions).toEqual([{ action: 'setSku', sku: null, variantId: 1 }]) + }) + + test('should handle unsetting the key of a variant', () => { + const before = { + id: '123', + masterVariant: { + id: 1, + key: 'v1', + attributes: [{ name: 'foo', value: 'bar' }], + }, + } + + const now = { + id: '123', + masterVariant: { + id: 1, + key: '', + attributes: [{ name: 'foo', value: 'bar' }], + }, + } + + const actions = productsSync.buildActions(now, before) + expect(actions).toEqual([ + { action: 'setProductVariantKey', key: null, variantId: 1 }, + ]) + }) + + test('should build attribute actions for all types', () => { + const before = { + id: '123', + masterVariant: { + id: 1, + attributes: [ + { name: 'foo', value: 'bar' }, // text + { name: 'dog', value: { en: 'Dog', de: 'Hund', es: 'perro' } }, // ltext + { name: 'num', value: 50 }, // number + { name: 'count', value: { label: 'One', key: 'one' } }, // enum + { name: 'size', value: { label: { en: 'Medium' }, key: 'medium' } }, // lenum + { name: 'color', value: { label: { en: 'Color' }, key: 'red' } }, // lenum + { name: 'cost', value: { centAmount: 990, currencyCode: 'EUR' } }, // money + { name: 'reference', value: { typeId: 'product', id: '111' } }, // reference + { name: 'welcome', value: ['hello', 'world'] }, // set text + { + name: 'welcome2', + value: [ + { en: 'hello', it: 'ciao' }, + { en: 'world', it: 'mondo' }, + ], + }, // set ltext + { name: 'multicolor', value: ['red'] }, // set enum + { + name: 'multicolor2', + value: [{ key: 'red', label: { en: 'red', it: 'rosso' } }], + }, // set lenum + ], + }, + } + + const now = { + id: '123', + masterVariant: { + id: 1, + attributes: [ + { name: 'foo', value: 'qux' }, // text + { name: 'dog', value: { en: 'Doggy', it: 'Cane', es: 'perro' } }, // ltext + { name: 'num', value: 100 }, // number + { name: 'count', value: { label: 'Two', key: 'two' } }, // enum + { name: 'size', value: { label: { en: 'Small' }, key: 'small' } }, // lenum + { name: 'color', value: { label: { en: 'Blue' }, key: 'blue' } }, // lenum + { name: 'cost', value: { centAmount: 550, currencyCode: 'EUR' } }, // money + { name: 'reference', value: { typeId: 'category', id: '222' } }, // reference + { name: 'welcome', value: ['hello'] }, // set text + { name: 'welcome2', value: [{ en: 'hello', it: 'ciao' }] }, // set ltext + { name: 'multicolor', value: ['red', 'yellow'] }, // set enum + { + name: 'multicolor2', + value: [ + { key: 'red', label: { en: 'red', it: 'rosso' } }, + { key: 'yellow', label: { en: 'yellow', it: 'giallo' } }, + ], + }, // set lenum + { + name: 'listWithEmptyValues', + value: ['', '', null, { id: '123', typeId: 'products' }], + }, // set reference + ], + }, + } + + const actions = productsSync.buildActions(now, before) + expect(actions).toEqual([ + { action: 'setAttribute', variantId: 1, name: 'foo', value: 'qux' }, + { + action: 'setAttribute', + variantId: 1, + name: 'dog', + value: { en: 'Doggy', it: 'Cane', de: undefined, es: 'perro' }, + }, + { action: 'setAttribute', variantId: 1, name: 'num', value: 100 }, + { action: 'setAttribute', variantId: 1, name: 'count', value: 'two' }, + { action: 'setAttribute', variantId: 1, name: 'size', value: 'small' }, + { action: 'setAttribute', variantId: 1, name: 'color', value: 'blue' }, + { + action: 'setAttribute', + variantId: 1, + name: 'cost', + value: { centAmount: 550, currencyCode: 'EUR' }, + }, + { + action: 'setAttribute', + variantId: 1, + name: 'reference', + value: { typeId: 'category', id: '222' }, + }, + { + action: 'setAttribute', + variantId: 1, + name: 'welcome', + value: ['hello'], + }, + { + action: 'setAttribute', + variantId: 1, + name: 'welcome2', + value: [{ en: 'hello', it: 'ciao' }], + }, + { + action: 'setAttribute', + variantId: 1, + name: 'multicolor', + value: ['red', 'yellow'], + }, + { + action: 'setAttribute', + variantId: 1, + name: 'multicolor2', + value: [ + { key: 'red', label: { en: 'red', it: 'rosso' } }, + { key: 'yellow', label: { en: 'yellow', it: 'giallo' } }, + ], + }, // set lenum + { + action: 'setAttribute', + variantId: 1, + name: 'listWithEmptyValues', + value: ['', '', null, { id: '123', typeId: 'products' }], + }, // set reference + ]) + }) + + test('should ignore set sku', () => { + // Case when sku is not set, and the new value is empty or null + const before = { + id: '123', + masterVariant: { + id: 1, + }, + variants: [{ id: 2 }], + } + + const now = { + id: '123', + masterVariant: { + id: 1, + sku: '', + }, + variants: [{ id: 2, sku: null }], + } + + const actions = productsSync.buildActions(now, before) + expect(actions).toEqual([]) + }) + + test('should ignore set key', () => { + // Case when key is not set, and the new value is empty or null + const before = { + id: '123', + masterVariant: { + id: 1, + }, + variants: [{ id: 2 }], + } + + const now = { + id: '123', + masterVariant: { + id: 1, + key: '', + }, + variants: [{ id: 2, key: null }], + } + + const actions = productsSync.buildActions(now, before) + expect(actions).toEqual([]) + }) + + test('should ignore set sku if the sku was and still is empty', () => { + // Case when sku is not set, and the new value is empty or null + const before = { + id: '123', + masterVariant: { + id: 1, + sku: '', + }, + variants: [{ id: 2 }], + } + + const now = { + id: '123', + masterVariant: { + id: 1, + sku: '', + }, + variants: [{ id: 2, sku: null }], + } + + const actions = productsSync.buildActions(now, before) + expect(actions).toEqual([]) + }) + + test('should ignore set key if the key was and still is empty', () => { + // Case when key is not set, and the new value is empty or null + const before = { + id: '123', + masterVariant: { + id: 1, + key: '', + }, + variants: [{ id: 2 }], + } + + const now = { + id: '123', + masterVariant: { + id: 1, + key: '', + }, + variants: [{ id: 2, key: null }], + } + + const actions = productsSync.buildActions(now, before) + expect(actions).toEqual([]) + }) + + test('should build `setAttribute` action text/ltext attributes with long text', () => { + const longText = ` + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + Nunc ultricies fringilla tortor eu egestas. + Praesent rhoncus molestie libero, eu tempor sapien placerat id. + Donec commodo nunc sed nulla scelerisque, eu pulvinar augue egestas. + Donec at leo dolor. Cras at molestie arcu. + Sed non fringilla quam, sit amet ultricies massa. + Donec luctus tempus erat, ut suscipit elit varius nec. + Mauris dolor enim, aliquet sed nulla et, dignissim lobortis augue. + Proin pharetra magna eu neque semper tristique sed. + ` + + const newLongText = `Hello, ${longText}` + + /* eslint-disable max-len */ + const before = { + masterVariant: { + id: 1, + attributes: [ + { + name: 'text', + value: longText, + }, + ], + }, + variants: [ + { + id: 2, + attributes: [ + { + name: 'ltext', + value: { + en: longText, + }, + }, + ], + }, + ], + } + const now = { + masterVariant: { + id: 1, + attributes: [ + { + name: 'text', + value: newLongText, + }, + ], + }, + variants: [ + { + id: 2, + attributes: [ + { + name: 'ltext', + value: { + en: newLongText, + }, + }, + ], + }, + ], + } + /* eslint-enable max-len */ + const actions = productsSync.buildActions(now, before) + + expect(actions).toEqual([ + { + action: 'setAttribute', + variantId: 1, + name: 'text', + value: newLongText, + }, + { + action: 'setAttribute', + variantId: 2, + name: 'ltext', + value: { en: newLongText }, + }, + ]) + }) + + test('should build `setAttribute` action', async () => { + const before = { + categories: [], + masterVariant: { + id: 1, + key: 'default-masterVariant-key-de07e9bc-e352-422f-abe6-910d9879b995', + isMasterVariant: true, + prices: [], + images: [], + attributes: [], + assets: [], + }, + } + + const now = { + masterVariant: { + id: 1, + key: 'default-masterVariant-key-de07e9bc-e352-422f-abe6-910d9879b995', + isMasterVariant: true, + attributes: [ + { + name: 'ct-imp-bool', + value: true, + }, + ], + }, + } + + const actions = productsSync.buildActions(now, before) + + expect(actions).toEqual([ + { + action: 'setAttribute', + variantId: 1, + name: 'ct-imp-bool', + value: true, + }, + ]) + }) + + test('should build `setPriceMode` action', async () => { + const before = { + masterVariant: { + id: 1, + prices: [], + images: [], + attributes: [], + assets: [], + }, + variants: [], + } + + const now = { + masterVariant: { + id: 1, + prices: [], + images: [], + attributes: [], + assets: [], + }, + variants: [], + priceMode: 'Standalone', + } + + const actions = productsSync.buildActions(now, before) + + expect(actions).toEqual([ + { + action: 'setPriceMode', + priceMode: 'Standalone', + }, + ]) + }) + + test('should not build `setPriceMode` action if priceModes did not change', async () => { + const before = { + masterVariant: { + id: 1, + prices: [], + images: [], + attributes: [], + assets: [], + }, + variants: [], + priceMode: 'Embedded', + } + + const now = { + masterVariant: { + id: 1, + prices: [], + images: [], + attributes: [], + assets: [], + }, + variants: [], + priceMode: 'Embedded', + } + + const actions = productsSync.buildActions(now, before) + + expect(actions).toHaveLength(0) + }) + + test('should change `setPriceMode` action', async () => { + const before = { + masterVariant: { + id: 1, + prices: [], + images: [], + attributes: [], + assets: [], + }, + variants: [], + priceMode: 'Embedded', + } + + const now = { + masterVariant: { + id: 1, + prices: [], + images: [], + attributes: [], + assets: [], + }, + variants: [], + priceMode: 'Standalone', + } + + const actions = productsSync.buildActions(now, before) + + expect(actions).toEqual([ + { + action: 'setPriceMode', + priceMode: 'Standalone', + }, + ]) + }) + + describe('assets', () => { + test('should build "addAsset" action with empty assets', () => { + const before = { + masterVariant: { + id: 1, + assets: [], + }, + } + const now = { + masterVariant: { + id: 1, + assets: [ + { + key: 'asset-key', + name: { + en: 'asset name ', + }, + sources: [ + { + uri: 'http://example.org/content/product-manual.pdf', + }, + ], + }, + ], + }, + } + const actual = productsSync.buildActions(now, before) + const expected = [ + { + action: 'addAsset', + asset: now.masterVariant.assets[0], + variantId: 1, + position: 0, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build "addAsset" action with non exist assets', () => { + const before = { + masterVariant: { + id: 1, + assets: [ + { + id: 'xyz', + key: 'asset-key-one', + }, + { + id: 'xyz2', + key: 'asset-key-two', + name: { + en: 'asset name two', + }, + }, + ], + }, + } + const now = { + masterVariant: { + id: 1, + assets: [ + { + id: 'xyz', + key: 'asset-key-one', + }, + { + id: 'xyz2', + key: 'asset-key-two', + }, + { + key: 'asset-key', + name: { + en: 'asset name ', + }, + sources: [ + { + uri: 'http://example.org/content/product-manual.pdf', + }, + ], + }, + ], + }, + } + const actual = productsSync.buildActions(now, before) + const expected = [ + { + action: 'addAsset', + asset: now.masterVariant.assets[2], + variantId: 1, + position: 2, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build "addAsset" action for variant with sku with empty assets', () => { + const before = { + variants: [ + { + sku: 'my-sku', + assets: [], + }, + ], + } + const now = { + variants: [ + { + sku: 'my-sku', + assets: [ + { + key: 'asset-key', + name: { + en: 'asset name ', + }, + sources: [ + { + uri: 'http://example.org/content/product-manual.pdf', + }, + ], + }, + ], + }, + ], + } + const actual = productsSync.buildActions(now, before) + const expected = [ + { + action: 'addAsset', + asset: now.variants[0].assets[0], + sku: 'my-sku', + position: 0, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build "addAsset" action with existing assets', () => { + const existingAsset = { + key: 'existing', + sources: [ + { + uri: 'http://example.org/content/product-manual.pdf', + }, + ], + } + const newAsset = { + key: 'new', + sources: [ + { + uri: 'http://example.org/content/product-manual.gif', + }, + ], + } + const before = { + variants: [ + { + id: 2, + assets: [existingAsset], + }, + ], + } + const now = { + variants: [ + { + id: 2, + assets: [existingAsset, newAsset], + }, + ], + } + const actual = productsSync.buildActions(now, before) + const expected = [ + { + action: 'addAsset', + asset: newAsset, + variantId: 2, + position: 1, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build "removeAsset" action with assetId prop', () => { + const before = { + variants: [ + { + id: 2, + assets: [ + { + id: 'c136c9dc-51e8-40fe-8e2e-2a4c159f3358', + name: { + en: 'asset name ', + }, + sources: [ + { + uri: 'http://example.org/content/product-manual.pdf', + }, + ], + }, + ], + }, + ], + } + const now = { + variants: [ + { + id: 2, + assets: [], + }, + ], + } + const actual = productsSync.buildActions(now, before) + const expected = [ + { + action: 'removeAsset', + assetId: before.variants[0].assets[0].id, + variantId: 2, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build "removeAsset" action with assetKey prop', () => { + const before = { + variants: [ + { + id: 2, + assets: [ + { + key: 'asset-key', + name: { + en: 'asset name ', + }, + sources: [ + { + uri: 'http://example.org/content/product-manual.pdf', + }, + ], + }, + ], + }, + ], + } + const now = { + variants: [ + { + id: 2, + assets: [], + }, + ], + } + const actual = productsSync.buildActions(now, before) + const expected = [ + { + action: 'removeAsset', + assetKey: before.variants[0].assets[0].key, + variantId: 2, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build "removeAsset" action for variant with sku and asset with assetKey prop', () => { + const before = { + variants: [ + { + sku: 'my-sku', + assets: [ + { + key: 'asset-key', + name: { + en: 'asset name ', + }, + sources: [ + { + uri: 'http://example.org/content/product-manual.pdf', + }, + ], + }, + ], + }, + ], + } + const now = { + variants: [ + { + sku: 'my-sku', + assets: [], + }, + ], + } + const actual = productsSync.buildActions(now, before) + const expected = [ + { + action: 'removeAsset', + assetKey: before.variants[0].assets[0].key, + sku: 'my-sku', + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build "changeAssetName" action when asset name is changed', () => { + const initialAsset = { + id: 'xyz', + key: 'asset-key', + name: { + en: 'asset name ', + }, + } + const changedName = { + name: { + en: 'asset name ', + de: 'Asset Name', + }, + } + const changedAsset = { ...initialAsset, ...changedName } + const before = { + variants: [ + { + id: 1, + assets: [initialAsset], + }, + ], + } + const now = { + variants: [ + { + id: 1, + assets: [changedAsset], + }, + ], + } + const actual = productsSync.buildActions(now, before) + const expected = [ + { + action: 'changeAssetName', + ...changedName, + assetId: 'xyz', + variantId: 1, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build "setAssetKey", "changeAssetName", "setAssetDescription", "setAssetSources", "setAssetTags", "setAssetCustomType" actions', () => { + const initialAsset = { + id: 'xyz', + key: 'asset-key', + name: { + en: 'asset name ', + }, + description: { + en: 'description', + }, + sources: [ + { + uri: 'http://example.org/content/product-manual.pdf', + contentType: 'application/pdf', + }, + ], + tags: ['manual', 'pdf'], + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + + const changedAsset = { + id: 'xyz', + key: 'update-asset-key', + name: { + en: 'update asset name ', + }, + description: { + en: 'update description', + }, + sources: [ + { + uri: 'http://example.org/content/product-manual.xml', + contentType: 'application/xml', + }, + ], + tags: ['manual', 'xml'], + custom: { + type: { + typeId: 'type', + id: 'customType2', + }, + fields: { + customField1: false, + }, + }, + } + + const before = { + variants: [ + { + id: 1, + assets: [initialAsset], + }, + ], + } + const now = { + variants: [ + { + id: 1, + assets: [changedAsset], + }, + ], + } + const actual = productsSync.buildActions(now, before) + const expected = [ + { + action: 'setAssetKey', + assetKey: 'update-asset-key', + variantId: 1, + assetId: 'xyz', + }, + { + action: 'changeAssetName', + name: { en: 'update asset name ' }, + variantId: 1, + assetId: 'xyz', + }, + { + action: 'setAssetDescription', + description: { en: 'update description' }, + variantId: 1, + assetId: 'xyz', + }, + { + action: 'setAssetTags', + tags: ['manual', 'xml'], + variantId: 1, + assetId: 'xyz', + }, + { + action: 'setAssetSources', + sources: [ + { + uri: 'http://example.org/content/product-manual.xml', + contentType: 'application/xml', + }, + ], + variantId: 1, + assetId: 'xyz', + }, + { + action: 'setAssetCustomType', + variantId: 1, + assetId: 'xyz', + type: { typeId: 'type', id: 'customType2' }, + fields: { customField1: false }, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build "setAssetKey", "changeAssetName" and "setAssetCustomField" ', () => { + const initialAsset = { + id: 'xyz', + key: 'asset-key', + name: { + en: 'asset name ', + }, + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const changedAsset = { + id: 'xyz', + key: 'asset-key-two', + name: { + en: 'asset name change', + }, + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: false, + }, + }, + } + const before = { + variants: [ + { + id: 1, + assets: [initialAsset], + }, + ], + } + const now = { + variants: [ + { + id: 1, + assets: [changedAsset], + }, + ], + } + const actual = productsSync.buildActions(now, before) + const expected = [ + { + action: 'setAssetKey', + assetKey: 'asset-key-two', + variantId: 1, + assetId: 'xyz', + }, + { + action: 'changeAssetName', + name: { + en: 'asset name change', + }, + variantId: 1, + assetId: 'xyz', + }, + { + action: 'setAssetCustomField', + variantId: 1, + assetId: 'xyz', + name: 'customField1', + value: false, + }, + ] + expect(actual).toEqual(expected) + }) + + describe('changeAssetOrder', () => { + const makeAsset = (asset) => { + const base = { + sources: [ + { + uri: 'http://example.org/content/product-manual.xml', + contentType: 'application/xml', + }, + ], + } + return { + ...base, + ...asset, + } + } + + const makeVariant = (assets) => ({ + variants: [ + { + id: 1, + assets, + }, + ], + }) + + test('should build "changeAssetOrder" if assets are simply re-ordered', () => { + const assetOne = makeAsset({ id: 'asset-one' }) + const assetTwo = makeAsset({ id: 'asset-two' }) + const assetThree = makeAsset({ id: 'asset-three' }) + + const before = makeVariant([assetOne, assetTwo, assetThree]) + const now = makeVariant([assetTwo, assetThree, assetOne]) + const actual = productsSync.buildActions(now, before) + const expected = [ + { + action: 'changeAssetOrder', + assetOrder: [assetTwo.id, assetThree.id, assetOne.id], + variantId: 1, + }, + ] + expect(actual).toEqual(expected) + }) + + test('moves to be deleted assets to the end of the ordering', () => { + const assetOne = makeAsset({ id: 'asset-one' }) + const assetTwo = makeAsset({ id: 'asset-two' }) + const assetThree = makeAsset({ id: 'asset-three' }) + + const before = makeVariant([assetOne, assetTwo, assetThree]) + const now = makeVariant([assetTwo, assetOne]) + const actual = productsSync.buildActions(now, before)[0] + const expected = { + action: 'changeAssetOrder', + assetOrder: [assetTwo.id, assetOne.id, assetThree.id], + variantId: 1, + } + + expect(actual).toEqual(expected) + }) + + test('`changeAssetOrder` ignores newly added assets', () => { + const assetOne = makeAsset({ id: 'asset-one' }) + const assetTwo = makeAsset({ id: 'asset-two' }) + const assetThree = makeAsset({ id: 'asset-three' }) + + const before = makeVariant([assetOne, assetTwo]) + const now = makeVariant([assetThree, assetTwo, assetOne]) + const actual = productsSync.buildActions(now, before) + const expected = { + action: 'changeAssetOrder', + assetOrder: [assetTwo.id, assetOne.id], + variantId: 1, + } + + expect(actual[0]).toEqual(expected) + expect(actual[1]).toEqual({ + action: 'addAsset', + asset: assetThree, + variantId: 1, + position: 0, + }) + }) + }) + }) +}) diff --git a/packages/sync-actions/test/product-types-sync-attribute-hints.spec.ts b/packages/sync-actions/test/product-types-sync-attribute-hints.spec.ts new file mode 100644 index 000000000..687139baa --- /dev/null +++ b/packages/sync-actions/test/product-types-sync-attribute-hints.spec.ts @@ -0,0 +1,491 @@ +import createSyncProductTypes from '../src/product-types' + +const createAttributeDefinitionDraftItem = (custom?) => ({ + previous: { + type: { name: 'text' }, + name: 'attribute-name', + label: { en: 'attribute-label' }, + isRequired: false, + attributeConstraint: 'SameForAll', + inputTip: { en: 'input-hint' }, + inputHint: 'SingleLine', + isSearchable: false, + }, + next: { + type: { name: 'text' }, + name: 'attribute-name', + label: { en: 'attribute-label' }, + isRequired: false, + attributeConstraint: 'SameForAll', + inputTip: { en: 'input-hint' }, + inputHint: 'SingleLine', + isSearchable: false, + }, + ...custom, +}) + +const createAttributeEnumDraftItem = (custom?) => ({ + previous: { + key: 'enum-key', + label: 'enum-label', + }, + next: { + key: 'enum-key', + label: 'enum-label', + }, + hint: { + attributeName: 'attribute-name', + isLocalized: false, + }, + ...custom, +}) + +describe('product type hints', () => { + let updateActions + let sync + beforeEach(() => { + sync = createSyncProductTypes([]) + }) + describe('attribute enum values', () => { + let attributeEnumDraftItem + describe('with previous', () => { + describe('with no changes', () => { + beforeEach(() => { + attributeEnumDraftItem = createAttributeEnumDraftItem() + updateActions = sync.buildActions( + {}, + {}, + { + nestedValuesChanges: { + attributeEnumValues: [attributeEnumDraftItem], + }, + } + ) + }) + it('should not generate any update-actions', () => { + expect(updateActions).toEqual([]) + }) + }) + describe('with changes', () => { + describe('when is not localized', () => { + beforeEach(() => { + attributeEnumDraftItem = createAttributeEnumDraftItem({ + next: { + key: 'next-key', + label: 'next-label', + }, + }) + updateActions = sync.buildActions( + {}, + {}, + { + nestedValuesChanges: { + attributeEnumValues: [attributeEnumDraftItem], + }, + } + ) + }) + it('should match snapshot', () => { + expect(updateActions).toMatchSnapshot() + }) + it('should generate `changeEnumKey` update-action', () => { + expect(updateActions).toEqual( + expect.arrayContaining([ + { + action: 'changeEnumKey', + attributeName: attributeEnumDraftItem.hint.attributeName, + key: 'enum-key', + newKey: 'next-key', + }, + ]) + ) + }) + it('should generate `changePlainEnumLabel` update-action', () => { + expect(updateActions).toEqual( + expect.arrayContaining([ + { + action: 'changePlainEnumValueLabel', + attributeName: attributeEnumDraftItem.hint.attributeName, + newValue: attributeEnumDraftItem.next, + }, + ]) + ) + }) + }) + describe('when is localized', () => { + beforeEach(() => { + attributeEnumDraftItem = createAttributeEnumDraftItem({ + next: { + key: 'next-key', + label: 'next-label', + }, + hint: { + isLocalized: true, + attributeName: 'attribute-name', + }, + }) + updateActions = sync.buildActions( + {}, + {}, + { + nestedValuesChanges: { + attributeEnumValues: [attributeEnumDraftItem], + }, + } + ) + }) + it('should match snapshot', () => { + expect(updateActions).toMatchSnapshot() + }) + it('should generate `changeEnumKey` update-action', () => { + expect(updateActions).toEqual( + expect.arrayContaining([ + { + action: 'changeEnumKey', + attributeName: attributeEnumDraftItem.hint.attributeName, + key: 'enum-key', + newKey: 'next-key', + }, + ]) + ) + }) + it('should generate `changeLocalizedEnumValueLabel` update-action', () => { + expect(updateActions).toEqual( + expect.arrayContaining([ + { + action: 'changeLocalizedEnumValueLabel', + attributeName: attributeEnumDraftItem.hint.attributeName, + newValue: attributeEnumDraftItem.next, + }, + ]) + ) + }) + }) + + describe('when removing, adding, and editing (in a single batch of actions)', () => { + let attributeEnumDraftItemToBeRemoved1 + let attributeEnumDraftItemToBeRemoved2 + let attributeEnumDraftItemToBeChanged + let attributeEnumDraftItemToBeAdded + beforeEach(() => { + attributeEnumDraftItemToBeRemoved1 = createAttributeEnumDraftItem({ + previous: { key: 'enum-key-1', label: 'enum-label-1' }, + next: undefined, + hint: { + attributeName: 'attribute-enum-with-2-enum-values-to-remove', + isLocalized: false, + }, + }) + attributeEnumDraftItemToBeRemoved2 = createAttributeEnumDraftItem({ + previous: { key: 'enum-key-2', label: 'enum-label-2' }, + next: undefined, + hint: { + attributeName: 'attribute-enum-with-2-enum-values-to-remove', + isLocalized: false, + }, + }) + attributeEnumDraftItemToBeChanged = createAttributeEnumDraftItem({ + next: { + key: 'next-enum-draft-item', + label: undefined, + }, + }) + attributeEnumDraftItemToBeAdded = createAttributeEnumDraftItem({ + previous: undefined, + next: { + key: 'new-enum-draft-item', + label: 'new-enum-draft-item', + }, + }) + updateActions = sync.buildActions( + {}, + {}, + { + nestedValuesChanges: { + // we mess around with the order of changes among the hints... + // we should expect that sync-actions gives us a list of changes with the following order: + // [ updateActionsToRemoveEnumValues, updateActionsToUpdateEnumValues, updateActionsToAddEnumValues ] + // when two enumvalues has the same attribute-name, we should also expect that they are "grouped" into a single update action as well. + attributeEnumValues: [ + attributeEnumDraftItemToBeAdded, + attributeEnumDraftItemToBeRemoved1, + attributeEnumDraftItemToBeChanged, + attributeEnumDraftItemToBeRemoved2, + ], + }, + } + ) + }) + it('should match snapshot', () => { + expect(updateActions).toMatchSnapshot() + }) + it('should generate update-actions (with an explicit order)', () => { + expect(updateActions).toEqual([ + { + action: 'removeEnumValues', + attributeName: 'attribute-enum-with-2-enum-values-to-remove', + keys: ['enum-key-1', 'enum-key-2'], + }, + { + action: 'changeEnumKey', + attributeName: 'attribute-name', + key: 'enum-key', + newKey: 'next-enum-draft-item', + }, + { + action: 'changePlainEnumValueLabel', + attributeName: 'attribute-name', + newValue: { + key: 'next-enum-draft-item', + // this is a possibility on clients. we ought to rely on the API, to return an error + // ref: https://docs.commercetools.com/http-api-projects-productTypes.html#change-the-label-of-an-enumvalue + label: undefined, + }, + }, + { + action: 'addPlainEnumValue', + attributeName: 'attribute-name', + value: attributeEnumDraftItemToBeAdded.next, + }, + ]) + }) + }) + }) + }) + describe('without previous', () => { + beforeEach(() => { + attributeEnumDraftItem = createAttributeEnumDraftItem({ + previous: undefined, + }) + updateActions = sync.buildActions( + {}, + {}, + { + nestedValuesChanges: { + attributeEnumValues: [attributeEnumDraftItem], + }, + } + ) + }) + it('should match snapshot', () => { + expect(updateActions).toMatchSnapshot() + }) + it('should generate `addPlainEnumValue`', () => { + expect(updateActions).toEqual([ + { + action: 'addPlainEnumValue', + attributeName: attributeEnumDraftItem.hint.attributeName, + value: attributeEnumDraftItem.next, + }, + ]) + }) + describe('when is localized', () => { + beforeEach(() => { + attributeEnumDraftItem = createAttributeEnumDraftItem({ + previous: undefined, + hint: { + // this hint value is used as `attributeName` for enum update actions + attributeName: 'attribute-name', + isLocalized: true, + }, + }) + updateActions = sync.buildActions( + {}, + {}, + { + nestedValuesChanges: { + attributeEnumValues: [attributeEnumDraftItem], + }, + } + ) + }) + it('should match snapshot', () => { + expect(updateActions).toMatchSnapshot() + }) + it('should generate `addLocalizedEnumValue`', () => { + expect(updateActions).toEqual([ + { + action: 'addLocalizedEnumValue', + attributeName: attributeEnumDraftItem.hint.attributeName, + value: attributeEnumDraftItem.next, + }, + ]) + }) + }) + }) + }) + describe('attribute hints', () => { + let attributeDefinitionDraftItem + describe('with previous', () => { + describe('with next', () => { + describe('with no changes', () => { + beforeEach(() => { + attributeDefinitionDraftItem = createAttributeDefinitionDraftItem() + updateActions = sync.buildActions( + {}, + {}, + { + nestedValuesChanges: { + attributeDefinitions: [attributeDefinitionDraftItem], + }, + } + ) + }) + it('should match snapshot', () => { + expect(updateActions).toMatchSnapshot() + }) + it('should not generate any update-actions', () => { + expect(updateActions).toEqual([]) + }) + }) + describe('with changes', () => { + beforeEach(() => { + attributeDefinitionDraftItem = createAttributeDefinitionDraftItem({ + next: { + type: { name: 'boolean' }, + name: 'next-attribute-name', + label: { en: 'next-attribute-label' }, + attributeConstraint: 'None', + inputTip: { en: 'next-input-tip' }, + inputHint: 'MultiLine', + isSearchable: true, + }, + }) + updateActions = sync.buildActions( + {}, + {}, + { + nestedValuesChanges: { + attributeDefinitions: [attributeDefinitionDraftItem], + }, + } + ) + }) + it('should match snapshot', () => { + expect(updateActions).toMatchSnapshot() + }) + it('should not generate update action for `name`', () => { + // the API supports changeAttributeName for now, + // however this is not something we support in the node.js for the moment. + expect(updateActions).toEqual( + expect.not.arrayContaining([ + { + action: 'changeAttributeName', + }, + ]) + ) + }) + const changes: Array = [ + [ + 'label', + { + action: 'changeLabel', + attributeName: 'attribute-name', + label: { en: 'next-attribute-label' }, + }, + ], + [ + 'inputTip', + { + action: 'setInputTip', + attributeName: 'attribute-name', + inputTip: { + en: 'next-input-tip', + }, + }, + ], + [ + 'inputHint', + { + action: 'changeInputHint', + attributeName: 'attribute-name', + newValue: 'MultiLine', + }, + ], + [ + 'isSearchable', + { + action: 'changeIsSearchable', + attributeName: 'attribute-name', + isSearchable: true, + }, + ], + [ + 'attributeConstraint', + { + action: 'changeAttributeConstraint', + attributeName: 'attribute-name', + newValue: 'None', + }, + ], + ] + + it.each(changes)( + 'should generate update action for %s', + (name, expectedUpdateAction) => { + expect(updateActions).toEqual( + expect.arrayContaining([expectedUpdateAction]) + ) + } + ) + }) + }) + describe('without next', () => { + beforeEach(() => { + attributeDefinitionDraftItem = createAttributeDefinitionDraftItem({ + next: undefined, + }) + updateActions = sync.buildActions( + {}, + {}, + { + nestedValuesChanges: { + attributeDefinitions: [attributeDefinitionDraftItem], + }, + } + ) + }) + it('should match snapshot', () => { + expect(updateActions).toMatchSnapshot() + }) + it('should generate `removeAttributeDefinition` update-action', () => { + expect(updateActions).toEqual( + expect.arrayContaining([ + { + action: 'removeAttributeDefinition', + name: 'attribute-name', + }, + ]) + ) + }) + }) + }) + describe('without previous', () => { + beforeEach(() => { + attributeDefinitionDraftItem = createAttributeDefinitionDraftItem({ + previous: undefined, + }) + updateActions = sync.buildActions( + {}, + {}, + { + nestedValuesChanges: { + attributeDefinitions: [attributeDefinitionDraftItem], + }, + } + ) + }) + it('should match snapshot', () => { + expect(updateActions).toMatchSnapshot() + }) + it('should generate `addAttributeDefinition` update-action', () => { + expect(updateActions).toEqual([ + { + action: 'addAttributeDefinition', + attribute: attributeDefinitionDraftItem.next, + }, + ]) + }) + }) + }) +}) diff --git a/packages/sync-actions/test/product-types-sync-base.spec.ts b/packages/sync-actions/test/product-types-sync-base.spec.ts new file mode 100644 index 000000000..74d1b52fb --- /dev/null +++ b/packages/sync-actions/test/product-types-sync-base.spec.ts @@ -0,0 +1,360 @@ +import clone from '../src/utils/clone' +import createSyncProductTypes, { actionGroups } from '../src/product-types' +import { + baseActionsList, + generateBaseFieldsUpdateActions, +} from '../src/product-types-actions' + +describe('ProductTypes sync', () => { + test('action group list', () => { + expect(actionGroups).toEqual(['base']) + }) + + test('correctly define base actions list', () => { + expect(baseActionsList).toEqual([ + { action: 'changeName', key: 'name' }, + { action: 'setKey', key: 'key' }, + { action: 'changeDescription', key: 'description' }, + ]) + }) + test('correctly define attribute definitions actions list', () => {}) +}) + +describe('Actions', () => { + let productTypesSync + let updateActions + let before + let now + beforeEach(() => { + productTypesSync = createSyncProductTypes() + }) + describe('mutation', () => { + test('should ensure given objects are not mutated', () => { + before = { + name: 'Sneakers', + key: 'unique-key', + } + now = { + name: 'Sneakers', + key: 'unique-key-2', + } + const beforeClone = clone(before) + const nowClone = clone(now) + productTypesSync.buildActions(nowClone, beforeClone) + expect(before).toEqual(beforeClone) + expect(now).toEqual(nowClone) + }) + }) + describe('with name change', () => { + beforeEach(() => { + before = { + name: 'Sneakers', + } + now = { + name: 'Kicks', + } + updateActions = productTypesSync.buildActions(now, before) + }) + test('should return `changeName` update-action', () => { + expect(updateActions).toEqual([ + { + action: 'changeName', + name: 'Kicks', + }, + ]) + }) + }) + describe('with key change', () => { + beforeEach(() => { + before = { + key: 'sneakers-key', + } + now = { + key: 'kicks-key', + } + updateActions = productTypesSync.buildActions(now, before) + }) + test('should return `setKey` update-action', () => { + expect(updateActions).toEqual([ + { + action: 'setKey', + key: 'kicks-key', + }, + ]) + }) + }) + describe('with description change', () => { + beforeEach(() => { + before = { + description: 'sneakers-description', + } + now = { + description: 'kicks-description', + } + updateActions = productTypesSync.buildActions(now, before) + }) + test('should return `changeKey` update-action', () => { + expect(updateActions).toEqual([ + { + action: 'changeDescription', + description: 'kicks-description', + }, + ]) + }) + }) + describe('with attribute order change', () => { + beforeEach(() => { + productTypesSync = createSyncProductTypes(undefined, { + shouldOmitEmptyString: false, + withHints: true, + }) + }) + + test('should not generate changeOrder action when the order did not change', () => { + before = { + name: 'Product Type', + attributes: [ + { name: 'attr1' }, + { name: 'attr2' }, // removed + ], + } + now = { + name: 'Product Type', + attributes: [{ name: 'attr1' }], + } + + updateActions = productTypesSync.buildActions(now, before, { + nestedValuesChanges: { + attributeDefinitions: [ + { + previous: { + name: 'attr2', + }, + }, + ], + }, + }) + + expect(updateActions).toEqual([ + { + action: 'removeAttributeDefinition', + name: 'attr2', + }, + ]) + }) + + test('should not generate changeOrder action when removing all attributes', () => { + before = { + name: 'Product Type', + attributes: [ + { name: 'attr1' }, // removed + ], + } + now = { + name: 'Product Type', + } + + updateActions = productTypesSync.buildActions(now, before, { + nestedValuesChanges: { + attributeDefinitions: [ + { + previous: { + name: 'attr1', + }, + }, + ], + }, + }) + + expect(updateActions).toEqual([ + { + action: 'removeAttributeDefinition', + name: 'attr1', + }, + ]) + }) + + test('should not generate changeOrder action when adding first attributes', () => { + before = { + name: 'Product Type', + } + now = { + name: 'Product Type', + attributes: [ + { name: 'attr1' }, // added + ], + } + + updateActions = productTypesSync.buildActions(now, before, { + nestedValuesChanges: { + attributeDefinitions: [ + { + next: { + name: 'attr1', + }, + }, + ], + }, + }) + + expect(updateActions).toEqual([ + { + action: 'addAttributeDefinition', + attribute: { + name: 'attr1', + }, + }, + ]) + }) + + test('should return `changeAttributeOrderByName` update-action', () => { + before = { + name: 'Product Type', + attributes: [{ name: 'color' }, { name: 'material' }], + } + now = { + name: 'Product Type', + attributes: [{ name: 'material' }, { name: 'color' }], + } + + updateActions = productTypesSync.buildActions(now, before) + expect(updateActions).toEqual([ + { + action: 'changeAttributeOrderByName', + attributeNames: ['material', 'color'], + }, + ]) + }) + + test('should remove, add and change order of attributes', () => { + before = { + name: 'Product Type', + attributes: [ + { name: 'attr1' }, + { name: 'attr2' }, // removed + { name: 'attr3' }, + ], + } + now = { + name: 'Product Type', + attributes: [ + { name: 'attr3' }, + { name: 'attr4' }, // added + { name: 'attr1' }, + ], + } + + updateActions = productTypesSync.buildActions(now, before, { + nestedValuesChanges: { + attributeDefinitions: [ + { + previous: { + name: 'attr2', + }, + }, + { + next: { + name: 'attr4', + }, + }, + ], + }, + }) + + expect(updateActions).toEqual([ + { + action: 'removeAttributeDefinition', + name: 'attr2', + }, + { + action: 'addAttributeDefinition', + attribute: { + name: 'attr4', + }, + }, + { + action: 'changeAttributeOrderByName', + attributeNames: ['attr3', 'attr4', 'attr1'], + }, + ]) + }) + }) +}) + +describe('generateBaseFieldsUpdateActions', () => { + let previous + let next + let updateActions + const field = 'name' + const actionDefinition = { + [field]: { action: 'changeName' }, + } + describe('with change', () => { + beforeEach(() => { + previous = { [field]: 'previous' } + next = { [field]: 'next' } + updateActions = generateBaseFieldsUpdateActions( + previous, + next, + actionDefinition + ) + }) + it('should generate `changeName` update action', () => { + expect(updateActions).toEqual([ + { + action: 'changeName', + [field]: next[field], + }, + ]) + }) + describe('with previous and empty `next`', () => { + const cases = [ + [null, { action: 'changeName' }], + [undefined, { action: 'changeName' }], + ['', { action: 'changeName' }], + ] + it.each(cases)( + 'should generate `changeName` for %s update action with omitted field indicating removing value', + (nextValue, updateActionWithMissingValue) => { + next = { [field]: nextValue } + updateActions = generateBaseFieldsUpdateActions( + previous, + next, + actionDefinition + ) + expect(updateActions).toEqual([updateActionWithMissingValue]) + } + ) + }) + }) + describe('without change', () => { + describe('with value on `previous` and `next`', () => { + beforeEach(() => { + previous = { [field]: 'foo' } + next = { [field]: 'foo' } + updateActions = generateBaseFieldsUpdateActions( + previous, + next, + actionDefinition + ) + }) + it('should not generate `changeName` update action', () => { + expect(updateActions).toEqual([]) + }) + }) + describe('without value on `previous` and `next`', () => { + beforeEach(() => { + previous = { [field]: '' } + next = { [field]: '' } + updateActions = generateBaseFieldsUpdateActions( + previous, + next, + actionDefinition + ) + }) + it('should not generate `changeName` update action', () => { + expect(updateActions).toEqual([]) + }) + }) + }) +}) diff --git a/packages/sync-actions/test/projects-sync.spec.ts b/packages/sync-actions/test/projects-sync.spec.ts new file mode 100644 index 000000000..8c27d4785 --- /dev/null +++ b/packages/sync-actions/test/projects-sync.spec.ts @@ -0,0 +1,215 @@ +import createProjectsSync, { actionGroups } from '../src/projects' +import { baseActionsList } from '../src/projects-actions' + +describe('Exports', () => { + test('action group list', () => { + expect(actionGroups).toEqual(['base']) + }) + + describe('action list', () => { + test('should contain `changeName` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'changeName', key: 'name' }]) + ) + }) + + test('should contain `changeCurrencies` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { action: 'changeCurrencies', key: 'currencies' }, + ]) + ) + }) + + test('should contain `changeCountries` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'changeCountries', + key: 'countries', + }, + ]) + ) + }) + + test('should contain `changeLanguages` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'changeLanguages', + key: 'languages', + }, + ]) + ) + }) + + test('should contain `changeMessagesConfiguration` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'changeMessagesConfiguration', + key: 'messagesConfiguration', + }, + ]) + ) + }) + + test('should contain `setShippingRateInputType` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'setShippingRateInputType', + key: 'shippingRateInputType', + }, + ]) + ) + }) + }) +}) + +describe('Actions', () => { + let projectsSync + beforeEach(() => { + projectsSync = createProjectsSync() + }) + + test('should build `changeName` action', () => { + const before = { name: 'nameBefore' } + const now = { name: 'nameAfter' } + const actual = projectsSync.buildActions(now, before) + const expected = [ + { + action: 'changeName', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `changeCurrencies` action', () => { + const before = { currencies: ['EUR', 'Dollar'] } + const now = { currencies: ['EUR'] } + const actual = projectsSync.buildActions(now, before) + const expected = [ + { + action: 'changeCurrencies', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `changeCountries` action', () => { + const before = { countries: ['Germany', 'Spain'] } + const now = { countries: ['Germany'] } + const actual = projectsSync.buildActions(now, before) + const expected = [ + { + action: 'changeCountries', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `changeLanguages` action', () => { + const before = { languages: ['German', 'Dutch'] } + const now = { languages: ['Dutch'] } + const actual = projectsSync.buildActions(now, before) + const expected = [ + { + action: 'changeLanguages', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + + describe('setShippingRateInputType', () => { + describe('given `shippingRateInputType` is of type `CartClassification`', () => { + const before = { + shippingRateInputType: { + type: 'CartClassification', + values: [ + { key: 'Small', label: { en: 'Small', de: 'Klein' } }, + { key: 'Medium', label: { en: 'Medium', de: 'Mittel' } }, + { key: 'Heavy', label: { en: 'Heavy', de: 'Schwergut' } }, + ], + }, + } + describe('given a value of `values` changes', () => { + const now = { + shippingRateInputType: { + type: 'CartClassification', + values: [ + { key: 'Small', label: { en: 'Small', de: 'Klein' } }, + { key: 'Medium', label: { en: 'Medium', de: 'Mittel' } }, + { key: 'Big', label: { en: 'Big', de: 'Groß' } }, + ], + }, + } + + test('should build `setShippingRateInputType` action', () => { + const actual = projectsSync.buildActions(now, before) + const expected = [ + { + action: 'setShippingRateInputType', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + }) + describe('given type changes to `CartValue`', () => { + let now = { + shippingRateInputType: { + type: 'CartValue', + }, + } + + test('should build `setShippingRateInputType` action', () => { + const actual = projectsSync.buildActions(now, before) + const expected = [ + { + action: 'setShippingRateInputType', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + + describe('given type changes to `CartScore`', () => { + now = { + shippingRateInputType: { + type: 'CartScore', + }, + } + + test('should build `setShippingRateInputType` action', () => { + const actual = projectsSync.buildActions(now, before) + const expected = [ + { + action: 'setShippingRateInputType', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + }) + }) + }) + }) + + test('should build `changeMessagesConfiguration` action', () => { + const before = { messagesConfiguration: { type: 'some-config' } } + const now = { messagesConfiguration: { type: 'some-other-config' } } + const actual = projectsSync.buildActions(now, before) + const expected = [ + { + action: 'changeMessagesConfiguration', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) +}) diff --git a/packages/sync-actions/test/quote-requests-sync.spec.ts b/packages/sync-actions/test/quote-requests-sync.spec.ts new file mode 100644 index 000000000..1375db167 --- /dev/null +++ b/packages/sync-actions/test/quote-requests-sync.spec.ts @@ -0,0 +1,129 @@ +import createQuoteRequestsSync, { actionGroups } from '../src/quote-requests' +import { baseActionsList } from '../src/quote-requests-actions' + +describe('Exports', () => { + test('action group list', () => { + expect(actionGroups).toEqual(['base', 'custom']) + }) + + describe('action list', () => { + test('should contain `changeQuoteRequestState` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { action: 'changeQuoteRequestState', key: 'quoteRequestState' }, + ]) + ) + }) + + test('should contain `transitionState` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'transitionState', key: 'state' }]) + ) + }) + }) +}) + +describe('Actions', () => { + let quoteRequestsSync + beforeEach(() => { + quoteRequestsSync = createQuoteRequestsSync() + }) + + test('should build `changeQuoteRequestState` action', () => { + const before = { quoteRequestState: 'Submitted' } + const now = { quoteRequestState: 'Accepted' } + const actual = quoteRequestsSync.buildActions(now, before) + const expected = [ + { + action: 'changeQuoteRequestState', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `transitionState` action', () => { + const before = { + state: { + typeId: 'state', + id: 'sid1', + }, + } + const now = { + state: { + typeId: 'state', + id: 'sid2', + }, + } + const actual = quoteRequestsSync.buildActions(now, before) + const expected = [ + { + action: 'transitionState', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setCustomType` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType2', + }, + fields: { + customField1: true, + }, + }, + } + const actual = quoteRequestsSync.buildActions(now, before) + const expected = [{ action: 'setCustomType', ...now.custom }] + expect(actual).toEqual(expected) + }) + + test('should build `setCustomField` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: false, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const actual = quoteRequestsSync.buildActions(now, before) + const expected = [ + { + action: 'setCustomField', + name: 'customField1', + value: true, + }, + ] + expect(actual).toEqual(expected) + }) +}) diff --git a/packages/sync-actions/test/quotes-sync.spec.ts b/packages/sync-actions/test/quotes-sync.spec.ts new file mode 100644 index 000000000..6862269ff --- /dev/null +++ b/packages/sync-actions/test/quotes-sync.spec.ts @@ -0,0 +1,150 @@ +import createQuotesSync, { actionGroups } from '../src/quotes' +import { baseActionsList } from '../src/quotes-actions' + +describe('Exports', () => { + test('action group list', () => { + expect(actionGroups).toEqual(['base', 'custom']) + }) + + describe('action list', () => { + test('should contain `changeQuoteState` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { action: 'changeQuoteState', key: 'quoteState' }, + ]) + ) + }) + + test('should contain `requestQuoteRenegotiation` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { action: 'requestQuoteRenegotiation', key: 'buyerComment' }, + ]) + ) + }) + + test('should contain `transitionState` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'transitionState', key: 'state' }]) + ) + }) + }) +}) + +describe('Actions', () => { + let quotesSync + beforeEach(() => { + quotesSync = createQuotesSync() + }) + + test('should build `changeQuoteState` action', () => { + const before = { quoteState: 'Pending' } + const now = { quoteState: 'Approved' } + const actual = quotesSync.buildActions(now, before) + const expected = [ + { + action: 'changeQuoteState', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `requestQuoteRenegotiation` action', () => { + const before = { buyerComment: '' } + const now = { buyerComment: 'give me a 10% discount' } + const actual = quotesSync.buildActions(now, before) + const expected = [ + { + action: 'requestQuoteRenegotiation', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `transitionState` action', () => { + const before = { + state: { + typeId: 'state', + id: 'sid1', + }, + } + const now = { + state: { + typeId: 'state', + id: 'sid2', + }, + } + const actual = quotesSync.buildActions(now, before) + const expected = [ + { + action: 'transitionState', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setCustomType` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType2', + }, + fields: { + customField1: true, + }, + }, + } + const actual = quotesSync.buildActions(now, before) + const expected = [{ action: 'setCustomType', ...now.custom }] + expect(actual).toEqual(expected) + }) + + test('should build `setCustomField` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: false, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const actual = quotesSync.buildActions(now, before) + const expected = [ + { + action: 'setCustomField', + name: 'customField1', + value: true, + }, + ] + expect(actual).toEqual(expected) + }) +}) diff --git a/packages/sync-actions/test/shipping-methods.spec.ts b/packages/sync-actions/test/shipping-methods.spec.ts new file mode 100644 index 000000000..cb8a81b2c --- /dev/null +++ b/packages/sync-actions/test/shipping-methods.spec.ts @@ -0,0 +1,642 @@ +import shippingMethodsSyncFn, { actionGroups } from '../src/shipping-methods' +import { baseActionsList } from '../src/shipping-methods-actions' + +describe('Exports', () => { + test('action group list', () => { + expect(actionGroups).toEqual(['base', 'zoneRates', 'custom']) + }) + + test('correctly define base actions list', () => { + expect(baseActionsList).toEqual([ + { action: 'setKey', key: 'key' }, + { action: 'changeName', key: 'name' }, + { action: 'setLocalizedName', key: 'localizedName' }, + { action: 'setDescription', key: 'description' }, + { action: 'setLocalizedDescription', key: 'localizedDescription' }, + { action: 'changeIsDefault', key: 'isDefault' }, + { action: 'setPredicate', key: 'predicate' }, + { action: 'changeTaxCategory', key: 'taxCategory' }, + ]) + }) +}) + +describe('Actions', () => { + let shippingMethodsSync + beforeEach(() => { + shippingMethodsSync = shippingMethodsSyncFn() + }) + + describe('base', () => { + test('should build `setKey` action', () => { + const before = { + key: 'Key 1', + } + const now = { + key: 'Key 2', + } + + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [{ action: 'setKey', key: now.key }] + expect(actual).toEqual(expected) + }) + + test('should build `changeName` action', () => { + const before = { + name: 'Shipping Method 1', + } + const now = { + name: 'Shipping Method 2', + } + + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [ + { + action: 'changeName', + name: now.name, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setLocalizedName` action', () => { + const before = { + localizedName: { + en: 'Shipping Method 1', + }, + } + const now = { + localizedName: { + fr: 'Méthode de expédition 1', + en: 'Shipping Method 1', + }, + } + + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [ + { + action: 'setLocalizedName', + localizedName: now.localizedName, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setLocalizedName` action with an empty localizedName', () => { + const before = { + localizedName: { + en: 'Shipping Method 1', + }, + } + const now = { + localizedName: undefined, + } + + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [ + { + action: 'setLocalizedName', + localizedName: now.localizedName, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setDescription` action', () => { + const before = { + description: 'Custom description', + } + const now = { + description: 'Another description', + } + + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [ + { + action: 'setDescription', + description: now.description, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setLocalizedDescription` action', () => { + const before = { + localizedDescription: { + en: 'Custom description', + }, + } + const now = { + localizedDescription: { + fr: 'Description personnalisée', + en: 'Custom description', + }, + } + + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [ + { + action: 'setLocalizedDescription', + localizedDescription: now.localizedDescription, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `changeIsDefault` action', () => { + const before = { + isDefault: true, + } + const now = { + isDefault: false, + } + + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [ + { + action: 'changeIsDefault', + isDefault: now.isDefault, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setPredicate` action', () => { + const before = { + predicate: 'id is defined', + } + const now = { + predicate: 'id is not defined', + } + + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [ + { + action: 'setPredicate', + predicate: now.predicate, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `changeTaxCategory` action', () => { + const before = { taxCategory: { typeId: 'taxCategory', id: 'id1' } } + const now = { taxCategory: { typeId: 'taxCategory', id: 'id2' } } + + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [ + { action: 'changeTaxCategory', taxCategory: now.taxCategory }, + ] + expect(actual).toEqual(expected) + }) + }) + + describe('`addZone`', () => { + test('should build `addZone` action with one zone', () => { + const before = { + zoneRates: [{ zone: { typeId: 'zone', id: 'z1' } }], + } + const now = { + zoneRates: [ + { zone: { typeId: 'zone', id: 'z1' } }, + { zone: { typeId: 'zone', id: 'z2' } }, + ], + } + + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [{ action: 'addZone', zone: now.zoneRates[1].zone }] + expect(actual).toEqual(expected) + }) + + test('should build `addZone` action with multiple zones', () => { + const before = { + zoneRates: [{ zone: { typeId: 'zone', id: 'z1' } }], + } + const now = { + zoneRates: [ + { zone: { typeId: 'zone', id: 'z1' } }, + { zone: { typeId: 'zone', id: 'z3' } }, + { zone: { typeId: 'zone', id: 'z4' } }, + { zone: { typeId: 'zone', id: 'z5' } }, + ], + } + + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [ + { action: 'addZone', zone: now.zoneRates[1].zone }, + { action: 'addZone', zone: now.zoneRates[2].zone }, + { action: 'addZone', zone: now.zoneRates[3].zone }, + ] + expect(actual).toEqual(expected) + }) + }) + + describe('`removeZone`', () => { + test('should build `removeZone` removing the last zone item', () => { + const before = { + zoneRates: [ + { zone: { typeId: 'zone', id: 'z1' } }, + { zone: { typeId: 'zone', id: 'z2' } }, + ], + } + const now = { + zoneRates: [{ zone: { typeId: 'zone', id: 'z1' } }], + } + + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [ + { action: 'removeZone', zone: before.zoneRates[1].zone }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `removeZone` removing all existing zones', () => { + const before = { + zoneRates: [ + { zone: { typeId: 'zone', id: 'z1' } }, + { zone: { typeId: 'zone', id: 'z2' } }, + { zone: { typeId: 'zone', id: 'z3' } }, + ], + } + const now = { + zoneRates: [], + } + + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [ + { action: 'removeZone', zone: before.zoneRates[0].zone }, + { action: 'removeZone', zone: before.zoneRates[1].zone }, + { action: 'removeZone', zone: before.zoneRates[2].zone }, + ] + expect(actual).toEqual(expected) + }) + }) + + describe('`addShippingRate`', () => { + test('should build `addShippingRate` action with one shipping rate', () => { + const before = { + zoneRates: [ + { + zone: { typeId: 'zone', id: 'z1' }, + shippingRates: [], + }, + ], + } + const now = { + zoneRates: [ + { + zone: { typeId: 'zone', id: 'z1' }, + shippingRates: [ + { price: { centAmount: 1000, currencyCode: 'EUR' } }, + ], + }, + ], + } + + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [ + { + action: 'addShippingRate', + zone: before.zoneRates[0].zone, + shippingRate: now.zoneRates[0].shippingRates[0], + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `addShippingRate` action with multiple shipping rate', () => { + const before = { + zoneRates: [{ zone: { typeId: 'zone', id: 'z1' }, shippingRates: [] }], + } + const now = { + zoneRates: [ + { + zone: { typeId: 'zone', id: 'z1' }, + shippingRates: [ + { price: { centAmount: 1000, currencyCode: 'EUR' } }, + { price: { centAmount: 1000, currencyCode: 'USD' } }, + ], + }, + ], + } + + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [ + { + action: 'addShippingRate', + zone: before.zoneRates[0].zone, + shippingRate: now.zoneRates[0].shippingRates[0], + }, + { + action: 'addShippingRate', + zone: before.zoneRates[0].zone, + shippingRate: now.zoneRates[0].shippingRates[1], + }, + ] + + expect(actual).toEqual(expected) + }) + }) + + describe('`removeShippingRate`', () => { + test('should build `removeShippingRate` removing one shippingRate', () => { + const before = { + zoneRates: [ + { + zone: { typeId: 'zone', id: 'z1' }, + shippingRates: [ + { price: { centAmount: 1000, currencyCode: 'EUR' } }, + { price: { centAmount: 3000, currencyCode: 'USD' } }, + ], + }, + ], + } + const now = { + zoneRates: [ + { + zone: { typeId: 'zone', id: 'z1' }, + shippingRates: [ + { price: { centAmount: 1000, currencyCode: 'EUR' } }, + ], + }, + ], + } + + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [ + { + action: 'removeShippingRate', + zone: before.zoneRates[0].zone, + shippingRate: before.zoneRates[0].shippingRates[1], + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `removeShippingRate` removing all existing zones', () => { + const before = { + zoneRates: [ + { + zone: { typeId: 'zone', id: 'z1' }, + shippingRates: [ + { price: { centAmount: 1000, currencyCode: 'EUR' } }, + { price: { centAmount: 3000, currencyCode: 'USD' } }, + ], + }, + ], + } + const now = { + zoneRates: [ + { + zone: { typeId: 'zone', id: 'z1' }, + shippingRates: [], + }, + ], + } + + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [ + { + action: 'removeShippingRate', + zone: before.zoneRates[0].zone, + shippingRate: before.zoneRates[0].shippingRates[0], + }, + { + action: 'removeShippingRate', + zone: before.zoneRates[0].zone, + shippingRate: before.zoneRates[0].shippingRates[1], + }, + ] + expect(actual).toEqual(expected) + }) + }) + + describe('Swap zones (create one + delete one)', () => { + test('should build `removeZone` and `addZone` when swaping zones', () => { + const before = { + zoneRates: [ + { zone: { typeId: 'zone', id: 'z1' } }, + { zone: { typeId: 'zone', id: 'z2' } }, + { zone: { typeId: 'zone', id: 'z3' } }, + ], + } + const now = { + zoneRates: [ + { zone: { typeId: 'zone', id: 'z4' } }, + { zone: { typeId: 'zone', id: 'z5' } }, + { zone: { typeId: 'zone', id: 'z6' } }, + ], + } + + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [ + { action: 'removeZone', zone: before.zoneRates[0].zone }, + { action: 'addZone', zone: now.zoneRates[0].zone }, + { action: 'removeZone', zone: before.zoneRates[1].zone }, + { action: 'addZone', zone: now.zoneRates[1].zone }, + { action: 'removeZone', zone: before.zoneRates[2].zone }, + { action: 'addZone', zone: now.zoneRates[2].zone }, + ] + expect(actual).toEqual(expected) + }) + }) + + describe('Swap shippingRates (create one + delete one)', () => { + test('should build `removeShippingRate` and `addShippingRate` when swaping zones', () => { + const before = { + zoneRates: [ + { + zone: { typeId: 'zone', id: 'z1' }, + shippingRates: [ + { price: { currencyCode: 'EUR', centAmount: 1000 } }, + { price: { currencyCode: 'USD', centAmount: 1000 } }, + ], + }, + ], + } + const now = { + zoneRates: [ + { + zone: { typeId: 'zone', id: 'z1' }, + shippingRates: [ + { price: { currencyCode: 'EUR', centAmount: 1000 } }, + { price: { currencyCode: 'USD', centAmount: 3000 } }, + ], + }, + ], + } + + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [ + { + action: 'removeShippingRate', + shippingRate: before.zoneRates[0].shippingRates[1], + zone: before.zoneRates[0].zone, + }, + { + action: 'addShippingRate', + shippingRate: now.zoneRates[0].shippingRates[1], + zone: before.zoneRates[0].zone, + }, + ] + expect(actual).toEqual(expected) + }) + }) + + describe('Multiple actions between zones and shippingRates', () => { + test('should build different actions for updating zones and shippingRates', () => { + const before = { + zoneRates: [ + { + zone: { typeId: 'zone', id: 'z1' }, + shippingRates: [ + { price: { currencyCode: 'EUR', centAmount: 1000 } }, + { price: { currencyCode: 'USD', centAmount: 1000 } }, + ], + }, + ], + } + const now = { + zoneRates: [ + { + zone: { typeId: 'zone', id: 'z1' }, + shippingRates: [], + }, + { + zone: { typeId: 'zone', id: 'z2' }, + shippingRates: [], + }, + ], + } + + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [ + { + action: 'removeShippingRate', + shippingRate: before.zoneRates[0].shippingRates[0], + zone: before.zoneRates[0].zone, + }, + { + action: 'removeShippingRate', + shippingRate: before.zoneRates[0].shippingRates[1], + zone: before.zoneRates[0].zone, + }, + { action: 'addZone', zone: now.zoneRates[1].zone }, + ] + expect(actual).toEqual(expected) + }) + }) + + describe('When adding a new zoneRate with zone and shippingRates (fixed rates)', () => { + it('should build different actions for adding zone and shippingRates', () => { + const before = { + zoneRates: [ + { + zone: { typeId: 'zone', id: 'z1' }, + shippingRates: [ + { price: { currencyCode: 'EUR', centAmount: 1000 } }, + { price: { currencyCode: 'USD', centAmount: 1000 } }, + ], + }, + ], + } + const now = { + zoneRates: [ + { + zone: { typeId: 'zone', id: 'z1' }, + shippingRates: [ + { price: { currencyCode: 'EUR', centAmount: 1000 } }, + { price: { currencyCode: 'USD', centAmount: 1000 } }, + ], + }, + { + zone: { typeId: 'zone 2', id: 'z2' }, + shippingRates: [ + { price: { currencyCode: 'EUR', centAmount: 1000 } }, + { price: { currencyCode: 'USD', centAmount: 1000 } }, + ], + }, + ], + } + + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [ + { action: 'addZone', zone: now.zoneRates[1].zone }, + { + action: 'addShippingRate', + shippingRate: now.zoneRates[1].shippingRates[0], + zone: now.zoneRates[1].zone, + }, + { + action: 'addShippingRate', + shippingRate: now.zoneRates[1].shippingRates[1], + zone: now.zoneRates[1].zone, + }, + ] + expect(actual).toEqual(expected) + }) + }) + + describe('custom fields', () => { + test('should build `setCustomType` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType2', + }, + fields: { + customField1: true, + }, + }, + } + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [{ action: 'setCustomType', ...now.custom }] + expect(actual).toEqual(expected) + }) + + test('should build `setCustomField` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: false, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [ + { + action: 'setCustomField', + name: 'customField1', + value: true, + }, + ] + expect(actual).toEqual(expected) + }) + }) +}) diff --git a/packages/sync-actions/test/staged-quotes-sync.spec.ts b/packages/sync-actions/test/staged-quotes-sync.spec.ts new file mode 100644 index 000000000..503890044 --- /dev/null +++ b/packages/sync-actions/test/staged-quotes-sync.spec.ts @@ -0,0 +1,171 @@ +import createStagedQuotesSync, { actionGroups } from '../src/staged-quotes' +import { baseActionsList } from '../src/staged-quotes-actions' + +describe('Exports', () => { + test('action group list', () => { + expect(actionGroups).toEqual(['base', 'custom']) + }) + + describe('action list', () => { + test('should contain `changeStagedQuoteState` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { action: 'changeStagedQuoteState', key: 'stagedQuoteState' }, + ]) + ) + }) + + test('should contain `setSellerComment` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { action: 'setSellerComment', key: 'sellerComment' }, + ]) + ) + }) + + test('should contain `setValidTo` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'setValidTo', key: 'validTo' }]) + ) + }) + + test('should contain `transitionState` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'transitionState', key: 'state' }]) + ) + }) + }) +}) + +describe('Actions', () => { + let stagedQuotesSync + beforeEach(() => { + stagedQuotesSync = createStagedQuotesSync() + }) + + test('should build `changeQuoteState` action', () => { + const before = { stagedQuoteState: 'InProgress' } + const now = { stagedQuoteState: 'Sent' } + const actual = stagedQuotesSync.buildActions(now, before) + const expected = [ + { + action: 'changeStagedQuoteState', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setSellerComment` action', () => { + const before = { sellerComment: '' } + const now = { + sellerComment: 'let me know if this matches your expectations', + } + const actual = stagedQuotesSync.buildActions(now, before) + const expected = [ + { + action: 'setSellerComment', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setValidTo` action', () => { + const before = { validTo: '' } + const now = { validTo: '2022-09-22T15:41:55.816Z' } + const actual = stagedQuotesSync.buildActions(now, before) + const expected = [ + { + action: 'setValidTo', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `transitionState` action', () => { + const before = { + state: { + typeId: 'state', + id: 'sid1', + }, + } + const now = { + state: { + typeId: 'state', + id: 'sid2', + }, + } + const actual = stagedQuotesSync.buildActions(now, before) + const expected = [ + { + action: 'transitionState', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setCustomType` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType2', + }, + fields: { + customField1: true, + }, + }, + } + const actual = stagedQuotesSync.buildActions(now, before) + const expected = [{ action: 'setCustomType', ...now.custom }] + expect(actual).toEqual(expected) + }) + + test('should build `setCustomField` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: false, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const actual = stagedQuotesSync.buildActions(now, before) + const expected = [ + { + action: 'setCustomField', + name: 'customField1', + value: true, + }, + ] + expect(actual).toEqual(expected) + }) +}) diff --git a/packages/sync-actions/test/states-sync.spec.ts b/packages/sync-actions/test/states-sync.spec.ts new file mode 100644 index 000000000..46f84fe34 --- /dev/null +++ b/packages/sync-actions/test/states-sync.spec.ts @@ -0,0 +1,258 @@ +import statesSyncFn, { actionGroups } from '../src/states' +import { baseActionsList } from '../src/state-actions' + +describe('Exports', () => { + test('action group list', () => { + expect(actionGroups).toEqual(['base']) + }) + + describe('action list', () => { + test('should contain `changeIsActive` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'changeKey', key: 'key' }]) + ) + }) + + test('should contain `setName` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([{ action: 'setName', key: 'name' }]) + ) + }) + + test('should contain `setDescription` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'setDescription', + key: 'description', + }, + ]) + ) + }) + + test('should contain `changeType` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'changeType', + key: 'type', + }, + ]) + ) + }) + + test('should contain `changeInitial` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'changeInitial', + key: 'initial', + }, + ]) + ) + }) + + test('should contain `setTransitions` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'setTransitions', + key: 'transitions', + }, + ]) + ) + }) + }) +}) + +describe('Actions', () => { + let statesSync + beforeEach(() => { + statesSync = statesSyncFn() + }) + + test('should build `setName` action', () => { + const before = { + name: { en: 'previous-en-name', de: 'previous-de-name' }, + } + const now = { + name: { en: 'current-en-name', de: 'current-de-name' }, + } + + const actual = statesSync.buildActions(now, before) + const expected = [ + { + action: 'setName', + name: { en: 'current-en-name', de: 'current-de-name' }, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setDescription` action', () => { + const before = { + description: { en: 'old-en-description', de: 'old-de-description' }, + } + const now = { + description: { en: 'new-en-description', de: 'new-de-description' }, + } + + const actual = statesSync.buildActions(now, before) + const expected = [ + { + action: 'setDescription', + description: { en: 'new-en-description', de: 'new-de-description' }, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `changeKey` action', () => { + const before = { key: 'oldKey' } + const now = { key: 'newKey' } + const actual = statesSync.buildActions(now, before) + const expected = [ + { + action: 'changeKey', + key: 'newKey', + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `changeType` action', () => { + const before = { key: 'state-1', type: 'ReviewState' } + const now = { key: 'state-1', type: 'ProductState' } + const actual = statesSync.buildActions(now, before) + const expected = [ + { + action: 'changeType', + type: 'ProductState', + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `changeInitial` action', () => { + const before = { key: 'state-1', initial: true } + const now = { key: 'state-1', initial: false } + const actual = statesSync.buildActions(now, before) + const expected = [ + { + action: 'changeInitial', + initial: false, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setTransitions` action', () => { + const before = { + key: 'state-1', + transitions: [ + { + typeId: 'state', + id: 'old-state-1', + }, + { + typeId: 'state', + id: 'old-state-2', + }, + ], + } + const now = { + key: 'state-1', + transitions: [ + { + typeId: 'state', + id: 'new-state-1', + }, + { + typeId: 'state', + id: 'new-state-2', + }, + ], + } + const actual = statesSync.buildActions(now, before) + const expected = [ + { + action: 'setTransitions', + transitions: [ + { + typeId: 'state', + id: 'new-state-1', + }, + { + typeId: 'state', + id: 'new-state-2', + }, + ], + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `addRoles` action', () => { + const before = { + key: 'state-1', + roles: ['ReviewIncludedInStatistics'], + } + const now = { + key: 'state-1', + roles: ['Return', 'Another', 'ReviewIncludedInStatistics'], + } + const actual = statesSync.buildActions(now, before) + const expected = [ + { + action: 'addRoles', + roles: ['Return', 'Another'], + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `removeRoles` action', () => { + const before = { + key: 'state-1', + roles: ['Return', 'Another', 'ReviewIncludedInStatistics'], + } + const now = { + key: 'state-1', + roles: ['ReviewIncludedInStatistics'], + } + const actual = statesSync.buildActions(now, before) + const expected = [ + { + action: 'removeRoles', + roles: ['Return', 'Another'], + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build the `removeRoles` and `addRoles` actions', () => { + // This is necessary because there is currently no way to differentiate + // between `setRoles` action and `addRoles || removeRoles` actions so we + // simply replace the roles that need to be replaced with add and remove + const before = { + key: 'state-1', + roles: ['Return', 'Another', 'Baz'], + } + const now = { + key: 'state-1', + roles: ['Another', 'ReviewIncludedInStatistics', 'Foo'], + } + const actual = statesSync.buildActions(now, before) + const expected = [ + { + action: 'removeRoles', + roles: ['Return', 'Baz'], + }, + { + action: 'addRoles', + roles: ['ReviewIncludedInStatistics', 'Foo'], + }, + ] + expect(actual).toEqual(expected) + }) +}) diff --git a/packages/sync-actions/test/stores-sync.spec.ts b/packages/sync-actions/test/stores-sync.spec.ts new file mode 100644 index 000000000..4bdb01273 --- /dev/null +++ b/packages/sync-actions/test/stores-sync.spec.ts @@ -0,0 +1,175 @@ +import storesSyncFn, { actionGroups } from '../src/stores' +import { baseActionsList } from '../src/stores-actions' + +describe('Exports', () => { + test('action group list', () => { + expect(actionGroups).toEqual(['base']) + }) + + test('correctly define base actions list', () => { + expect(baseActionsList).toEqual([ + { action: 'setName', key: 'name' }, + { action: 'setLanguages', key: 'languages' }, + { action: 'setDistributionChannels', key: 'distributionChannels' }, + { action: 'setSupplyChannels', key: 'supplyChannels' }, + ]) + }) +}) + +describe('Actions', () => { + let storesSync + beforeEach(() => { + storesSync = storesSyncFn() + }) + + test('should build `setName` action', () => { + const before = { + name: { en: 'Algeria' }, + } + const now = { + name: { en: 'Algeria', de: 'Algerian' }, + } + + const actual = storesSync.buildActions(now, before) + const expected = [{ action: 'setName', name: now.name }] + expect(actual).toEqual(expected) + }) + + test('should build `setLanguages` action', () => { + const before = { + languages: ['en'], + } + const now = { + languages: ['en', 'de'], + } + + const actual = storesSync.buildActions(now, before) + const expected = [{ action: 'setLanguages', languages: now.languages }] + expect(actual).toEqual(expected) + }) + + test('should build `setDistributionsChannels` action', () => { + const before = { + distributionChannels: [ + { + typeId: 'channel', + id: 'pd-001', + }, + ], + } + const now = { + distributionChannels: [ + { + typeId: 'channel', + id: 'pd-001', + }, + { + typeId: 'channel', + key: 'pd-002', + }, + ], + } + + const actual = storesSync.buildActions(now, before) + expect(actual).toEqual([ + { + action: 'setDistributionChannels', + distributionChannels: now.distributionChannels, + }, + ]) + }) + test('should build `setSupplyChannels` action', () => { + const before = { + supplyChannels: [ + { + typeId: 'channel', + id: 'inventory-supply-001', + }, + ], + } + const now = { + supplyChannels: [ + { + typeId: 'channel', + id: 'inventory-supply-001', + }, + { + typeId: 'channel', + key: 'inventory-supply-002', + }, + ], + } + + const actual = storesSync.buildActions(now, before) + expect(actual).toEqual([ + { + action: 'setSupplyChannels', + supplyChannels: now.supplyChannels, + }, + ]) + }) + + describe('custom fields', () => { + test('should build `setCustomType` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType2', + }, + fields: { + customField1: true, + }, + }, + } + const actual = storesSync.buildActions(now, before) + const expected = [{ action: 'setCustomType', ...now.custom }] + expect(actual).toEqual(expected) + }) + }) + + test('should build `setCustomField` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: false, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const actual = storesSync.buildActions(now, before) + const expected = [ + { + action: 'setCustomField', + name: 'customField1', + value: true, + }, + ] + expect(actual).toEqual(expected) + }) +}) diff --git a/packages/sync-actions/test/tax-categories-sync.spec.ts b/packages/sync-actions/test/tax-categories-sync.spec.ts new file mode 100644 index 000000000..9a1afda97 --- /dev/null +++ b/packages/sync-actions/test/tax-categories-sync.spec.ts @@ -0,0 +1,257 @@ +import taxCategorySyncFn, { actionGroups } from '../src/tax-categories' +import { baseActionsList } from '../src/tax-categories-actions' + +describe('Exports', () => { + test('action group list', () => { + expect(actionGroups).toEqual(['base', 'rates']) + }) + + test('correctly define base actions list', () => { + expect(baseActionsList).toEqual([ + { action: 'changeName', key: 'name' }, + { action: 'setKey', key: 'key' }, + { action: 'setDescription', key: 'description' }, + ]) + }) +}) + +describe('Actions', () => { + let taxCategorySync + beforeEach(() => { + taxCategorySync = taxCategorySyncFn() + }) + + test('should build `changeName` action', () => { + const before = { + name: 'John', + } + const now = { + name: 'Robert', + } + + const actual = taxCategorySync.buildActions(now, before) + const expected = [{ action: 'changeName', name: now.name }] + expect(actual).toEqual(expected) + }) + + test('should build `setDescription` action', () => { + const before = { + description: 'some description', + } + const now = { + description: 'some updated description', + } + + const actual = taxCategorySync.buildActions(now, before) + const expected = [ + { + action: 'setDescription', + description: now.description, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `addTaxRate` action', () => { + const before = { addresses: [] } + const now = { + rates: [{ name: '5% US', amount: '0.05' }], + } + + const actual = taxCategorySync.buildActions(now, before) + const expected = [{ action: 'addTaxRate', taxRate: now.rates[0] }] + expect(actual).toEqual(expected) + }) + + test('should build `replaceTaxRate` action', () => { + const before = { + rates: [ + { + id: 'taxRate-1', + name: '5% US', + amount: '0.05', + }, + ], + } + const now = { + rates: [ + { + id: 'taxRate-1', + name: '11% US', + amount: '0.11', + }, + ], + } + + const actual = taxCategorySync.buildActions(now, before) + const expected = [ + { + action: 'replaceTaxRate', + taxRateId: before.rates[0].id, + taxRate: now.rates[0], + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `removeTaxRate` action', () => { + const before = { + rates: [{ id: 'taxRate-1' }], + } + const now = { rates: [] } + + const actual = taxCategorySync.buildActions(now, before) + const expected = [ + { + action: 'removeTaxRate', + taxRateId: before.rates[0].id, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build complex mixed actions (1)', () => { + const before = { + rates: [ + { + id: 'taxRate-1', + name: '11% US', + amount: '0.11', + }, + { + id: 'taxRate-2', + name: '8% DE', + amount: '0.08', + }, + { + id: 'taxRate-3', + name: '21% ES', + amount: '0.21', + }, + ], + } + const now = { + rates: [ + { + id: 'taxRate-1', + name: '11% US', + amount: '0.11', + country: 'US', + }, + // REMOVED RATE 2 + { + // UNCHANGED RATE 3 + id: 'taxRate-3', + name: '21% ES', + amount: '0.21', + }, + { + // ADD NEW RATE + id: 'taxRate-4', + name: '15% FR', + amount: '0.15', + }, + ], + } + + const actual = taxCategorySync.buildActions(now, before) + const expected = [ + { + action: 'replaceTaxRate', + taxRate: { + amount: '0.11', + country: 'US', // added country to an existing rate + id: 'taxRate-1', + name: '11% US', + }, + taxRateId: 'taxRate-1', + }, + { action: 'removeTaxRate', taxRateId: 'taxRate-2' }, // removed second tax rate + { + action: 'addTaxRate', + taxRate: { amount: '0.15', id: 'taxRate-4', name: '15% FR' }, // adds new tax rate + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build complex mixed actions (2)', () => { + const before = { + rates: [ + { + id: 'taxRate-1', + name: '11% US', + amount: '0.11', + }, + { + id: 'taxRate-2', + name: '8% DE', + amount: '0.08', + }, + { + id: 'taxRate-3', + name: '21% ES', + amount: '0.21', + }, + ], + } + const now = { + rates: [ + // REMOVED RATE 1 + // REMOVED RATE 2 + { + // CHANGED RATE 3 + id: 'taxRate-3', + name: '21% ES', + state: 'NY', + amount: '0.21', + }, + { + // ADD NEW RATE + id: 'taxRate-4', + name: '15% FR', + amount: '0.15', + }, + ], + } + + const actual = taxCategorySync.buildActions(now, before) + const expected = [ + { + action: 'replaceTaxRate', + taxRate: { + amount: '0.21', + id: 'taxRate-3', + name: '21% ES', + state: 'NY', + }, + taxRateId: 'taxRate-3', + }, + { action: 'removeTaxRate', taxRateId: 'taxRate-1' }, // removed first tax rate + { action: 'removeTaxRate', taxRateId: 'taxRate-2' }, // removed second tax rate + { + action: 'addTaxRate', + taxRate: { amount: '0.15', id: 'taxRate-4', name: '15% FR' }, // adds new tax rate + }, + ] + + expect(actual).toEqual(expected) + }) + + test('should build `setKey` action', () => { + const before = { + key: '1234', + } + const now = { + key: '4321', + } + const actual = taxCategorySync.buildActions(now, before) + const expected = [ + { + action: 'setKey', + key: now.key, + }, + ] + expect(actual).toEqual(expected) + }) +}) diff --git a/packages/sync-actions/test/types-sync-base.spec.ts b/packages/sync-actions/test/types-sync-base.spec.ts new file mode 100644 index 000000000..0ca6af5a6 --- /dev/null +++ b/packages/sync-actions/test/types-sync-base.spec.ts @@ -0,0 +1,118 @@ +import clone from '../src/utils/clone' +import createSyncTypes, { actionGroups } from '../src/types' +import { baseActionsList } from '../src/types-actions' + +describe('Exports', () => { + test('action group list', () => { + expect(actionGroups).toEqual(['base', 'fieldDefinitions']) + }) + + test('correctly define base actions list', () => { + expect(baseActionsList).toEqual([ + { action: 'changeKey', key: 'key' }, + { action: 'changeName', key: 'name' }, + { action: 'setDescription', key: 'description' }, + ]) + }) +}) + +describe('Actions', () => { + let typesSync + let updateActions + let before + let now + beforeEach(() => { + typesSync = createSyncTypes() + }) + describe('mutation', () => { + test('should ensure given objects are not mutated', () => { + before = { + name: 'Orwell', + key: 'War-is-Peace', + } + now = { + name: 'Orwell', + key: 'Freedom-is-slavery', + } + typesSync.buildActions(now, before) + expect(before).toEqual(clone(before)) + expect(now).toEqual(clone(now)) + }) + }) + describe('with name change', () => { + beforeEach(() => { + before = { + name: 'Orwell', + } + now = { + name: 'Ignorance-is-Strength', + } + updateActions = typesSync.buildActions(now, before) + }) + test('should return `changeName` update-action', () => { + expect(updateActions).toEqual([ + { + action: 'changeName', + name: 'Ignorance-is-Strength', + }, + ]) + }) + }) + describe('with key change', () => { + beforeEach(() => { + before = { + key: 'orwell-key', + } + now = { + key: 'huxley-key', + } + updateActions = typesSync.buildActions(now, before) + }) + test('should return `changeKey` update-action', () => { + expect(updateActions).toEqual([ + { + action: 'changeKey', + key: 'huxley-key', + }, + ]) + }) + }) + describe('with empty key change (shouldOmitEmptyString=false)', () => { + beforeEach(() => { + before = { + key: null, + } + now = { + key: '', + } + updateActions = typesSync.buildActions(now, before) + }) + test('should return `changeKey` update-action', () => { + expect(updateActions).toEqual([ + { + action: 'changeKey', + key: '', + }, + ]) + }) + }) + describe('with description change', () => { + beforeEach(() => { + before = { + description: 'orwell-description', + } + now = { + description: 'huxley-description', + } + updateActions = typesSync.buildActions(now, before) + }) + test('should return `setDescription` update-action', () => { + expect(updateActions).toEqual([ + { + action: 'setDescription', + description: 'huxley-description', + }, + ]) + }) + }) +}) diff --git a/packages/sync-actions/test/types-sync-enums.spec.ts b/packages/sync-actions/test/types-sync-enums.spec.ts new file mode 100644 index 000000000..88f6989f0 --- /dev/null +++ b/packages/sync-actions/test/types-sync-enums.spec.ts @@ -0,0 +1,616 @@ +import typesSyncFn from '../src/types' + +const createTestType = (custom) => ({ + id: 'type-id', + fieldDefinitions: [], + ...custom, +}) + +describe('Actions', () => { + let before + let now + let typesSync + let updateActions + beforeEach(() => { + typesSync = typesSyncFn() + }) + describe('enum values', () => { + describe('with new enum', () => { + beforeEach(() => { + before = createTestType({ + fieldDefinitions: [ + { + name: 'enum', + type: { + name: 'Enum', + values: [], + }, + }, + ], + }) + now = createTestType({ + fieldDefinitions: [ + { + name: 'enum', + type: { + name: 'Enum', + values: [ + { + key: 'enum_1', + label: 'enum-1', + }, + ], + }, + }, + ], + }) + // we get a change operation only here. + updateActions = typesSync.buildActions(now, before) + }) + test('should return `addEnumValue` updateAction', () => { + expect(updateActions).toEqual([ + { + action: 'addEnumValue', + fieldName: 'enum', + value: { + key: 'enum_1', + label: 'enum-1', + }, + }, + ]) + }) + }) + describe('with multiple enums added to non-empty stack', () => { + beforeEach(() => { + before = createTestType({ + fieldDefinitions: [ + { + name: 'enum', + type: { + name: 'Enum', + values: [ + { key: 'enum_0', label: 'enum-0' }, + { key: 'enum_2', label: 'enum-2' }, + { key: 'enum_4', label: 'enum-4' }, + ], + }, + }, + ], + }) + now = createTestType({ + fieldDefinitions: [ + { + name: 'enum', + type: { + name: 'Enum', + values: [ + { key: 'enum_1', label: 'enum-1' }, + { key: 'enum_3', label: 'enum-3' }, + { key: 'enum_5', label: 'enum-5' }, + ], + }, + }, + ], + }) + updateActions = typesSync.buildActions(now, before) + }) + test('should return multiple `addEnumValue` updateActions', () => { + expect(updateActions).toEqual([ + { + action: 'addEnumValue', + fieldName: 'enum', + value: { key: 'enum_1', label: 'enum-1' }, + }, + { + action: 'addEnumValue', + fieldName: 'enum', + value: { key: 'enum_3', label: 'enum-3' }, + }, + { + action: 'addEnumValue', + fieldName: 'enum', + value: { key: 'enum_5', label: 'enum-5' }, + }, + ]) + }) + }) + describe('with enum reordered', () => { + beforeEach(() => { + before = createTestType({ + fieldDefinitions: [ + { + name: 'enum', + type: { + name: 'Enum', + values: [ + { key: 'enum_1', label: 'enum-1' }, + { key: 'enum_2', label: 'enum-2' }, + { key: 'enum_4', label: 'enum-4' }, + ], + }, + }, + ], + }) + now = createTestType({ + fieldDefinitions: [ + { + name: 'enum', + type: { + name: 'Enum', + values: [ + { key: 'enum_4', label: 'enum-4' }, + { key: 'enum_1', label: 'enum-1' }, + { key: 'enum_2', label: 'enum-2' }, + ], + }, + }, + ], + }) + updateActions = typesSync.buildActions(now, before) + }) + test('should return `changeEnumValueOrder` updateAction', () => { + expect(updateActions).toEqual([ + { + action: 'changeEnumValueOrder', + fieldName: 'enum', + keys: ['enum_4', 'enum_1', 'enum_2'], + }, + ]) + }) + }) + }) + describe('localized enum values', () => { + describe('with new enum', () => { + beforeEach(() => { + before = createTestType({ + fieldDefinitions: [ + { + name: 'lenum', + type: { + name: 'lenum', + values: [], + }, + }, + ], + }) + now = createTestType({ + fieldDefinitions: [ + { + name: 'lenum', + type: { + name: 'lenum', + values: [ + { + key: 'lenum_1', + label: { + en: 'lenum-en', + de: 'lenum-de', + }, + }, + ], + }, + }, + ], + }) + // we get a change operation only here. + updateActions = typesSync.buildActions(now, before) + }) + test('should return `addLocalizedEnumValue` updateAction', () => { + expect(updateActions).toEqual([ + { + action: 'addLocalizedEnumValue', + fieldName: 'lenum', + value: { + key: 'lenum_1', + label: { + en: 'lenum-en', + de: 'lenum-de', + }, + }, + }, + ]) + }) + }) + describe('with added to non-empty stack', () => { + beforeEach(() => { + before = createTestType({ + fieldDefinitions: [ + { + name: 'lenum', + type: { + name: 'lenum', + values: [ + { key: 'enum_0', label: { en: 'enum-0' } }, + { key: 'enum_2', label: { en: 'enum-2' } }, + { key: 'enum_4', label: { en: 'enum-4' } }, + ], + }, + }, + ], + }) + now = createTestType({ + fieldDefinitions: [ + { + name: 'lenum', + type: { + name: 'lenum', + values: [ + { key: 'enum_0', label: { en: 'enum-0' } }, + { key: 'enum_3', label: { en: 'enum-3' } }, + ], + }, + }, + ], + }) + + updateActions = typesSync.buildActions(now, before) + }) + test('should return `addLocalizedEnumValue` updateAction', () => { + expect(updateActions).toEqual([ + { + fieldName: 'lenum', + action: 'addLocalizedEnumValue', + value: { + key: 'enum_3', + label: { en: 'enum-3' }, + }, + }, + ]) + }) + }) + describe('with lenum reordered', () => { + beforeEach(() => { + before = createTestType({ + fieldDefinitions: [ + { + name: 'lenum', + type: { + name: 'lenum', + values: [ + { key: 'enum_1', label: { en: 'enum-1' } }, + { key: 'enum_2', label: { en: 'enum-2' } }, + { key: 'enum_4', label: { en: 'enum-4' } }, + ], + }, + }, + ], + }) + now = createTestType({ + fieldDefinitions: [ + { + name: 'lenum', + type: { + name: 'lenum', + values: [ + { key: 'enum_4', label: { en: 'enum-4' } }, + { key: 'enum_1', label: { en: 'enum-1' } }, + { key: 'enum_2', label: { en: 'enum-2' } }, + ], + }, + }, + ], + }) + updateActions = typesSync.buildActions(now, before) + }) + test('should return `changeLocalizedEnumValueOrder` updateAction', () => { + expect(updateActions).toEqual([ + { + action: 'changeLocalizedEnumValueOrder', + fieldName: 'lenum', + keys: ['enum_4', 'enum_1', 'enum_2'], + }, + ]) + }) + }) + describe('with Change LocalizedEnumValue Label', () => { + beforeEach(() => { + before = createTestType({ + fieldDefinitions: [ + { + name: 'lenum', + type: { + name: 'lenum', + values: [ + { key: 'enum_4_key', label: { en: 'enum-4' } }, + { key: 'enum_1_key', label: { en: 'enum-1' } }, + { key: 'enum_2_key', label: { en: 'enum-2' } }, + ], + }, + }, + ], + }) + now = createTestType({ + fieldDefinitions: [ + { + name: 'lenum', + type: { + name: 'lenum', + values: [ + { key: 'enum_4_key', label: { en: 'updated-enum-4' } }, + { key: 'enum_1_key', label: { en: 'enum-1' } }, + { key: 'enum_2_key', label: { en: 'enum-2' } }, + ], + }, + }, + ], + }) + updateActions = typesSync.buildActions(now, before) + }) + test('should return `changeLocalizedEnumValueLabel` updateAction', () => { + expect(updateActions).toEqual([ + { + action: 'changeLocalizedEnumValueLabel', + fieldName: 'lenum', + value: { + key: 'enum_4_key', + label: { en: 'updated-enum-4' }, + }, + }, + ]) + }) + }) + describe('with Change LocalizedEnumValue Label, and lenum reordered ', () => { + beforeEach(() => { + before = createTestType({ + fieldDefinitions: [ + { + name: 'lenum', + type: { + name: 'lenum', + values: [ + { + key: 'enum_1_key', + label: { en: 'enum-1', de: 'Aufzählung-1' }, + }, + { + key: 'enum_2_key', + label: { en: 'enum-2', de: 'Aufzählung-2' }, + }, + { + key: 'enum_4_key', + label: { en: 'enum-4', de: 'Aufzählung-4' }, + }, + ], + }, + }, + ], + }) + now = createTestType({ + fieldDefinitions: [ + { + name: 'lenum', + type: { + name: 'lenum', + values: [ + { + key: 'enum_4_key', + label: { en: 'enum-4', de: 'Aufzählung-4' }, + }, + { + key: 'enum_1_key', + label: { en: 'updated-enum-1', de: 'Aufzählung-1' }, + }, + { + key: 'enum_2_key', + label: { en: 'enum-2', de: 'Aufzählung-2' }, + }, + ], + }, + }, + ], + }) + updateActions = typesSync.buildActions(now, before) + }) + test('should return `changeLocalizedEnumValueLabel` `changeLocalizedEnumValueOrder` updateAction', () => { + expect(updateActions).toEqual([ + { + action: 'changeLocalizedEnumValueLabel', + fieldName: 'lenum', + value: { + key: 'enum_1_key', + label: { de: 'Aufzählung-1', en: 'updated-enum-1' }, + }, + }, + { + action: 'changeLocalizedEnumValueOrder', + fieldName: 'lenum', + keys: ['enum_4_key', 'enum_1_key', 'enum_2_key'], + }, + ]) + }) + }) + describe('with Change LocalizedEnumValue Label, should ignore label object ordering', () => { + beforeEach(() => { + before = createTestType({ + fieldDefinitions: [ + { + name: 'lenum', + type: { + name: 'lenum', + values: [ + { + key: 'enum_4_key', + label: { en: 'enum-4', de: 'Aufzählung-4' }, + }, + { + key: 'enum_1_key', + label: { en: 'enum-1', de: 'Aufzählung-1' }, + }, + { + key: 'enum_2_key', + label: { en: 'enum-2', de: 'Aufzählung-2' }, + }, + ], + }, + }, + ], + }) + now = createTestType({ + fieldDefinitions: [ + { + name: 'lenum', + type: { + name: 'lenum', + values: [ + { + key: 'enum_4_key', + label: { de: 'Aufzählung-4', en: 'enum-4' }, + }, + { + key: 'enum_1_key', + label: { de: 'Aufzählung-1', en: 'enum-1' }, + }, + { + key: 'enum_2_key', + label: { de: 'Aufzählung-2', en: 'enum-2' }, + }, + ], + }, + }, + ], + }) + updateActions = typesSync.buildActions(now, before) + }) + test('should return no updateAction', () => { + expect(updateActions).toEqual([]) + }) + }) + describe('with Change EnumValue Label', () => { + beforeEach(() => { + before = createTestType({ + fieldDefinitions: [ + { + name: 'enum', + type: { + name: 'Enum', + values: [ + { key: 'enum_4_key', label: 'enum-4' }, + { key: 'enum_1_key', label: 'enum-1' }, + { key: 'enum_2_key', label: 'enum-2' }, + ], + }, + }, + ], + }) + now = createTestType({ + fieldDefinitions: [ + { + name: 'enum', + type: { + name: 'Enum', + values: [ + { key: 'enum_4_key', label: 'updated-enum-4' }, + { key: 'enum_1_key', label: 'enum-1' }, + { key: 'enum_2_key', label: 'enum-2' }, + ], + }, + }, + ], + }) + updateActions = typesSync.buildActions(now, before) + }) + test('should return `changeEnumValueLabel` updateAction', () => { + expect(updateActions).toEqual([ + { + action: 'changeEnumValueLabel', + fieldName: 'enum', + value: { + key: 'enum_4_key', + label: 'updated-enum-4', + }, + }, + ]) + }) + }) + describe('with Change EnumValue Label, and enum reordered ', () => { + beforeEach(() => { + before = createTestType({ + fieldDefinitions: [ + { + name: 'enum', + type: { + name: 'Enum', + values: [ + { key: 'enum_1_key', label: 'enum-1' }, + { key: 'enum_2_key', label: 'enum-2' }, + { key: 'enum_4_key', label: 'enum-4' }, + ], + }, + }, + ], + }) + now = createTestType({ + fieldDefinitions: [ + { + name: 'enum', + type: { + name: 'Enum', + values: [ + { key: 'enum_4_key', label: 'enum-4' }, + { key: 'enum_1_key', label: 'updated-enum-1' }, + { key: 'enum_2_key', label: 'enum-2' }, + ], + }, + }, + ], + }) + updateActions = typesSync.buildActions(now, before) + }) + test('should return `changeEnumValueLabel` `changeEnumValueOrder` updateAction', () => { + expect(updateActions).toEqual([ + { + action: 'changeEnumValueLabel', + fieldName: 'enum', + value: { + key: 'enum_1_key', + label: 'updated-enum-1', + }, + }, + { + action: 'changeEnumValueOrder', + fieldName: 'enum', + keys: ['enum_4_key', 'enum_1_key', 'enum_2_key'], + }, + ]) + }) + }) + describe('with Change EnumValue Label, should ignore label object ordering', () => { + beforeEach(() => { + before = createTestType({ + fieldDefinitions: [ + { + name: 'enum', + type: { + name: 'Enum', + values: [ + { key: 'enum_4_key', label: 'enum-4' }, + { key: 'enum_1_key', label: 'enum-1' }, + { key: 'enum_2_key', label: 'enum-2' }, + ], + }, + }, + ], + }) + now = createTestType({ + fieldDefinitions: [ + { + name: 'enum', + type: { + name: 'Enum', + values: [ + { key: 'enum_4_key', label: 'enum-4' }, + { key: 'enum_1_key', label: 'enum-1' }, + { key: 'enum_2_key', label: 'enum-2' }, + ], + }, + }, + ], + }) + updateActions = typesSync.buildActions(now, before) + }) + test('should return no updateAction', () => { + expect(updateActions).toEqual([]) + }) + }) + }) +}) diff --git a/packages/sync-actions/test/types-sync-fields.spec.ts b/packages/sync-actions/test/types-sync-fields.spec.ts new file mode 100644 index 000000000..01f2e567b --- /dev/null +++ b/packages/sync-actions/test/types-sync-fields.spec.ts @@ -0,0 +1,408 @@ +import typesSyncFn from '../src/types' + +const createTestType = (custom) => ({ + id: 'type-id', + fieldDefinitions: [], + ...custom, +}) + +describe('Actions', () => { + let typesSync + let updateActions + let before + let now + beforeEach(() => { + typesSync = typesSyncFn() + }) + describe('with new fields', () => { + beforeEach(() => { + before = createTestType({ + fieldDefinitions: [], + }) + now = createTestType({ + fieldDefinitions: [ + { + type: { name: 'text' }, + name: 'name-field-definition', + label: { + en: 'EN field definition', + }, + }, + { + type: { name: 'number' }, + name: 'number-field-definition', + label: { + en: 'EN field definition', + }, + }, + ], + }) + updateActions = typesSync.buildActions(now, before) + }) + test('should return `addFieldDefinition` action', () => { + expect(updateActions).toEqual( + now.fieldDefinitions.map((fieldDefinition) => ({ + action: 'addFieldDefinition', + fieldDefinition, + })) + ) + }) + }) + describe('change InputHint', () => { + beforeEach(() => { + before = createTestType({ + fieldDefinitions: [ + { + type: { name: 'text' }, + name: 'name-field-definition', + label: { + en: 'EN field definition', + }, + inputHint: 'SingleLine', + }, + ], + }) + now = createTestType({ + fieldDefinitions: [ + { + type: { name: 'text' }, + name: 'name-field-definition', + label: { + en: 'EN field definition', + }, + inputHint: 'MultipleLine', + }, + ], + }) + updateActions = typesSync.buildActions(now, before) + }) + test('should return `changeInputHint` action', () => { + expect(updateActions).toEqual( + now.fieldDefinitions.map((fieldDefinition) => ({ + action: 'changeInputHint', + fieldName: fieldDefinition.name, + inputHint: 'MultipleLine', + })) + ) + }) + }) + describe('with fieldDefinitions removed', () => { + beforeEach(() => { + before = createTestType({ + fieldDefinitions: [ + { + type: { name: 'text' }, + name: 'name-field-definition', + label: { + en: 'EN field definition', + }, + }, + { + type: { name: 'number' }, + name: 'number-field-definition', + label: { + en: 'EN field definition', + }, + }, + ], + }) + now = createTestType({ + fieldDefinitions: [], + }) + updateActions = typesSync.buildActions(now, before) + }) + test('should return `removeFieldDefinition` actions', () => { + expect(updateActions).toEqual( + before.fieldDefinitions.map((fieldDefinition) => ({ + action: 'removeFieldDefinition', + fieldName: fieldDefinition.name, + })) + ) + }) + }) + describe('with changing order of fieldDefinitions', () => { + beforeEach(() => { + before = createTestType({ + fieldDefinitions: [ + { + name: 'first', + }, + { + name: 'second', + }, + ], + }) + now = createTestType({ + fieldDefinitions: [ + { + name: 'second', + }, + { + name: 'first', + }, + ], + }) + updateActions = typesSync.buildActions(now, before) + }) + test('should return `changeFieldDefinitionOrder` action', () => { + expect(updateActions).toEqual([ + { + action: 'changeFieldDefinitionOrder', + fieldNames: ['second', 'first'], + }, + ]) + }) + }) + describe('with fieldDefinitions replaced', () => { + beforeEach(() => { + before = createTestType({ + fieldDefinitions: [ + { + type: { name: 'number' }, + name: 'number-field-definition', + label: { + en: 'number-en', + }, + }, + ], + }) + now = createTestType({ + fieldDefinitions: [ + { + type: { name: 'text' }, + name: 'text-field-definition', + label: { + en: 'text-en', + }, + }, + ], + }) + updateActions = typesSync.buildActions(now, before) + }) + test('should return `removeFieldDefinition` and `addFieldDefinition` actions', () => { + expect(updateActions).toEqual([ + { + action: 'removeFieldDefinition', + fieldName: 'number-field-definition', + }, + { + action: 'addFieldDefinition', + fieldDefinition: { + type: { name: 'text' }, + name: 'text-field-definition', + label: { + en: 'text-en', + }, + }, + }, + ]) + }) + }) + describe('when changing field definition label', () => { + describe('when changing single locale value', () => { + beforeEach(() => { + before = createTestType({ + fieldDefinitions: [ + { + type: { name: 'text' }, + name: 'name-text-field-definition', + label: { + en: 'text-en-previous', + }, + }, + ], + }) + now = createTestType({ + fieldDefinitions: [ + { + type: { name: 'text' }, + name: 'name-text-field-definition', + label: { + en: 'text-en-next', + }, + }, + ], + }) + updateActions = typesSync.buildActions(now, before) + }) + test('should return `changeLabel` action', () => { + expect(updateActions).toEqual([ + { + action: 'changeLabel', + fieldName: 'name-text-field-definition', + label: { + en: 'text-en-next', + }, + }, + ]) + }) + }) + describe('when changing multiple locale value', () => { + beforeEach(() => { + before = createTestType({ + fieldDefinitions: [ + { + type: { name: 'text' }, + name: 'name-text-field-definition', + label: { + en: 'text-en-previous', + de: 'text-de-previous', + }, + }, + ], + }) + now = createTestType({ + fieldDefinitions: [ + { + type: { name: 'text' }, + name: 'name-text-field-definition', + label: { + en: 'text-en-next', + de: 'text-de-next', + }, + }, + ], + }) + updateActions = typesSync.buildActions(now, before) + }) + test('should return `changeLabel` action', () => { + expect(updateActions).toEqual([ + { + action: 'changeLabel', + fieldName: 'name-text-field-definition', + label: { + en: 'text-en-next', + de: 'text-de-next', + }, + }, + ]) + }) + }) + describe('when removing label', () => { + beforeEach(() => { + before = createTestType({ + fieldDefinitions: [ + { + type: { name: 'text' }, + name: 'name-text-field-definition', + label: { + en: 'text-en-previous', + de: 'text-de-previous', + }, + }, + ], + }) + now = createTestType({ + fieldDefinitions: [ + { + type: { name: 'text' }, + name: 'name-text-field-definition', + label: undefined, + }, + ], + }) + updateActions = typesSync.buildActions(now, before) + }) + test('should return `changeLabel` action', () => { + expect(updateActions).toEqual([ + { + action: 'changeLabel', + fieldName: 'name-text-field-definition', + label: undefined, + }, + ]) + }) + }) + }) + describe('with removal and changing label of fieldDefinitions', () => { + beforeEach(() => { + before = createTestType({ + fieldDefinitions: [ + { + type: { name: 'text' }, + name: 'should-not-change', + label: { + en: 'should-not-change', + }, + }, + { + type: { name: 'text' }, + name: 'should-be-removed', + label: { + en: 'should-be-removed', + }, + }, + { + type: { name: 'text' }, + name: 'should-change', + label: { + en: 'from-this', + }, + }, + ], + }) + now = createTestType({ + fieldDefinitions: [ + { + type: { name: 'text' }, + name: 'should-not-change', + label: { + en: 'should-not-change', + }, + }, + { + type: { name: 'text' }, + name: 'should-change', + label: { + en: 'to-this', + }, + }, + ], + }) + updateActions = typesSync.buildActions(now, before) + }) + test('should return `changeLabel` and `removeFieldDefinition` action', () => { + expect(updateActions).toEqual([ + { action: 'removeFieldDefinition', fieldName: 'should-be-removed' }, + { + action: 'changeLabel', + fieldName: 'should-change', + label: { + en: 'to-this', + }, + }, + ]) + }) + }) + + /** + * there is no update action for fieldDefinition -> required, + * so this field is immutable and unchangeable. + * in case of changing it, this were throwing `Cannot read properties of undefined` cause its nested field. + * below test is making sure this field is ignored and without any internal package errors. + */ + describe('should ignore changes in required field in fieldDefinition', () => { + beforeEach(() => { + before = createTestType({ + fieldDefinitions: [ + { + name: 'first', + required: true, + }, + ], + }) + now = createTestType({ + fieldDefinitions: [ + { + name: 'first', + required: false, + }, + ], + }) + updateActions = typesSync.buildActions(now, before) + }) + test('should return no action', () => { + expect(updateActions).toEqual([]) + }) + }) +}) diff --git a/packages/sync-actions/test/utils/action-map-custom.spec.ts b/packages/sync-actions/test/utils/action-map-custom.spec.ts new file mode 100644 index 000000000..194070140 --- /dev/null +++ b/packages/sync-actions/test/utils/action-map-custom.spec.ts @@ -0,0 +1,248 @@ +import * as diffpatcher from '../../src/utils/diffpatcher' +import createBuildActions from '../../src/utils/create-build-actions' +import doMapActions from '../../src/utils/action-map-custom' + +describe('buildActions', () => { + let buildActions + beforeEach(() => { + buildActions = createBuildActions(diffpatcher.diff, doMapActions) + }) + + test('should build `setCustomType` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType2', + }, + fields: { + customField1: true, + }, + }, + } + const actual = buildActions(now, before) + const expected = [{ action: 'setCustomType', ...now.custom }] + expect(actual).toEqual(expected) + }) + + test('should build `setCustomType` action with key', () => { + const before = { + custom: { + type: { + typeId: 'type', + key: 'customType1', + }, + fields: { + customField1: true, + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + key: 'customType2', + }, + fields: { + customField1: true, + }, + }, + } + const actual = buildActions(now, before) + const expected = [{ action: 'setCustomType', ...now.custom }] + expect(actual).toEqual(expected) + }) + + test('should build `setCustomField` action', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: true, // will change + customField2: true, // will stay unchanged + customField3: false, // will be removed + }, + }, + } + const now = { + custom: { + type: { + typeId: 'type', + id: 'customType1', + }, + fields: { + customField1: false, + customField2: true, + customField4: true, // was added + }, + }, + } + const actual = buildActions(now, before) + const expected = [ + { + action: 'setCustomField', + name: 'customField1', + value: false, + }, + { + action: 'setCustomField', + name: 'customField3', + value: undefined, + }, + { + action: 'setCustomField', + name: 'customField4', + value: true, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setCustomField` action for a long text field', () => { + const before = { + custom: { + type: { + typeId: 'type', + id: 'customType', + }, + fields: { + customField: 'word '.repeat(200), + }, + }, + } + const updatedValue = before.custom.fields.customField.concat('1') + const now = { + custom: { + ...before.custom, + fields: { + customField: updatedValue, + }, + }, + } + const actual = buildActions(now, before) + const expected = [ + { + action: 'setCustomField', + name: 'customField', + value: updatedValue, + }, + ] + expect(actual).toEqual(expected) + }) + + describe('changing the custom type of a category', () => { + describe('existing category has no `custom` object', () => { + test('should build `setCustomType` action with the new type', () => { + const before = { + key: 'category-key', + } + const now = { + key: 'category-key', + custom: { + type: { + typeId: 'type', + id: 'customType2', + }, + fields: { + customField1: true, + }, + }, + } + const actual = buildActions(now, before) + const expected = [{ action: 'setCustomType', ...now.custom }] + expect(actual).toEqual(expected) + }) + }) + + describe('existing category has an empty `custom` object', () => { + test('should build `setCustomType` action with the new type', () => { + const before = { + key: 'category-key', + custom: {}, + } + const now = { + key: 'category-key', + custom: { + type: { + typeId: 'type', + id: 'customType2', + }, + fields: { + customField1: true, + }, + }, + } + const actual = buildActions(now, before) + const expected = [{ action: 'setCustomType', ...now.custom }] + expect(actual).toEqual(expected) + }) + }) + + describe('existing category has a `custom` object', () => { + describe('new category has no `custom` object', () => { + test('build `setCustomType` action to unset the `custom` type', () => { + const before = { + key: 'category-key', + custom: { + type: { + typeId: 'type', + id: 'customType2', + }, + fields: { + customField1: true, + }, + }, + } + const now = { + key: 'category-key', + custom: {}, + } + const actual = buildActions(now, before) + const expected = [{ action: 'setCustomType' }] + expect(actual).toEqual(expected) + }) + }) + + describe('new category has an empty `custom` object', () => { + test('build `setCustomType` action to unset the `custom` type', () => { + const before = { + key: 'category-key', + custom: { + type: { + typeId: 'type', + id: 'customType2', + }, + fields: { + customField1: true, + }, + }, + } + const now = { + key: 'category-key', + // no custom object + } + const actual = buildActions(now, before) + const expected = [{ action: 'setCustomType' }] + expect(actual).toEqual(expected) + }) + test('throw error if either argument function arguments are not provided', () => { + expect(() => buildActions(null, null)).toThrow() + }) + }) + }) + }) +}) diff --git a/packages/sync-actions/test/utils/combine-validity-actions.spec.ts b/packages/sync-actions/test/utils/combine-validity-actions.spec.ts new file mode 100644 index 000000000..72af0c720 --- /dev/null +++ b/packages/sync-actions/test/utils/combine-validity-actions.spec.ts @@ -0,0 +1,65 @@ +import combineValidityActions from '../../src/utils/combine-validity-actions' + +describe('combineValidityActions', () => { + let combinedActions + let validFromAction + let validUntilAction + let otherAction + beforeEach(() => { + validFromAction = { + action: 'setValidFrom', + validFrom: 'date-from-1', + } + validUntilAction = { + action: 'setValidUntil', + validUntil: 'date-until-1', + } + otherAction = { + action: 'changeRequiresDiscountCode', + requiresDiscountCode: true, + } + }) + describe('when both `setValidFrom` and `setValidUntil` available', () => { + beforeEach(() => { + combinedActions = combineValidityActions([ + otherAction, + validFromAction, + validUntilAction, + ]) + }) + it('should combine both actions into `setValidFromAndUntil` action', () => { + expect(combinedActions).toMatchObject([ + otherAction, + { + action: 'setValidFromAndUntil', + validFrom: validFromAction.validFrom, + validUntil: validUntilAction.validUntil, + }, + ]) + }) + }) + describe('when only `setValidFrom` is available', () => { + beforeEach(() => { + combinedActions = combineValidityActions([otherAction, validFromAction]) + }) + it('should not combine into `setValidFromAndUntil` and keep `validFromAction`', () => { + expect(combinedActions).toMatchObject([otherAction, validFromAction]) + }) + }) + describe('when only `setValidUntil` is available', () => { + beforeEach(() => { + combinedActions = combineValidityActions([otherAction, validUntilAction]) + }) + it('should not combine into `setValidFromAndUntil` and keep `validUntilAction`', () => { + expect(combinedActions).toMatchObject([otherAction, validUntilAction]) + }) + }) + describe('when neither `setValidFrom` nor `setValidUntil` are available', () => { + beforeEach(() => { + combinedActions = combineValidityActions([otherAction]) + }) + it('should return same actions without any change', () => { + expect(combinedActions).toMatchObject([otherAction]) + }) + }) +}) diff --git a/packages/sync-actions/test/utils/common-actions.spec.ts b/packages/sync-actions/test/utils/common-actions.spec.ts new file mode 100644 index 000000000..79202d2f8 --- /dev/null +++ b/packages/sync-actions/test/utils/common-actions.spec.ts @@ -0,0 +1,315 @@ +import { + buildBaseAttributesActions, + buildReferenceActions, +} from '../../src/utils/common-actions' +import * as diffpatcher from '../../src/utils/diffpatcher' + +describe('Common actions', () => { + describe('::buildBaseAttributesActions', () => { + let actions + let before + let now + const testActions = [ + { + action: 'changeName', + key: 'name', + }, + { + action: 'setDescription', + key: 'description', + }, + { + action: 'setKey', + key: 'key', + }, + { + action: 'setExternalId', + key: 'externalId', + }, + { + action: 'changeSlug', + key: 'slug', + }, + { + action: 'setCustomerNumber', + key: 'customerNumber', + }, + { + action: 'setCustomerNumber', + key: 'customerNumber', + }, + { + action: 'changeQuantity', + key: 'quantityOnStock', + actionKey: 'quantity', + }, + ] + + test('should build base actions', () => { + before = { + name: { en: 'Foo' }, + description: undefined, + externalId: '123', + slug: { en: 'foo' }, + customerNumber: undefined, + quantityOnStock: 1, + } + now = { + name: { en: 'Foo1', de: 'Foo2' }, + description: { en: 'foo bar' }, + externalId: null, + slug: { en: 'foo' }, + customerNumber: null, + quantityOnStock: 0, + } + + actions = buildBaseAttributesActions({ + actions: testActions, + diff: diffpatcher.diff(before, now), + oldObj: before, + newObj: now, + }) + + expect(actions).toEqual([ + { action: 'changeName', name: now.name }, + { action: 'setDescription', description: now.description }, + { action: 'setExternalId' }, + { action: 'changeQuantity', quantity: now.quantityOnStock }, + ]) + }) + + describe('with `shouldOmitEmptyString`', () => { + beforeEach(() => { + before = { key: undefined } + now = { key: '' } + actions = buildBaseAttributesActions({ + actions: testActions, + diff: diffpatcher.diff(before, now), + oldObj: before, + newObj: now, + shouldOmitEmptyString: true, + }) + }) + it('should not return `setKey` action', () => { + expect(actions).toEqual([]) + }) + }) + + describe('without `shouldOmitEmptyString`', () => { + beforeEach(() => { + before = { key: undefined } + now = { key: '' } + actions = buildBaseAttributesActions({ + actions: testActions, + diff: diffpatcher.diff(before, now), + oldObj: before, + newObj: now, + shouldOmitEmptyString: false, + }) + }) + it('should not return `setKey` action', () => { + expect(actions).toEqual([ + { + action: 'setKey', + key: '', + }, + ]) + }) + }) + }) + + describe('::buildReferenceActions', () => { + const testActions = [ + { action: 'setTaxCategory', key: 'taxCategory' }, + { action: 'setCustomerGroup', key: 'customerGroup' }, + { action: 'setSupplyChannel', key: 'supplyChannel' }, + { action: 'setProductType', key: 'productType' }, + { action: 'transitionState', key: 'state' }, + { action: 'setKey', key: 'key' }, + ] + + describe('without expanded references', () => { + describe('taxCategory', () => { + let actions + const before = { + taxCategory: { id: 'tc-1', typeId: 'tax-category' }, + } + const now = { + // id changed + taxCategory: { id: 'tc-2', typeId: 'tax-category' }, + } + + beforeEach(() => { + actions = buildReferenceActions({ + actions: testActions, + diff: diffpatcher.diff(before, now), + oldObj: before, + newObj: now, + }) + }) + + test('should build reference action', () => { + expect(actions).toContainEqual({ + action: 'setTaxCategory', + taxCategory: now.taxCategory, + }) + }) + }) + + describe('customerGroup', () => { + let actions + const before = { + customerGroup: undefined, + } + const now = { + // new ref + customerGroup: { id: 'cg-1', typeId: 'customer-group' }, + } + + beforeEach(() => { + actions = buildReferenceActions({ + actions: testActions, + diff: diffpatcher.diff(before, now), + oldObj: before, + newObj: now, + }) + }) + + test('should build reference action', () => { + expect(actions).toContainEqual({ + action: 'setCustomerGroup', + customerGroup: now.customerGroup, + }) + }) + }) + + describe('supplyChannel', () => { + let actions + const before = { + supplyChannel: { id: 'sc-1', typeId: 'channel' }, + } + const now = { + // unset + supplyChannel: null, + } + + beforeEach(() => { + actions = buildReferenceActions({ + actions: testActions, + diff: diffpatcher.diff(before, now), + oldObj: before, + newObj: now, + }) + }) + + test('should build reference action', () => { + expect(actions).toContainEqual({ action: 'setSupplyChannel' }) + }) + }) + + describe('productType', () => { + let actions + const before = { + productType: { + id: 'pt-1', + typeId: 'product-type', + obj: { id: 'pt-1' }, + }, + } + const now = { + // ignore update + productType: { + id: 'pt-1', + typeId: 'product-type', + }, + } + beforeEach(() => { + actions = buildReferenceActions({ + actions: testActions, + diff: diffpatcher.diff(before, now), + oldObj: before, + newObj: now, + }) + }) + + test('should not build reference action', () => { + expect(actions).not.toContainEqual({ action: 'productType' }) + }) + }) + + describe('state', () => { + let actions + const before = { + state: { + id: 's-1', + typeId: 'state', + obj: { id: 's-1' }, + }, + } + const now = { + // new ref: transition state + state: { + id: 's-2', + typeId: 'state', + }, + } + + beforeEach(() => { + actions = buildReferenceActions({ + actions: testActions, + diff: diffpatcher.diff(before, now), + oldObj: before, + newObj: now, + }) + }) + + test('should build reference action', () => { + expect(actions).toContainEqual({ + action: 'transitionState', + state: now.state, + }) + }) + }) + }) + + describe('with expanded references', () => { + describe('state', () => { + let actions + const before = { + state: { + id: 's-1', + typeId: 'state', + obj: { id: 's-1' }, + }, + } + const now = { + // new ref: transition state + state: { + id: 's-2', + typeId: 'state', + obj: { id: 's-1' }, + }, + } + + beforeEach(() => { + actions = buildReferenceActions({ + actions: testActions, + diff: diffpatcher.diff(before, now), + oldObj: before, + newObj: now, + }) + }) + + test('should build reference action without expansion in action', () => { + expect(actions).toContainEqual({ + action: 'transitionState', + state: { + typeId: now.state.typeId, + id: now.state.id, + }, + }) + }) + }) + }) + }) +}) diff --git a/packages/sync-actions/test/utils/copy-empty-array-props.spec.ts b/packages/sync-actions/test/utils/copy-empty-array-props.spec.ts new file mode 100644 index 000000000..0d5ae5ef8 --- /dev/null +++ b/packages/sync-actions/test/utils/copy-empty-array-props.spec.ts @@ -0,0 +1,331 @@ +import { performance } from 'perf_hooks' +import copyEmptyArrayProps from '../../src/utils/copy-empty-array-props' + +describe('null check on root value', () => { + test('old root value', () => { + const oldObj = null + const newObj = { + metaDescription: { + en: 'new value', + }, + } + const [old, fixedNewObj] = copyEmptyArrayProps(oldObj, newObj) + expect(fixedNewObj).toEqual(newObj) + expect(old).toEqual(oldObj) + }) + test('new root value', () => { + const oldObj = { + metaDescription: { + en: 'new value', + }, + } + const newObj = null + const [old, fixedNewObj] = copyEmptyArrayProps(oldObj, newObj) + expect(fixedNewObj).toEqual(newObj) + expect(old).toEqual(oldObj) + }) +}) + +test('null check', () => { + const oldObj = { + // typeof `null` === 'object' + metaDescription: null, + } + const newObj = { + metaDescription: { + en: 'new value', + }, + } + const [, fixedNewObj] = copyEmptyArrayProps(oldObj, newObj) + expect(fixedNewObj).toEqual(newObj) +}) + +test('undefined check', () => { + const [old, fixed] = copyEmptyArrayProps(undefined, undefined) + expect(old).toEqual({}) + expect(fixed).toEqual({}) +}) + +test('should add empty array for undefined prop', () => { + const oldObj = { + emptyArray: [], + anotherProp: 1, + } + const newObj = { + anotherProp: 2, + newObjProp: true, + } + const [old, fixedNewObj] = copyEmptyArrayProps(oldObj, newObj) + + expect(old).toEqual(oldObj) + expect(fixedNewObj).toEqual({ ...newObj, emptyArray: [] }) +}) + +test('should add empty array for `nestedObject`', () => { + const oldObj = { + emptyArray: [], + nestedObject: { + anotherProp: 1, + nestedEmptyArray: [], + }, + anotherProp: 1, + } + + const newObj = { + nestedObject: {}, + anotherProp: 2, + } + + const [old, fixedNewObj] = copyEmptyArrayProps(oldObj, newObj) + + expect(old).toEqual(oldObj) + expect(fixedNewObj).toEqual({ + ...newObj, + emptyArray: [], + nestedObject: { + nestedEmptyArray: [], + }, + }) +}) + +test('shouldnt copy `nestedEmptyArrayOne` since parent key not found on `newObj`', () => { + const oldObj = { + nestedObject: { + anotherProp: 1, + nestedObjectOne: { + anotherPropOne: 1, + nestedEmptyArrayOne: [], + }, + }, + anotherProp: 1, + } + + const newObj = { + nestedObject: {}, + anotherProp: 2, + } + const [old, fixedNewObj] = copyEmptyArrayProps(oldObj, newObj) + + expect(old).toEqual(oldObj) + expect(fixedNewObj).toEqual(newObj) +}) + +test('should add empty array for `nestedObject`, `nestedObjectOne`', () => { + const oldObj = { + emptyArray: [], + nestedObject: { + anotherProp: 1, + nestedEmptyArray: [], + nestedObjectOne: { + anotherPropOne: 1, + nestedEmptyArrayOne: [], + }, + }, + anotherProp: 1, + } + + const newObj = { + nestedObject: { + nestedObjectOne: { + anotherPropOne: 2, + }, + }, + anotherProp: 2, + } + const [old, fixedNewObj] = copyEmptyArrayProps(oldObj, newObj) + + expect(old).toEqual(oldObj) + expect(fixedNewObj).toEqual({ + ...newObj, + emptyArray: [], + nestedObject: { + nestedEmptyArray: [], + nestedObjectOne: { + anotherPropOne: 2, + nestedEmptyArrayOne: [], + }, + }, + }) +}) + +test('should init empty arrays into nested objects', () => { + const oldObj = { + variants: [ + { + id: 1, + prices: [ + { + id: 1, + customerGroup: [], + }, + { + id: 2, + customerGroup: [], + }, + ], + assets: [], + }, + { + id: 2, + }, + { + id: 3, + prices: [], + }, + { + id: 4, + att: '44444', + prices: [], + }, + ], + } + + const newObj = { + variants: [ + { + id: 1, + prices: [ + { + id: 1, + att: '11111', + p: [], + }, + { + id: 2, + att: '22222', + }, + { + id: 3, + att: '333333', + }, + ], + att: 'anything', + }, + { + id: 4, + }, + ], + } + const [old, fixedNewObj] = copyEmptyArrayProps(oldObj, newObj) + + expect(old).toEqual(oldObj) + expect(fixedNewObj).toEqual({ + variants: [ + { + id: 1, + prices: [ + { + id: 1, + att: '11111', + p: [], + customerGroup: [], + }, + { + id: 2, + att: '22222', + customerGroup: [], + }, + { + id: 3, + att: '333333', + }, + ], + att: 'anything', + assets: [], + }, + { + id: 4, + prices: [], + }, + ], + }) +}) + +test('should ignore dates', () => { + const dateNow = new Date() + const oldObj = { + variants: [ + { + id: 1, + prices: [], + date: dateNow, + }, + ], + } + + const newObj = { + variants: [ + { + id: 1, + date: dateNow, + }, + ], + } + const [old, fixedNewObj] = copyEmptyArrayProps(oldObj, newObj) + + expect(old).toEqual(oldObj) + expect(fixedNewObj).toEqual({ + variants: [ + { + id: 1, + prices: [], + date: dateNow, + }, + ], + }) +}) + +test('shouldnt mutate `newObj`', () => { + const oldObj = { + emptyArray: [], + anotherProp: 1, + } + + const newObj = { + anotherProp: 2, + } + + const [old, fixedNewObj] = copyEmptyArrayProps(oldObj, newObj) + + expect(old).toEqual(oldObj) + expect(fixedNewObj).toEqual({ ...newObj, emptyArray: [] }) + expect(newObj).toEqual({ anotherProp: 2 }) +}) + +test('shouldnt change objects since there is no arrays to copy', () => { + const oldObj = {} + + const newObj = { + customerGroup: { + typeId: 'customer-group', + key: 'foo-customer-group', + }, + } + + const [old, fixedNewObj] = copyEmptyArrayProps(oldObj, newObj) + + expect(old).toEqual(oldObj) + expect(fixedNewObj).toEqual(newObj) +}) + +test('performance test for large arrays should be less than 200 ms', () => { + const oldObj = { + addresses: Array(5000) + .fill(null) + .map((a, index) => ({ id: `address-${index}` })), + } + + const newObj = { + addresses: Array(5000) + .fill(null) + .map((a, index) => ({ id: `address-${index}` })), + } + + const start = performance.now() + const [old, fixedNewObj] = copyEmptyArrayProps(oldObj, newObj) + const end = performance.now() + + expect(old).toEqual(oldObj) + expect(fixedNewObj).toEqual(newObj) + expect(end - start).toBeLessThan(200) +}) diff --git a/packages/sync-actions/test/utils/create-build-array-actions.spec.ts b/packages/sync-actions/test/utils/create-build-array-actions.spec.ts new file mode 100644 index 000000000..a368ab8f1 --- /dev/null +++ b/packages/sync-actions/test/utils/create-build-array-actions.spec.ts @@ -0,0 +1,155 @@ +import { diff, getDeltaValue } from '../../src/utils/diffpatcher' +import createBuildArrayActions, { + ADD_ACTIONS, + REMOVE_ACTIONS, + CHANGE_ACTIONS, +} from '../../src/utils/create-build-array-actions' + +const testObjKey = 'someNestedObjects' +const getTestObj = (list?: Array) => ({ [testObjKey]: list || [] }) + +describe('createBuildArrayActions', () => { + test('returns function', () => { + expect(typeof createBuildArrayActions('test', {})).toBe('function') + }) + + test('correctly detects add actions', () => { + const before = getTestObj() + const now = getTestObj([{ name: 'a new object' }]) + const addActionSpy = jest.fn() + + const handler = createBuildArrayActions(testObjKey, { + [ADD_ACTIONS]: addActionSpy, + }) + + handler(diff(before, now), before, now) + + expect(addActionSpy).toHaveBeenCalledWith( + { name: 'a new object' }, + expect.any(Number) + ) + + expect(addActionSpy).toHaveBeenCalledWith(expect.any(Object), 0) + }) + + test('correctly detects change actions', () => { + const before = getTestObj([{ name: 'a new object' }]) + const now = getTestObj([{ name: 'a changed object' }]) + const changeActionSpy = jest.fn() + + const handler = createBuildArrayActions(testObjKey, { + [CHANGE_ACTIONS]: changeActionSpy, + }) + + handler(diff(before, now), before, now) + + expect(changeActionSpy).toHaveBeenCalledWith( + { name: 'a new object' }, + { name: 'a changed object' }, + expect.any(Number) + ) + + expect(changeActionSpy).toHaveBeenCalledWith( + expect.any(Object), + expect.any(Object), + 0 + ) + }) + + test('correctly detects remove actions', () => { + const before = getTestObj([{ name: 'an object' }]) + const now = getTestObj() + const removeActionSpy = jest.fn() + + const handler = createBuildArrayActions(testObjKey, { + [REMOVE_ACTIONS]: removeActionSpy, + }) + + handler(diff(before, now), before, now) + + expect(removeActionSpy).toHaveBeenCalledWith( + { name: 'an object' }, + expect.any(Number) + ) + + expect(removeActionSpy).toHaveBeenCalledWith(expect.any(Object), 0) + }) + + test('should throw an error for non array parameter', () => { + expect(() => + getDeltaValue('non-array-imput', { sample: 'object' }) + ).toThrow() + }) + test('throw an error if `originalObject` is not provided', () => { + const sampleArray = [ + { + measurements: { + heightInMillimeter: 10, + lengthInMillimeter: 20, + widthInMillimeter: 2, + weightInGram: 5, + }, + trackingData: { trackingId: 'tracking-id-1' }, + }, + { + measurements: { + heightInMillimeter: 10, + lengthInMillimeter: 20, + widthInMillimeter: 2, + weightInGram: 5, + }, + trackingData: { trackingId: 'tracking-id-2' }, + }, + 2, + ] + expect(() => getDeltaValue(sampleArray, null)).toThrow() + }) + test('throw an error if array is length 3 and second item is 3', () => { + const sampleArray = [ + { + measurements: { + heightInMillimeter: 10, + lengthInMillimeter: 20, + widthInMillimeter: 2, + weightInGram: 5, + }, + trackingData: { trackingId: 'tracking-id-1' }, + }, + { + measurements: { + heightInMillimeter: 10, + lengthInMillimeter: 20, + widthInMillimeter: 2, + weightInGram: 5, + }, + trackingData: { trackingId: 'tracking-id-2' }, + }, + 3, + ] + expect(() => getDeltaValue(sampleArray, null)).toThrow() + }) + test('throw an error if array is length 3 and second item is 4', () => { + const sampleArray = [ + { + measurements: { + heightInMillimeter: 10, + lengthInMillimeter: 20, + widthInMillimeter: 2, + weightInGram: 5, + }, + trackingData: { trackingId: 'tracking-id-1' }, + }, + { + measurements: { + heightInMillimeter: 10, + lengthInMillimeter: 20, + widthInMillimeter: 2, + weightInGram: 5, + }, + trackingData: { trackingId: 'tracking-id-2' }, + }, + 4, + ] + expect(() => getDeltaValue(sampleArray, null)).toThrow() + }) +}) diff --git a/packages/sync-actions/test/utils/create-map-action-group.spec.ts b/packages/sync-actions/test/utils/create-map-action-group.spec.ts new file mode 100644 index 000000000..5e3de8d77 --- /dev/null +++ b/packages/sync-actions/test/utils/create-map-action-group.spec.ts @@ -0,0 +1,89 @@ +import createMapActionGroup from '../../src/utils/create-map-action-group' + +describe('createMapActionGroup', () => { + describe('without actionGroups', () => { + const fn = jest.fn() + let mapActionGroup + + beforeEach(() => { + mapActionGroup = createMapActionGroup([]) + mapActionGroup('foo-type', fn) + }) + + test('should invoke the `fn` (callback)', () => { + expect(fn).toHaveBeenCalled() + }) + }) + + describe('with found `actionGroup` (type)', () => { + describe('with `group` being `allow`', () => { + const fn = jest.fn() + const actionGroups = [{ type: 'base', group: 'allow' }] + let mapActionGroup + + beforeEach(() => { + mapActionGroup = createMapActionGroup(actionGroups) + mapActionGroup(actionGroups[0].type, fn) + }) + + test('should invoke the `fn` (callback)', () => { + expect(fn).toHaveBeenCalled() + }) + }) + + describe('with `group` being `ignore`', () => { + const fn = jest.fn() + const actionGroups = [{ type: 'base', group: 'ignore' }] + let mapActionGroup + + beforeEach(() => { + mapActionGroup = createMapActionGroup(actionGroups) + mapActionGroup(actionGroups[0].type, fn) + }) + + test('should not invoke the `fn` (callback)', () => { + expect(fn).not.toHaveBeenCalled() + }) + }) + + describe('without `group`', () => { + const fn = jest.fn() + const actionGroups = [{ type: 'base', group: 'grey' }] + let mapActionGroup + + beforeEach(() => { + mapActionGroup = createMapActionGroup(actionGroups) + }) + + test('should throw an error', () => { + expect(() => { + mapActionGroup(actionGroups[0].type, fn) + }).toThrow() + }) + + test('should throw an error with message', () => { + expect(() => { + mapActionGroup(actionGroups[0].type, fn) + }).toThrow( + `Action group '${actionGroups[0].group}' ` + + 'not supported. Use either "allow" or "ignore".' + ) + }) + }) + }) + + describe('with non found `actionGroup` (type)', () => { + const fn = jest.fn() + const actionGroups = [{ type: 'base', group: 'allow' }] + let mapActionGroup + + beforeEach(() => { + mapActionGroup = createMapActionGroup(actionGroups) + mapActionGroup('foo-non-existent-type', fn) + }) + + test('should not invoke the `fn` (callback)', () => { + expect(fn).not.toHaveBeenCalled() + }) + }) +}) diff --git a/packages/sync-actions/test/utils/extract-matching-pairs.spec.ts b/packages/sync-actions/test/utils/extract-matching-pairs.spec.ts new file mode 100644 index 000000000..d0f374d2c --- /dev/null +++ b/packages/sync-actions/test/utils/extract-matching-pairs.spec.ts @@ -0,0 +1,55 @@ +import extractMatchingPairs from '../../src/utils/extract-matching-pairs' + +describe('extractMatchingPairs', () => { + let key + let path + let oldObj + let newObj + let pairs + describe('with found path', () => { + beforeEach(() => { + key = '0' + path = { + [key]: ['0', '0'], + } + oldObj = [ + { + name: 'foo', + }, + ] + newObj = [ + { + name: 'bar', + }, + ] + pairs = extractMatchingPairs(path, key, oldObj, newObj) + }) + test('should return `newObj` and `oldObj`', () => { + expect(pairs).toEqual({ + oldObj: { name: 'foo' }, + newObj: { name: 'bar' }, + }) + }) + }) + describe('without found pairs', () => { + beforeEach(() => { + key = '0' + path = { + [key]: ['0', '0'], + } + oldObj = [ + { + name: 'foo', + }, + ] + newObj = [] + pairs = extractMatchingPairs(path, key, oldObj, newObj) + }) + test('should return `oldObj` and empty `newObj`', () => { + expect(pairs).toEqual({ + oldObj: { name: 'foo' }, + newObj: undefined, + }) + }) + }) +}) diff --git a/packages/sync-actions/test/utils/find-matching-pairs.spec.ts b/packages/sync-actions/test/utils/find-matching-pairs.spec.ts new file mode 100644 index 000000000..1e391c361 --- /dev/null +++ b/packages/sync-actions/test/utils/find-matching-pairs.spec.ts @@ -0,0 +1,34 @@ +import findMatchingPairs from '../../src/utils/find-matching-pairs' + +describe('findMatchingPairs', () => { + let diff + let newVariants + let oldVariants + beforeEach(() => { + diff = { + _t: 'a', + _3: ['', 0, 3], + _4: [{ id: 10 }, 0, 0], + _5: ['', 1, 3], + } + oldVariants = [ + { id: 3 }, + { id: 4 }, + { id: 5 }, + { id: 1 }, + { id: 10 }, + { id: 2 }, + ] + newVariants = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }] + }) + + test('should find matching pairs', () => { + const actualResult = findMatchingPairs(diff, oldVariants, newVariants) + const expectedResult = { + _3: ['3', '0'], + _4: ['4', undefined], + _5: ['5', '1'], + } + expect(actualResult).toEqual(expectedResult) + }) +}) diff --git a/packages/sync-actions/test/zones.spec.ts b/packages/sync-actions/test/zones.spec.ts new file mode 100644 index 000000000..692561c57 --- /dev/null +++ b/packages/sync-actions/test/zones.spec.ts @@ -0,0 +1,214 @@ +import zonesSyncFn, { actionGroups } from '../src/zones' +import { baseActionsList } from '../src/zones-actions' + +describe('Exports', () => { + test('action group list', () => { + expect(actionGroups).toEqual(['base', 'locations']) + }) + + test('correctly define base actions list', () => { + expect(baseActionsList).toEqual([ + { action: 'changeName', key: 'name' }, + { action: 'setDescription', key: 'description' }, + { action: 'setKey', key: 'key' }, + ]) + }) +}) + +describe('Actions', () => { + let zonesSync + beforeEach(() => { + zonesSync = zonesSyncFn() + }) + + test('should build `changeName` action', () => { + const before = { + name: 'Europe', + } + const now = { + name: 'Asia', + } + + const actual = zonesSync.buildActions(now, before) + const expected = [{ action: 'changeName', name: now.name }] + expect(actual).toEqual(expected) + }) + + test('should build `setDescription` action', () => { + const before = { + description: 'Zone for Europe', + } + const now = { + description: 'Zone for Asia', + } + + const actual = zonesSync.buildActions(now, before) + const expected = [ + { + action: 'setDescription', + description: now.description, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setKey` action', () => { + const before = { + key: 'key-before', + } + + const now = { + key: 'key-now', + } + + const actual = zonesSync.buildActions(now, before) + const expected = [ + { + action: 'setKey', + key: 'key-now', + }, + ] + expect(actual).toEqual(expected) + }) + + describe('`addLocation`', () => { + test('should build `addLocation` action with one location', () => { + const before = { locations: [] } + const now = { locations: [{ country: 'Spain' }] } + + const actual = zonesSync.buildActions(now, before) + const expected = [{ action: 'addLocation', location: now.locations[0] }] + expect(actual).toEqual(expected) + }) + test('should build `addLocation` action with two locations', () => { + const before = { locations: [] } + const now = { locations: [{ country: 'Spain' }, { country: 'Italy' }] } + + const actual = zonesSync.buildActions(now, before) + const expected = [ + { action: 'addLocation', location: now.locations[0] }, + { action: 'addLocation', location: now.locations[1] }, + ] + expect(actual).toEqual(expected) + }) + }) + + describe('`removeLocation`', () => { + test('should build `removeLocation` action removing one location', () => { + const before = { + locations: [{ country: 'Spain' }, { country: 'Italy' }], + } + const now = { locations: [{ country: 'Spain' }] } + + const actual = zonesSync.buildActions(now, before) + const expected = [ + { action: 'removeLocation', location: before.locations[1] }, + ] + expect(actual).toEqual(expected) + }) + test('should build `removeLocation` action removing two locations', () => { + const before = { + locations: [{ country: 'Spain' }, { country: 'Italy' }], + } + const now = { locations: [] } + + const actual = zonesSync.buildActions(now, before) + const expected = [ + { action: 'removeLocation', location: before.locations[0] }, + { action: 'removeLocation', location: before.locations[1] }, + ] + expect(actual).toEqual(expected) + }) + }) + + describe('Swap locations (create one + delete one)', () => { + test('should build `removeLocation` and `addLocation`', () => { + const before = { locations: [{ country: 'Spain' }] } + const now = { locations: [{ country: 'Italy' }] } + + const actual = zonesSync.buildActions(now, before) + const expected = [ + { action: 'removeLocation', location: before.locations[0] }, + { action: 'addLocation', location: now.locations[0] }, + ] + expect(actual).toEqual(expected) + }) + }) + + describe('Multiple actions', () => { + test('should build multiple actions for required changes', () => { + const before = { + locations: [{ country: 'Spain' }, { country: 'France' }], + } + const now = { + locations: [ + { country: 'Italy' }, + { country: 'France' }, + { country: 'Germany' }, + ], + } + + const actual = zonesSync.buildActions(now, before) + const expected = [ + { action: 'removeLocation', location: before.locations[0] }, + { action: 'addLocation', location: now.locations[0] }, + { action: 'addLocation', location: now.locations[2] }, + ] + expect(actual).toEqual(expected) + }) + }) + + describe('Delete first locations', () => { + test('should build multiple actions for required changes', () => { + const before = { + locations: [ + { country: 'Spain' }, + { country: 'Italy' }, + { country: 'France' }, + ], + } + const now = { + locations: [{ country: 'France' }], + } + + const actual = zonesSync.buildActions(now, before) + const expected = [ + { action: 'removeLocation', location: before.locations[0] }, + { action: 'removeLocation', location: before.locations[1] }, + ] + expect(actual).toEqual(expected) + }) + }) + + describe('Delete multiple locations', () => { + test('should build multiple actions for required changes', () => { + const before = { + locations: [ + { country: 'Spain' }, + { country: 'Italy' }, + { country: 'Poland' }, + { country: 'France' }, + { country: 'Portugal' }, + { country: 'Germany' }, + ], + } + const now = { + locations: [ + { country: 'Italy' }, + { country: 'Poland' }, + { country: 'Portugal' }, + { country: 'Russia' }, + ], + } + + const actual = zonesSync.buildActions(now, before) + const expected = [ + { action: 'removeLocation', location: before.locations[0] }, + { action: 'removeLocation', location: before.locations[3] }, + { action: 'addLocation', location: now.locations[3] }, + { action: 'removeLocation', location: before.locations[5] }, + ] + expect(actual).toEqual(expected) + }) + }) +}) From 23ffa139e6189c01d8bf232eb6a61c69b1fdcaaf Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Tue, 7 Nov 2023 11:33:10 +0100 Subject: [PATCH 02/33] feat(migrate): run tests --- ...t-types-sync-attribute-hints.spec.ts.snap} | 78 +++++++++---------- 1 file changed, 39 insertions(+), 39 deletions(-) rename packages/sync-actions/test/__snapshots__/{product-types-sync-attribute-hints.spec.js.snap => product-types-sync-attribute-hints.spec.ts.snap} (84%) diff --git a/packages/sync-actions/test/__snapshots__/product-types-sync-attribute-hints.spec.js.snap b/packages/sync-actions/test/__snapshots__/product-types-sync-attribute-hints.spec.ts.snap similarity index 84% rename from packages/sync-actions/test/__snapshots__/product-types-sync-attribute-hints.spec.js.snap rename to packages/sync-actions/test/__snapshots__/product-types-sync-attribute-hints.spec.ts.snap index 008887c01..8f28203de 100644 --- a/packages/sync-actions/test/__snapshots__/product-types-sync-attribute-hints.spec.js.snap +++ b/packages/sync-actions/test/__snapshots__/product-types-sync-attribute-hints.spec.ts.snap @@ -1,17 +1,17 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`product type hints attribute enum values with previous with changes when is localized should match snapshot 1`] = ` -Array [ - Object { +[ + { "action": "changeEnumKey", "attributeName": "attribute-name", "key": "enum-key", "newKey": "next-key", }, - Object { + { "action": "changeLocalizedEnumValueLabel", "attributeName": "attribute-name", - "newValue": Object { + "newValue": { "key": "next-key", "label": "next-label", }, @@ -20,17 +20,17 @@ Array [ `; exports[`product type hints attribute enum values with previous with changes when is not localized should match snapshot 1`] = ` -Array [ - Object { +[ + { "action": "changeEnumKey", "attributeName": "attribute-name", "key": "enum-key", "newKey": "next-key", }, - Object { + { "action": "changePlainEnumValueLabel", "attributeName": "attribute-name", - "newValue": Object { + "newValue": { "key": "next-key", "label": "next-label", }, @@ -39,33 +39,33 @@ Array [ `; exports[`product type hints attribute enum values with previous with changes when removing, adding, and editing (in a single batch of actions) should match snapshot 1`] = ` -Array [ - Object { +[ + { "action": "removeEnumValues", "attributeName": "attribute-enum-with-2-enum-values-to-remove", - "keys": Array [ + "keys": [ "enum-key-1", "enum-key-2", ], }, - Object { + { "action": "changeEnumKey", "attributeName": "attribute-name", "key": "enum-key", "newKey": "next-enum-draft-item", }, - Object { + { "action": "changePlainEnumValueLabel", "attributeName": "attribute-name", - "newValue": Object { + "newValue": { "key": "next-enum-draft-item", "label": undefined, }, }, - Object { + { "action": "addPlainEnumValue", "attributeName": "attribute-name", - "value": Object { + "value": { "key": "new-enum-draft-item", "label": "new-enum-draft-item", }, @@ -74,11 +74,11 @@ Array [ `; exports[`product type hints attribute enum values without previous should match snapshot 1`] = ` -Array [ - Object { +[ + { "action": "addPlainEnumValue", "attributeName": "attribute-name", - "value": Object { + "value": { "key": "enum-key", "label": "enum-label", }, @@ -87,11 +87,11 @@ Array [ `; exports[`product type hints attribute enum values without previous when is localized should match snapshot 1`] = ` -Array [ - Object { +[ + { "action": "addLocalizedEnumValue", "attributeName": "attribute-name", - "value": Object { + "value": { "key": "enum-key", "label": "enum-label", }, @@ -100,32 +100,32 @@ Array [ `; exports[`product type hints attribute hints with previous with next with changes should match snapshot 1`] = ` -Array [ - Object { +[ + { "action": "changeLabel", "attributeName": "attribute-name", - "label": Object { + "label": { "en": "next-attribute-label", }, }, - Object { + { "action": "setInputTip", "attributeName": "attribute-name", - "inputTip": Object { + "inputTip": { "en": "next-input-tip", }, }, - Object { + { "action": "changeInputHint", "attributeName": "attribute-name", "newValue": "MultiLine", }, - Object { + { "action": "changeIsSearchable", "attributeName": "attribute-name", "isSearchable": true, }, - Object { + { "action": "changeAttributeConstraint", "attributeName": "attribute-name", "newValue": "None", @@ -133,11 +133,11 @@ Array [ ] `; -exports[`product type hints attribute hints with previous with next with no changes should match snapshot 1`] = `Array []`; +exports[`product type hints attribute hints with previous with next with no changes should match snapshot 1`] = `[]`; exports[`product type hints attribute hints with previous without next should match snapshot 1`] = ` -Array [ - Object { +[ + { "action": "removeAttributeDefinition", "name": "attribute-name", }, @@ -145,22 +145,22 @@ Array [ `; exports[`product type hints attribute hints without previous should match snapshot 1`] = ` -Array [ - Object { +[ + { "action": "addAttributeDefinition", - "attribute": Object { + "attribute": { "attributeConstraint": "SameForAll", "inputHint": "SingleLine", - "inputTip": Object { + "inputTip": { "en": "input-hint", }, "isRequired": false, "isSearchable": false, - "label": Object { + "label": { "en": "attribute-label", }, "name": "attribute-name", - "type": Object { + "type": { "name": "text", }, }, From 26d555fc62598d86b6e1be2c83b2d8ddd8894309 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Tue, 7 Nov 2023 11:33:21 +0100 Subject: [PATCH 03/33] feat(migrate): remove @flow --- packages/sync-actions/src/attribute-groups.ts | 1 - packages/sync-actions/src/categories.ts | 1 - packages/sync-actions/src/customers.ts | 1 - packages/sync-actions/src/inventories.ts | 1 - packages/sync-actions/src/orders.ts | 1 - packages/sync-actions/src/prices.ts | 1 - packages/sync-actions/src/product-selections.ts | 1 - packages/sync-actions/src/product-types.ts | 1 - packages/sync-actions/src/products.ts | 1 - packages/sync-actions/src/quote-requests.ts | 1 - packages/sync-actions/src/quotes.ts | 1 - packages/sync-actions/src/shipping-methods.ts | 1 - packages/sync-actions/src/staged-quotes.ts | 1 - packages/sync-actions/src/states.ts | 1 - packages/sync-actions/src/stores.ts | 1 - packages/sync-actions/src/tax-categories.ts | 1 - packages/sync-actions/src/zones.ts | 1 - 17 files changed, 17 deletions(-) diff --git a/packages/sync-actions/src/attribute-groups.ts b/packages/sync-actions/src/attribute-groups.ts index a193f76c5..9da8772ea 100644 --- a/packages/sync-actions/src/attribute-groups.ts +++ b/packages/sync-actions/src/attribute-groups.ts @@ -1,4 +1,3 @@ -/* @flow */ import flatten from 'lodash.flatten' import type { SyncAction, diff --git a/packages/sync-actions/src/categories.ts b/packages/sync-actions/src/categories.ts index 92d71f098..e91dfc7fd 100644 --- a/packages/sync-actions/src/categories.ts +++ b/packages/sync-actions/src/categories.ts @@ -1,4 +1,3 @@ -/* @flow */ import flatten from 'lodash.flatten' import type { SyncAction, diff --git a/packages/sync-actions/src/customers.ts b/packages/sync-actions/src/customers.ts index 5e91f6bb1..e96cf08d6 100644 --- a/packages/sync-actions/src/customers.ts +++ b/packages/sync-actions/src/customers.ts @@ -1,4 +1,3 @@ -/* @flow */ import flatten from 'lodash.flatten' import type { SyncAction, diff --git a/packages/sync-actions/src/inventories.ts b/packages/sync-actions/src/inventories.ts index 1ed7edf38..7ff26734b 100644 --- a/packages/sync-actions/src/inventories.ts +++ b/packages/sync-actions/src/inventories.ts @@ -1,4 +1,3 @@ -/* @flow */ import flatten from 'lodash.flatten' import type { SyncAction, diff --git a/packages/sync-actions/src/orders.ts b/packages/sync-actions/src/orders.ts index 01a22a7d1..8c4238245 100644 --- a/packages/sync-actions/src/orders.ts +++ b/packages/sync-actions/src/orders.ts @@ -1,4 +1,3 @@ -/* @flow */ import flatten from 'lodash.flatten' import type { SyncAction, diff --git a/packages/sync-actions/src/prices.ts b/packages/sync-actions/src/prices.ts index ce4b7928c..6e7184f6e 100644 --- a/packages/sync-actions/src/prices.ts +++ b/packages/sync-actions/src/prices.ts @@ -1,4 +1,3 @@ -/* @flow */ import type { SyncAction, SyncActionConfig, diff --git a/packages/sync-actions/src/product-selections.ts b/packages/sync-actions/src/product-selections.ts index 1969eaf12..4f954a655 100644 --- a/packages/sync-actions/src/product-selections.ts +++ b/packages/sync-actions/src/product-selections.ts @@ -1,4 +1,3 @@ -/* @flow */ import flatten from 'lodash.flatten' import type { SyncAction, diff --git a/packages/sync-actions/src/product-types.ts b/packages/sync-actions/src/product-types.ts index b5ca614f9..fbf61b177 100644 --- a/packages/sync-actions/src/product-types.ts +++ b/packages/sync-actions/src/product-types.ts @@ -1,4 +1,3 @@ -/* @flow */ import flatten from 'lodash.flatten' import type { SyncAction, diff --git a/packages/sync-actions/src/products.ts b/packages/sync-actions/src/products.ts index b1d504be6..6edd85ba9 100644 --- a/packages/sync-actions/src/products.ts +++ b/packages/sync-actions/src/products.ts @@ -1,4 +1,3 @@ -/* @flow */ import flatten from 'lodash.flatten' import type { SyncAction, diff --git a/packages/sync-actions/src/quote-requests.ts b/packages/sync-actions/src/quote-requests.ts index 2a1f13ce0..98fad5450 100644 --- a/packages/sync-actions/src/quote-requests.ts +++ b/packages/sync-actions/src/quote-requests.ts @@ -1,4 +1,3 @@ -/* @flow */ import flatten from 'lodash.flatten' import type { SyncAction, diff --git a/packages/sync-actions/src/quotes.ts b/packages/sync-actions/src/quotes.ts index 1eedeb6d8..99d221cba 100644 --- a/packages/sync-actions/src/quotes.ts +++ b/packages/sync-actions/src/quotes.ts @@ -1,4 +1,3 @@ -/* @flow */ import flatten from 'lodash.flatten' import type { SyncAction, diff --git a/packages/sync-actions/src/shipping-methods.ts b/packages/sync-actions/src/shipping-methods.ts index f94aec3c0..67426fbe9 100644 --- a/packages/sync-actions/src/shipping-methods.ts +++ b/packages/sync-actions/src/shipping-methods.ts @@ -1,4 +1,3 @@ -/* @flow */ import flatten from 'lodash.flatten' import type { SyncAction, diff --git a/packages/sync-actions/src/staged-quotes.ts b/packages/sync-actions/src/staged-quotes.ts index fb98232e4..62c93b1a2 100644 --- a/packages/sync-actions/src/staged-quotes.ts +++ b/packages/sync-actions/src/staged-quotes.ts @@ -1,4 +1,3 @@ -/* @flow */ import flatten from 'lodash.flatten' import type { SyncAction, diff --git a/packages/sync-actions/src/states.ts b/packages/sync-actions/src/states.ts index c18e26fc5..fe13b69cd 100644 --- a/packages/sync-actions/src/states.ts +++ b/packages/sync-actions/src/states.ts @@ -1,4 +1,3 @@ -/* @flow */ import flatten from 'lodash.flatten' import type { UpdateAction, diff --git a/packages/sync-actions/src/stores.ts b/packages/sync-actions/src/stores.ts index de9df04c1..0f9f2ce08 100644 --- a/packages/sync-actions/src/stores.ts +++ b/packages/sync-actions/src/stores.ts @@ -1,4 +1,3 @@ -/* @flow */ import flatten from 'lodash.flatten' import type { SyncAction, diff --git a/packages/sync-actions/src/tax-categories.ts b/packages/sync-actions/src/tax-categories.ts index f5b2e5bbe..8b93b493f 100644 --- a/packages/sync-actions/src/tax-categories.ts +++ b/packages/sync-actions/src/tax-categories.ts @@ -1,4 +1,3 @@ -/* @flow */ import flatten from 'lodash.flatten' import type { SyncAction, diff --git a/packages/sync-actions/src/zones.ts b/packages/sync-actions/src/zones.ts index e2aad4a9f..4dfcb0481 100644 --- a/packages/sync-actions/src/zones.ts +++ b/packages/sync-actions/src/zones.ts @@ -1,4 +1,3 @@ -/* @flow */ import flatten from 'lodash.flatten' import type { SyncAction, From b61881da85e67dd82012966684636f389d095ab4 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Tue, 7 Nov 2023 11:44:42 +0100 Subject: [PATCH 04/33] feat(migrate): remove lodash.flatten --- packages/sync-actions/package.json | 1 - packages/sync-actions/src/attribute-groups.ts | 15 ++++++--------- packages/sync-actions/src/cart-discounts.ts | 3 +-- packages/sync-actions/src/categories.ts | 3 +-- packages/sync-actions/src/channels.ts | 3 +-- packages/sync-actions/src/customer-group.ts | 3 +-- packages/sync-actions/src/customers.ts | 3 +-- packages/sync-actions/src/discount-codes.ts | 3 +-- packages/sync-actions/src/inventories.ts | 3 +-- packages/sync-actions/src/orders.ts | 15 ++++++--------- packages/sync-actions/src/product-discounts.ts | 3 +-- packages/sync-actions/src/product-selections.ts | 3 +-- .../sync-actions/src/product-types-actions.ts | 13 ++++++------- packages/sync-actions/src/product-types.ts | 5 ++--- packages/sync-actions/src/products.ts | 5 ++--- packages/sync-actions/src/projects.ts | 3 +-- packages/sync-actions/src/quote-requests.ts | 3 +-- packages/sync-actions/src/quotes.ts | 3 +-- .../sync-actions/src/shipping-methods-actions.ts | 5 ++--- packages/sync-actions/src/shipping-methods.ts | 15 ++++++--------- packages/sync-actions/src/staged-quotes.ts | 3 +-- packages/sync-actions/src/states.ts | 3 +-- packages/sync-actions/src/stores.ts | 3 +-- packages/sync-actions/src/tax-categories.ts | 3 +-- packages/sync-actions/src/types-actions.ts | 9 ++++----- packages/sync-actions/src/types.ts | 4 +--- packages/sync-actions/src/zones.ts | 15 ++++++--------- 27 files changed, 57 insertions(+), 93 deletions(-) diff --git a/packages/sync-actions/package.json b/packages/sync-actions/package.json index ead2f182a..522e272bf 100644 --- a/packages/sync-actions/package.json +++ b/packages/sync-actions/package.json @@ -25,7 +25,6 @@ "dependencies": { "fast-equals": "^2.0.0", "jsondiffpatch": "^0.4.0", - "lodash.flatten": "^4.4.0", "lodash.foreach": "^4.5.0", "lodash.intersection": "^4.4.0", "lodash.isequal": "^4.5.0", diff --git a/packages/sync-actions/src/attribute-groups.ts b/packages/sync-actions/src/attribute-groups.ts index 9da8772ea..aac5f4cc3 100644 --- a/packages/sync-actions/src/attribute-groups.ts +++ b/packages/sync-actions/src/attribute-groups.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import type { SyncAction, ActionGroup, @@ -36,15 +35,13 @@ function createAttributeGroupsMapActions( ) ) allActions.push( - flatten( - mapActionGroup( - 'attributes', - (): Array => - attributeGroupsActions.actionsMapAttributes(diff, oldObj, newObj) - ) - ) + mapActionGroup( + 'attributes', + (): Array => + attributeGroupsActions.actionsMapAttributes(diff, oldObj, newObj) + ).flat() ) - return flatten(allActions) + return allActions.flat() } } diff --git a/packages/sync-actions/src/cart-discounts.ts b/packages/sync-actions/src/cart-discounts.ts index 3c7c2b941..de57ae4bb 100644 --- a/packages/sync-actions/src/cart-discounts.ts +++ b/packages/sync-actions/src/cart-discounts.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import actionsMapCustom from './utils/action-map-custom' @@ -23,7 +22,7 @@ function createCartDiscountsMapActions(mapActionGroup, syncActionConfig) { mapActionGroup('custom', () => actionsMapCustom(diff, newObj, oldObj)) ) - return combineValidityActions(flatten(allActions)) + return combineValidityActions(allActions.flat()) } } diff --git a/packages/sync-actions/src/categories.ts b/packages/sync-actions/src/categories.ts index e91dfc7fd..b904c5407 100644 --- a/packages/sync-actions/src/categories.ts +++ b/packages/sync-actions/src/categories.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import type { SyncAction, SyncActionConfig, @@ -64,7 +63,7 @@ function createCategoryMapActions( ) ) - return flatten(allActions) + return allActions.flat() } } diff --git a/packages/sync-actions/src/channels.ts b/packages/sync-actions/src/channels.ts index a59a86077..0a5260521 100644 --- a/packages/sync-actions/src/channels.ts +++ b/packages/sync-actions/src/channels.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import actionsMapCustom from './utils/action-map-custom' @@ -22,7 +21,7 @@ function createChannelsMapActions(mapActionGroup, syncActionConfig) { mapActionGroup('custom', () => actionsMapCustom(diff, newObj, oldObj)) ) - return flatten(allActions) + return allActions.flat() } } diff --git a/packages/sync-actions/src/customer-group.ts b/packages/sync-actions/src/customer-group.ts index 3ea3949d2..08225537d 100644 --- a/packages/sync-actions/src/customer-group.ts +++ b/packages/sync-actions/src/customer-group.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import actionsMapCustom from './utils/action-map-custom' @@ -22,7 +21,7 @@ function createCustomerGroupMapActions(mapActionGroup, syncActionConfig) { mapActionGroup('custom', () => actionsMapCustom(diff, newObj, oldObj)) ) - return flatten(allActions) + return allActions.flat() } } diff --git a/packages/sync-actions/src/customers.ts b/packages/sync-actions/src/customers.ts index e96cf08d6..60e4dd599 100644 --- a/packages/sync-actions/src/customers.ts +++ b/packages/sync-actions/src/customers.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import type { SyncAction, SyncActionConfig, @@ -99,7 +98,7 @@ function createCustomerMapActions( ) ) - return flatten(allActions) + return allActions.flat() } } diff --git a/packages/sync-actions/src/discount-codes.ts b/packages/sync-actions/src/discount-codes.ts index d864de17a..dfbb230bb 100644 --- a/packages/sync-actions/src/discount-codes.ts +++ b/packages/sync-actions/src/discount-codes.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import actionsMapCustom from './utils/action-map-custom' @@ -20,7 +19,7 @@ function createDiscountCodesMapActions(mapActionGroup, syncActionConfig) { allActions.push( mapActionGroup('custom', () => actionsMapCustom(diff, newObj, oldObj)) ) - return combineValidityActions(flatten(allActions)) + return combineValidityActions(allActions.flat()) } } diff --git a/packages/sync-actions/src/inventories.ts b/packages/sync-actions/src/inventories.ts index 7ff26734b..c3ed1045d 100644 --- a/packages/sync-actions/src/inventories.ts +++ b/packages/sync-actions/src/inventories.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import type { SyncAction, SyncActionConfig, @@ -48,7 +47,7 @@ function createInventoryMapActions( (): Array => actionsMapCustom(diff, newObj, oldObj) ) ) - return flatten(allActions) + return allActions.flat() } } diff --git a/packages/sync-actions/src/orders.ts b/packages/sync-actions/src/orders.ts index 8c4238245..81fbacc07 100644 --- a/packages/sync-actions/src/orders.ts +++ b/packages/sync-actions/src/orders.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import type { SyncAction, SyncActionConfig, @@ -72,20 +71,18 @@ function createOrderMapActions( ) allActions.push( - flatten( - mapActionGroup( - 'returnInfo', - (): Array => - orderActions.actionsMapReturnsInfo(diff, oldObj, newObj) - ) - ) + mapActionGroup( + 'returnInfo', + (): Array => + orderActions.actionsMapReturnsInfo(diff, oldObj, newObj) + ).flat() ) allActions.push( mapActionGroup('custom', () => actionsMapCustom(diff, newObj, oldObj)) ) - return flatten(allActions) + return allActions.flat() } } diff --git a/packages/sync-actions/src/product-discounts.ts b/packages/sync-actions/src/product-discounts.ts index 3bfd17574..7d0b1b5b7 100644 --- a/packages/sync-actions/src/product-discounts.ts +++ b/packages/sync-actions/src/product-discounts.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import { actionsMapBase } from './product-discounts-actions' @@ -17,7 +16,7 @@ function createProductDiscountsMapActions(mapActionGroup, syncActionConfig) { actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) - return combineValidityActions(flatten(allActions)) + return combineValidityActions(allActions.flat()) } } diff --git a/packages/sync-actions/src/product-selections.ts b/packages/sync-actions/src/product-selections.ts index 4f954a655..a34d2dcdb 100644 --- a/packages/sync-actions/src/product-selections.ts +++ b/packages/sync-actions/src/product-selections.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import type { SyncAction, UpdateAction, @@ -38,7 +37,7 @@ function createProductSelectionsMapActions( ) ) - return flatten(allActions) + return allActions.flat() } } diff --git a/packages/sync-actions/src/product-types-actions.ts b/packages/sync-actions/src/product-types-actions.ts index afb926e1d..96802b3fe 100644 --- a/packages/sync-actions/src/product-types-actions.ts +++ b/packages/sync-actions/src/product-types-actions.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import { deepEqual } from 'fast-equals' import { createIsEmptyValue, @@ -135,8 +134,8 @@ const generateUpdateActionsForAttributeDefinitions = ( action: 'removeAttributeDefinition', name: attributeDef.previous.name, })), - ...flatten( - updatedAttributeDefinitions.map((updatedAttributeDefinition) => + ...updatedAttributeDefinitions + .map((updatedAttributeDefinition) => generateBaseFieldsUpdateActions( updatedAttributeDefinition.previous, updatedAttributeDefinition.next, @@ -164,7 +163,7 @@ const generateUpdateActionsForAttributeDefinitions = ( } ) ) - ), + .flat(), ...addedAttributeDefinitions.map((attributeDef) => ({ action: 'addAttributeDefinition', attribute: attributeDef.next, @@ -213,8 +212,8 @@ const generateUpdateActionsForAttributeEnumValues = ( {} ) ), - ...flatten( - updatedAttributeEnumValues.map((updatedAttributeEnumValue) => { + ...updatedAttributeEnumValues + .map((updatedAttributeEnumValue) => { const updateActions = generateBaseFieldsUpdateActions( updatedAttributeEnumValue.previous, updatedAttributeEnumValue.next, @@ -252,7 +251,7 @@ const generateUpdateActionsForAttributeEnumValues = ( } return updateActions }) - ), + .flat(), ...addedAttributeEnumValues.map((addedAttributeEnumValue) => ({ action: addedAttributeEnumValue.hint.isLocalized ? 'addLocalizedEnumValue' diff --git a/packages/sync-actions/src/product-types.ts b/packages/sync-actions/src/product-types.ts index fbf61b177..817d7daa9 100644 --- a/packages/sync-actions/src/product-types.ts +++ b/packages/sync-actions/src/product-types.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import type { SyncAction, UpdateAction, @@ -27,7 +26,7 @@ function createProductTypeMapActions( previous: any, options: any ): Array { - return flatten([ + return [ // we support only base fields for the product type, // for attributes, applying hints would be recommended mapActionGroup( @@ -45,7 +44,7 @@ function createProductTypeMapActions( previous, next ), - ]) + ].flat() } } diff --git a/packages/sync-actions/src/products.ts b/packages/sync-actions/src/products.ts index 6edd85ba9..0db1bcbbd 100644 --- a/packages/sync-actions/src/products.ts +++ b/packages/sync-actions/src/products.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import type { SyncAction, SyncActionConfig, @@ -160,9 +159,9 @@ function createProductMapActions( ) if (publish === true || staged === false) - return flatten(allActions).map((action) => ({ ...action, staged: false })) + return allActions.flat().map((action) => ({ ...action, staged: false })) - return flatten(allActions) + return allActions.flat() } } diff --git a/packages/sync-actions/src/projects.ts b/packages/sync-actions/src/projects.ts index 848de9de9..a98f62fe3 100644 --- a/packages/sync-actions/src/projects.ts +++ b/packages/sync-actions/src/projects.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import { actionsMapBase } from './projects-actions' @@ -16,7 +15,7 @@ function createChannelsMapActions(mapActionGroup, syncActionConfig) { ) ) - return flatten(allActions) + return allActions.flat() } } diff --git a/packages/sync-actions/src/quote-requests.ts b/packages/sync-actions/src/quote-requests.ts index 98fad5450..c76e52e90 100644 --- a/packages/sync-actions/src/quote-requests.ts +++ b/packages/sync-actions/src/quote-requests.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import type { SyncAction, SyncActionConfig, @@ -44,7 +43,7 @@ function createQuoteRequestsMapActions( ) ) - return flatten(allActions) + return allActions.flat() } } diff --git a/packages/sync-actions/src/quotes.ts b/packages/sync-actions/src/quotes.ts index 99d221cba..71ab5b432 100644 --- a/packages/sync-actions/src/quotes.ts +++ b/packages/sync-actions/src/quotes.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import type { SyncAction, SyncActionConfig, @@ -39,7 +38,7 @@ function createQuotesMapActions( ) ) - return flatten(allActions) + return allActions.flat() } } diff --git a/packages/sync-actions/src/shipping-methods-actions.ts b/packages/sync-actions/src/shipping-methods-actions.ts index 57cea1fc8..2110b99c8 100644 --- a/packages/sync-actions/src/shipping-methods-actions.ts +++ b/packages/sync-actions/src/shipping-methods-actions.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import createBuildArrayActions, { ADD_ACTIONS, REMOVE_ACTIONS, @@ -104,7 +103,7 @@ export function actionsMapZoneRates(diff, oldObj, newObj) { [] ) - return flatten( + return ( hasZoneActions ? [ ...shippingRateActions, @@ -120,7 +119,7 @@ export function actionsMapZoneRates(diff, oldObj, newObj) { ], ] : shippingRateActions - ) + ).flat() }, }) diff --git a/packages/sync-actions/src/shipping-methods.ts b/packages/sync-actions/src/shipping-methods.ts index 67426fbe9..9c28ec182 100644 --- a/packages/sync-actions/src/shipping-methods.ts +++ b/packages/sync-actions/src/shipping-methods.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import type { SyncAction, SyncActionConfig, @@ -36,13 +35,11 @@ function createShippingMethodsMapActions( ) ) allActions.push( - flatten( - mapActionGroup( - 'zoneRates', - (): Array => - shippingMethodsActions.actionsMapZoneRates(diff, oldObj, newObj) - ) - ) + mapActionGroup( + 'zoneRates', + (): Array => + shippingMethodsActions.actionsMapZoneRates(diff, oldObj, newObj) + ).flat() ) allActions.push( mapActionGroup( @@ -50,7 +47,7 @@ function createShippingMethodsMapActions( (): Array => actionsMapCustom(diff, newObj, oldObj) ) ) - return flatten(allActions) + return allActions.flat() } } diff --git a/packages/sync-actions/src/staged-quotes.ts b/packages/sync-actions/src/staged-quotes.ts index 62c93b1a2..b55a50bb2 100644 --- a/packages/sync-actions/src/staged-quotes.ts +++ b/packages/sync-actions/src/staged-quotes.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import type { SyncAction, SyncActionConfig, @@ -44,7 +43,7 @@ function createStagedQuotesMapActions( ) ) - return flatten(allActions) + return allActions.flat() } } diff --git a/packages/sync-actions/src/states.ts b/packages/sync-actions/src/states.ts index fe13b69cd..484c0c060 100644 --- a/packages/sync-actions/src/states.ts +++ b/packages/sync-actions/src/states.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import type { UpdateAction, SyncAction, @@ -56,7 +55,7 @@ function createStatesMapActions( stateActions.actionsMapRoles(diff, oldObj, newObj) ) ) - return flatten([...baseActions, ...groupRoleActions(roleActions)]) + return [...baseActions, ...groupRoleActions(roleActions)].flat() } } diff --git a/packages/sync-actions/src/stores.ts b/packages/sync-actions/src/stores.ts index 0f9f2ce08..83aead82c 100644 --- a/packages/sync-actions/src/stores.ts +++ b/packages/sync-actions/src/stores.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import type { SyncAction, UpdateAction, @@ -38,7 +37,7 @@ function createStoresMapActions( ) ) - return flatten(allActions) + return allActions.flat() } } diff --git a/packages/sync-actions/src/tax-categories.ts b/packages/sync-actions/src/tax-categories.ts index 8b93b493f..542d2cf59 100644 --- a/packages/sync-actions/src/tax-categories.ts +++ b/packages/sync-actions/src/tax-categories.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import type { SyncAction, ActionGroup, @@ -44,7 +43,7 @@ function createTaxCategoriesMapActions( taxCategoriesActions.actionsMapRates(diff, oldObj, newObj) ) ) - return flatten(allActions) + return allActions.flat() } } diff --git a/packages/sync-actions/src/types-actions.ts b/packages/sync-actions/src/types-actions.ts index 1b8f9bd43..2123e09ae 100644 --- a/packages/sync-actions/src/types-actions.ts +++ b/packages/sync-actions/src/types-actions.ts @@ -1,5 +1,4 @@ import forEach from 'lodash.foreach' -import flatten from 'lodash.flatten' import sortBy from 'lodash.sortby' import isEqual from 'lodash.isequal' @@ -112,13 +111,13 @@ function actionsMapEnums( // order of enumValues, we generate one updateAction instead of one at a time. let newEnumValuesOrder = [] - flatten(buildArrayActions(attributeDiff, previous, next)).forEach( - (updateAction) => { + buildArrayActions(attributeDiff, previous, next) + .flat() + .forEach((updateAction) => { if (updateAction.action === changeEnumOrderActionName) { newEnumValuesOrder = next.values.map((enumValue) => enumValue.key) } else actions.push(updateAction) - } - ) + }) return [ ...actions, diff --git a/packages/sync-actions/src/types.ts b/packages/sync-actions/src/types.ts index 9627e80d1..4564e6048 100644 --- a/packages/sync-actions/src/types.ts +++ b/packages/sync-actions/src/types.ts @@ -1,5 +1,3 @@ -import flatten from 'lodash.flatten' - import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import * as typeActions from './types-actions' @@ -33,7 +31,7 @@ function createTypeMapActions( ) ) ) - return flatten(allActions) + return allActions.flat() } } diff --git a/packages/sync-actions/src/zones.ts b/packages/sync-actions/src/zones.ts index 4dfcb0481..003efc88c 100644 --- a/packages/sync-actions/src/zones.ts +++ b/packages/sync-actions/src/zones.ts @@ -1,4 +1,3 @@ -import flatten from 'lodash.flatten' import type { SyncAction, ActionGroup, @@ -33,15 +32,13 @@ function createZonesMapActions( ) ) allActions.push( - flatten( - mapActionGroup( - 'locations', - (): Array => - zonesActions.actionsMapLocations(diff, oldObj, newObj) - ) - ) + mapActionGroup( + 'locations', + (): Array => + zonesActions.actionsMapLocations(diff, oldObj, newObj) + ).flat() ) - return flatten(allActions) + return allActions.flat() } } From dd3ffc4290e4ddcf3f184648ebed3883113ec335 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Tue, 7 Nov 2023 12:57:59 +0100 Subject: [PATCH 05/33] feat(migrate): remove lodash.forEach --- packages/sync-actions/package.json | 1 - packages/sync-actions/src/order-actions.ts | 64 +- packages/sync-actions/src/product-actions.ts | 609 +++++++++--------- packages/sync-actions/src/types-actions.ts | 104 +-- .../src/utils/find-matching-pairs.ts | 23 +- 5 files changed, 412 insertions(+), 389 deletions(-) diff --git a/packages/sync-actions/package.json b/packages/sync-actions/package.json index 522e272bf..69af8179b 100644 --- a/packages/sync-actions/package.json +++ b/packages/sync-actions/package.json @@ -25,7 +25,6 @@ "dependencies": { "fast-equals": "^2.0.0", "jsondiffpatch": "^0.4.0", - "lodash.foreach": "^4.5.0", "lodash.intersection": "^4.4.0", "lodash.isequal": "^4.5.0", "lodash.isnil": "^4.0.0", diff --git a/packages/sync-actions/src/order-actions.ts b/packages/sync-actions/src/order-actions.ts index 6d9a9fe15..e64ac5e97 100644 --- a/packages/sync-actions/src/order-actions.ts +++ b/packages/sync-actions/src/order-actions.ts @@ -1,4 +1,3 @@ -import forEach from 'lodash.foreach' import * as diffpatcher from './utils/diffpatcher' import { buildBaseAttributesActions } from './utils/common-actions' import createBuildArrayActions, { @@ -71,30 +70,31 @@ function _buildDeliveryParcelsAction( oldDelivery.parcels, newDelivery.parcels ) - forEach(diffedParcels, (parcel, key) => { - const { oldObj } = extractMatchingPairs( - matchingParcelPairs, - key, - oldDelivery.parcels, - newDelivery.parcels - ) + diffedParcels && + Object.entries(diffedParcels).forEach(([key, parcel]) => { + const { oldObj } = extractMatchingPairs( + matchingParcelPairs, + key, + oldDelivery.parcels, + newDelivery.parcels + ) - if (isAddAction(key, parcel)) { - addParcelActions.push({ - action: 'addParcelToDelivery', - deliveryId: oldDelivery.id, - ...diffpatcher.getDeltaValue(parcel), - }) - return - } + if (isAddAction(key, parcel)) { + addParcelActions.push({ + action: 'addParcelToDelivery', + deliveryId: oldDelivery.id, + ...diffpatcher.getDeltaValue(parcel), + }) + return + } - if (isRemoveAction(key, parcel)) { - removeParcelActions.push({ - action: 'removeParcelFromDelivery', - parcelId: oldObj.id, - }) - } - }) + if (isRemoveAction(key, parcel)) { + removeParcelActions.push({ + action: 'removeParcelFromDelivery', + parcelId: oldObj.id, + }) + } + }) return [addParcelActions, removeParcelActions] } @@ -116,7 +116,12 @@ function _buildDeliveryItemsAction(diffedItems, newDelivery: any = {}) { return [setDeliveryItemsAction] } -export function actionsMapParcels(diff, oldObj, newObj, deliveryHashMap) { +export function actionsMapParcels( + diff: { shippingInfo: { deliveries: { any } } }, + oldObj, + newObj, + deliveryHashMap +) { const shippingInfo = diff.shippingInfo if (!shippingInfo) return [] @@ -127,7 +132,7 @@ export function actionsMapParcels(diff, oldObj, newObj, deliveryHashMap) { let removeParcelActions = [] if (deliveries) - forEach(deliveries, (delivery, key) => { + Object.entries(deliveries).forEach(([key, delivery]) => { const { oldObj: oldDelivery, newObj: newDelivery } = extractMatchingPairs( deliveryHashMap, key, @@ -150,7 +155,12 @@ export function actionsMapParcels(diff, oldObj, newObj, deliveryHashMap) { return removeParcelActions.concat(addParcelActions) } -export function actionsMapDeliveryItems(diff, oldObj, newObj, deliveryHashMap) { +export function actionsMapDeliveryItems( + diff: { shippingInfo: { deliveries: { any } } }, + oldObj, + newObj, + deliveryHashMap +) { const shippingInfo = diff.shippingInfo if (!shippingInfo) return [] @@ -159,7 +169,7 @@ export function actionsMapDeliveryItems(diff, oldObj, newObj, deliveryHashMap) { let setDeliveryItemsActions = [] - forEach(deliveries, (delivery, key) => { + Object.entries(deliveries).forEach(([key, delivery]) => { const { newObj: newDelivery } = extractMatchingPairs( deliveryHashMap, key, diff --git a/packages/sync-actions/src/product-actions.ts b/packages/sync-actions/src/product-actions.ts index 4f5de1a05..396e36d66 100644 --- a/packages/sync-actions/src/product-actions.ts +++ b/packages/sync-actions/src/product-actions.ts @@ -1,5 +1,4 @@ /* eslint-disable max-len */ -import forEach from 'lodash.foreach' import uniqWith from 'lodash.uniqwith' import intersection from 'lodash.intersection' import without from 'lodash.without' @@ -15,6 +14,7 @@ import createBuildArrayActions, { REMOVE_ACTIONS, } from './utils/create-build-array-actions' import findMatchingPairs from './utils/find-matching-pairs' +import { ProductVariant } from '@commercetools/platform-sdk/src' const REGEX_NUMBER = new RegExp(/^\d+$/) const REGEX_UNDERSCORE_NUMBER = new RegExp(/^_\d+$/) @@ -182,7 +182,7 @@ function _buildSetAttributeAction( } function _buildVariantImagesAction( - diffedImages, + diffedImages: any, oldVariant: any = {}, newVariant: any = {} ) { @@ -194,63 +194,68 @@ function _buildVariantImagesAction( newVariant.images, 'url' ) - forEach(diffedImages, (image, key) => { - const { oldObj, newObj } = extractMatchingPairs( - matchingImagePairs, - key, - oldVariant.images, - newVariant.images - ) - if (REGEX_NUMBER.test(key)) { - // New image - if (Array.isArray(image) && image.length) - actions.push({ - action: 'addExternalImage', - variantId: oldVariant.id, - image: diffpatcher.getDeltaValue(image), - }) - else if (typeof image === 'object') - if ({}.hasOwnProperty.call(image, 'url') && image.url.length === 2) { - // There is a new image, remove the old one first. - actions.push({ - action: 'removeImage', - variantId: oldVariant.id, - imageUrl: oldObj.url, - }) + diffedImages && + Object.entries(diffedImages).forEach(([key, image]) => { + const { oldObj, newObj } = extractMatchingPairs( + matchingImagePairs, + key, + oldVariant.images, + newVariant.images + ) + if (REGEX_NUMBER.test(key)) { + // New image + if (Array.isArray(image) && image.length) actions.push({ action: 'addExternalImage', variantId: oldVariant.id, - image: newObj, + image: diffpatcher.getDeltaValue(image), }) - } else if ( - {}.hasOwnProperty.call(image, 'label') && - (image.label.length === 1 || image.label.length === 2) - ) - actions.push({ - action: 'setImageLabel', - variantId: oldVariant.id, - imageUrl: oldObj.url, - label: diffpatcher.getDeltaValue(image.label), - }) - } else if (REGEX_UNDERSCORE_NUMBER.test(key)) - if (Array.isArray(image) && image.length === 3) { - if (Number(image[2]) === 3) - // image position changed - actions.push({ - action: 'moveImageToPosition', - variantId: oldVariant.id, - imageUrl: oldObj.url, - position: Number(image[1]), - }) - else if (Number(image[2]) === 0) - // image removed - actions.push({ - action: 'removeImage', - variantId: oldVariant.id, - imageUrl: oldObj.url, - }) - } - }) + else if (typeof image === 'object') + if ( + {}.hasOwnProperty.call(image, 'url') && + (image as any).url.length === 2 + ) { + // There is a new image, remove the old one first. + actions.push({ + action: 'removeImage', + variantId: oldVariant.id, + imageUrl: oldObj.url, + }) + actions.push({ + action: 'addExternalImage', + variantId: oldVariant.id, + image: newObj, + }) + } else if ( + {}.hasOwnProperty.call(image, 'label') && + ((image as any).label.length === 1 || + (image as any).label.length === 2) + ) + actions.push({ + action: 'setImageLabel', + variantId: oldVariant.id, + imageUrl: oldObj.url, + label: diffpatcher.getDeltaValue((image as any).label), + }) + } else if (REGEX_UNDERSCORE_NUMBER.test(key)) + if (Array.isArray(image) && image.length === 3) { + if (Number(image[2]) === 3) + // image position changed + actions.push({ + action: 'moveImageToPosition', + variantId: oldVariant.id, + imageUrl: oldObj.url, + position: Number(image[1]), + }) + else if (Number(image[2]) === 0) + // image removed + actions.push({ + action: 'removeImage', + variantId: oldVariant.id, + imageUrl: oldObj.url, + }) + } + }) return actions } @@ -271,56 +276,57 @@ function _buildVariantPricesAction( oldVariant.prices, newVariant.prices ) - forEach(diffedPrices, (price, key) => { - const { oldObj, newObj } = extractMatchingPairs( - matchingPricePairs, - key, - oldVariant.prices, - newVariant.prices - ) - if (getIsAddAction(key, price)) { - // Remove read-only fields - const patchedPrice = price.map((p) => { - const shallowClone = { ...p } - if (enableDiscounted !== true) delete shallowClone.discounted - return shallowClone - }) - - addPriceActions.push({ - action: 'addPrice', - variantId: oldVariant.id, - price: diffpatcher.getDeltaValue(patchedPrice), - }) - return - } + diffedPrices && + Object.entries(diffedPrices).forEach(([key, price]) => { + const { oldObj, newObj } = extractMatchingPairs( + matchingPricePairs, + key, + oldVariant.prices, + newVariant.prices + ) + if (getIsAddAction(key, price)) { + // Remove read-only fields + const patchedPrice = (price as any).map((p) => { + const shallowClone = { ...p } + if (enableDiscounted !== true) delete shallowClone.discounted + return shallowClone + }) - if (getIsUpdateAction(key, price)) { - // Remove the discounted field and make sure that the price - // still has other values, otherwise simply return - const filteredPrice = { ...price } - if (enableDiscounted !== true) delete filteredPrice.discounted - if (Object.keys(filteredPrice).length) { - // At this point price should have changed, simply pick the new one - const newPrice = { ...newObj } - if (enableDiscounted !== true) delete newPrice.discounted - - changePriceActions.push({ - action: 'changePrice', - priceId: oldObj.id, - price: newPrice, + addPriceActions.push({ + action: 'addPrice', + variantId: oldVariant.id, + price: diffpatcher.getDeltaValue(patchedPrice), }) + return } - return - } - if (getIsRemoveAction(key, price)) { - // price removed - removePriceActions.push({ - action: 'removePrice', - priceId: oldObj.id, - }) - } - }) + if (getIsUpdateAction(key, price)) { + // Remove the discounted field and make sure that the price + // still has other values, otherwise simply return + const filteredPrice = { ...(price as any) } + if (enableDiscounted !== true) delete filteredPrice.discounted + if (Object.keys(filteredPrice).length) { + // At this point price should have changed, simply pick the new one + const newPrice = { ...newObj } + if (enableDiscounted !== true) delete newPrice.discounted + + changePriceActions.push({ + action: 'changePrice', + priceId: oldObj.id, + price: newPrice, + }) + } + return + } + + if (getIsRemoveAction(key, price)) { + // price removed + removePriceActions.push({ + action: 'removePrice', + priceId: oldObj.id, + }) + } + }) return [addPriceActions, changePriceActions, removePriceActions] } @@ -334,62 +340,62 @@ function _buildVariantAttributesActions( const actions = [] if (!attributes) return actions + attributes && + Object.entries(attributes).forEach(([key, value]) => { + if (REGEX_NUMBER.test(key)) { + if (Array.isArray(value)) { + const { id } = oldVariant + const deltaValue = diffpatcher.getDeltaValue(value) + const setAction = _buildNewSetAttributeAction( + id, + deltaValue, + sameForAllAttributeNames + ) - forEach(attributes, (value, key) => { - if (REGEX_NUMBER.test(key)) { - if (Array.isArray(value)) { - const { id } = oldVariant - const deltaValue = diffpatcher.getDeltaValue(value) - const setAction = _buildNewSetAttributeAction( - id, - deltaValue, - sameForAllAttributeNames - ) - - if (setAction) actions.push(setAction) - } else if (newVariant.attributes) { - const setAction = _buildSetAttributeAction( - value.value, - oldVariant, - newVariant.attributes[key], - sameForAllAttributeNames - ) - if (setAction) actions.push(setAction) - } - } else if (REGEX_UNDERSCORE_NUMBER.test(key)) - if (Array.isArray(value)) { - // Ignore pure array moves! - if (value.length === 3 && value[2] === 3) return - - const { id } = oldVariant - - let deltaValue = diffpatcher.getDeltaValue(value) - if (!deltaValue) - if (value[0] && value[0].name) - // unset attribute if - deltaValue = { name: value[0].name } - else deltaValue = undefined - - const setAction = _buildNewSetAttributeAction( - id, - deltaValue, - sameForAllAttributeNames - ) - - if (setAction) actions.push(setAction) - } else { - const index = key.substring(1) - if (newVariant.attributes) { + if (setAction) actions.push(setAction) + } else if (newVariant.attributes) { const setAction = _buildSetAttributeAction( - value.value, + (value as any).value, oldVariant, - newVariant.attributes[index], + newVariant.attributes[key], sameForAllAttributeNames ) if (setAction) actions.push(setAction) } - } - }) + } else if (REGEX_UNDERSCORE_NUMBER.test(key)) + if (Array.isArray(value)) { + // Ignore pure array moves! + if (value.length === 3 && value[2] === 3) return + + const { id } = oldVariant + + let deltaValue = diffpatcher.getDeltaValue(value) + if (!deltaValue) + if (value[0] && value[0].name) + // unset attribute if + deltaValue = { name: value[0].name } + else deltaValue = undefined + + const setAction = _buildNewSetAttributeAction( + id, + deltaValue, + sameForAllAttributeNames + ) + + if (setAction) actions.push(setAction) + } else { + const index = key.substring(1) + if (newVariant.attributes) { + const setAction = _buildSetAttributeAction( + (value as any).value, + oldVariant, + newVariant.attributes[index], + sameForAllAttributeNames + ) + if (setAction) actions.push(setAction) + } + } + }) return actions } @@ -440,72 +446,73 @@ function _buildVariantAssetsActions(diffAssets, oldVariant, newVariant) { newVariant.assets ) - forEach(diffAssets, (asset, key) => { - const { oldObj: oldAsset, newObj: newAsset } = extractMatchingPairs( - matchingAssetPairs, - key, - oldVariant.assets, - newVariant.assets - ) + diffAssets && + Object.entries(diffAssets).forEach(([key, asset]) => { + const { oldObj: oldAsset, newObj: newAsset } = extractMatchingPairs( + matchingAssetPairs, + key, + oldVariant.assets, + newVariant.assets + ) - if (getIsAddAction(key, asset)) { - assetActions.push({ - action: 'addAsset', - asset: diffpatcher.getDeltaValue(asset), - ...toVariantIdentifier(newVariant), - position: Number(key), - }) - return - } + if (getIsAddAction(key, asset)) { + assetActions.push({ + action: 'addAsset', + asset: diffpatcher.getDeltaValue(asset), + ...toVariantIdentifier(newVariant), + position: Number(key), + }) + return + } + + if (getIsUpdateAction(key, asset)) { + // todo add changeAssetOrder + const basicActions = buildBaseAttributesActions({ + actions: baseAssetActionsList, + diff: asset, + oldObj: oldAsset, + newObj: newAsset, + }).map((action) => { + // in case of 'setAssetKey' then the identifier will be only 'assetId' + if (action.action === 'setAssetKey') { + return { + ...action, + ...toVariantIdentifier(oldVariant), + assetId: oldAsset.id, + } + } - if (getIsUpdateAction(key, asset)) { - // todo add changeAssetOrder - const basicActions = buildBaseAttributesActions({ - actions: baseAssetActionsList, - diff: asset, - oldObj: oldAsset, - newObj: newAsset, - }).map((action) => { - // in case of 'setAssetKey' then the identifier will be only 'assetId' - if (action.action === 'setAssetKey') { return { ...action, ...toVariantIdentifier(oldVariant), - assetId: oldAsset.id, + ...toAssetIdentifier(oldAsset), } + }) + assetActions.push(...basicActions) + + if ((asset as any).custom) { + const customActions = actionsMapCustom(asset, newAsset, oldAsset, { + actions: { + setCustomType: 'setAssetCustomType', + setCustomField: 'setAssetCustomField', + }, + ...toVariantIdentifier(oldVariant), + ...toAssetIdentifier(oldAsset), + }) + assetActions.push(...customActions) } - return { - ...action, - ...toVariantIdentifier(oldVariant), + return + } + + if (getIsRemoveAction(key, asset)) { + assetActions.push({ + action: 'removeAsset', ...toAssetIdentifier(oldAsset), - } - }) - assetActions.push(...basicActions) - - if (asset.custom) { - const customActions = actionsMapCustom(asset, newAsset, oldAsset, { - actions: { - setCustomType: 'setAssetCustomType', - setCustomField: 'setAssetCustomField', - }, ...toVariantIdentifier(oldVariant), - ...toAssetIdentifier(oldAsset), }) - assetActions.push(...customActions) } - - return - } - - if (getIsRemoveAction(key, asset)) { - assetActions.push({ - action: 'removeAsset', - ...toAssetIdentifier(oldAsset), - ...toVariantIdentifier(oldVariant), - }) - } - }) + }) const changedAssetOrderAction = _buildVariantChangeAssetOrderAction( diffAssets, @@ -579,7 +586,7 @@ export function actionsMapCategories(diff) { const addToCategoryActions = [] const removeFromCategoryActions = [] - forEach(diff.categories, (category) => { + Object.entries(diff.categories).forEach(([key, category]) => { if (Array.isArray(category)) { const action: any = { category: category[0] } @@ -632,26 +639,28 @@ export function actionsMapAssets(diff, oldObj, newObj, variantHashMap) { const { variants } = diff if (variants) - forEach(variants, (variant, key) => { - const { oldObj: oldVariant, newObj: newVariant } = extractMatchingPairs( - variantHashMap, - key, - oldObj.variants, - newObj.variants - ) - if ( - variant.assets && - (REGEX_UNDERSCORE_NUMBER.test(key) || REGEX_NUMBER.test(key)) - ) { - const assetActions = _buildVariantAssetsActions( - variant.assets, - oldVariant, - newVariant + Object.entries(variants as { [key: string]: ProductVariant }).forEach( + ([key, variant]) => { + const { oldObj: oldVariant, newObj: newVariant } = extractMatchingPairs( + variantHashMap, + key, + oldObj.variants, + newObj.variants ) + if ( + variant.assets && + (REGEX_UNDERSCORE_NUMBER.test(key) || REGEX_NUMBER.test(key)) + ) { + const assetActions = _buildVariantAssetsActions( + variant.assets, + oldVariant, + newVariant + ) - allAssetsActions = allAssetsActions.concat(assetActions) + allAssetsActions = allAssetsActions.concat(assetActions) + } } - }) + ) return allAssetsActions } @@ -667,7 +676,7 @@ export function actionsMapAttributes( const { variants } = diff if (variants) - forEach(variants, (variant, key) => { + Object.entries(variants).forEach(([key, variant]) => { const { oldObj: oldVariant, newObj: newVariant } = extractMatchingPairs( variantHashMap, key, @@ -680,7 +689,7 @@ export function actionsMapAttributes( if (skuAction) actions.push(skuAction) if (keyAction) actions.push(keyAction) - const { attributes } = variant + const { attributes } = variant as any const attrActions = _buildVariantAttributesActions( attributes, @@ -705,22 +714,24 @@ export function actionsMapImages(diff, oldObj, newObj, variantHashMap) { let actions = [] const { variants } = diff if (variants) - forEach(variants, (variant, key) => { - const { oldObj: oldVariant, newObj: newVariant } = extractMatchingPairs( - variantHashMap, - key, - oldObj.variants, - newObj.variants - ) - if (REGEX_UNDERSCORE_NUMBER.test(key) || REGEX_NUMBER.test(key)) { - const vActions = _buildVariantImagesAction( - variant.images, - oldVariant, - newVariant + Object.entries(variants as { [key: string]: ProductVariant }).forEach( + ([key, variant]) => { + const { oldObj: oldVariant, newObj: newVariant } = extractMatchingPairs( + variantHashMap, + key, + oldObj.variants, + newObj.variants ) - actions = actions.concat(vActions) + if (REGEX_UNDERSCORE_NUMBER.test(key) || REGEX_NUMBER.test(key)) { + const vActions = _buildVariantImagesAction( + variant.images, + oldVariant, + newVariant + ) + actions = actions.concat(vActions) + } } - }) + ) return actions } @@ -739,27 +750,29 @@ export function actionsMapPrices( const { variants } = diff if (variants) - forEach(variants, (variant, key) => { - const { oldObj: oldVariant, newObj: newVariant } = extractMatchingPairs( - variantHashMap, - key, - oldObj.variants, - newObj.variants - ) - if (REGEX_UNDERSCORE_NUMBER.test(key) || REGEX_NUMBER.test(key)) { - const [addPriceAction, changePriceAction, removePriceAction] = - _buildVariantPricesAction( - variant.prices, - oldVariant, - newVariant, - enableDiscounted - ) + Object.entries(variants as { [key: string]: ProductVariant }).forEach( + ([key, variant]) => { + const { oldObj: oldVariant, newObj: newVariant } = extractMatchingPairs( + variantHashMap, + key, + oldObj.variants, + newObj.variants + ) + if (REGEX_UNDERSCORE_NUMBER.test(key) || REGEX_NUMBER.test(key)) { + const [addPriceAction, changePriceAction, removePriceAction] = + _buildVariantPricesAction( + variant.prices, + oldVariant, + newVariant, + enableDiscounted + ) - addPriceActions = addPriceActions.concat(addPriceAction) - changePriceActions = changePriceActions.concat(changePriceAction) - removePriceActions = removePriceActions.concat(removePriceAction) + addPriceActions = addPriceActions.concat(addPriceAction) + changePriceActions = changePriceActions.concat(changePriceAction) + removePriceActions = removePriceActions.concat(removePriceAction) + } } - }) + ) // price actions need to be in this below order return changePriceActions.concat(removePriceActions).concat(addPriceActions) @@ -771,55 +784,57 @@ export function actionsMapPricesCustom(diff, oldObj, newObj, variantHashMap) { const { variants } = diff if (variants) - forEach(variants, (variant, key) => { - const { oldObj: oldVariant, newObj: newVariant } = extractMatchingPairs( - variantHashMap, - key, - oldObj.variants, - newObj.variants - ) - - if ( - variant && - variant.prices && - (REGEX_UNDERSCORE_NUMBER.test(key) || REGEX_NUMBER.test(key)) - ) { - const priceHashMap = findMatchingPairs( - variant.prices, - oldVariant.prices, - newVariant.prices + Object.entries(variants as { [key: string]: ProductVariant }).forEach( + ([key, variant]) => { + const { oldObj: oldVariant, newObj: newVariant } = extractMatchingPairs( + variantHashMap, + key, + oldObj.variants, + newObj.variants ) - forEach(variant.prices, (price, index) => { - const { oldObj: oldPrice, newObj: newPrice } = extractMatchingPairs( - priceHashMap, - index, + if ( + variant && + variant.prices && + (REGEX_UNDERSCORE_NUMBER.test(key) || REGEX_NUMBER.test(key)) + ) { + const priceHashMap = findMatchingPairs( + variant.prices, oldVariant.prices, newVariant.prices ) - if ( - price.custom && - (REGEX_UNDERSCORE_NUMBER.test(index) || REGEX_NUMBER.test(index)) - ) { - const generatedActions = actionsMapCustom( - price, - newPrice, - oldPrice, - { - actions: { - setCustomType: 'setProductPriceCustomType', - setCustomField: 'setProductPriceCustomField', - }, - priceId: oldPrice.id, - } + Object.entries(variant.prices).forEach(([key, price]) => { + const { oldObj: oldPrice, newObj: newPrice } = extractMatchingPairs( + priceHashMap, + key, + oldVariant.prices, + newVariant.prices ) - actions = actions.concat(generatedActions) - } - }) + if ( + price.custom && + (REGEX_UNDERSCORE_NUMBER.test(key) || REGEX_NUMBER.test(key)) + ) { + const generatedActions = actionsMapCustom( + price, + newPrice, + oldPrice, + { + actions: { + setCustomType: 'setProductPriceCustomType', + setCustomField: 'setProductPriceCustomField', + }, + priceId: oldPrice.id, + } + ) + + actions = actions.concat(generatedActions) + } + }) + } } - }) + ) return actions } diff --git a/packages/sync-actions/src/types-actions.ts b/packages/sync-actions/src/types-actions.ts index 2123e09ae..389bdad34 100644 --- a/packages/sync-actions/src/types-actions.ts +++ b/packages/sync-actions/src/types-actions.ts @@ -1,4 +1,3 @@ -import forEach from 'lodash.foreach' import sortBy from 'lodash.sortby' import isEqual from 'lodash.isequal' @@ -134,70 +133,71 @@ function actionsMapEnums( } export function actionsMapFieldDefinitions( - fieldDefinitionsDiff, + fieldDefinitionsDiff: { [key: string]: any }, previous, next, diffPaths ) { const actions = [] - forEach(fieldDefinitionsDiff, (diffValue, diffKey) => { - const extractedPairs = extractMatchingPairs( - diffPaths, - diffKey, - previous, - next - ) - - if (getIsChangedOperation(diffKey)) { - if (Array.isArray(diffValue)) { - const deltaValue = diffPatcher.getDeltaValue(diffValue) - if (deltaValue.name) { + fieldDefinitionsDiff && + Object.entries(fieldDefinitionsDiff).forEach(([diffKey, diffValue]) => { + const extractedPairs = extractMatchingPairs( + diffPaths, + diffKey, + previous, + next + ) + + if (getIsChangedOperation(diffKey)) { + if (Array.isArray(diffValue)) { + const deltaValue = diffPatcher.getDeltaValue(diffValue) + if (deltaValue.name) { + actions.push({ + action: 'addFieldDefinition', + fieldDefinition: deltaValue, + }) + } + } else if (diffValue.label) { actions.push({ - action: 'addFieldDefinition', - fieldDefinition: deltaValue, + action: 'changeLabel', + label: extractedPairs.newObj.label, + fieldName: extractedPairs.oldObj.name, }) - } - } else if (diffValue.label) { - actions.push({ - action: 'changeLabel', - label: extractedPairs.newObj.label, - fieldName: extractedPairs.oldObj.name, - }) - } else if (diffValue.inputHint) { - actions.push({ - action: 'changeInputHint', - inputHint: extractedPairs.newObj.inputHint, - fieldName: extractedPairs.oldObj.name, - }) - } else if (diffValue?.type?.values) { - actions.push( - ...actionsMapEnums( - extractedPairs.oldObj.name, - extractedPairs.oldObj.type.name, - diffValue.type, - extractedPairs.oldObj.type, - extractedPairs.newObj.type - ) - ) - } - } else if (getIsRemovedOperation(diffKey)) { - if (Array.isArray(diffValue)) { - if (diffValue.length === 3 && diffValue[2] === 3) { + } else if (diffValue.inputHint) { actions.push({ - action: 'changeFieldDefinitionOrder', - fieldNames: next.map((n) => n.name), + action: 'changeInputHint', + inputHint: extractedPairs.newObj.inputHint, + fieldName: extractedPairs.oldObj.name, }) - } else { - const deltaValue = diffPatcher.getDeltaValue(diffValue) - if (deltaValue === undefined && diffValue[0].name) + } else if (diffValue?.type?.values) { + actions.push( + ...actionsMapEnums( + extractedPairs.oldObj.name, + extractedPairs.oldObj.type.name, + diffValue.type, + extractedPairs.oldObj.type, + extractedPairs.newObj.type + ) + ) + } + } else if (getIsRemovedOperation(diffKey)) { + if (Array.isArray(diffValue)) { + if (diffValue.length === 3 && diffValue[2] === 3) { actions.push({ - action: 'removeFieldDefinition', - fieldName: diffValue[0].name, + action: 'changeFieldDefinitionOrder', + fieldNames: next.map((n) => n.name), }) + } else { + const deltaValue = diffPatcher.getDeltaValue(diffValue) + if (deltaValue === undefined && diffValue[0].name) + actions.push({ + action: 'removeFieldDefinition', + fieldName: diffValue[0].name, + }) + } } } - } - }) + }) // Make sure to execute removeActions before creating new ones // in order to prevent any eventual removal of `addAction`. diff --git a/packages/sync-actions/src/utils/find-matching-pairs.ts b/packages/sync-actions/src/utils/find-matching-pairs.ts index 05149138b..f1abbf8a3 100644 --- a/packages/sync-actions/src/utils/find-matching-pairs.ts +++ b/packages/sync-actions/src/utils/find-matching-pairs.ts @@ -1,5 +1,3 @@ -import forEach from 'lodash.foreach' - const REGEX_NUMBER = new RegExp(/^\d+$/) const REGEX_UNDERSCORE_NUMBER = new RegExp(/^_\d+$/) @@ -33,15 +31,16 @@ export default function findMatchingPairs( refByIdentifier: nowObjRefByIdentifier, refByIndex: nowObjRefByIndex, } = preProcessCollection(now, identifier) - forEach(diff, (item, key) => { - if (REGEX_NUMBER.test(key)) { - const matchingIdentifier = nowObjRefByIndex[key] - result[key] = [beforeObjRefByIdentifier[matchingIdentifier], key] - } else if (REGEX_UNDERSCORE_NUMBER.test(key)) { - const index = key.substring(1) - const matchingIdentifier = beforeObjRefByIndex[index] - result[key] = [index, nowObjRefByIdentifier[matchingIdentifier]] - } - }) + diff && + Object.entries(diff).forEach(([key, item]) => { + if (REGEX_NUMBER.test(key)) { + const matchingIdentifier = nowObjRefByIndex[key] + result[key] = [beforeObjRefByIdentifier[matchingIdentifier], key] + } else if (REGEX_UNDERSCORE_NUMBER.test(key)) { + const index = key.substring(1) + const matchingIdentifier = beforeObjRefByIndex[index] + result[key] = [index, nowObjRefByIdentifier[matchingIdentifier]] + } + }) return result } From 54b985698ae637a5941f6fc9ce22fa5363de6eb4 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Tue, 7 Nov 2023 13:22:10 +0100 Subject: [PATCH 06/33] feat(migrate): replace * imports --- packages/sync-actions/src/attribute-groups.ts | 19 +++++------ packages/sync-actions/src/cart-discounts.ts | 4 +-- packages/sync-actions/src/categories.ts | 18 +++++----- packages/sync-actions/src/channels.ts | 4 +-- packages/sync-actions/src/customer-actions.ts | 4 +-- packages/sync-actions/src/customer-group.ts | 4 +-- packages/sync-actions/src/customers.ts | 4 +-- packages/sync-actions/src/discount-codes.ts | 4 +-- packages/sync-actions/src/inventories.ts | 4 +-- packages/sync-actions/src/order-actions.ts | 4 +-- packages/sync-actions/src/orders.ts | 4 +-- packages/sync-actions/src/prices.ts | 4 +-- packages/sync-actions/src/product-actions.ts | 33 +++++++++---------- .../sync-actions/src/product-discounts.ts | 4 +-- .../sync-actions/src/product-selections.ts | 4 +-- packages/sync-actions/src/product-types.ts | 4 +-- packages/sync-actions/src/products.ts | 4 +-- packages/sync-actions/src/projects.ts | 4 +-- packages/sync-actions/src/quote-requests.ts | 4 +-- packages/sync-actions/src/quotes.ts | 4 +-- packages/sync-actions/src/shipping-methods.ts | 4 +-- packages/sync-actions/src/staged-quotes.ts | 4 +-- packages/sync-actions/src/states.ts | 4 +-- packages/sync-actions/src/stores.ts | 4 +-- packages/sync-actions/src/tax-categories.ts | 4 +-- packages/sync-actions/src/types-actions.ts | 6 ++-- packages/sync-actions/src/types.ts | 4 +-- .../src/utils/action-map-custom.ts | 17 ++++------ .../sync-actions/src/utils/common-actions.ts | 5 +-- packages/sync-actions/src/zones.ts | 4 +-- .../test/utils/action-map-custom.spec.ts | 4 +-- .../test/utils/common-actions.spec.ts | 20 +++++------ 32 files changed, 105 insertions(+), 113 deletions(-) diff --git a/packages/sync-actions/src/attribute-groups.ts b/packages/sync-actions/src/attribute-groups.ts index aac5f4cc3..ba97c210e 100644 --- a/packages/sync-actions/src/attribute-groups.ts +++ b/packages/sync-actions/src/attribute-groups.ts @@ -4,10 +4,13 @@ import type { UpdateAction, SyncActionConfig, } from '@commercetools/sdk-client-v2' -import * as attributeGroupsActions from './attribute-groups-actions' +import { + actionsMapAttributes, + actionsMapBase, +} from './attribute-groups-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' -import * as diffpatcher from './utils/diffpatcher' +import { diff } from './utils/diffpatcher' function createAttributeGroupsMapActions( mapActionGroup: ( @@ -26,19 +29,13 @@ function createAttributeGroupsMapActions( mapActionGroup( 'base', (): Array => - attributeGroupsActions.actionsMapBase( - diff, - oldObj, - newObj, - syncActionConfig - ) + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) allActions.push( mapActionGroup( 'attributes', - (): Array => - attributeGroupsActions.actionsMapAttributes(diff, oldObj, newObj) + (): Array => actionsMapAttributes(diff, oldObj, newObj) ).flat() ) return allActions.flat() @@ -54,6 +51,6 @@ export default ( mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + const buildActions = createBuildActions(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/cart-discounts.ts b/packages/sync-actions/src/cart-discounts.ts index de57ae4bb..e270618d7 100644 --- a/packages/sync-actions/src/cart-discounts.ts +++ b/packages/sync-actions/src/cart-discounts.ts @@ -3,7 +3,7 @@ import createMapActionGroup from './utils/create-map-action-group' import actionsMapCustom from './utils/action-map-custom' import { actionsMapBase } from './cart-discounts-actions' import combineValidityActions from './utils/combine-validity-actions' -import * as diffpatcher from './utils/diffpatcher' +import { diff } from './utils/diffpatcher' import { SyncActionConfig } from '@commercetools/sdk-client-v2' export const actionGroups = ['base', 'custom'] @@ -32,6 +32,6 @@ export default (actionGroupList?, syncActionConfig?: SyncActionConfig) => { mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + const buildActions = createBuildActions(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/categories.ts b/packages/sync-actions/src/categories.ts index b904c5407..61819a568 100644 --- a/packages/sync-actions/src/categories.ts +++ b/packages/sync-actions/src/categories.ts @@ -8,9 +8,13 @@ import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import actionsMapCustom from './utils/action-map-custom' import actionsMapAssets from './assets-actions' -import * as categoryActions from './category-actions' -import * as diffpatcher from './utils/diffpatcher' +import { + actionsMapBase, + actionsMapMeta, + actionsMapReferences, +} from './category-actions' import copyEmptyArrayProps from './utils/copy-empty-array-props' +import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'references', 'meta', 'custom', 'assets'] @@ -29,23 +33,21 @@ function createCategoryMapActions( mapActionGroup( 'base', (): Array => - categoryActions.actionsMapBase(diff, oldObj, newObj, syncActionConfig) + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) allActions.push( mapActionGroup( 'references', - (): Array => - categoryActions.actionsMapReferences(diff, oldObj, newObj) + (): Array => actionsMapReferences(diff, oldObj, newObj) ) ) allActions.push( mapActionGroup( 'meta', - (): Array => - categoryActions.actionsMapMeta(diff, oldObj, newObj) + (): Array => actionsMapMeta(diff, oldObj, newObj) ) ) @@ -88,7 +90,7 @@ export default ( syncActionConfig ) const buildActions = createBuildActions( - diffpatcher.diff, + diff, doMapActions, copyEmptyArrayProps ) diff --git a/packages/sync-actions/src/channels.ts b/packages/sync-actions/src/channels.ts index 0a5260521..690e915a0 100644 --- a/packages/sync-actions/src/channels.ts +++ b/packages/sync-actions/src/channels.ts @@ -2,7 +2,7 @@ import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import actionsMapCustom from './utils/action-map-custom' import { actionsMapBase } from './channels-actions' -import * as diffpatcher from './utils/diffpatcher' +import { diff } from './utils/diffpatcher' import { SyncActionConfig } from '@commercetools/sdk-client-v2' export const actionGroups = ['base', 'custom'] @@ -31,6 +31,6 @@ export default (actionGroupList?, syncActionConfig?: SyncActionConfig) => { mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + const buildActions = createBuildActions(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/customer-actions.ts b/packages/sync-actions/src/customer-actions.ts index 4582a7760..aa9d6f55b 100644 --- a/packages/sync-actions/src/customer-actions.ts +++ b/packages/sync-actions/src/customer-actions.ts @@ -9,7 +9,7 @@ import createBuildArrayActions, { REMOVE_ACTIONS, CHANGE_ACTIONS, } from './utils/create-build-array-actions' -import * as diffpatcher from './utils/diffpatcher' +import { patch } from './utils/diffpatcher' import clone from './utils/clone' const isEmptyValue = createIsEmptyValue([undefined, null, '']) @@ -205,7 +205,7 @@ function buildAuthenticationModeActions({ actions, diff, oldObj, newObj }) { return undefined // We need to clone `before` as `patch` will mutate it - const patched = diffpatcher.patch(clone(before), delta) + const patched = patch(clone(before), delta) if (newObj.authenticationMode === 'ExternalAuth') return { action: item.action, authMode: patched } return { diff --git a/packages/sync-actions/src/customer-group.ts b/packages/sync-actions/src/customer-group.ts index 08225537d..053898dcf 100644 --- a/packages/sync-actions/src/customer-group.ts +++ b/packages/sync-actions/src/customer-group.ts @@ -2,7 +2,7 @@ import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import actionsMapCustom from './utils/action-map-custom' import { actionsMapBase } from './customer-group-actions' -import * as diffpatcher from './utils/diffpatcher' +import { diff } from './utils/diffpatcher' import { SyncActionConfig } from '@commercetools/sdk-client-v2' export const actionGroups = ['base', 'custom'] @@ -31,6 +31,6 @@ export default (actionGroupList?, syncActionConfig?: SyncActionConfig) => { mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + const buildActions = createBuildActions(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/customers.ts b/packages/sync-actions/src/customers.ts index 60e4dd599..123a1c5a5 100644 --- a/packages/sync-actions/src/customers.ts +++ b/packages/sync-actions/src/customers.ts @@ -8,7 +8,7 @@ import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import actionsMapCustom from './utils/action-map-custom' import * as customerActions from './customer-actions' -import * as diffpatcher from './utils/diffpatcher' +import { diff } from './utils/diffpatcher' import copyEmptyArrayProps from './utils/copy-empty-array-props' export const actionGroups = [ @@ -123,7 +123,7 @@ export default ( syncActionConfig ) const buildActions = createBuildActions( - diffpatcher.diff, + diff, doMapActions, copyEmptyArrayProps ) diff --git a/packages/sync-actions/src/discount-codes.ts b/packages/sync-actions/src/discount-codes.ts index dfbb230bb..724f8640e 100644 --- a/packages/sync-actions/src/discount-codes.ts +++ b/packages/sync-actions/src/discount-codes.ts @@ -3,7 +3,7 @@ import createMapActionGroup from './utils/create-map-action-group' import actionsMapCustom from './utils/action-map-custom' import { actionsMapBase } from './discount-codes-actions' import combineValidityActions from './utils/combine-validity-actions' -import * as diffpatcher from './utils/diffpatcher' +import { diff } from './utils/diffpatcher' import { SyncActionConfig } from '@commercetools/sdk-client-v2' export const actionGroups = ['base', 'custom'] @@ -40,6 +40,6 @@ export default (actionGroupList?, syncActionConfig?: SyncActionConfig) => { mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + const buildActions = createBuildActions(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/inventories.ts b/packages/sync-actions/src/inventories.ts index c3ed1045d..c28e066f5 100644 --- a/packages/sync-actions/src/inventories.ts +++ b/packages/sync-actions/src/inventories.ts @@ -8,7 +8,7 @@ import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import actionsMapCustom from './utils/action-map-custom' import * as inventoryActions from './inventory-actions' -import * as diffpatcher from './utils/diffpatcher' +import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'references'] @@ -71,6 +71,6 @@ export default ( mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + const buildActions = createBuildActions(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/order-actions.ts b/packages/sync-actions/src/order-actions.ts index e64ac5e97..25dcda95a 100644 --- a/packages/sync-actions/src/order-actions.ts +++ b/packages/sync-actions/src/order-actions.ts @@ -1,4 +1,4 @@ -import * as diffpatcher from './utils/diffpatcher' +import { diff, getDeltaValue } from './utils/diffpatcher' import { buildBaseAttributesActions } from './utils/common-actions' import createBuildArrayActions, { ADD_ACTIONS, @@ -83,7 +83,7 @@ function _buildDeliveryParcelsAction( addParcelActions.push({ action: 'addParcelToDelivery', deliveryId: oldDelivery.id, - ...diffpatcher.getDeltaValue(parcel), + ...getDeltaValue(parcel), }) return } diff --git a/packages/sync-actions/src/orders.ts b/packages/sync-actions/src/orders.ts index 81fbacc07..8a2c715f1 100644 --- a/packages/sync-actions/src/orders.ts +++ b/packages/sync-actions/src/orders.ts @@ -8,7 +8,7 @@ import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import actionsMapCustom from './utils/action-map-custom' import * as orderActions from './order-actions' -import * as diffpatcher from './utils/diffpatcher' +import { diff } from './utils/diffpatcher' import findMatchingPairs from './utils/find-matching-pairs' export const actionGroups = ['base', 'deliveries'] @@ -103,6 +103,6 @@ export default ( // It will return an empty array for ignored action groups const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createOrderMapActions(mapActionGroup, syncActionConfig) - const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + const buildActions = createBuildActions(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/prices.ts b/packages/sync-actions/src/prices.ts index 6e7184f6e..58454f892 100644 --- a/packages/sync-actions/src/prices.ts +++ b/packages/sync-actions/src/prices.ts @@ -8,7 +8,7 @@ import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import actionsMapCustom from './utils/action-map-custom' import * as pricesActions from './prices-actions' -import * as diffpatcher from './utils/diffpatcher' +import { diff } from './utils/diffpatcher' import combineValidityActions from './utils/combine-validity-actions' const actionGroups = ['base', 'custom'] @@ -44,7 +44,7 @@ export default ( const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createPriceMapActions(mapActionGroup, syncActionConfig) - const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + const buildActions = createBuildActions(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/product-actions.ts b/packages/sync-actions/src/product-actions.ts index 396e36d66..9605715de 100644 --- a/packages/sync-actions/src/product-actions.ts +++ b/packages/sync-actions/src/product-actions.ts @@ -2,7 +2,7 @@ import uniqWith from 'lodash.uniqwith' import intersection from 'lodash.intersection' import without from 'lodash.without' -import * as diffpatcher from './utils/diffpatcher' +import { diff, getDeltaValue } from './utils/diffpatcher' import extractMatchingPairs from './utils/extract-matching-pairs' import actionsMapCustom from './utils/action-map-custom' import { @@ -65,7 +65,7 @@ const getIsItemMovedAction = (key, resource) => function _buildSkuActions(variantDiff, oldVariant) { if ({}.hasOwnProperty.call(variantDiff, 'sku')) { - const newValue = diffpatcher.getDeltaValue(variantDiff.sku) + const newValue = getDeltaValue(variantDiff.sku) if (!newValue && !oldVariant.sku) return null return { @@ -79,7 +79,7 @@ function _buildSkuActions(variantDiff, oldVariant) { function _buildKeyActions(variantDiff, oldVariant) { if ({}.hasOwnProperty.call(variantDiff, 'key')) { - const newValue = diffpatcher.getDeltaValue(variantDiff.key) + const newValue = getDeltaValue(variantDiff.key) if (!newValue && !oldVariant.key) return null return { @@ -134,7 +134,7 @@ function _buildSetAttributeAction( } if (Array.isArray(diffedValue)) - action.value = diffpatcher.getDeltaValue(diffedValue, oldAttribute.value) + action.value = getDeltaValue(diffedValue, oldAttribute.value) else if (typeof diffedValue === 'string') // LText: value: {en: "", de: ""} // Enum: value: {key: "foo", label: "Foo"} @@ -143,20 +143,20 @@ function _buildSetAttributeAction( // *: value: "" // normal - action.value = diffpatcher.getDeltaValue(diffedValue, oldAttribute.value) + action.value = getDeltaValue(diffedValue, oldAttribute.value) else if (diffedValue.centAmount || diffedValue.currencyCode) // Money action.value = { centAmount: diffedValue.centAmount - ? diffpatcher.getDeltaValue(diffedValue.centAmount) + ? getDeltaValue(diffedValue.centAmount) : attribute.value.centAmount, currencyCode: diffedValue.currencyCode - ? diffpatcher.getDeltaValue(diffedValue.currencyCode) + ? getDeltaValue(diffedValue.currencyCode) : attribute.value.currencyCode, } else if (diffedValue.key) // Enum / LEnum (use only the key) - action.value = diffpatcher.getDeltaValue(diffedValue.key) + action.value = getDeltaValue(diffedValue.key) else if (typeof diffedValue === 'object') if ({}.hasOwnProperty.call(diffedValue, '_t') && diffedValue._t === 'a') { // set-typed attribute @@ -166,10 +166,7 @@ function _buildSetAttributeAction( const updatedValue = Object.keys(diffedValue).reduce( (acc, lang) => { - const patchedValue = diffpatcher.getDeltaValue( - diffedValue[lang], - acc[lang] - ) + const patchedValue = getDeltaValue(diffedValue[lang], acc[lang]) return Object.assign(acc, { [lang]: patchedValue }) }, { ...oldAttribute.value } @@ -208,7 +205,7 @@ function _buildVariantImagesAction( actions.push({ action: 'addExternalImage', variantId: oldVariant.id, - image: diffpatcher.getDeltaValue(image), + image: getDeltaValue(image), }) else if (typeof image === 'object') if ( @@ -235,7 +232,7 @@ function _buildVariantImagesAction( action: 'setImageLabel', variantId: oldVariant.id, imageUrl: oldObj.url, - label: diffpatcher.getDeltaValue((image as any).label), + label: getDeltaValue((image as any).label), }) } else if (REGEX_UNDERSCORE_NUMBER.test(key)) if (Array.isArray(image) && image.length === 3) { @@ -295,7 +292,7 @@ function _buildVariantPricesAction( addPriceActions.push({ action: 'addPrice', variantId: oldVariant.id, - price: diffpatcher.getDeltaValue(patchedPrice), + price: getDeltaValue(patchedPrice), }) return } @@ -345,7 +342,7 @@ function _buildVariantAttributesActions( if (REGEX_NUMBER.test(key)) { if (Array.isArray(value)) { const { id } = oldVariant - const deltaValue = diffpatcher.getDeltaValue(value) + const deltaValue = getDeltaValue(value) const setAction = _buildNewSetAttributeAction( id, deltaValue, @@ -369,7 +366,7 @@ function _buildVariantAttributesActions( const { id } = oldVariant - let deltaValue = diffpatcher.getDeltaValue(value) + let deltaValue = getDeltaValue(value) if (!deltaValue) if (value[0] && value[0].name) // unset attribute if @@ -458,7 +455,7 @@ function _buildVariantAssetsActions(diffAssets, oldVariant, newVariant) { if (getIsAddAction(key, asset)) { assetActions.push({ action: 'addAsset', - asset: diffpatcher.getDeltaValue(asset), + asset: getDeltaValue(asset), ...toVariantIdentifier(newVariant), position: Number(key), }) diff --git a/packages/sync-actions/src/product-discounts.ts b/packages/sync-actions/src/product-discounts.ts index 7d0b1b5b7..1b86da58b 100644 --- a/packages/sync-actions/src/product-discounts.ts +++ b/packages/sync-actions/src/product-discounts.ts @@ -2,7 +2,7 @@ import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import { actionsMapBase } from './product-discounts-actions' import combineValidityActions from './utils/combine-validity-actions' -import * as diffpatcher from './utils/diffpatcher' +import { diff } from './utils/diffpatcher' import { SyncActionConfig } from '@commercetools/sdk-client-v2' export const actionGroups = ['base'] @@ -26,6 +26,6 @@ export default (actionGroupList?, syncActionConfig?: SyncActionConfig) => { mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + const buildActions = createBuildActions(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/product-selections.ts b/packages/sync-actions/src/product-selections.ts index a34d2dcdb..6fc061d10 100644 --- a/packages/sync-actions/src/product-selections.ts +++ b/packages/sync-actions/src/product-selections.ts @@ -7,7 +7,7 @@ import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import actionsMapCustom from './utils/action-map-custom' import * as productSelectionsActions from './product-selections-actions' -import * as diffpatcher from './utils/diffpatcher' +import { diff } from './utils/diffpatcher' export const actionGroups = ['base'] @@ -46,7 +46,7 @@ export default (actionGroupList?: Array): SyncAction => { const doMapActions = createProductSelectionsMapActions(mapActionGroup) const onBeforeApplyingDiff = null const buildActions = createBuildActions( - diffpatcher.diff, + diff, doMapActions, onBeforeApplyingDiff ) diff --git a/packages/sync-actions/src/product-types.ts b/packages/sync-actions/src/product-types.ts index 817d7daa9..ac7a678a0 100644 --- a/packages/sync-actions/src/product-types.ts +++ b/packages/sync-actions/src/product-types.ts @@ -7,7 +7,7 @@ import type { import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import * as productTypeActions from './product-types-actions' -import * as diffpatcher from './utils/diffpatcher' +import { diff } from './utils/diffpatcher' type SyncActionConfig = { withHints?: boolean } & BaseSyncActionConfig @@ -59,7 +59,7 @@ export default ( ) const onBeforeApplyingDiff = null const buildActions = createBuildActions( - diffpatcher.diff, + diff, doMapActions, onBeforeApplyingDiff, { withHints: true } diff --git a/packages/sync-actions/src/products.ts b/packages/sync-actions/src/products.ts index 0db1bcbbd..7919b2ffe 100644 --- a/packages/sync-actions/src/products.ts +++ b/packages/sync-actions/src/products.ts @@ -7,7 +7,7 @@ import type { import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import * as productActions from './product-actions' -import * as diffpatcher from './utils/diffpatcher' +import { diff } from './utils/diffpatcher' import findMatchingPairs from './utils/find-matching-pairs' import copyEmptyArrayProps from './utils/copy-empty-array-props' @@ -188,7 +188,7 @@ export default ( const doMapActions = createProductMapActions(mapActionGroup, syncActionConfig) const buildActions = createBuildActions( - diffpatcher.diff, + diff, doMapActions, moveMasterVariantsIntoVariants ) diff --git a/packages/sync-actions/src/projects.ts b/packages/sync-actions/src/projects.ts index a98f62fe3..5f7afd653 100644 --- a/packages/sync-actions/src/projects.ts +++ b/packages/sync-actions/src/projects.ts @@ -1,7 +1,7 @@ import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import { actionsMapBase } from './projects-actions' -import * as diffpatcher from './utils/diffpatcher' +import { diff } from './utils/diffpatcher' export const actionGroups = ['base'] @@ -25,6 +25,6 @@ export default (actionGroupList?, syncActionConfig?) => { mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + const buildActions = createBuildActions(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/quote-requests.ts b/packages/sync-actions/src/quote-requests.ts index c76e52e90..807d2c472 100644 --- a/packages/sync-actions/src/quote-requests.ts +++ b/packages/sync-actions/src/quote-requests.ts @@ -8,7 +8,7 @@ import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import actionsMapCustom from './utils/action-map-custom' import * as QuoteRequestsActions from './quote-requests-actions' -import * as diffpatcher from './utils/diffpatcher' +import { diff } from './utils/diffpatcher' const actionGroups = ['base', 'custom'] @@ -57,7 +57,7 @@ export default ( syncActionConfig ) - const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + const buildActions = createBuildActions(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/quotes.ts b/packages/sync-actions/src/quotes.ts index 71ab5b432..b37937803 100644 --- a/packages/sync-actions/src/quotes.ts +++ b/packages/sync-actions/src/quotes.ts @@ -8,7 +8,7 @@ import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import actionsMapCustom from './utils/action-map-custom' import * as QuotesActions from './quotes-actions' -import * as diffpatcher from './utils/diffpatcher' +import { diff } from './utils/diffpatcher' const actionGroups = ['base', 'custom'] @@ -49,7 +49,7 @@ export default ( const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createQuotesMapActions(mapActionGroup, syncActionConfig) - const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + const buildActions = createBuildActions(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/shipping-methods.ts b/packages/sync-actions/src/shipping-methods.ts index 9c28ec182..90e87e41e 100644 --- a/packages/sync-actions/src/shipping-methods.ts +++ b/packages/sync-actions/src/shipping-methods.ts @@ -8,7 +8,7 @@ import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import actionsMapCustom from './utils/action-map-custom' import * as shippingMethodsActions from './shipping-methods-actions' -import * as diffpatcher from './utils/diffpatcher' +import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'zoneRates', 'custom'] @@ -71,6 +71,6 @@ export default ( mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + const buildActions = createBuildActions(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/staged-quotes.ts b/packages/sync-actions/src/staged-quotes.ts index b55a50bb2..6004a7286 100644 --- a/packages/sync-actions/src/staged-quotes.ts +++ b/packages/sync-actions/src/staged-quotes.ts @@ -8,7 +8,7 @@ import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import actionsMapCustom from './utils/action-map-custom' import * as StagedQuotesActions from './staged-quotes-actions' -import * as diffpatcher from './utils/diffpatcher' +import { diff } from './utils/diffpatcher' const actionGroups = ['base', 'custom'] @@ -57,7 +57,7 @@ export default ( syncActionConfig ) - const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + const buildActions = createBuildActions(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/states.ts b/packages/sync-actions/src/states.ts index 484c0c060..d7c9d8330 100644 --- a/packages/sync-actions/src/states.ts +++ b/packages/sync-actions/src/states.ts @@ -7,7 +7,7 @@ import type { import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import * as stateActions from './state-actions' -import * as diffpatcher from './utils/diffpatcher' +import { diff } from './utils/diffpatcher' type RoleUpdate = { action: string @@ -65,6 +65,6 @@ export default ( ): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createStatesMapActions(mapActionGroup, syncActionConfig) - const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + const buildActions = createBuildActions(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/stores.ts b/packages/sync-actions/src/stores.ts index 83aead82c..91b666384 100644 --- a/packages/sync-actions/src/stores.ts +++ b/packages/sync-actions/src/stores.ts @@ -7,7 +7,7 @@ import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import actionsMapCustom from './utils/action-map-custom' import * as storesActions from './stores-actions' -import * as diffpatcher from './utils/diffpatcher' +import { diff } from './utils/diffpatcher' export const actionGroups = ['base'] @@ -46,7 +46,7 @@ export default (actionGroupList?: Array): SyncAction => { const doMapActions = createStoresMapActions(mapActionGroup) const onBeforeApplyingDiff = null const buildActions = createBuildActions( - diffpatcher.diff, + diff, doMapActions, onBeforeApplyingDiff ) diff --git a/packages/sync-actions/src/tax-categories.ts b/packages/sync-actions/src/tax-categories.ts index 542d2cf59..4c7a66a5b 100644 --- a/packages/sync-actions/src/tax-categories.ts +++ b/packages/sync-actions/src/tax-categories.ts @@ -7,7 +7,7 @@ import type { import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import * as taxCategoriesActions from './tax-categories-actions' -import * as diffpatcher from './utils/diffpatcher' +import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'rates'] @@ -67,6 +67,6 @@ export default ( mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + const buildActions = createBuildActions(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/types-actions.ts b/packages/sync-actions/src/types-actions.ts index 389bdad34..b9040398d 100644 --- a/packages/sync-actions/src/types-actions.ts +++ b/packages/sync-actions/src/types-actions.ts @@ -6,7 +6,7 @@ import createBuildArrayActions, { CHANGE_ACTIONS, } from './utils/create-build-array-actions' import { buildBaseAttributesActions } from './utils/common-actions' -import * as diffPatcher from './utils/diffpatcher' +import { diff, getDeltaValue } from './utils/diffpatcher' import extractMatchingPairs from './utils/extract-matching-pairs' const REGEX_NUMBER = new RegExp(/^\d+$/) @@ -150,7 +150,7 @@ export function actionsMapFieldDefinitions( if (getIsChangedOperation(diffKey)) { if (Array.isArray(diffValue)) { - const deltaValue = diffPatcher.getDeltaValue(diffValue) + const deltaValue = getDeltaValue(diffValue) if (deltaValue.name) { actions.push({ action: 'addFieldDefinition', @@ -188,7 +188,7 @@ export function actionsMapFieldDefinitions( fieldNames: next.map((n) => n.name), }) } else { - const deltaValue = diffPatcher.getDeltaValue(diffValue) + const deltaValue = getDeltaValue(diffValue) if (deltaValue === undefined && diffValue[0].name) actions.push({ action: 'removeFieldDefinition', diff --git a/packages/sync-actions/src/types.ts b/packages/sync-actions/src/types.ts index 4564e6048..08dfdd8ad 100644 --- a/packages/sync-actions/src/types.ts +++ b/packages/sync-actions/src/types.ts @@ -1,7 +1,7 @@ import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import * as typeActions from './types-actions' -import * as diffPatcher from './utils/diffpatcher' +import { diff } from './utils/diffpatcher' import findMatchingPairs from './utils/find-matching-pairs' import { SyncActionConfig } from '@commercetools/sdk-client-v2' @@ -41,7 +41,7 @@ export default ( ) => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createTypeMapActions(mapActionGroup, syncActionConfig) - const buildActions = createBuildActions(diffPatcher.diff, doMapActions) + const buildActions = createBuildActions(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/utils/action-map-custom.ts b/packages/sync-actions/src/utils/action-map-custom.ts index ba6b303be..94b4676f5 100644 --- a/packages/sync-actions/src/utils/action-map-custom.ts +++ b/packages/sync-actions/src/utils/action-map-custom.ts @@ -1,4 +1,5 @@ import * as diffpatcher from './diffpatcher' +import { getDeltaValue } from './diffpatcher' const Actions = { setCustomType: 'setCustomType', @@ -10,20 +11,14 @@ const haveMultipleCustomFieldsChanged = (diff) => Boolean(diff.custom.fields) const hasCustomTypeChanged = (diff) => Boolean(diff.custom.type) const extractCustomType = (diff, previousObject) => Array.isArray(diff.custom.type) - ? diffpatcher.getDeltaValue(diff.custom.type, previousObject) + ? getDeltaValue(diff.custom.type, previousObject) : diff.custom.type const extractTypeId = (type, nextObject) => - Array.isArray(type.id) - ? diffpatcher.getDeltaValue(type.id) - : nextObject.custom.type.id + Array.isArray(type.id) ? getDeltaValue(type.id) : nextObject.custom.type.id const extractTypeKey = (type, nextObject) => - Array.isArray(type.key) - ? diffpatcher.getDeltaValue(type.key) - : nextObject.custom.type.key + Array.isArray(type.key) ? getDeltaValue(type.key) : nextObject.custom.type.key const extractTypeFields = (diffedFields, nextFields) => - Array.isArray(diffedFields) - ? diffpatcher.getDeltaValue(diffedFields) - : nextFields + Array.isArray(diffedFields) ? getDeltaValue(diffedFields) : nextFields const extractFieldValue = (newFields, fieldName) => newFields[fieldName] export default function actionsMapCustom( @@ -41,7 +36,7 @@ export default function actionsMapCustom( if (!diff.custom) return actions if (hasSingleCustomFieldChanged(diff)) { // If custom is not defined on the new or old category - const custom = diffpatcher.getDeltaValue(diff.custom, oldObj) + const custom = getDeltaValue(diff.custom, oldObj) actions.push({ action: actionGroup.setCustomType, ...options, ...custom }) } else if (hasCustomTypeChanged(diff)) { // If custom is set to an empty object on the new or old category diff --git a/packages/sync-actions/src/utils/common-actions.ts b/packages/sync-actions/src/utils/common-actions.ts index fe7ed7fa5..49cce0815 100644 --- a/packages/sync-actions/src/utils/common-actions.ts +++ b/packages/sync-actions/src/utils/common-actions.ts @@ -1,6 +1,7 @@ import isNil from 'lodash.isnil' import clone from './clone' import * as diffpatcher from './diffpatcher' +import { getDeltaValue, patch } from './diffpatcher' const normalizeValue = (value) => typeof value === 'string' ? value.trim() : value @@ -61,7 +62,7 @@ export function buildBaseAttributesActions({ return { action: item.action } // We need to clone `before` as `patch` will mutate it - const patched = diffpatcher.patch(clone(before), delta) + const patched = patch(clone(before), delta) return { action: item.action, [actionKey]: patched } }) .filter((action) => !isNil(action)) @@ -91,7 +92,7 @@ export function buildReferenceActions({ actions, diff, oldObj, newObj }) { diff[key].id) ) { const newValue = Array.isArray(diff[key]) - ? diffpatcher.getDeltaValue(diff[key]) + ? getDeltaValue(diff[key]) : newObj[key] if (!newValue) return { action } diff --git a/packages/sync-actions/src/zones.ts b/packages/sync-actions/src/zones.ts index 003efc88c..6429c0d60 100644 --- a/packages/sync-actions/src/zones.ts +++ b/packages/sync-actions/src/zones.ts @@ -7,7 +7,7 @@ import type { import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import * as zonesActions from './zones-actions' -import * as diffpatcher from './utils/diffpatcher' +import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'locations'] @@ -59,6 +59,6 @@ export default ( // It will return an empty array for ignored action groups const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createZonesMapActions(mapActionGroup, syncActionConfig) - const buildActions = createBuildActions(diffpatcher.diff, doMapActions) + const buildActions = createBuildActions(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/test/utils/action-map-custom.spec.ts b/packages/sync-actions/test/utils/action-map-custom.spec.ts index 194070140..4bafd37c5 100644 --- a/packages/sync-actions/test/utils/action-map-custom.spec.ts +++ b/packages/sync-actions/test/utils/action-map-custom.spec.ts @@ -1,11 +1,11 @@ -import * as diffpatcher from '../../src/utils/diffpatcher' import createBuildActions from '../../src/utils/create-build-actions' import doMapActions from '../../src/utils/action-map-custom' +import { diff } from '../../src/utils/diffpatcher' describe('buildActions', () => { let buildActions beforeEach(() => { - buildActions = createBuildActions(diffpatcher.diff, doMapActions) + buildActions = createBuildActions(diff, doMapActions) }) test('should build `setCustomType` action', () => { diff --git a/packages/sync-actions/test/utils/common-actions.spec.ts b/packages/sync-actions/test/utils/common-actions.spec.ts index 79202d2f8..fa237bdfa 100644 --- a/packages/sync-actions/test/utils/common-actions.spec.ts +++ b/packages/sync-actions/test/utils/common-actions.spec.ts @@ -2,7 +2,7 @@ import { buildBaseAttributesActions, buildReferenceActions, } from '../../src/utils/common-actions' -import * as diffpatcher from '../../src/utils/diffpatcher' +import { diff } from '../../src/utils/diffpatcher' describe('Common actions', () => { describe('::buildBaseAttributesActions', () => { @@ -65,7 +65,7 @@ describe('Common actions', () => { actions = buildBaseAttributesActions({ actions: testActions, - diff: diffpatcher.diff(before, now), + diff: diff(before, now), oldObj: before, newObj: now, }) @@ -84,7 +84,7 @@ describe('Common actions', () => { now = { key: '' } actions = buildBaseAttributesActions({ actions: testActions, - diff: diffpatcher.diff(before, now), + diff: diff(before, now), oldObj: before, newObj: now, shouldOmitEmptyString: true, @@ -101,7 +101,7 @@ describe('Common actions', () => { now = { key: '' } actions = buildBaseAttributesActions({ actions: testActions, - diff: diffpatcher.diff(before, now), + diff: diff(before, now), oldObj: before, newObj: now, shouldOmitEmptyString: false, @@ -142,7 +142,7 @@ describe('Common actions', () => { beforeEach(() => { actions = buildReferenceActions({ actions: testActions, - diff: diffpatcher.diff(before, now), + diff: diff(before, now), oldObj: before, newObj: now, }) @@ -169,7 +169,7 @@ describe('Common actions', () => { beforeEach(() => { actions = buildReferenceActions({ actions: testActions, - diff: diffpatcher.diff(before, now), + diff: diff(before, now), oldObj: before, newObj: now, }) @@ -196,7 +196,7 @@ describe('Common actions', () => { beforeEach(() => { actions = buildReferenceActions({ actions: testActions, - diff: diffpatcher.diff(before, now), + diff: diff(before, now), oldObj: before, newObj: now, }) @@ -226,7 +226,7 @@ describe('Common actions', () => { beforeEach(() => { actions = buildReferenceActions({ actions: testActions, - diff: diffpatcher.diff(before, now), + diff: diff(before, now), oldObj: before, newObj: now, }) @@ -257,7 +257,7 @@ describe('Common actions', () => { beforeEach(() => { actions = buildReferenceActions({ actions: testActions, - diff: diffpatcher.diff(before, now), + diff: diff(before, now), oldObj: before, newObj: now, }) @@ -294,7 +294,7 @@ describe('Common actions', () => { beforeEach(() => { actions = buildReferenceActions({ actions: testActions, - diff: diffpatcher.diff(before, now), + diff: diff(before, now), oldObj: before, newObj: now, }) From 63d76007f00b24b128c471b15d466b892ef91af5 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Tue, 7 Nov 2023 14:27:26 +0100 Subject: [PATCH 07/33] feat(migrate): type results --- packages/sync-actions/src/assets-actions.ts | 2 +- .../src/attribute-groups-actions.ts | 2 +- packages/sync-actions/src/attribute-groups.ts | 7 ++--- packages/sync-actions/src/cart-discounts.ts | 15 +++++++---- packages/sync-actions/src/categories.ts | 13 +++++----- packages/sync-actions/src/channels.ts | 13 +++++++--- packages/sync-actions/src/customer-actions.ts | 4 +-- packages/sync-actions/src/customer-group.ts | 13 +++++++--- packages/sync-actions/src/customers.ts | 13 +++++----- packages/sync-actions/src/discount-codes.ts | 15 +++++++---- packages/sync-actions/src/index.ts | 26 +++++++++---------- packages/sync-actions/src/inventories.ts | 11 ++++---- packages/sync-actions/src/order-actions.ts | 2 +- packages/sync-actions/src/orders.ts | 11 ++++---- packages/sync-actions/src/prices.ts | 8 +++--- packages/sync-actions/src/product-actions.ts | 8 +++--- .../sync-actions/src/product-discounts.ts | 13 +++++++--- .../sync-actions/src/product-selections.ts | 16 ++++++------ .../sync-actions/src/product-types-actions.ts | 2 +- packages/sync-actions/src/product-types.ts | 9 ++++--- packages/sync-actions/src/products.ts | 11 ++++---- packages/sync-actions/src/projects.ts | 10 +++++-- packages/sync-actions/src/quote-requests.ts | 11 ++++---- packages/sync-actions/src/quotes.ts | 11 ++++---- .../src/shipping-methods-actions.ts | 4 +-- packages/sync-actions/src/shipping-methods.ts | 11 ++++---- packages/sync-actions/src/staged-quotes.ts | 18 +++++-------- packages/sync-actions/src/states.ts | 9 ++++--- packages/sync-actions/src/stores.ts | 16 ++++++------ .../src/tax-categories-actions.ts | 2 +- packages/sync-actions/src/tax-categories.ts | 9 ++++--- packages/sync-actions/src/types-actions.ts | 4 +-- packages/sync-actions/src/types.ts | 4 +-- .../sync-actions/src/types/update-actions.ts | 5 ++++ .../src/utils/action-map-custom.ts | 1 - .../sync-actions/src/utils/common-actions.ts | 1 - packages/sync-actions/src/zones-actions.ts | 4 +-- packages/sync-actions/src/zones.ts | 7 ++--- 38 files changed, 192 insertions(+), 149 deletions(-) create mode 100644 packages/sync-actions/src/types/update-actions.ts diff --git a/packages/sync-actions/src/assets-actions.ts b/packages/sync-actions/src/assets-actions.ts index 3f08c4ccd..749a87c9e 100644 --- a/packages/sync-actions/src/assets-actions.ts +++ b/packages/sync-actions/src/assets-actions.ts @@ -1,7 +1,7 @@ import createBuildArrayActions, { ADD_ACTIONS, - REMOVE_ACTIONS, CHANGE_ACTIONS, + REMOVE_ACTIONS, } from './utils/create-build-array-actions' function toAssetIdentifier(asset) { diff --git a/packages/sync-actions/src/attribute-groups-actions.ts b/packages/sync-actions/src/attribute-groups-actions.ts index 7f3d8dbb6..036a70603 100644 --- a/packages/sync-actions/src/attribute-groups-actions.ts +++ b/packages/sync-actions/src/attribute-groups-actions.ts @@ -1,8 +1,8 @@ import { buildBaseAttributesActions } from './utils/common-actions' import createBuildArrayActions, { ADD_ACTIONS, - REMOVE_ACTIONS, CHANGE_ACTIONS, + REMOVE_ACTIONS, } from './utils/create-build-array-actions' const hasAttribute = (attributes, newValue) => diff --git a/packages/sync-actions/src/attribute-groups.ts b/packages/sync-actions/src/attribute-groups.ts index ba97c210e..3c18b378d 100644 --- a/packages/sync-actions/src/attribute-groups.ts +++ b/packages/sync-actions/src/attribute-groups.ts @@ -1,13 +1,14 @@ +import { AttributeGroupUpdateAction } from '@commercetools/platform-sdk' import type { - SyncAction, ActionGroup, - UpdateAction, SyncActionConfig, + UpdateAction, } from '@commercetools/sdk-client-v2' import { actionsMapAttributes, actionsMapBase, } from './attribute-groups-actions' +import { SyncAction } from './types/update-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' @@ -45,7 +46,7 @@ function createAttributeGroupsMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createAttributeGroupsMapActions( mapActionGroup, diff --git a/packages/sync-actions/src/cart-discounts.ts b/packages/sync-actions/src/cart-discounts.ts index e270618d7..09ea8c512 100644 --- a/packages/sync-actions/src/cart-discounts.ts +++ b/packages/sync-actions/src/cart-discounts.ts @@ -1,10 +1,12 @@ -import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' -import actionsMapCustom from './utils/action-map-custom' +import { CartDiscountUpdateAction } from '@commercetools/platform-sdk' +import { ActionGroup, SyncActionConfig } from '@commercetools/sdk-client-v2' import { actionsMapBase } from './cart-discounts-actions' +import { SyncAction } from './types/update-actions' +import actionsMapCustom from './utils/action-map-custom' import combineValidityActions from './utils/combine-validity-actions' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' -import { SyncActionConfig } from '@commercetools/sdk-client-v2' export const actionGroups = ['base', 'custom'] @@ -26,7 +28,10 @@ function createCartDiscountsMapActions(mapActionGroup, syncActionConfig) { } } -export default (actionGroupList?, syncActionConfig?: SyncActionConfig) => { +export default ( + actionGroupList?: Array, + syncActionConfig?: SyncActionConfig +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createCartDiscountsMapActions( mapActionGroup, diff --git a/packages/sync-actions/src/categories.ts b/packages/sync-actions/src/categories.ts index 61819a568..e7ee2aac4 100644 --- a/packages/sync-actions/src/categories.ts +++ b/packages/sync-actions/src/categories.ts @@ -1,19 +1,20 @@ +import { CategoryUpdateAction } from '@commercetools/platform-sdk' import type { - SyncAction, + ActionGroup, SyncActionConfig, UpdateAction, - ActionGroup, } from '@commercetools/sdk-client-v2' -import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' -import actionsMapCustom from './utils/action-map-custom' import actionsMapAssets from './assets-actions' import { actionsMapBase, actionsMapMeta, actionsMapReferences, } from './category-actions' +import { SyncAction } from './types/update-actions' +import actionsMapCustom from './utils/action-map-custom' import copyEmptyArrayProps from './utils/copy-empty-array-props' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'references', 'meta', 'custom', 'assets'] @@ -72,7 +73,7 @@ function createCategoryMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { // actionGroupList contains information about which action groups // are allowed or ignored diff --git a/packages/sync-actions/src/channels.ts b/packages/sync-actions/src/channels.ts index 690e915a0..24919ea7e 100644 --- a/packages/sync-actions/src/channels.ts +++ b/packages/sync-actions/src/channels.ts @@ -1,9 +1,11 @@ +import { ChannelUpdateAction } from '@commercetools/platform-sdk' +import { ActionGroup, SyncActionConfig } from '@commercetools/sdk-client-v2' +import { actionsMapBase } from './channels-actions' +import { SyncAction } from './types/update-actions' +import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' -import actionsMapCustom from './utils/action-map-custom' -import { actionsMapBase } from './channels-actions' import { diff } from './utils/diffpatcher' -import { SyncActionConfig } from '@commercetools/sdk-client-v2' export const actionGroups = ['base', 'custom'] @@ -25,7 +27,10 @@ function createChannelsMapActions(mapActionGroup, syncActionConfig) { } } -export default (actionGroupList?, syncActionConfig?: SyncActionConfig) => { +export default ( + actionGroupList?: Array, + syncActionConfig?: SyncActionConfig +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createChannelsMapActions( mapActionGroup, diff --git a/packages/sync-actions/src/customer-actions.ts b/packages/sync-actions/src/customer-actions.ts index aa9d6f55b..443c99902 100644 --- a/packages/sync-actions/src/customer-actions.ts +++ b/packages/sync-actions/src/customer-actions.ts @@ -1,4 +1,5 @@ import isNil from 'lodash.isnil' +import clone from './utils/clone' import { buildBaseAttributesActions, buildReferenceActions, @@ -6,11 +7,10 @@ import { } from './utils/common-actions' import createBuildArrayActions, { ADD_ACTIONS, - REMOVE_ACTIONS, CHANGE_ACTIONS, + REMOVE_ACTIONS, } from './utils/create-build-array-actions' import { patch } from './utils/diffpatcher' -import clone from './utils/clone' const isEmptyValue = createIsEmptyValue([undefined, null, '']) diff --git a/packages/sync-actions/src/customer-group.ts b/packages/sync-actions/src/customer-group.ts index 053898dcf..752a60e07 100644 --- a/packages/sync-actions/src/customer-group.ts +++ b/packages/sync-actions/src/customer-group.ts @@ -1,9 +1,11 @@ +import { CustomerGroupUpdateAction } from '@commercetools/platform-sdk' +import { ActionGroup, SyncActionConfig } from '@commercetools/sdk-client-v2' +import { actionsMapBase } from './customer-group-actions' +import { SyncAction } from './types/update-actions' +import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' -import actionsMapCustom from './utils/action-map-custom' -import { actionsMapBase } from './customer-group-actions' import { diff } from './utils/diffpatcher' -import { SyncActionConfig } from '@commercetools/sdk-client-v2' export const actionGroups = ['base', 'custom'] @@ -25,7 +27,10 @@ function createCustomerGroupMapActions(mapActionGroup, syncActionConfig) { } } -export default (actionGroupList?, syncActionConfig?: SyncActionConfig) => { +export default ( + actionGroupList?: Array, + syncActionConfig?: SyncActionConfig +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createCustomerGroupMapActions( mapActionGroup, diff --git a/packages/sync-actions/src/customers.ts b/packages/sync-actions/src/customers.ts index 123a1c5a5..cd4880887 100644 --- a/packages/sync-actions/src/customers.ts +++ b/packages/sync-actions/src/customers.ts @@ -1,15 +1,16 @@ +import { CustomerUpdateAction } from '@commercetools/platform-sdk' import type { - SyncAction, + ActionGroup, SyncActionConfig, UpdateAction, - ActionGroup, } from '@commercetools/sdk-client-v2' +import * as customerActions from './customer-actions' +import { SyncAction } from './types/update-actions' +import actionsMapCustom from './utils/action-map-custom' +import copyEmptyArrayProps from './utils/copy-empty-array-props' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' -import actionsMapCustom from './utils/action-map-custom' -import * as customerActions from './customer-actions' import { diff } from './utils/diffpatcher' -import copyEmptyArrayProps from './utils/copy-empty-array-props' export const actionGroups = [ 'base', @@ -105,7 +106,7 @@ function createCustomerMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { // actionGroupList contains information about which action groups // are allowed or ignored diff --git a/packages/sync-actions/src/discount-codes.ts b/packages/sync-actions/src/discount-codes.ts index 724f8640e..363ba8ba4 100644 --- a/packages/sync-actions/src/discount-codes.ts +++ b/packages/sync-actions/src/discount-codes.ts @@ -1,10 +1,12 @@ -import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' -import actionsMapCustom from './utils/action-map-custom' +import { DiscountCodeUpdateAction } from '@commercetools/platform-sdk' +import { ActionGroup, SyncActionConfig } from '@commercetools/sdk-client-v2' import { actionsMapBase } from './discount-codes-actions' +import { SyncAction } from './types/update-actions' +import actionsMapCustom from './utils/action-map-custom' import combineValidityActions from './utils/combine-validity-actions' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' -import { SyncActionConfig } from '@commercetools/sdk-client-v2' export const actionGroups = ['base', 'custom'] @@ -23,7 +25,10 @@ function createDiscountCodesMapActions(mapActionGroup, syncActionConfig) { } } -export default (actionGroupList?, syncActionConfig?: SyncActionConfig) => { +export default ( + actionGroupList?: Array, + syncActionConfig?: SyncActionConfig +): SyncAction => { // actionGroupList contains information about which action groups // are allowed or ignored diff --git a/packages/sync-actions/src/index.ts b/packages/sync-actions/src/index.ts index 348e1d398..423c2b327 100644 --- a/packages/sync-actions/src/index.ts +++ b/packages/sync-actions/src/index.ts @@ -1,21 +1,21 @@ +export { default as createSyncAttributeGroups } from './attribute-groups' +export { default as createSyncCartDiscounts } from './cart-discounts' export { default as createSyncCategories } from './categories' +export { default as createSyncChannels } from './channels' +export { default as createSyncCustomerGroup } from './customer-group' export { default as createSyncCustomers } from './customers' +export { default as createSyncDiscountCodes } from './discount-codes' export { default as createSyncInventories } from './inventories' -export { default as createSyncProducts } from './products' export { default as createSyncOrders } from './orders' +export { default as createSyncStandalonePrices } from './prices' export { default as createSyncProductDiscounts } from './product-discounts' -export { default as createSyncDiscountCodes } from './discount-codes' -export { default as createSyncCustomerGroup } from './customer-group' -export { default as createSyncCartDiscounts } from './cart-discounts' -export { default as createSyncTaxCategories } from './tax-categories' -export { default as createSyncZones } from './zones' -export { default as createSyncShippingMethods } from './shipping-methods' +export { default as createSyncProductSelections } from './product-selections' export { default as createSyncProductTypes } from './product-types' -export { default as createSyncStates } from './states' -export { default as createSyncChannels } from './channels' -export { default as createSyncTypes } from './types' +export { default as createSyncProducts } from './products' export { default as createSyncProjects } from './projects' +export { default as createSyncShippingMethods } from './shipping-methods' +export { default as createSyncStates } from './states' export { default as createSyncStores } from './stores' -export { default as createSyncProductSelections } from './product-selections' -export { default as createSyncStandalonePrices } from './prices' -export { default as createSyncAttributeGroups } from './attribute-groups' +export { default as createSyncTaxCategories } from './tax-categories' +export { default as createSyncTypes } from './types' +export { default as createSyncZones } from './zones' diff --git a/packages/sync-actions/src/inventories.ts b/packages/sync-actions/src/inventories.ts index c28e066f5..5e4bc89b6 100644 --- a/packages/sync-actions/src/inventories.ts +++ b/packages/sync-actions/src/inventories.ts @@ -1,13 +1,14 @@ +import { InventoryEntryUpdateAction } from '@commercetools/platform-sdk' import type { - SyncAction, + ActionGroup, SyncActionConfig, UpdateAction, - ActionGroup, } from '@commercetools/sdk-client-v2' +import * as inventoryActions from './inventory-actions' +import { SyncAction } from './types/update-actions' +import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' -import actionsMapCustom from './utils/action-map-custom' -import * as inventoryActions from './inventory-actions' import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'references'] @@ -54,7 +55,7 @@ function createInventoryMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { // actionGroupList contains information about which action groups // are allowed or ignored diff --git a/packages/sync-actions/src/order-actions.ts b/packages/sync-actions/src/order-actions.ts index 25dcda95a..be0312fdd 100644 --- a/packages/sync-actions/src/order-actions.ts +++ b/packages/sync-actions/src/order-actions.ts @@ -1,9 +1,9 @@ -import { diff, getDeltaValue } from './utils/diffpatcher' import { buildBaseAttributesActions } from './utils/common-actions' import createBuildArrayActions, { ADD_ACTIONS, CHANGE_ACTIONS, } from './utils/create-build-array-actions' +import { getDeltaValue } from './utils/diffpatcher' import extractMatchingPairs from './utils/extract-matching-pairs' import findMatchingPairs from './utils/find-matching-pairs' diff --git a/packages/sync-actions/src/orders.ts b/packages/sync-actions/src/orders.ts index 8a2c715f1..3d8807ecb 100644 --- a/packages/sync-actions/src/orders.ts +++ b/packages/sync-actions/src/orders.ts @@ -1,13 +1,14 @@ +import { OrderUpdateAction } from '@commercetools/platform-sdk' import type { - SyncAction, - SyncActionConfig, ActionGroup, + SyncActionConfig, UpdateAction, } from '@commercetools/sdk-client-v2' +import * as orderActions from './order-actions' +import { SyncAction } from './types/update-actions' +import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' -import actionsMapCustom from './utils/action-map-custom' -import * as orderActions from './order-actions' import { diff } from './utils/diffpatcher' import findMatchingPairs from './utils/find-matching-pairs' @@ -89,7 +90,7 @@ function createOrderMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { // actionGroupList contains information about which action groups // are allowed or ignored diff --git a/packages/sync-actions/src/prices.ts b/packages/sync-actions/src/prices.ts index 58454f892..e2fa3f095 100644 --- a/packages/sync-actions/src/prices.ts +++ b/packages/sync-actions/src/prices.ts @@ -1,15 +1,15 @@ import type { + ActionGroup, SyncAction, SyncActionConfig, - ActionGroup, UpdateAction, } from '@commercetools/sdk-client-v2' +import * as pricesActions from './prices-actions' +import actionsMapCustom from './utils/action-map-custom' +import combineValidityActions from './utils/combine-validity-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' -import actionsMapCustom from './utils/action-map-custom' -import * as pricesActions from './prices-actions' import { diff } from './utils/diffpatcher' -import combineValidityActions from './utils/combine-validity-actions' const actionGroups = ['base', 'custom'] diff --git a/packages/sync-actions/src/product-actions.ts b/packages/sync-actions/src/product-actions.ts index 9605715de..d0484b458 100644 --- a/packages/sync-actions/src/product-actions.ts +++ b/packages/sync-actions/src/product-actions.ts @@ -1,9 +1,8 @@ /* eslint-disable max-len */ -import uniqWith from 'lodash.uniqwith' +import { ProductVariant } from '@commercetools/platform-sdk/src' import intersection from 'lodash.intersection' +import uniqWith from 'lodash.uniqwith' import without from 'lodash.without' -import { diff, getDeltaValue } from './utils/diffpatcher' -import extractMatchingPairs from './utils/extract-matching-pairs' import actionsMapCustom from './utils/action-map-custom' import { buildBaseAttributesActions, @@ -13,8 +12,9 @@ import createBuildArrayActions, { ADD_ACTIONS, REMOVE_ACTIONS, } from './utils/create-build-array-actions' +import { getDeltaValue } from './utils/diffpatcher' +import extractMatchingPairs from './utils/extract-matching-pairs' import findMatchingPairs from './utils/find-matching-pairs' -import { ProductVariant } from '@commercetools/platform-sdk/src' const REGEX_NUMBER = new RegExp(/^\d+$/) const REGEX_UNDERSCORE_NUMBER = new RegExp(/^_\d+$/) diff --git a/packages/sync-actions/src/product-discounts.ts b/packages/sync-actions/src/product-discounts.ts index 1b86da58b..11b33d511 100644 --- a/packages/sync-actions/src/product-discounts.ts +++ b/packages/sync-actions/src/product-discounts.ts @@ -1,9 +1,11 @@ -import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import { ProductDiscountUpdateAction } from '@commercetools/platform-sdk' +import { ActionGroup, SyncActionConfig } from '@commercetools/sdk-client-v2' import { actionsMapBase } from './product-discounts-actions' +import { SyncAction } from './types/update-actions' import combineValidityActions from './utils/combine-validity-actions' +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' -import { SyncActionConfig } from '@commercetools/sdk-client-v2' export const actionGroups = ['base'] @@ -20,7 +22,10 @@ function createProductDiscountsMapActions(mapActionGroup, syncActionConfig) { } } -export default (actionGroupList?, syncActionConfig?: SyncActionConfig) => { +export default ( + actionGroupList?: Array, + syncActionConfig?: SyncActionConfig +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createProductDiscountsMapActions( mapActionGroup, diff --git a/packages/sync-actions/src/product-selections.ts b/packages/sync-actions/src/product-selections.ts index 6fc061d10..3c6c90d1a 100644 --- a/packages/sync-actions/src/product-selections.ts +++ b/packages/sync-actions/src/product-selections.ts @@ -1,12 +1,10 @@ -import type { - SyncAction, - UpdateAction, - ActionGroup, -} from '@commercetools/sdk-client-v2' +import { ProductSelectionUpdateAction } from '@commercetools/platform-sdk' +import type { ActionGroup, UpdateAction } from '@commercetools/sdk-client-v2' +import * as productSelectionsActions from './product-selections-actions' +import { SyncAction } from './types/update-actions' +import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' -import actionsMapCustom from './utils/action-map-custom' -import * as productSelectionsActions from './product-selections-actions' import { diff } from './utils/diffpatcher' export const actionGroups = ['base'] @@ -41,7 +39,9 @@ function createProductSelectionsMapActions( } } -export default (actionGroupList?: Array): SyncAction => { +export default ( + actionGroupList?: Array +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createProductSelectionsMapActions(mapActionGroup) const onBeforeApplyingDiff = null diff --git a/packages/sync-actions/src/product-types-actions.ts b/packages/sync-actions/src/product-types-actions.ts index 96802b3fe..571abd449 100644 --- a/packages/sync-actions/src/product-types-actions.ts +++ b/packages/sync-actions/src/product-types-actions.ts @@ -1,7 +1,7 @@ import { deepEqual } from 'fast-equals' import { - createIsEmptyValue, buildBaseAttributesActions, + createIsEmptyValue, } from './utils/common-actions' export const baseActionsList = [ diff --git a/packages/sync-actions/src/product-types.ts b/packages/sync-actions/src/product-types.ts index ac7a678a0..880e36c29 100644 --- a/packages/sync-actions/src/product-types.ts +++ b/packages/sync-actions/src/product-types.ts @@ -1,12 +1,13 @@ +import { ProductTypeUpdateAction } from '@commercetools/platform-sdk' import type { - SyncAction, - UpdateAction, ActionGroup, SyncActionConfig as BaseSyncActionConfig, + UpdateAction, } from '@commercetools/sdk-client-v2' +import * as productTypeActions from './product-types-actions' +import { SyncAction } from './types/update-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' -import * as productTypeActions from './product-types-actions' import { diff } from './utils/diffpatcher' type SyncActionConfig = { withHints?: boolean } & BaseSyncActionConfig @@ -51,7 +52,7 @@ function createProductTypeMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createProductTypeMapActions( mapActionGroup, diff --git a/packages/sync-actions/src/products.ts b/packages/sync-actions/src/products.ts index 7919b2ffe..4d241a86f 100644 --- a/packages/sync-actions/src/products.ts +++ b/packages/sync-actions/src/products.ts @@ -1,15 +1,16 @@ +import { ProductUpdateAction } from '@commercetools/platform-sdk' import type { - SyncAction, - SyncActionConfig, ActionGroup, + SyncActionConfig, UpdateAction, } from '@commercetools/sdk-client-v2' +import * as productActions from './product-actions' +import { SyncAction } from './types/update-actions' +import copyEmptyArrayProps from './utils/copy-empty-array-props' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' -import * as productActions from './product-actions' import { diff } from './utils/diffpatcher' import findMatchingPairs from './utils/find-matching-pairs' -import copyEmptyArrayProps from './utils/copy-empty-array-props' const actionGroups = [ 'base', @@ -183,7 +184,7 @@ function moveMasterVariantsIntoVariants(before: any, now: any): Array { export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createProductMapActions(mapActionGroup, syncActionConfig) diff --git a/packages/sync-actions/src/projects.ts b/packages/sync-actions/src/projects.ts index 5f7afd653..4933e881d 100644 --- a/packages/sync-actions/src/projects.ts +++ b/packages/sync-actions/src/projects.ts @@ -1,6 +1,9 @@ +import { ProjectUpdateAction } from '@commercetools/platform-sdk' +import { ActionGroup, SyncActionConfig } from '@commercetools/sdk-client-v2' +import { actionsMapBase } from './projects-actions' +import { SyncAction } from './types/update-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' -import { actionsMapBase } from './projects-actions' import { diff } from './utils/diffpatcher' export const actionGroups = ['base'] @@ -19,7 +22,10 @@ function createChannelsMapActions(mapActionGroup, syncActionConfig) { } } -export default (actionGroupList?, syncActionConfig?) => { +export default ( + actionGroupList?: Array, + syncActionConfig?: SyncActionConfig +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createChannelsMapActions( mapActionGroup, diff --git a/packages/sync-actions/src/quote-requests.ts b/packages/sync-actions/src/quote-requests.ts index 807d2c472..cf1353569 100644 --- a/packages/sync-actions/src/quote-requests.ts +++ b/packages/sync-actions/src/quote-requests.ts @@ -1,13 +1,14 @@ +import { QuoteRequestUpdateAction } from '@commercetools/platform-sdk' import type { - SyncAction, - SyncActionConfig, ActionGroup, + SyncActionConfig, UpdateAction, } from '@commercetools/sdk-client-v2' +import * as QuoteRequestsActions from './quote-requests-actions' +import { SyncAction } from './types/update-actions' +import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' -import actionsMapCustom from './utils/action-map-custom' -import * as QuoteRequestsActions from './quote-requests-actions' import { diff } from './utils/diffpatcher' const actionGroups = ['base', 'custom'] @@ -50,7 +51,7 @@ function createQuoteRequestsMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createQuoteRequestsMapActions( mapActionGroup, diff --git a/packages/sync-actions/src/quotes.ts b/packages/sync-actions/src/quotes.ts index b37937803..02e46ca3f 100644 --- a/packages/sync-actions/src/quotes.ts +++ b/packages/sync-actions/src/quotes.ts @@ -1,13 +1,14 @@ +import { QuoteUpdateAction } from '@commercetools/platform-sdk' import type { - SyncAction, - SyncActionConfig, ActionGroup, + SyncActionConfig, UpdateAction, } from '@commercetools/sdk-client-v2' +import * as QuotesActions from './quotes-actions' +import { SyncAction } from './types/update-actions' +import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' -import actionsMapCustom from './utils/action-map-custom' -import * as QuotesActions from './quotes-actions' import { diff } from './utils/diffpatcher' const actionGroups = ['base', 'custom'] @@ -45,7 +46,7 @@ function createQuotesMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createQuotesMapActions(mapActionGroup, syncActionConfig) diff --git a/packages/sync-actions/src/shipping-methods-actions.ts b/packages/sync-actions/src/shipping-methods-actions.ts index 2110b99c8..bf299318f 100644 --- a/packages/sync-actions/src/shipping-methods-actions.ts +++ b/packages/sync-actions/src/shipping-methods-actions.ts @@ -1,9 +1,9 @@ +import { buildBaseAttributesActions } from './utils/common-actions' import createBuildArrayActions, { ADD_ACTIONS, - REMOVE_ACTIONS, CHANGE_ACTIONS, + REMOVE_ACTIONS, } from './utils/create-build-array-actions' -import { buildBaseAttributesActions } from './utils/common-actions' export const baseActionsList = [ { action: 'setKey', key: 'key' }, diff --git a/packages/sync-actions/src/shipping-methods.ts b/packages/sync-actions/src/shipping-methods.ts index 90e87e41e..6770280a8 100644 --- a/packages/sync-actions/src/shipping-methods.ts +++ b/packages/sync-actions/src/shipping-methods.ts @@ -1,13 +1,14 @@ +import { ShippingMethodUpdateAction } from '@commercetools/platform-sdk' import type { - SyncAction, - SyncActionConfig, ActionGroup, + SyncActionConfig, UpdateAction, } from '@commercetools/sdk-client-v2' +import * as shippingMethodsActions from './shipping-methods-actions' +import { SyncAction } from './types/update-actions' +import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' -import actionsMapCustom from './utils/action-map-custom' -import * as shippingMethodsActions from './shipping-methods-actions' import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'zoneRates', 'custom'] @@ -54,7 +55,7 @@ function createShippingMethodsMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { // actionGroupList contains information about which action groups // are allowed or ignored diff --git a/packages/sync-actions/src/staged-quotes.ts b/packages/sync-actions/src/staged-quotes.ts index 6004a7286..517d09b71 100644 --- a/packages/sync-actions/src/staged-quotes.ts +++ b/packages/sync-actions/src/staged-quotes.ts @@ -1,13 +1,14 @@ +import { StagedQuoteUpdateAction } from '@commercetools/platform-sdk' import type { - SyncAction, - SyncActionConfig, ActionGroup, + SyncActionConfig, UpdateAction, } from '@commercetools/sdk-client-v2' +import { actionsMapBase } from './staged-quotes-actions' +import { SyncAction } from './types/update-actions' +import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' -import actionsMapCustom from './utils/action-map-custom' -import * as StagedQuotesActions from './staged-quotes-actions' import { diff } from './utils/diffpatcher' const actionGroups = ['base', 'custom'] @@ -27,12 +28,7 @@ function createStagedQuotesMapActions( mapActionGroup( 'base', (): Array => - StagedQuotesActions.actionsMapBase( - diff, - oldObj, - newObj, - syncActionConfig - ) + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) @@ -50,7 +46,7 @@ function createStagedQuotesMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createStagedQuotesMapActions( mapActionGroup, diff --git a/packages/sync-actions/src/states.ts b/packages/sync-actions/src/states.ts index d7c9d8330..22693c6b8 100644 --- a/packages/sync-actions/src/states.ts +++ b/packages/sync-actions/src/states.ts @@ -1,12 +1,13 @@ +import { StateUpdateAction } from '@commercetools/platform-sdk' import type { - UpdateAction, - SyncAction, ActionGroup, SyncActionConfig, + UpdateAction, } from '@commercetools/sdk-client-v2' +import * as stateActions from './state-actions' +import { SyncAction } from './types/update-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' -import * as stateActions from './state-actions' import { diff } from './utils/diffpatcher' type RoleUpdate = { @@ -62,7 +63,7 @@ function createStatesMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createStatesMapActions(mapActionGroup, syncActionConfig) const buildActions = createBuildActions(diff, doMapActions) diff --git a/packages/sync-actions/src/stores.ts b/packages/sync-actions/src/stores.ts index 91b666384..acba8ddb8 100644 --- a/packages/sync-actions/src/stores.ts +++ b/packages/sync-actions/src/stores.ts @@ -1,12 +1,10 @@ -import type { - SyncAction, - UpdateAction, - ActionGroup, -} from '@commercetools/sdk-client-v2' +import { StoreUpdateAction } from '@commercetools/platform-sdk' +import type { ActionGroup, UpdateAction } from '@commercetools/sdk-client-v2' +import * as storesActions from './stores-actions' +import { SyncAction } from './types/update-actions' +import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' -import actionsMapCustom from './utils/action-map-custom' -import * as storesActions from './stores-actions' import { diff } from './utils/diffpatcher' export const actionGroups = ['base'] @@ -41,7 +39,9 @@ function createStoresMapActions( } } -export default (actionGroupList?: Array): SyncAction => { +export default ( + actionGroupList?: Array +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createStoresMapActions(mapActionGroup) const onBeforeApplyingDiff = null diff --git a/packages/sync-actions/src/tax-categories-actions.ts b/packages/sync-actions/src/tax-categories-actions.ts index a62b869d5..921b2e2f4 100644 --- a/packages/sync-actions/src/tax-categories-actions.ts +++ b/packages/sync-actions/src/tax-categories-actions.ts @@ -1,8 +1,8 @@ import { buildBaseAttributesActions } from './utils/common-actions' import createBuildArrayActions, { ADD_ACTIONS, - REMOVE_ACTIONS, CHANGE_ACTIONS, + REMOVE_ACTIONS, } from './utils/create-build-array-actions' export const baseActionsList = [ diff --git a/packages/sync-actions/src/tax-categories.ts b/packages/sync-actions/src/tax-categories.ts index 4c7a66a5b..01b52bf74 100644 --- a/packages/sync-actions/src/tax-categories.ts +++ b/packages/sync-actions/src/tax-categories.ts @@ -1,12 +1,13 @@ +import { TaxCategoryUpdateAction } from '@commercetools/platform-sdk' import type { - SyncAction, ActionGroup, - UpdateAction, SyncActionConfig, + UpdateAction, } from '@commercetools/sdk-client-v2' +import * as taxCategoriesActions from './tax-categories-actions' +import { SyncAction } from './types/update-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' -import * as taxCategoriesActions from './tax-categories-actions' import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'rates'] @@ -50,7 +51,7 @@ function createTaxCategoriesMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { // config contains information about which action groups // are allowed or ignored diff --git a/packages/sync-actions/src/types-actions.ts b/packages/sync-actions/src/types-actions.ts index b9040398d..59c30020b 100644 --- a/packages/sync-actions/src/types-actions.ts +++ b/packages/sync-actions/src/types-actions.ts @@ -1,12 +1,12 @@ import sortBy from 'lodash.sortby' import isEqual from 'lodash.isequal' +import { buildBaseAttributesActions } from './utils/common-actions' import createBuildArrayActions, { ADD_ACTIONS, CHANGE_ACTIONS, } from './utils/create-build-array-actions' -import { buildBaseAttributesActions } from './utils/common-actions' -import { diff, getDeltaValue } from './utils/diffpatcher' +import { getDeltaValue } from './utils/diffpatcher' import extractMatchingPairs from './utils/extract-matching-pairs' const REGEX_NUMBER = new RegExp(/^\d+$/) diff --git a/packages/sync-actions/src/types.ts b/packages/sync-actions/src/types.ts index 08dfdd8ad..0fc51c22d 100644 --- a/packages/sync-actions/src/types.ts +++ b/packages/sync-actions/src/types.ts @@ -1,9 +1,9 @@ +import { SyncActionConfig } from '@commercetools/sdk-client-v2' +import * as typeActions from './types-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' -import * as typeActions from './types-actions' import { diff } from './utils/diffpatcher' import findMatchingPairs from './utils/find-matching-pairs' -import { SyncActionConfig } from '@commercetools/sdk-client-v2' const actionGroups = ['base', 'fieldDefinitions'] diff --git a/packages/sync-actions/src/types/update-actions.ts b/packages/sync-actions/src/types/update-actions.ts new file mode 100644 index 000000000..0970bc78e --- /dev/null +++ b/packages/sync-actions/src/types/update-actions.ts @@ -0,0 +1,5 @@ +import { UpdateAction } from '@commercetools/sdk-client-v2' + +export type SyncAction = { + buildActions: (now: Object, before: Object) => Array +} diff --git a/packages/sync-actions/src/utils/action-map-custom.ts b/packages/sync-actions/src/utils/action-map-custom.ts index 94b4676f5..d61f6b2c5 100644 --- a/packages/sync-actions/src/utils/action-map-custom.ts +++ b/packages/sync-actions/src/utils/action-map-custom.ts @@ -1,4 +1,3 @@ -import * as diffpatcher from './diffpatcher' import { getDeltaValue } from './diffpatcher' const Actions = { diff --git a/packages/sync-actions/src/utils/common-actions.ts b/packages/sync-actions/src/utils/common-actions.ts index 49cce0815..e3eef2c68 100644 --- a/packages/sync-actions/src/utils/common-actions.ts +++ b/packages/sync-actions/src/utils/common-actions.ts @@ -1,6 +1,5 @@ import isNil from 'lodash.isnil' import clone from './clone' -import * as diffpatcher from './diffpatcher' import { getDeltaValue, patch } from './diffpatcher' const normalizeValue = (value) => diff --git a/packages/sync-actions/src/zones-actions.ts b/packages/sync-actions/src/zones-actions.ts index 44616f9bf..0fb10c257 100644 --- a/packages/sync-actions/src/zones-actions.ts +++ b/packages/sync-actions/src/zones-actions.ts @@ -1,9 +1,9 @@ +import { buildBaseAttributesActions } from './utils/common-actions' import createBuildArrayActions, { ADD_ACTIONS, - REMOVE_ACTIONS, CHANGE_ACTIONS, + REMOVE_ACTIONS, } from './utils/create-build-array-actions' -import { buildBaseAttributesActions } from './utils/common-actions' export const baseActionsList = [ { action: 'changeName', key: 'name' }, diff --git a/packages/sync-actions/src/zones.ts b/packages/sync-actions/src/zones.ts index 6429c0d60..545d7809d 100644 --- a/packages/sync-actions/src/zones.ts +++ b/packages/sync-actions/src/zones.ts @@ -1,13 +1,14 @@ +import { ZoneUpdateAction } from '@commercetools/platform-sdk' import type { - SyncAction, ActionGroup, SyncActionConfig, UpdateAction, } from '@commercetools/sdk-client-v2' +import { SyncAction } from './types/update-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' -import * as zonesActions from './zones-actions' import { diff } from './utils/diffpatcher' +import * as zonesActions from './zones-actions' export const actionGroups = ['base', 'locations'] @@ -45,7 +46,7 @@ function createZonesMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { // config contains information about which action groups // are allowed or ignored From 324a66294c53bf9612d13535e143006c4373b6b8 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Tue, 7 Nov 2023 14:42:14 +0100 Subject: [PATCH 08/33] feat(migrate): replace import * as with proper imports --- packages/sync-actions/src/customers.ts | 31 +++++------ packages/sync-actions/src/inventories.ts | 13 ++--- packages/sync-actions/src/orders.ts | 25 +++++---- packages/sync-actions/src/prices.ts | 4 +- .../sync-actions/src/product-selections.ts | 5 +- packages/sync-actions/src/products.ts | 51 ++++++++++--------- packages/sync-actions/src/quote-requests.ts | 9 +--- packages/sync-actions/src/quotes.ts | 4 +- packages/sync-actions/src/shipping-methods.ts | 12 ++--- packages/sync-actions/src/states.ts | 7 ++- packages/sync-actions/src/stores.ts | 5 +- packages/sync-actions/src/tax-categories.ts | 12 ++--- packages/sync-actions/src/types.ts | 6 +-- 13 files changed, 82 insertions(+), 102 deletions(-) diff --git a/packages/sync-actions/src/customers.ts b/packages/sync-actions/src/customers.ts index cd4880887..94b45c42d 100644 --- a/packages/sync-actions/src/customers.ts +++ b/packages/sync-actions/src/customers.ts @@ -4,7 +4,15 @@ import type { SyncActionConfig, UpdateAction, } from '@commercetools/sdk-client-v2' -import * as customerActions from './customer-actions' +import { + actionsMapAddresses, + actionsMapAuthenticationModes, + actionsMapBase, + actionsMapBillingAddresses, + actionsMapReferences, + actionsMapSetDefaultBase, + actionsMapShippingAddresses, +} from './customer-actions' import { SyncAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import copyEmptyArrayProps from './utils/copy-empty-array-props' @@ -35,23 +43,21 @@ function createCustomerMapActions( mapActionGroup( 'base', (): Array => - customerActions.actionsMapBase(diff, oldObj, newObj, syncActionConfig) + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) allActions.push( mapActionGroup( 'references', - (): Array => - customerActions.actionsMapReferences(diff, oldObj, newObj) + (): Array => actionsMapReferences(diff, oldObj, newObj) ) ) allActions.push( mapActionGroup( 'addresses', - (): Array => - customerActions.actionsMapAddresses(diff, oldObj, newObj) + (): Array => actionsMapAddresses(diff, oldObj, newObj) ) ) @@ -59,12 +65,7 @@ function createCustomerMapActions( mapActionGroup( 'base', (): Array => - customerActions.actionsMapSetDefaultBase( - diff, - oldObj, - newObj, - syncActionConfig - ) + actionsMapSetDefaultBase(diff, oldObj, newObj, syncActionConfig) ) ) @@ -72,7 +73,7 @@ function createCustomerMapActions( mapActionGroup( 'billingAddressIds', (): Array => - customerActions.actionsMapBillingAddresses(diff, oldObj, newObj) + actionsMapBillingAddresses(diff, oldObj, newObj) ) ) @@ -80,7 +81,7 @@ function createCustomerMapActions( mapActionGroup( 'shippingAddressIds', (): Array => - customerActions.actionsMapShippingAddresses(diff, oldObj, newObj) + actionsMapShippingAddresses(diff, oldObj, newObj) ) ) @@ -95,7 +96,7 @@ function createCustomerMapActions( mapActionGroup( 'authenticationModes', (): Array => - customerActions.actionsMapAuthenticationModes(diff, oldObj, newObj) + actionsMapAuthenticationModes(diff, oldObj, newObj) ) ) diff --git a/packages/sync-actions/src/inventories.ts b/packages/sync-actions/src/inventories.ts index 5e4bc89b6..e3758d684 100644 --- a/packages/sync-actions/src/inventories.ts +++ b/packages/sync-actions/src/inventories.ts @@ -4,12 +4,12 @@ import type { SyncActionConfig, UpdateAction, } from '@commercetools/sdk-client-v2' -import * as inventoryActions from './inventory-actions' import { SyncAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' +import { actionsMapBase, actionsMapReferences } from './inventory-actions' export const actionGroups = ['base', 'references'] @@ -27,19 +27,14 @@ function createInventoryMapActions( mapActionGroup( 'base', (): Array => - inventoryActions.actionsMapBase( - diff, - oldObj, - newObj, - syncActionConfig - ) + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) + allActions.push( mapActionGroup( 'references', - (): Array => - inventoryActions.actionsMapReferences(diff, oldObj, newObj) + (): Array => actionsMapReferences(diff, oldObj, newObj) ) ) allActions.push( diff --git a/packages/sync-actions/src/orders.ts b/packages/sync-actions/src/orders.ts index 3d8807ecb..28933d8bb 100644 --- a/packages/sync-actions/src/orders.ts +++ b/packages/sync-actions/src/orders.ts @@ -4,7 +4,13 @@ import type { SyncActionConfig, UpdateAction, } from '@commercetools/sdk-client-v2' -import * as orderActions from './order-actions' +import { + actionsMapBase, + actionsMapDeliveries, + actionsMapDeliveryItems, + actionsMapParcels, + actionsMapReturnsInfo, +} from './order-actions' import { SyncAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' @@ -38,15 +44,14 @@ function createOrderMapActions( mapActionGroup( 'base', (): Array => - orderActions.actionsMapBase(diff, oldObj, newObj, syncActionConfig) + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) allActions.push( mapActionGroup( 'deliveries', - (): Array => - orderActions.actionsMapDeliveries(diff, oldObj, newObj) + (): Array => actionsMapDeliveries(diff, oldObj, newObj) ) ) @@ -54,7 +59,7 @@ function createOrderMapActions( mapActionGroup( 'parcels', (): Array => - orderActions.actionsMapParcels(diff, oldObj, newObj, deliveryHashMap) + actionsMapParcels(diff, oldObj, newObj, deliveryHashMap) ) ) @@ -62,20 +67,14 @@ function createOrderMapActions( mapActionGroup( 'items', (): Array => - orderActions.actionsMapDeliveryItems( - diff, - oldObj, - newObj, - deliveryHashMap - ) + actionsMapDeliveryItems(diff, oldObj, newObj, deliveryHashMap) ) ) allActions.push( mapActionGroup( 'returnInfo', - (): Array => - orderActions.actionsMapReturnsInfo(diff, oldObj, newObj) + (): Array => actionsMapReturnsInfo(diff, oldObj, newObj) ).flat() ) diff --git a/packages/sync-actions/src/prices.ts b/packages/sync-actions/src/prices.ts index e2fa3f095..4f6c77372 100644 --- a/packages/sync-actions/src/prices.ts +++ b/packages/sync-actions/src/prices.ts @@ -4,7 +4,7 @@ import type { SyncActionConfig, UpdateAction, } from '@commercetools/sdk-client-v2' -import * as pricesActions from './prices-actions' +import { actionsMapBase } from './prices-actions' import actionsMapCustom from './utils/action-map-custom' import combineValidityActions from './utils/combine-validity-actions' import createBuildActions from './utils/create-build-actions' @@ -25,7 +25,7 @@ function createPriceMapActions( const baseActions = mapActionGroup( 'base', (): Array => - pricesActions.actionsMapBase(diff, oldObj, newObj, syncActionConfig) + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) const customActions = mapActionGroup( diff --git a/packages/sync-actions/src/product-selections.ts b/packages/sync-actions/src/product-selections.ts index 3c6c90d1a..99a1d27c9 100644 --- a/packages/sync-actions/src/product-selections.ts +++ b/packages/sync-actions/src/product-selections.ts @@ -1,6 +1,6 @@ import { ProductSelectionUpdateAction } from '@commercetools/platform-sdk' import type { ActionGroup, UpdateAction } from '@commercetools/sdk-client-v2' -import * as productSelectionsActions from './product-selections-actions' +import { actionsMapBase } from './product-selections-actions' import { SyncAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' @@ -24,8 +24,7 @@ function createProductSelectionsMapActions( allActions.push( mapActionGroup( 'base', - (): Array => - productSelectionsActions.actionsMapBase(diff, previous, next) + (): Array => actionsMapBase(diff, previous, next) ) ) allActions.push( diff --git a/packages/sync-actions/src/products.ts b/packages/sync-actions/src/products.ts index 4d241a86f..7c41fe4c7 100644 --- a/packages/sync-actions/src/products.ts +++ b/packages/sync-actions/src/products.ts @@ -4,7 +4,21 @@ import type { SyncActionConfig, UpdateAction, } from '@commercetools/sdk-client-v2' -import * as productActions from './product-actions' +import { + actionsMapAddVariants, + actionsMapAssets, + actionsMapAttributes, + actionsMapBase, + actionsMapCategories, + actionsMapCategoryOrderHints, + actionsMapImages, + actionsMapMasterVariant, + actionsMapMeta, + actionsMapPrices, + actionsMapPricesCustom, + actionsMapReferences, + actionsMapRemoveVariants, +} from './product-actions' import { SyncAction } from './types/update-actions' import copyEmptyArrayProps from './utils/copy-empty-array-props' import createBuildActions from './utils/create-build-actions' @@ -49,7 +63,7 @@ function createProductMapActions( mapActionGroup( 'attributes', (): Array => - productActions.actionsMapAttributes( + actionsMapAttributes( diff, oldObj, newObj, @@ -62,18 +76,17 @@ function createProductMapActions( allActions.push( mapActionGroup( 'variants', - (): Array => - productActions.actionsMapAddVariants(diff, oldObj, newObj) + (): Array => actionsMapAddVariants(diff, oldObj, newObj) ) ) - allActions.push(productActions.actionsMapMasterVariant(oldObj, newObj)) + allActions.push(actionsMapMasterVariant(oldObj, newObj)) allActions.push( mapActionGroup( 'variants', (): Array => - productActions.actionsMapRemoveVariants(diff, oldObj, newObj) + actionsMapRemoveVariants(diff, oldObj, newObj) ) ) @@ -81,23 +94,21 @@ function createProductMapActions( mapActionGroup( 'base', (): Array => - productActions.actionsMapBase(diff, oldObj, newObj, syncActionConfig) + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) allActions.push( mapActionGroup( 'meta', - (): Array => - productActions.actionsMapMeta(diff, oldObj, newObj) + (): Array => actionsMapMeta(diff, oldObj, newObj) ) ) allActions.push( mapActionGroup( 'references', - (): Array => - productActions.actionsMapReferences(diff, oldObj, newObj) + (): Array => actionsMapReferences(diff, oldObj, newObj) ) ) @@ -105,7 +116,7 @@ function createProductMapActions( mapActionGroup( 'images', (): Array => - productActions.actionsMapImages(diff, oldObj, newObj, variantHashMap) + actionsMapImages(diff, oldObj, newObj, variantHashMap) ) ) @@ -113,12 +124,7 @@ function createProductMapActions( mapActionGroup( 'pricesCustom', (): Array => - productActions.actionsMapPricesCustom( - diff, - oldObj, - newObj, - variantHashMap - ) + actionsMapPricesCustom(diff, oldObj, newObj, variantHashMap) ) ) @@ -126,7 +132,7 @@ function createProductMapActions( mapActionGroup( 'prices', (): Array => - productActions.actionsMapPrices( + actionsMapPrices( diff, oldObj, newObj, @@ -139,15 +145,14 @@ function createProductMapActions( allActions.push( mapActionGroup( 'categories', - (): Array => productActions.actionsMapCategories(diff) + (): Array => actionsMapCategories(diff) ) ) allActions.push( mapActionGroup( 'categories', - (): Array => - productActions.actionsMapCategoryOrderHints(diff) + (): Array => actionsMapCategoryOrderHints(diff) ) ) @@ -155,7 +160,7 @@ function createProductMapActions( mapActionGroup( 'assets', (): Array => - productActions.actionsMapAssets(diff, oldObj, newObj, variantHashMap) + actionsMapAssets(diff, oldObj, newObj, variantHashMap) ) ) diff --git a/packages/sync-actions/src/quote-requests.ts b/packages/sync-actions/src/quote-requests.ts index cf1353569..eeb943b45 100644 --- a/packages/sync-actions/src/quote-requests.ts +++ b/packages/sync-actions/src/quote-requests.ts @@ -4,7 +4,7 @@ import type { SyncActionConfig, UpdateAction, } from '@commercetools/sdk-client-v2' -import * as QuoteRequestsActions from './quote-requests-actions' +import { actionsMapBase } from './quote-requests-actions' import { SyncAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' @@ -28,12 +28,7 @@ function createQuoteRequestsMapActions( mapActionGroup( 'base', (): Array => - QuoteRequestsActions.actionsMapBase( - diff, - oldObj, - newObj, - syncActionConfig - ) + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) diff --git a/packages/sync-actions/src/quotes.ts b/packages/sync-actions/src/quotes.ts index 02e46ca3f..a9238c4de 100644 --- a/packages/sync-actions/src/quotes.ts +++ b/packages/sync-actions/src/quotes.ts @@ -4,7 +4,7 @@ import type { SyncActionConfig, UpdateAction, } from '@commercetools/sdk-client-v2' -import * as QuotesActions from './quotes-actions' +import { actionsMapBase } from './quotes-actions' import { SyncAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' @@ -28,7 +28,7 @@ function createQuotesMapActions( mapActionGroup( 'base', (): Array => - QuotesActions.actionsMapBase(diff, oldObj, newObj, syncActionConfig) + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) diff --git a/packages/sync-actions/src/shipping-methods.ts b/packages/sync-actions/src/shipping-methods.ts index 6770280a8..bf537a11d 100644 --- a/packages/sync-actions/src/shipping-methods.ts +++ b/packages/sync-actions/src/shipping-methods.ts @@ -4,7 +4,7 @@ import type { SyncActionConfig, UpdateAction, } from '@commercetools/sdk-client-v2' -import * as shippingMethodsActions from './shipping-methods-actions' +import { actionsMapBase, actionsMapZoneRates } from './shipping-methods-actions' import { SyncAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' @@ -27,19 +27,13 @@ function createShippingMethodsMapActions( mapActionGroup( 'base', (): Array => - shippingMethodsActions.actionsMapBase( - diff, - oldObj, - newObj, - syncActionConfig - ) + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) allActions.push( mapActionGroup( 'zoneRates', - (): Array => - shippingMethodsActions.actionsMapZoneRates(diff, oldObj, newObj) + (): Array => actionsMapZoneRates(diff, oldObj, newObj) ).flat() ) allActions.push( diff --git a/packages/sync-actions/src/states.ts b/packages/sync-actions/src/states.ts index 22693c6b8..54635be10 100644 --- a/packages/sync-actions/src/states.ts +++ b/packages/sync-actions/src/states.ts @@ -4,7 +4,7 @@ import type { SyncActionConfig, UpdateAction, } from '@commercetools/sdk-client-v2' -import * as stateActions from './state-actions' +import { actionsMapBase, actionsMapRoles } from './state-actions' import { SyncAction } from './types/update-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' @@ -46,14 +46,13 @@ function createStatesMapActions( mapActionGroup( 'base', (): Array => - stateActions.actionsMapBase(diff, oldObj, newObj, syncActionConfig) + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) roleActions.push( mapActionGroup( 'roles', - (): Array => - stateActions.actionsMapRoles(diff, oldObj, newObj) + (): Array => actionsMapRoles(diff, oldObj, newObj) ) ) return [...baseActions, ...groupRoleActions(roleActions)].flat() diff --git a/packages/sync-actions/src/stores.ts b/packages/sync-actions/src/stores.ts index acba8ddb8..a78ba7b8c 100644 --- a/packages/sync-actions/src/stores.ts +++ b/packages/sync-actions/src/stores.ts @@ -1,6 +1,6 @@ import { StoreUpdateAction } from '@commercetools/platform-sdk' import type { ActionGroup, UpdateAction } from '@commercetools/sdk-client-v2' -import * as storesActions from './stores-actions' +import { actionsMapBase } from './stores-actions' import { SyncAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' @@ -24,8 +24,7 @@ function createStoresMapActions( allActions.push( mapActionGroup( 'base', - (): Array => - storesActions.actionsMapBase(diff, previous, next) + (): Array => actionsMapBase(diff, previous, next) ) ) allActions.push( diff --git a/packages/sync-actions/src/tax-categories.ts b/packages/sync-actions/src/tax-categories.ts index 01b52bf74..a65a13291 100644 --- a/packages/sync-actions/src/tax-categories.ts +++ b/packages/sync-actions/src/tax-categories.ts @@ -4,7 +4,7 @@ import type { SyncActionConfig, UpdateAction, } from '@commercetools/sdk-client-v2' -import * as taxCategoriesActions from './tax-categories-actions' +import { actionsMapBase, actionsMapRates } from './tax-categories-actions' import { SyncAction } from './types/update-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' @@ -29,19 +29,13 @@ function createTaxCategoriesMapActions( mapActionGroup( 'base', (): Array => - taxCategoriesActions.actionsMapBase( - diff, - oldObj, - newObj, - syncActionConfig - ) + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) allActions.push( mapActionGroup( 'rates', - (): Array => - taxCategoriesActions.actionsMapRates(diff, oldObj, newObj) + (): Array => actionsMapRates(diff, oldObj, newObj) ) ) return allActions.flat() diff --git a/packages/sync-actions/src/types.ts b/packages/sync-actions/src/types.ts index 0fc51c22d..1f5d672be 100644 --- a/packages/sync-actions/src/types.ts +++ b/packages/sync-actions/src/types.ts @@ -1,5 +1,5 @@ import { SyncActionConfig } from '@commercetools/sdk-client-v2' -import * as typeActions from './types-actions' +import { actionsMapBase, actionsMapFieldDefinitions } from './types-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' @@ -15,10 +15,10 @@ function createTypeMapActions( const allActions = [] allActions.push( mapActionGroup('base', () => - typeActions.actionsMapBase(diff, previous, next, syncActionConfig) + actionsMapBase(diff, previous, next, syncActionConfig) ), mapActionGroup('fieldDefinitions', () => - typeActions.actionsMapFieldDefinitions( + actionsMapFieldDefinitions( diff.fieldDefinitions, previous.fieldDefinitions, next.fieldDefinitions, From f0a5b322b43eae6aeec82b51ff3dbe3d33711cf9 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Tue, 7 Nov 2023 14:51:14 +0100 Subject: [PATCH 09/33] feat(migrate): replace lodash.isequal --- packages/sync-actions/package.json | 1 - packages/sync-actions/src/types-actions.ts | 5 ++--- packages/sync-actions/src/utils/create-build-actions.ts | 4 ++-- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/packages/sync-actions/package.json b/packages/sync-actions/package.json index 69af8179b..1903456d8 100644 --- a/packages/sync-actions/package.json +++ b/packages/sync-actions/package.json @@ -26,7 +26,6 @@ "fast-equals": "^2.0.0", "jsondiffpatch": "^0.4.0", "lodash.intersection": "^4.4.0", - "lodash.isequal": "^4.5.0", "lodash.isnil": "^4.0.0", "lodash.shuffle": "^4.2.0", "lodash.sortby": "^4.7.0", diff --git a/packages/sync-actions/src/types-actions.ts b/packages/sync-actions/src/types-actions.ts index 59c30020b..b5cea89b6 100644 --- a/packages/sync-actions/src/types-actions.ts +++ b/packages/sync-actions/src/types-actions.ts @@ -1,6 +1,4 @@ import sortBy from 'lodash.sortby' - -import isEqual from 'lodash.isequal' import { buildBaseAttributesActions } from './utils/common-actions' import createBuildArrayActions, { ADD_ACTIONS, @@ -8,6 +6,7 @@ import createBuildArrayActions, { } from './utils/create-build-array-actions' import { getDeltaValue } from './utils/diffpatcher' import extractMatchingPairs from './utils/extract-matching-pairs' +import { deepEqual } from 'fast-equals' const REGEX_NUMBER = new RegExp(/^\d+$/) const REGEX_UNDERSCORE_NUMBER = new RegExp(/^_\d+$/) @@ -76,7 +75,7 @@ function actionsMapEnums( const foundPreviousEnum = previous.values.find( (previousEnum) => previousEnum.key === newEnum.key ) - const isLabelEqual = isEqual(foundPreviousEnum.label, newEnum.label) + const isLabelEqual = deepEqual(foundPreviousEnum.label, newEnum.label) if (isKeyChanged) { // these actions is then flatten in the end diff --git a/packages/sync-actions/src/utils/create-build-actions.ts b/packages/sync-actions/src/utils/create-build-actions.ts index a3ee4c7af..e7ca3a87e 100644 --- a/packages/sync-actions/src/utils/create-build-actions.ts +++ b/packages/sync-actions/src/utils/create-build-actions.ts @@ -1,5 +1,5 @@ -import isEqual from 'lodash.isequal' import isNil from 'lodash.isnil' +import { deepEqual } from 'fast-equals' function applyOnBeforeDiff(before, now, fn?: (before, now) => Array) { return fn && typeof fn === 'function' ? fn(before, now) : [before, now] @@ -17,7 +17,7 @@ const createPriceComparator = (price) => ({ function arePricesStructurallyEqual(oldPrice, newPrice) { const oldPriceComparison = createPriceComparator(oldPrice) const newPriceComparison = createPriceComparator(newPrice) - return isEqual(newPriceComparison, oldPriceComparison) + return deepEqual(newPriceComparison, oldPriceComparison) } function extractPriceFromPreviousVariant(newPrice, previousVariant) { From a3786205f71ba4cceb78811061e98a86fd6d95df Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Tue, 7 Nov 2023 15:06:07 +0100 Subject: [PATCH 10/33] feat(migrate): replace lodash.isnil --- packages/sync-actions/package.json | 1 - packages/sync-actions/src/customer-actions.ts | 5 ++--- packages/sync-actions/src/inventories.ts | 2 +- packages/sync-actions/src/types-actions.ts | 2 +- packages/sync-actions/src/utils/clone.ts | 6 ++++++ .../sync-actions/src/utils/common-actions.ts | 5 ++--- .../src/utils/copy-empty-array-props.ts | 14 ++++++-------- .../src/utils/create-build-actions.ts | 18 ++++++++++-------- 8 files changed, 28 insertions(+), 25 deletions(-) diff --git a/packages/sync-actions/package.json b/packages/sync-actions/package.json index 1903456d8..4a779cf1d 100644 --- a/packages/sync-actions/package.json +++ b/packages/sync-actions/package.json @@ -26,7 +26,6 @@ "fast-equals": "^2.0.0", "jsondiffpatch": "^0.4.0", "lodash.intersection": "^4.4.0", - "lodash.isnil": "^4.0.0", "lodash.shuffle": "^4.2.0", "lodash.sortby": "^4.7.0", "lodash.uniqwith": "^4.5.0", diff --git a/packages/sync-actions/src/customer-actions.ts b/packages/sync-actions/src/customer-actions.ts index 443c99902..a21f7bcbc 100644 --- a/packages/sync-actions/src/customer-actions.ts +++ b/packages/sync-actions/src/customer-actions.ts @@ -1,5 +1,4 @@ -import isNil from 'lodash.isnil' -import clone from './utils/clone' +import clone, { notEmpty } from './utils/clone' import { buildBaseAttributesActions, buildReferenceActions, @@ -214,5 +213,5 @@ function buildAuthenticationModeActions({ actions, diff, oldObj, newObj }) { [value]: newObj.password, } }) - .filter((action) => !isNil(action)) + .filter(notEmpty) } diff --git a/packages/sync-actions/src/inventories.ts b/packages/sync-actions/src/inventories.ts index e3758d684..9fa73882b 100644 --- a/packages/sync-actions/src/inventories.ts +++ b/packages/sync-actions/src/inventories.ts @@ -4,12 +4,12 @@ import type { SyncActionConfig, UpdateAction, } from '@commercetools/sdk-client-v2' +import { actionsMapBase, actionsMapReferences } from './inventory-actions' import { SyncAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' -import { actionsMapBase, actionsMapReferences } from './inventory-actions' export const actionGroups = ['base', 'references'] diff --git a/packages/sync-actions/src/types-actions.ts b/packages/sync-actions/src/types-actions.ts index b5cea89b6..7eaab1a9f 100644 --- a/packages/sync-actions/src/types-actions.ts +++ b/packages/sync-actions/src/types-actions.ts @@ -1,3 +1,4 @@ +import { deepEqual } from 'fast-equals' import sortBy from 'lodash.sortby' import { buildBaseAttributesActions } from './utils/common-actions' import createBuildArrayActions, { @@ -6,7 +7,6 @@ import createBuildArrayActions, { } from './utils/create-build-array-actions' import { getDeltaValue } from './utils/diffpatcher' import extractMatchingPairs from './utils/extract-matching-pairs' -import { deepEqual } from 'fast-equals' const REGEX_NUMBER = new RegExp(/^\d+$/) const REGEX_UNDERSCORE_NUMBER = new RegExp(/^_\d+$/) diff --git a/packages/sync-actions/src/utils/clone.ts b/packages/sync-actions/src/utils/clone.ts index 96a7ef9e7..c28a356f5 100644 --- a/packages/sync-actions/src/utils/clone.ts +++ b/packages/sync-actions/src/utils/clone.ts @@ -1,3 +1,9 @@ export default function clone(obj) { return JSON.parse(JSON.stringify(obj)) } + +export function notEmpty( + value: TValue | null | undefined +): value is TValue { + return value !== null && value !== undefined +} diff --git a/packages/sync-actions/src/utils/common-actions.ts b/packages/sync-actions/src/utils/common-actions.ts index e3eef2c68..8a170a685 100644 --- a/packages/sync-actions/src/utils/common-actions.ts +++ b/packages/sync-actions/src/utils/common-actions.ts @@ -1,5 +1,4 @@ -import isNil from 'lodash.isnil' -import clone from './clone' +import clone, { notEmpty } from './clone' import { getDeltaValue, patch } from './diffpatcher' const normalizeValue = (value) => @@ -64,7 +63,7 @@ export function buildBaseAttributesActions({ const patched = patch(clone(before), delta) return { action: item.action, [actionKey]: patched } }) - .filter((action) => !isNil(action)) + .filter(notEmpty) } /** diff --git a/packages/sync-actions/src/utils/copy-empty-array-props.ts b/packages/sync-actions/src/utils/copy-empty-array-props.ts index d6767cdae..cc9f6a7b5 100644 --- a/packages/sync-actions/src/utils/copy-empty-array-props.ts +++ b/packages/sync-actions/src/utils/copy-empty-array-props.ts @@ -1,5 +1,3 @@ -import isNil from 'lodash.isnil' - const CUSTOM = 'custom' /** @@ -11,7 +9,7 @@ const CUSTOM = 'custom' * @returns {Array} Ordered Array [oldObj, newObj] */ export default function copyEmptyArrayProps(oldObj = {}, newObj = {}) { - if (!isNil(oldObj) && !isNil(newObj)) { + if (oldObj && newObj) { const nextObjectWithEmptyArray = Object.entries(oldObj).reduce( (merged, [key, value]) => { // Ignore CUSTOM key as this object is dynamic and its up to the user to dynamically change it @@ -26,13 +24,13 @@ export default function copyEmptyArrayProps(oldObj = {}, newObj = {}) { }, {}) for (let i = 0; i < newObj[key].length; i++) { if ( - !isNil(newObj[key][i]) && + newObj[key][i] && typeof newObj[key][i] === 'object' && - !isNil(newObj[key][i].id) + newObj[key][i].id ) { // Since its unordered array elements then check if the element on `oldObj` exists by id const foundObject = hashMapValue[newObj[key][i].id] - if (!isNil(foundObject)) { + if (foundObject) { const [, nestedObject] = copyEmptyArrayProps( foundObject, newObj[key][i] @@ -50,11 +48,11 @@ export default function copyEmptyArrayProps(oldObj = {}, newObj = {}) { return merged } if (Array.isArray(value)) { - merged[key] = isNil(newObj[key]) ? [] : newObj[key] + merged[key] = newObj[key] ? newObj[key] : [] return merged } if ( - !isNil(newObj[key]) && + newObj[key] && typeof value === 'object' && // Ignore Date as this will create invalid object since typeof date === 'object' return true // ex: {date: new Date()} will result {date: {}} diff --git a/packages/sync-actions/src/utils/create-build-actions.ts b/packages/sync-actions/src/utils/create-build-actions.ts index e7ca3a87e..a3eab4ed6 100644 --- a/packages/sync-actions/src/utils/create-build-actions.ts +++ b/packages/sync-actions/src/utils/create-build-actions.ts @@ -1,4 +1,3 @@ -import isNil from 'lodash.isnil' import { deepEqual } from 'fast-equals' function applyOnBeforeDiff(before, now, fn?: (before, now) => Array) { @@ -35,10 +34,9 @@ function injectMissingPriceIds(nextVariants, previousVariants) { if (!prices) return restOfVariant const oldVariant = previousVariants.find( (previousVariant) => - (!isNil(previousVariant.id) && previousVariant.id === newVariant.id) || - (!isNil(previousVariant.key) && - previousVariant.key === newVariant.key) || - (!isNil(previousVariant.sku) && previousVariant.sku === newVariant.sku) + (previousVariant.id && previousVariant.id === newVariant.id) || + (previousVariant.key && previousVariant.key === newVariant.key) || + (previousVariant.sku && previousVariant.sku === newVariant.sku) ) return { @@ -49,13 +47,17 @@ function injectMissingPriceIds(nextVariants, previousVariants) { if (oldPrice) { // copy ID if not provided - if (!newPrice.id) newPrice.id = oldPrice.id + if (!newPrice.id) { + newPrice.id = oldPrice.id + } - if (isNil(newPrice.value.type)) + if (!newPrice.value.type) { newPrice.value.type = oldPrice.value.type + } - if (isNil(newPrice.value.fractionDigits)) + if (!newPrice.value.fractionDigits) { newPrice.value.fractionDigits = oldPrice.value.fractionDigits + } } return newPrice From cddcda48ed057a72f237dd4b800cced466136358 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Tue, 7 Nov 2023 15:20:28 +0100 Subject: [PATCH 11/33] feat(migrate): replace lodash.without --- packages/sync-actions/package.json | 3 +-- packages/sync-actions/src/product-actions.ts | 5 +++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/sync-actions/package.json b/packages/sync-actions/package.json index 4a779cf1d..1d65cf37e 100644 --- a/packages/sync-actions/package.json +++ b/packages/sync-actions/package.json @@ -28,8 +28,7 @@ "lodash.intersection": "^4.4.0", "lodash.shuffle": "^4.2.0", "lodash.sortby": "^4.7.0", - "lodash.uniqwith": "^4.5.0", - "lodash.without": "^4.4.0" + "lodash.uniqwith": "^4.5.0" }, "files": ["dist", "CHANGELOG.md"], "author": "Nicola Molinari (https://github.com/emmenko)", diff --git a/packages/sync-actions/src/product-actions.ts b/packages/sync-actions/src/product-actions.ts index d0484b458..731f03a79 100644 --- a/packages/sync-actions/src/product-actions.ts +++ b/packages/sync-actions/src/product-actions.ts @@ -2,7 +2,6 @@ import { ProductVariant } from '@commercetools/platform-sdk/src' import intersection from 'lodash.intersection' import uniqWith from 'lodash.uniqwith' -import without from 'lodash.without' import actionsMapCustom from './utils/action-map-custom' import { buildBaseAttributesActions, @@ -425,7 +424,9 @@ function _buildVariantChangeAssetOrderAction( .map((_) => _.id) .filter((_) => _ !== undefined) const assetIdsToKeep = intersection(assetIdsCurrent, assetIdsBefore) - const assetIdsToRemove = without(assetIdsBefore, ...assetIdsToKeep) + const assetIdsToRemove = assetIdsBefore.filter( + (item) => !assetIdsToKeep.includes(item) + ) const changeAssetOrderAction = { action: 'changeAssetOrder', assetOrder: assetIdsToKeep.concat(assetIdsToRemove), From cf7d4c1a46c64f3440ac0656dc40ccce78367691 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Tue, 7 Nov 2023 15:41:02 +0100 Subject: [PATCH 12/33] feat(migrate): replace lodash.intersection --- packages/sync-actions/package.json | 1 - packages/sync-actions/src/product-actions.ts | 6 +++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/sync-actions/package.json b/packages/sync-actions/package.json index 1d65cf37e..aef8cdc18 100644 --- a/packages/sync-actions/package.json +++ b/packages/sync-actions/package.json @@ -25,7 +25,6 @@ "dependencies": { "fast-equals": "^2.0.0", "jsondiffpatch": "^0.4.0", - "lodash.intersection": "^4.4.0", "lodash.shuffle": "^4.2.0", "lodash.sortby": "^4.7.0", "lodash.uniqwith": "^4.5.0" diff --git a/packages/sync-actions/src/product-actions.ts b/packages/sync-actions/src/product-actions.ts index 731f03a79..415a642b8 100644 --- a/packages/sync-actions/src/product-actions.ts +++ b/packages/sync-actions/src/product-actions.ts @@ -1,6 +1,4 @@ -/* eslint-disable max-len */ import { ProductVariant } from '@commercetools/platform-sdk/src' -import intersection from 'lodash.intersection' import uniqWith from 'lodash.uniqwith' import actionsMapCustom from './utils/action-map-custom' import { @@ -423,7 +421,9 @@ function _buildVariantChangeAssetOrderAction( const assetIdsCurrent = newVariant.assets .map((_) => _.id) .filter((_) => _ !== undefined) - const assetIdsToKeep = intersection(assetIdsCurrent, assetIdsBefore) + const assetIdsToKeep = assetIdsCurrent.filter((value) => + assetIdsBefore.includes(value) + ) const assetIdsToRemove = assetIdsBefore.filter( (item) => !assetIdsToKeep.includes(item) ) From eff813f33298f2fbd422282ae58947793455d650 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Tue, 7 Nov 2023 15:57:16 +0100 Subject: [PATCH 13/33] feat(migrate): replace lodash.shuffle --- packages/sync-actions/package.json | 1 - packages/sync-actions/test/product-sync-prices.spec.ts | 5 +++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/sync-actions/package.json b/packages/sync-actions/package.json index aef8cdc18..526bce0a9 100644 --- a/packages/sync-actions/package.json +++ b/packages/sync-actions/package.json @@ -25,7 +25,6 @@ "dependencies": { "fast-equals": "^2.0.0", "jsondiffpatch": "^0.4.0", - "lodash.shuffle": "^4.2.0", "lodash.sortby": "^4.7.0", "lodash.uniqwith": "^4.5.0" }, diff --git a/packages/sync-actions/test/product-sync-prices.spec.ts b/packages/sync-actions/test/product-sync-prices.spec.ts index e2b3a2942..f9925b99e 100644 --- a/packages/sync-actions/test/product-sync-prices.spec.ts +++ b/packages/sync-actions/test/product-sync-prices.spec.ts @@ -1,4 +1,3 @@ -import shuffle from 'lodash.shuffle' import productsSyncFn from '../src/products' /* eslint-disable max-len */ @@ -552,7 +551,9 @@ describe('Actions', () => { } beforeEach(() => { - now.masterVariant.prices = shuffle(now.masterVariant.prices) + now.masterVariant.prices = now.masterVariant.prices.sort( + () => Math.random() - 0.5 + ) actions = productsSync.buildActions(now, before) }) From 83e9c167e3634d33fe7b857ec727602dcf8ec223 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Tue, 7 Nov 2023 16:26:10 +0100 Subject: [PATCH 14/33] feat(migrate): replace lodash.uniqwith --- packages/sync-actions/package.json | 3 +-- packages/sync-actions/src/product-actions.ts | 14 +++++++++----- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/packages/sync-actions/package.json b/packages/sync-actions/package.json index 526bce0a9..0640cfc37 100644 --- a/packages/sync-actions/package.json +++ b/packages/sync-actions/package.json @@ -25,8 +25,7 @@ "dependencies": { "fast-equals": "^2.0.0", "jsondiffpatch": "^0.4.0", - "lodash.sortby": "^4.7.0", - "lodash.uniqwith": "^4.5.0" + "lodash.sortby": "^4.7.0" }, "files": ["dist", "CHANGELOG.md"], "author": "Nicola Molinari (https://github.com/emmenko)", diff --git a/packages/sync-actions/src/product-actions.ts b/packages/sync-actions/src/product-actions.ts index 415a642b8..4a1ea6b65 100644 --- a/packages/sync-actions/src/product-actions.ts +++ b/packages/sync-actions/src/product-actions.ts @@ -1,5 +1,4 @@ import { ProductVariant } from '@commercetools/platform-sdk/src' -import uniqWith from 'lodash.uniqwith' import actionsMapCustom from './utils/action-map-custom' import { buildBaseAttributesActions, @@ -701,10 +700,15 @@ export function actionsMapAttributes( // Ensure that an action is unique. // This is especially necessary for SFA attributes. - return uniqWith( - actions, - (a, b) => - a.action === b.action && a.name === b.name && a.variantId === b.variantId + return actions.filter( + (b, index, self) => + index === + self.findIndex( + (a) => + a.action === b.action && + a.name === b.name && + a.variantId === b.variantId + ) ) } From 1e20f61e29b19eef9bee964f1785a10d69d8b3c3 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Tue, 7 Nov 2023 16:45:06 +0100 Subject: [PATCH 15/33] feat(migrate): replace lodash.sortby --- packages/sync-actions/package.json | 3 +-- packages/sync-actions/src/types-actions.ts | 19 +++++++++++++------ 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/packages/sync-actions/package.json b/packages/sync-actions/package.json index 0640cfc37..9d1e394c0 100644 --- a/packages/sync-actions/package.json +++ b/packages/sync-actions/package.json @@ -24,8 +24,7 @@ }, "dependencies": { "fast-equals": "^2.0.0", - "jsondiffpatch": "^0.4.0", - "lodash.sortby": "^4.7.0" + "jsondiffpatch": "^0.4.0" }, "files": ["dist", "CHANGELOG.md"], "author": "Nicola Molinari (https://github.com/emmenko)", diff --git a/packages/sync-actions/src/types-actions.ts b/packages/sync-actions/src/types-actions.ts index 7eaab1a9f..98c927ee7 100644 --- a/packages/sync-actions/src/types-actions.ts +++ b/packages/sync-actions/src/types-actions.ts @@ -1,5 +1,4 @@ import { deepEqual } from 'fast-equals' -import sortBy from 'lodash.sortby' import { buildBaseAttributesActions } from './utils/common-actions' import createBuildArrayActions, { ADD_ACTIONS, @@ -202,10 +201,18 @@ export function actionsMapFieldDefinitions( // in order to prevent any eventual removal of `addAction`. // List of `removeActions` can be found here // https://docs.commercetools.com/http-api-projects-types.html#change-key - const sortedActions = sortBy( - actions, - (action) => action.action !== 'removeFieldDefinition' - ) - return sortedActions + return actions.sort((a, b) => { + if ( + a.action === 'removeFieldDefinition' && + a.action === 'removeFieldDefinition' + ) { + return (a.fieldName as string).localeCompare(b.fieldName) + } else if (a.action === 'removeFieldDefinition') { + return -1 + } else if (b.action === 'removeFieldDefinition') { + return -1 + } + return 0 + }) } From e8321e155fa027ccbb98926511ceda683cd345b6 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Wed, 8 Nov 2023 10:42:17 +0100 Subject: [PATCH 16/33] feat(migrate): type product-type sync --- .../sync-actions/src/product-types-actions.ts | 38 +++++++++++--- packages/sync-actions/src/product-types.ts | 7 ++- .../sync-actions/src/types/update-actions.ts | 4 +- ...product-types-sync-attribute-hints.spec.ts | 51 ++++++++++++++++--- 4 files changed, 83 insertions(+), 17 deletions(-) diff --git a/packages/sync-actions/src/product-types-actions.ts b/packages/sync-actions/src/product-types-actions.ts index 571abd449..db147d1cd 100644 --- a/packages/sync-actions/src/product-types-actions.ts +++ b/packages/sync-actions/src/product-types-actions.ts @@ -3,6 +3,7 @@ import { buildBaseAttributesActions, createIsEmptyValue, } from './utils/common-actions' +import { LocalizedString } from '@commercetools/platform-sdk' export const baseActionsList = [ { action: 'changeName', key: 'name' }, @@ -112,8 +113,14 @@ export const generateBaseFieldsUpdateActions = ( ) } +type AttributeDefinition = { + previous?: { name: string } | undefined + next?: { name: string } | undefined + hint?: { attributeName: string; isLocalized: boolean } +} + const generateUpdateActionsForAttributeDefinitions = ( - attributeDefinitions = [] + attributeDefinitions: Array = [] ) => { const removedAttributeDefinitions = attributeDefinitions.filter( (attributeDefinition) => @@ -170,8 +177,22 @@ const generateUpdateActionsForAttributeDefinitions = ( })), ] } + +export type AttributeEnumValues = { + previous?: { + key: string + label: LocalizedString | string | undefined + [key: string]: unknown + } + next?: { + key: string + label: LocalizedString | string | undefined + [key: string]: unknown + } + hint?: { attributeName: string; isLocalized: boolean } +} const generateUpdateActionsForAttributeEnumValues = ( - attributeEnumValues = [] + attributeEnumValues: Array = [] ) => { const removedAttributeEnumValues = attributeEnumValues.filter( (attributeEnumValue) => @@ -295,20 +316,21 @@ const generateChangeAttributeOrderAction = ( return null } +export type NestedValues = { + attributeDefinitions?: Array + attributeEnumValues?: Array +} export const actionsMapForHints = ( - nestedValuesChanges: { - attributeDefinitions: Array - attributeEnumValues: Array - } = { attributeDefinitions: [], attributeEnumValues: [] }, + nestedValuesChanges: NestedValues, ptOld, ptNew ) => { const updateActions = [ ...generateUpdateActionsForAttributeDefinitions( - nestedValuesChanges.attributeDefinitions + nestedValuesChanges?.attributeDefinitions ), ...generateUpdateActionsForAttributeEnumValues( - nestedValuesChanges.attributeEnumValues + nestedValuesChanges?.attributeEnumValues ), ] diff --git a/packages/sync-actions/src/product-types.ts b/packages/sync-actions/src/product-types.ts index 880e36c29..8a05d4b51 100644 --- a/packages/sync-actions/src/product-types.ts +++ b/packages/sync-actions/src/product-types.ts @@ -9,6 +9,7 @@ import { SyncAction } from './types/update-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' +import { NestedValues } from './product-types-actions' type SyncActionConfig = { withHints?: boolean } & BaseSyncActionConfig @@ -49,10 +50,14 @@ function createProductTypeMapActions( } } +export type ProductTypeConfig = { + nestedValuesChanges: NestedValues +} + export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createProductTypeMapActions( mapActionGroup, diff --git a/packages/sync-actions/src/types/update-actions.ts b/packages/sync-actions/src/types/update-actions.ts index 0970bc78e..ce60a8583 100644 --- a/packages/sync-actions/src/types/update-actions.ts +++ b/packages/sync-actions/src/types/update-actions.ts @@ -1,5 +1,5 @@ import { UpdateAction } from '@commercetools/sdk-client-v2' -export type SyncAction = { - buildActions: (now: Object, before: Object) => Array +export type SyncAction = { + buildActions: (now: any, before: any, config: S) => Array } diff --git a/packages/sync-actions/test/product-types-sync-attribute-hints.spec.ts b/packages/sync-actions/test/product-types-sync-attribute-hints.spec.ts index 687139baa..e07e91960 100644 --- a/packages/sync-actions/test/product-types-sync-attribute-hints.spec.ts +++ b/packages/sync-actions/test/product-types-sync-attribute-hints.spec.ts @@ -1,6 +1,9 @@ -import createSyncProductTypes from '../src/product-types' +import createSyncProductTypes, { ProductTypeConfig } from '../src/product-types' +import { SyncAction } from '../src/types/update-actions' +import { ProductTypeUpdateAction } from '@commercetools/platform-sdk/src' +import { AttributeEnumValues } from '../src/product-types-actions' -const createAttributeDefinitionDraftItem = (custom?) => ({ +const createAttributeDefinitionDraftItem = (custom?): AttributeEnumValues => ({ previous: { type: { name: 'text' }, name: 'attribute-name', @@ -24,7 +27,9 @@ const createAttributeDefinitionDraftItem = (custom?) => ({ ...custom, }) -const createAttributeEnumDraftItem = (custom?) => ({ +const createAttributeEnumDraftItem = ( + custom?: AttributeEnumValues +): AttributeEnumValues => ({ previous: { key: 'enum-key', label: 'enum-label', @@ -41,13 +46,13 @@ const createAttributeEnumDraftItem = (custom?) => ({ }) describe('product type hints', () => { - let updateActions - let sync + let updateActions: Array + let sync: SyncAction beforeEach(() => { sync = createSyncProductTypes([]) }) describe('attribute enum values', () => { - let attributeEnumDraftItem + let attributeEnumDraftItem: AttributeEnumValues describe('with previous', () => { describe('with no changes', () => { beforeEach(() => { @@ -312,6 +317,40 @@ describe('product type hints', () => { ]) }) }) + describe('when is truly localized', () => { + beforeEach(() => { + attributeEnumDraftItem = createAttributeEnumDraftItem({ + previous: { label: { 'en-GB': 'uk-label' }, key: 'enum-key' }, + next: { label: { 'en-GB': 'uk-label-new' }, key: 'enum-key' }, + hint: { + // this hint value is used as `attributeName` for enum update actions + attributeName: 'attribute-name', + isLocalized: true, + }, + }) + updateActions = sync.buildActions( + {}, + {}, + { + nestedValuesChanges: { + attributeEnumValues: [attributeEnumDraftItem], + }, + } + ) + }) + it('should match snapshot', () => { + expect(updateActions).toMatchSnapshot() + }) + it('should generate `addLocalizedEnumValue`', () => { + expect(updateActions).toEqual([ + { + action: 'changeLocalizedEnumValueLabel', + attributeName: attributeEnumDraftItem.hint.attributeName, + newValue: attributeEnumDraftItem.next, + }, + ]) + }) + }) }) }) describe('attribute hints', () => { From e0c47d26eac4b700450da4d7144530b0fe1fcccb Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Wed, 8 Nov 2023 10:59:05 +0100 Subject: [PATCH 17/33] feat(migrate): type tests --- packages/sync-actions/src/types/update-actions.ts | 2 +- ...roduct-types-sync-attribute-hints.spec.ts.snap | 15 +++++++++++++++ .../test/attribute-groups-sync.spec.ts | 4 +++- .../sync-actions/test/cart-discounts-sync.spec.ts | 4 +++- packages/sync-actions/test/category-sync.spec.ts | 4 +++- packages/sync-actions/test/channels-sync-.spec.ts | 4 +++- .../sync-actions/test/customer-group-sync.spec.ts | 4 +++- packages/sync-actions/test/customer-sync.spec.ts | 4 +++- .../sync-actions/test/discount-codes-sync.spec.ts | 4 +++- packages/sync-actions/test/inventory-sync.spec.ts | 4 +++- packages/sync-actions/test/order-sync.spec.ts | 6 ++++-- .../test/product-discounts-sync.spec.ts | 4 +++- .../test/product-selections-sync.spec.ts | 4 +++- .../sync-actions/test/product-sync-base.spec.ts | 4 +++- .../sync-actions/test/product-sync-images.spec.ts | 4 +++- .../sync-actions/test/product-sync-prices.spec.ts | 4 +++- .../test/product-sync-variants.spec.ts | 4 +++- .../test/product-types-sync-base.spec.ts | 6 ++++-- packages/sync-actions/test/projects-sync.spec.ts | 4 +++- .../sync-actions/test/quote-requests-sync.spec.ts | 4 +++- packages/sync-actions/test/quotes-sync.spec.ts | 4 +++- .../sync-actions/test/shipping-methods.spec.ts | 4 +++- .../sync-actions/test/staged-quotes-sync.spec.ts | 4 +++- packages/sync-actions/test/states-sync.spec.ts | 4 +++- packages/sync-actions/test/stores-sync.spec.ts | 4 +++- .../sync-actions/test/tax-categories-sync.spec.ts | 4 +++- .../sync-actions/test/types-sync-base.spec.ts | 6 ++++-- .../sync-actions/test/types-sync-enums.spec.ts | 6 ++++-- .../sync-actions/test/types-sync-fields.spec.ts | 6 ++++-- packages/sync-actions/test/zones.spec.ts | 4 +++- 30 files changed, 105 insertions(+), 34 deletions(-) diff --git a/packages/sync-actions/src/types/update-actions.ts b/packages/sync-actions/src/types/update-actions.ts index ce60a8583..0654d171e 100644 --- a/packages/sync-actions/src/types/update-actions.ts +++ b/packages/sync-actions/src/types/update-actions.ts @@ -1,5 +1,5 @@ import { UpdateAction } from '@commercetools/sdk-client-v2' export type SyncAction = { - buildActions: (now: any, before: any, config: S) => Array + buildActions: (now: any, before: any, config?: S) => Array } diff --git a/packages/sync-actions/test/__snapshots__/product-types-sync-attribute-hints.spec.ts.snap b/packages/sync-actions/test/__snapshots__/product-types-sync-attribute-hints.spec.ts.snap index 8f28203de..26c6294f1 100644 --- a/packages/sync-actions/test/__snapshots__/product-types-sync-attribute-hints.spec.ts.snap +++ b/packages/sync-actions/test/__snapshots__/product-types-sync-attribute-hints.spec.ts.snap @@ -99,6 +99,21 @@ exports[`product type hints attribute enum values without previous when is local ] `; +exports[`product type hints attribute enum values without previous when is truly localized should match snapshot 1`] = ` +[ + { + "action": "changeLocalizedEnumValueLabel", + "attributeName": "attribute-name", + "newValue": { + "key": "enum-key", + "label": { + "en-GB": "uk-label-new", + }, + }, + }, +] +`; + exports[`product type hints attribute hints with previous with next with changes should match snapshot 1`] = ` [ { diff --git a/packages/sync-actions/test/attribute-groups-sync.spec.ts b/packages/sync-actions/test/attribute-groups-sync.spec.ts index 57766d0bc..4de9b02b2 100644 --- a/packages/sync-actions/test/attribute-groups-sync.spec.ts +++ b/packages/sync-actions/test/attribute-groups-sync.spec.ts @@ -1,5 +1,7 @@ import attributeGroupSyncFn from '../src/attribute-groups' import { baseActionsList } from '../src/attribute-groups-actions' +import { AttributeGroupUpdateAction } from '@commercetools/platform-sdk/src' +import { SyncAction } from '../src/types/update-actions' describe('Exports', () => { test('correctly define base actions list', () => { @@ -12,7 +14,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let attributeGroupSync + let attributeGroupSync: SyncAction beforeEach(() => { attributeGroupSync = attributeGroupSyncFn() }) diff --git a/packages/sync-actions/test/cart-discounts-sync.spec.ts b/packages/sync-actions/test/cart-discounts-sync.spec.ts index 340f86723..cdfce4ef7 100644 --- a/packages/sync-actions/test/cart-discounts-sync.spec.ts +++ b/packages/sync-actions/test/cart-discounts-sync.spec.ts @@ -1,5 +1,7 @@ import cartDiscountsSyncFn, { actionGroups } from '../src/cart-discounts' import { baseActionsList } from '../src/cart-discounts-actions' +import { SyncAction } from '../src/types/update-actions' +import { CartDiscountUpdateAction } from '@commercetools/platform-sdk/src' describe('Cart Discounts Exports', () => { test('action group list', () => { @@ -109,7 +111,7 @@ describe('Cart Discounts Exports', () => { }) describe('Cart Discounts Actions', () => { - let cartDiscountsSync + let cartDiscountsSync: SyncAction beforeEach(() => { cartDiscountsSync = cartDiscountsSyncFn() }) diff --git a/packages/sync-actions/test/category-sync.spec.ts b/packages/sync-actions/test/category-sync.spec.ts index 52401979e..236fd62fb 100644 --- a/packages/sync-actions/test/category-sync.spec.ts +++ b/packages/sync-actions/test/category-sync.spec.ts @@ -1,9 +1,11 @@ import categorySyncFn, { actionGroups } from '../src/categories' +import { SyncAction } from '../src/types/update-actions' import { baseActionsList, metaActionsList, referenceActionsList, } from '../src/category-actions' +import { CategoryUpdateAction } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -43,7 +45,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let categorySync + let categorySync: SyncAction beforeEach(() => { categorySync = categorySyncFn() }) diff --git a/packages/sync-actions/test/channels-sync-.spec.ts b/packages/sync-actions/test/channels-sync-.spec.ts index 9061c4490..ad48d4701 100644 --- a/packages/sync-actions/test/channels-sync-.spec.ts +++ b/packages/sync-actions/test/channels-sync-.spec.ts @@ -1,5 +1,7 @@ import createChannelsSync, { actionGroups } from '../src/channels' import { baseActionsList } from '../src/channels-actions' +import { SyncAction } from '../src/types/update-actions' +import { ChannelUpdateAction } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -66,7 +68,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let channelsSync + let channelsSync: SyncAction beforeEach(() => { channelsSync = createChannelsSync() }) diff --git a/packages/sync-actions/test/customer-group-sync.spec.ts b/packages/sync-actions/test/customer-group-sync.spec.ts index 1213fe173..a9485f3e7 100644 --- a/packages/sync-actions/test/customer-group-sync.spec.ts +++ b/packages/sync-actions/test/customer-group-sync.spec.ts @@ -1,5 +1,7 @@ import customerGroupSyncFn, { actionGroups } from '../src/customer-group' import { baseActionsList } from '../src/customer-group-actions' +import { SyncAction } from '../src/types/update-actions' +import { CustomerGroupUpdateAction } from '@commercetools/platform-sdk/src' describe('Customer Groups Exports', () => { test('action group list', () => { @@ -27,7 +29,7 @@ describe('Customer Groups Exports', () => { }) describe('Customer Groups Actions', () => { - let customerGroupSync + let customerGroupSync: SyncAction beforeEach(() => { customerGroupSync = customerGroupSyncFn() }) diff --git a/packages/sync-actions/test/customer-sync.spec.ts b/packages/sync-actions/test/customer-sync.spec.ts index ec5bbe1ad..cab1c2210 100644 --- a/packages/sync-actions/test/customer-sync.spec.ts +++ b/packages/sync-actions/test/customer-sync.spec.ts @@ -4,6 +4,8 @@ import { setDefaultBaseActionsList, referenceActionsList, } from '../src/customer-actions' +import { SyncAction } from '../src/types/update-actions' +import { CustomerUpdateAction } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -64,7 +66,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let customerSync + let customerSync: SyncAction beforeEach(() => { customerSync = customerSyncFn() }) diff --git a/packages/sync-actions/test/discount-codes-sync.spec.ts b/packages/sync-actions/test/discount-codes-sync.spec.ts index a2bfd2e94..5dbc7548e 100644 --- a/packages/sync-actions/test/discount-codes-sync.spec.ts +++ b/packages/sync-actions/test/discount-codes-sync.spec.ts @@ -1,5 +1,7 @@ import discountCodesSyncFn, { actionGroups } from '../src/discount-codes' import { baseActionsList } from '../src/discount-codes-actions' +import { SyncAction } from '../src/types/update-actions' +import { DiscountCodeUpdateAction } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -84,7 +86,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let discountCodesSync + let discountCodesSync: SyncAction beforeEach(() => { discountCodesSync = discountCodesSyncFn() }) diff --git a/packages/sync-actions/test/inventory-sync.spec.ts b/packages/sync-actions/test/inventory-sync.spec.ts index df114f1f8..1890aa687 100644 --- a/packages/sync-actions/test/inventory-sync.spec.ts +++ b/packages/sync-actions/test/inventory-sync.spec.ts @@ -1,5 +1,7 @@ import inventorySyncFn, { actionGroups } from '../src/inventories' import { baseActionsList, referenceActionsList } from '../src/inventory-actions' +import { SyncAction } from '../src/types/update-actions' +import { InventoryEntryUpdateAction } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -26,7 +28,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let inventorySync + let inventorySync: SyncAction beforeEach(() => { inventorySync = inventorySyncFn() }) diff --git a/packages/sync-actions/test/order-sync.spec.ts b/packages/sync-actions/test/order-sync.spec.ts index 0e7d66592..99d9a403b 100644 --- a/packages/sync-actions/test/order-sync.spec.ts +++ b/packages/sync-actions/test/order-sync.spec.ts @@ -1,6 +1,8 @@ import { performance } from 'perf_hooks' import orderSyncFn, { actionGroups } from '../src/orders' import { baseActionsList } from '../src/order-actions' +import { SyncAction } from '../src/types/update-actions' +import { OrderUpdateAction } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -17,7 +19,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let orderSync + let orderSync: SyncAction beforeEach(() => { orderSync = orderSyncFn() }) @@ -839,7 +841,7 @@ describe('Actions', () => { }) describe('custom fields', () => { - let orderSync + let orderSync: SyncAction beforeEach(() => { orderSync = orderSyncFn() }) diff --git a/packages/sync-actions/test/product-discounts-sync.spec.ts b/packages/sync-actions/test/product-discounts-sync.spec.ts index 0932a1b01..b60761f8f 100644 --- a/packages/sync-actions/test/product-discounts-sync.spec.ts +++ b/packages/sync-actions/test/product-discounts-sync.spec.ts @@ -1,5 +1,7 @@ import productDiscountsSyncFn, { actionGroups } from '../src/product-discounts' import { baseActionsList } from '../src/product-discounts-actions' +import { SyncAction } from '../src/types/update-actions' +import { ProductDiscountUpdateAction } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -76,7 +78,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let productDiscountsSync + let productDiscountsSync: SyncAction beforeEach(() => { productDiscountsSync = productDiscountsSyncFn() }) diff --git a/packages/sync-actions/test/product-selections-sync.spec.ts b/packages/sync-actions/test/product-selections-sync.spec.ts index e9c9164f0..25399d195 100644 --- a/packages/sync-actions/test/product-selections-sync.spec.ts +++ b/packages/sync-actions/test/product-selections-sync.spec.ts @@ -2,6 +2,8 @@ import { baseActionsList } from '../src/product-selections-actions' import productSelectionsSyncFn, { actionGroups, } from '../src/product-selections' +import { SyncAction } from '../src/types/update-actions' +import { ProductSelectionUpdateAction } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -17,7 +19,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let productSelectionsSync + let productSelectionsSync: SyncAction beforeEach(() => { productSelectionsSync = productSelectionsSyncFn() }) diff --git a/packages/sync-actions/test/product-sync-base.spec.ts b/packages/sync-actions/test/product-sync-base.spec.ts index 959b91ed7..4581ee373 100644 --- a/packages/sync-actions/test/product-sync-base.spec.ts +++ b/packages/sync-actions/test/product-sync-base.spec.ts @@ -5,6 +5,8 @@ import { metaActionsList, referenceActionsList, } from '../src/product-actions' +import { SyncAction } from '../src/types/update-actions' +import { ProductUpdateAction } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -50,7 +52,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let productsSync + let productsSync: SyncAction beforeEach(() => { productsSync = productsSyncFn() }) diff --git a/packages/sync-actions/test/product-sync-images.spec.ts b/packages/sync-actions/test/product-sync-images.spec.ts index 727e6acd6..b2ffa446b 100644 --- a/packages/sync-actions/test/product-sync-images.spec.ts +++ b/packages/sync-actions/test/product-sync-images.spec.ts @@ -1,8 +1,10 @@ +import { SyncAction } from '../src/types/update-actions' import productsSyncFn from '../src/products' +import { ProductUpdateAction } from '@commercetools/platform-sdk/src' /* eslint-disable max-len */ describe('Actions', () => { - let productsSync + let productsSync: SyncAction beforeEach(() => { productsSync = productsSyncFn() }) diff --git a/packages/sync-actions/test/product-sync-prices.spec.ts b/packages/sync-actions/test/product-sync-prices.spec.ts index f9925b99e..14dcac0fa 100644 --- a/packages/sync-actions/test/product-sync-prices.spec.ts +++ b/packages/sync-actions/test/product-sync-prices.spec.ts @@ -1,8 +1,10 @@ +import { SyncAction } from '../src/types/update-actions' import productsSyncFn from '../src/products' +import { ProductUpdateAction } from '@commercetools/platform-sdk/src' /* eslint-disable max-len */ describe('Actions', () => { - let productsSync + let productsSync: SyncAction beforeEach(() => { productsSync = productsSyncFn() }) diff --git a/packages/sync-actions/test/product-sync-variants.spec.ts b/packages/sync-actions/test/product-sync-variants.spec.ts index a4129f3a8..80e93b601 100644 --- a/packages/sync-actions/test/product-sync-variants.spec.ts +++ b/packages/sync-actions/test/product-sync-variants.spec.ts @@ -1,8 +1,10 @@ +import { SyncAction } from '../src/types/update-actions' import productsSyncFn from '../src/products' +import { ProductUpdateAction } from '@commercetools/platform-sdk/src' /* eslint-disable max-len */ describe('Actions', () => { - let productsSync + let productsSync: SyncAction beforeEach(() => { productsSync = productsSyncFn() }) diff --git a/packages/sync-actions/test/product-types-sync-base.spec.ts b/packages/sync-actions/test/product-types-sync-base.spec.ts index 74d1b52fb..fa83ed0e0 100644 --- a/packages/sync-actions/test/product-types-sync-base.spec.ts +++ b/packages/sync-actions/test/product-types-sync-base.spec.ts @@ -4,6 +4,8 @@ import { baseActionsList, generateBaseFieldsUpdateActions, } from '../src/product-types-actions' +import { SyncAction } from '../src/types/update-actions' +import { ProductTypeUpdateAction } from '@commercetools/platform-sdk/src' describe('ProductTypes sync', () => { test('action group list', () => { @@ -21,8 +23,8 @@ describe('ProductTypes sync', () => { }) describe('Actions', () => { - let productTypesSync - let updateActions + let productTypesSync: SyncAction + let updateActions: Array let before let now beforeEach(() => { diff --git a/packages/sync-actions/test/projects-sync.spec.ts b/packages/sync-actions/test/projects-sync.spec.ts index 8c27d4785..0ac75cd74 100644 --- a/packages/sync-actions/test/projects-sync.spec.ts +++ b/packages/sync-actions/test/projects-sync.spec.ts @@ -1,5 +1,7 @@ import createProjectsSync, { actionGroups } from '../src/projects' import { baseActionsList } from '../src/projects-actions' +import { SyncAction } from '../src/types/update-actions' +import { ProjectUpdateAction } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -68,7 +70,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let projectsSync + let projectsSync: SyncAction beforeEach(() => { projectsSync = createProjectsSync() }) diff --git a/packages/sync-actions/test/quote-requests-sync.spec.ts b/packages/sync-actions/test/quote-requests-sync.spec.ts index 1375db167..b40c1f826 100644 --- a/packages/sync-actions/test/quote-requests-sync.spec.ts +++ b/packages/sync-actions/test/quote-requests-sync.spec.ts @@ -1,5 +1,7 @@ import createQuoteRequestsSync, { actionGroups } from '../src/quote-requests' import { baseActionsList } from '../src/quote-requests-actions' +import { SyncAction } from '../src/types/update-actions' +import { QuoteRequestUpdateAction } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -24,7 +26,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let quoteRequestsSync + let quoteRequestsSync: SyncAction beforeEach(() => { quoteRequestsSync = createQuoteRequestsSync() }) diff --git a/packages/sync-actions/test/quotes-sync.spec.ts b/packages/sync-actions/test/quotes-sync.spec.ts index 6862269ff..191d5bf43 100644 --- a/packages/sync-actions/test/quotes-sync.spec.ts +++ b/packages/sync-actions/test/quotes-sync.spec.ts @@ -1,5 +1,7 @@ import createQuotesSync, { actionGroups } from '../src/quotes' import { baseActionsList } from '../src/quotes-actions' +import { SyncAction } from '../src/types/update-actions' +import { QuoteUpdateAction } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -32,7 +34,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let quotesSync + let quotesSync: SyncAction beforeEach(() => { quotesSync = createQuotesSync() }) diff --git a/packages/sync-actions/test/shipping-methods.spec.ts b/packages/sync-actions/test/shipping-methods.spec.ts index cb8a81b2c..ca62ed67e 100644 --- a/packages/sync-actions/test/shipping-methods.spec.ts +++ b/packages/sync-actions/test/shipping-methods.spec.ts @@ -1,5 +1,7 @@ import shippingMethodsSyncFn, { actionGroups } from '../src/shipping-methods' import { baseActionsList } from '../src/shipping-methods-actions' +import { SyncAction } from '../src/types/update-actions' +import { ShippingMethodUpdateAction } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -21,7 +23,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let shippingMethodsSync + let shippingMethodsSync: SyncAction beforeEach(() => { shippingMethodsSync = shippingMethodsSyncFn() }) diff --git a/packages/sync-actions/test/staged-quotes-sync.spec.ts b/packages/sync-actions/test/staged-quotes-sync.spec.ts index 503890044..c873f5df5 100644 --- a/packages/sync-actions/test/staged-quotes-sync.spec.ts +++ b/packages/sync-actions/test/staged-quotes-sync.spec.ts @@ -1,5 +1,7 @@ import createStagedQuotesSync, { actionGroups } from '../src/staged-quotes' import { baseActionsList } from '../src/staged-quotes-actions' +import { SyncAction } from '../src/types/update-actions' +import { StagedQuoteUpdateAction } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -38,7 +40,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let stagedQuotesSync + let stagedQuotesSync: SyncAction beforeEach(() => { stagedQuotesSync = createStagedQuotesSync() }) diff --git a/packages/sync-actions/test/states-sync.spec.ts b/packages/sync-actions/test/states-sync.spec.ts index 46f84fe34..046052865 100644 --- a/packages/sync-actions/test/states-sync.spec.ts +++ b/packages/sync-actions/test/states-sync.spec.ts @@ -1,5 +1,7 @@ import statesSyncFn, { actionGroups } from '../src/states' import { baseActionsList } from '../src/state-actions' +import { SyncAction } from '../src/types/update-actions' +import { StateUpdateAction } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -66,7 +68,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let statesSync + let statesSync: SyncAction beforeEach(() => { statesSync = statesSyncFn() }) diff --git a/packages/sync-actions/test/stores-sync.spec.ts b/packages/sync-actions/test/stores-sync.spec.ts index 4bdb01273..a9ac3ed0c 100644 --- a/packages/sync-actions/test/stores-sync.spec.ts +++ b/packages/sync-actions/test/stores-sync.spec.ts @@ -1,5 +1,7 @@ import storesSyncFn, { actionGroups } from '../src/stores' import { baseActionsList } from '../src/stores-actions' +import { SyncAction } from '../src/types/update-actions' +import { StoreUpdateAction } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -17,7 +19,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let storesSync + let storesSync: SyncAction beforeEach(() => { storesSync = storesSyncFn() }) diff --git a/packages/sync-actions/test/tax-categories-sync.spec.ts b/packages/sync-actions/test/tax-categories-sync.spec.ts index 9a1afda97..10facd935 100644 --- a/packages/sync-actions/test/tax-categories-sync.spec.ts +++ b/packages/sync-actions/test/tax-categories-sync.spec.ts @@ -1,5 +1,7 @@ import taxCategorySyncFn, { actionGroups } from '../src/tax-categories' import { baseActionsList } from '../src/tax-categories-actions' +import { SyncAction } from '../src/types/update-actions' +import { TaxCategoryUpdateAction } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -16,7 +18,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let taxCategorySync + let taxCategorySync: SyncAction beforeEach(() => { taxCategorySync = taxCategorySyncFn() }) diff --git a/packages/sync-actions/test/types-sync-base.spec.ts b/packages/sync-actions/test/types-sync-base.spec.ts index 0ca6af5a6..59c797618 100644 --- a/packages/sync-actions/test/types-sync-base.spec.ts +++ b/packages/sync-actions/test/types-sync-base.spec.ts @@ -1,6 +1,8 @@ import clone from '../src/utils/clone' import createSyncTypes, { actionGroups } from '../src/types' import { baseActionsList } from '../src/types-actions' +import { SyncAction } from '../src/types/update-actions' +import { TypeUpdateAction } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -17,8 +19,8 @@ describe('Exports', () => { }) describe('Actions', () => { - let typesSync - let updateActions + let typesSync: SyncAction + let updateActions: Array let before let now beforeEach(() => { diff --git a/packages/sync-actions/test/types-sync-enums.spec.ts b/packages/sync-actions/test/types-sync-enums.spec.ts index 88f6989f0..980388755 100644 --- a/packages/sync-actions/test/types-sync-enums.spec.ts +++ b/packages/sync-actions/test/types-sync-enums.spec.ts @@ -1,4 +1,6 @@ import typesSyncFn from '../src/types' +import { SyncAction } from '../src/types/update-actions' +import { TypeUpdateAction } from '@commercetools/platform-sdk/src' const createTestType = (custom) => ({ id: 'type-id', @@ -9,8 +11,8 @@ const createTestType = (custom) => ({ describe('Actions', () => { let before let now - let typesSync - let updateActions + let typesSync: SyncAction + let updateActions: Array beforeEach(() => { typesSync = typesSyncFn() }) diff --git a/packages/sync-actions/test/types-sync-fields.spec.ts b/packages/sync-actions/test/types-sync-fields.spec.ts index 01f2e567b..89de63ea2 100644 --- a/packages/sync-actions/test/types-sync-fields.spec.ts +++ b/packages/sync-actions/test/types-sync-fields.spec.ts @@ -1,4 +1,6 @@ import typesSyncFn from '../src/types' +import { SyncAction } from '../src/types/update-actions' +import { TypeUpdateAction } from '@commercetools/platform-sdk/src' const createTestType = (custom) => ({ id: 'type-id', @@ -7,8 +9,8 @@ const createTestType = (custom) => ({ }) describe('Actions', () => { - let typesSync - let updateActions + let typesSync: SyncAction + let updateActions: Array let before let now beforeEach(() => { diff --git a/packages/sync-actions/test/zones.spec.ts b/packages/sync-actions/test/zones.spec.ts index 692561c57..b407fdc29 100644 --- a/packages/sync-actions/test/zones.spec.ts +++ b/packages/sync-actions/test/zones.spec.ts @@ -1,5 +1,7 @@ import zonesSyncFn, { actionGroups } from '../src/zones' import { baseActionsList } from '../src/zones-actions' +import { SyncAction } from '../src/types/update-actions' +import { ZoneUpdateAction } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -16,7 +18,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let zonesSync + let zonesSync: SyncAction beforeEach(() => { zonesSync = zonesSyncFn() }) From fe4f143d662e13baa690c3c21c2bd22b2911a055 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Wed, 8 Nov 2023 18:04:27 +0100 Subject: [PATCH 18/33] feat(migrate): types united --- packages/sync-actions/src/attribute-groups.ts | 12 ++- packages/sync-actions/src/cart-discounts.ts | 12 ++- packages/sync-actions/src/categories.ts | 6 +- packages/sync-actions/src/channels.ts | 9 +- packages/sync-actions/src/customer-group.ts | 12 ++- packages/sync-actions/src/customers.ts | 6 +- packages/sync-actions/src/discount-codes.ts | 12 ++- packages/sync-actions/src/inventories.ts | 12 ++- packages/sync-actions/src/orders.ts | 24 +++++- .../sync-actions/src/product-discounts.ts | 12 ++- .../sync-actions/src/product-selections.ts | 16 ++-- .../sync-actions/src/product-types-actions.ts | 2 +- packages/sync-actions/src/product-types.ts | 12 +-- packages/sync-actions/src/products.ts | 9 +- packages/sync-actions/src/projects.ts | 14 +++- packages/sync-actions/src/quote-requests.ts | 12 ++- packages/sync-actions/src/quotes.ts | 9 +- packages/sync-actions/src/shipping-methods.ts | 12 ++- packages/sync-actions/src/staged-quotes.ts | 18 +++- packages/sync-actions/src/states.ts | 9 +- packages/sync-actions/src/stores.ts | 6 +- packages/sync-actions/src/tax-categories.ts | 12 ++- packages/sync-actions/src/types.ts | 9 +- .../sync-actions/src/types/update-actions.ts | 18 +++- .../src/utils/create-build-actions.ts | 12 ++- packages/sync-actions/src/zones.ts | 9 +- .../test/attribute-groups-sync.spec.ts | 10 +-- .../test/cart-discounts-sync.spec.ts | 25 +++--- .../sync-actions/test/category-sync.spec.ts | 18 ++-- .../sync-actions/test/channels-sync-.spec.ts | 42 ++++++---- .../test/customer-group-sync.spec.ts | 28 ++++--- .../sync-actions/test/customer-sync.spec.ts | 27 +++--- .../test/discount-codes-sync.spec.ts | 38 ++++----- .../sync-actions/test/inventory-sync.spec.ts | 15 ++-- packages/sync-actions/test/order-sync.spec.ts | 41 +++++----- .../test/product-discounts-sync.spec.ts | 10 +-- .../test/product-selections-sync.spec.ts | 17 ++-- .../test/product-sync-base.spec.ts | 20 +++-- .../test/product-sync-images.spec.ts | 17 ++-- .../test/product-sync-prices.spec.ts | 82 ++++++++----------- .../test/product-sync-variants.spec.ts | 55 ++++++------- ...product-types-sync-attribute-hints.spec.ts | 5 +- .../test/product-types-sync-base.spec.ts | 18 ++-- .../sync-actions/test/projects-sync.spec.ts | 22 +++-- .../test/quote-requests-sync.spec.ts | 21 +++-- .../sync-actions/test/quotes-sync.spec.ts | 30 ++++--- .../test/shipping-methods.spec.ts | 77 +++++++++-------- .../test/staged-quotes-sync.spec.ts | 21 +++-- .../sync-actions/test/states-sync.spec.ts | 14 ++-- .../sync-actions/test/stores-sync.spec.ts | 26 +++--- .../test/tax-categories-sync.spec.ts | 57 +++++++------ .../sync-actions/test/types-sync-base.spec.ts | 3 +- .../test/types-sync-enums.spec.ts | 2 +- .../test/types-sync-fields.spec.ts | 2 +- packages/sync-actions/test/zones.spec.ts | 4 +- 55 files changed, 611 insertions(+), 432 deletions(-) diff --git a/packages/sync-actions/src/attribute-groups.ts b/packages/sync-actions/src/attribute-groups.ts index 3c18b378d..556296a08 100644 --- a/packages/sync-actions/src/attribute-groups.ts +++ b/packages/sync-actions/src/attribute-groups.ts @@ -1,4 +1,7 @@ -import { AttributeGroupUpdateAction } from '@commercetools/platform-sdk' +import { + AttributeGroup, + AttributeGroupUpdateAction, +} from '@commercetools/platform-sdk' import type { ActionGroup, SyncActionConfig, @@ -46,12 +49,15 @@ function createAttributeGroupsMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createAttributeGroupsMapActions( mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions(diff, doMapActions) + const buildActions = createBuildActions< + AttributeGroup, + AttributeGroupUpdateAction + >(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/cart-discounts.ts b/packages/sync-actions/src/cart-discounts.ts index 09ea8c512..9c769c6d5 100644 --- a/packages/sync-actions/src/cart-discounts.ts +++ b/packages/sync-actions/src/cart-discounts.ts @@ -1,4 +1,7 @@ -import { CartDiscountUpdateAction } from '@commercetools/platform-sdk' +import { + CartDiscount, + CartDiscountUpdateAction, +} from '@commercetools/platform-sdk' import { ActionGroup, SyncActionConfig } from '@commercetools/sdk-client-v2' import { actionsMapBase } from './cart-discounts-actions' import { SyncAction } from './types/update-actions' @@ -31,12 +34,15 @@ function createCartDiscountsMapActions(mapActionGroup, syncActionConfig) { export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createCartDiscountsMapActions( mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions(diff, doMapActions) + const buildActions = createBuildActions< + CartDiscount, + CartDiscountUpdateAction + >(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/categories.ts b/packages/sync-actions/src/categories.ts index e7ee2aac4..adf36bcce 100644 --- a/packages/sync-actions/src/categories.ts +++ b/packages/sync-actions/src/categories.ts @@ -1,4 +1,4 @@ -import { CategoryUpdateAction } from '@commercetools/platform-sdk' +import { Category, CategoryUpdateAction } from '@commercetools/platform-sdk' import type { ActionGroup, SyncActionConfig, @@ -73,7 +73,7 @@ function createCategoryMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { // actionGroupList contains information about which action groups // are allowed or ignored @@ -90,7 +90,7 @@ export default ( mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions( + const buildActions = createBuildActions( diff, doMapActions, copyEmptyArrayProps diff --git a/packages/sync-actions/src/channels.ts b/packages/sync-actions/src/channels.ts index 24919ea7e..18f90d307 100644 --- a/packages/sync-actions/src/channels.ts +++ b/packages/sync-actions/src/channels.ts @@ -1,4 +1,4 @@ -import { ChannelUpdateAction } from '@commercetools/platform-sdk' +import { Channel, ChannelUpdateAction } from '@commercetools/platform-sdk' import { ActionGroup, SyncActionConfig } from '@commercetools/sdk-client-v2' import { actionsMapBase } from './channels-actions' import { SyncAction } from './types/update-actions' @@ -30,12 +30,15 @@ function createChannelsMapActions(mapActionGroup, syncActionConfig) { export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createChannelsMapActions( mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions(diff, doMapActions) + const buildActions = createBuildActions( + diff, + doMapActions + ) return { buildActions } } diff --git a/packages/sync-actions/src/customer-group.ts b/packages/sync-actions/src/customer-group.ts index 752a60e07..ee940e2a7 100644 --- a/packages/sync-actions/src/customer-group.ts +++ b/packages/sync-actions/src/customer-group.ts @@ -1,4 +1,7 @@ -import { CustomerGroupUpdateAction } from '@commercetools/platform-sdk' +import { + CustomerGroup, + CustomerGroupUpdateAction, +} from '@commercetools/platform-sdk' import { ActionGroup, SyncActionConfig } from '@commercetools/sdk-client-v2' import { actionsMapBase } from './customer-group-actions' import { SyncAction } from './types/update-actions' @@ -30,12 +33,15 @@ function createCustomerGroupMapActions(mapActionGroup, syncActionConfig) { export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createCustomerGroupMapActions( mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions(diff, doMapActions) + const buildActions = createBuildActions< + CustomerGroup, + CustomerGroupUpdateAction + >(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/customers.ts b/packages/sync-actions/src/customers.ts index 94b45c42d..a13807778 100644 --- a/packages/sync-actions/src/customers.ts +++ b/packages/sync-actions/src/customers.ts @@ -1,4 +1,4 @@ -import { CustomerUpdateAction } from '@commercetools/platform-sdk' +import { Customer, CustomerUpdateAction } from '@commercetools/platform-sdk' import type { ActionGroup, SyncActionConfig, @@ -107,7 +107,7 @@ function createCustomerMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { // actionGroupList contains information about which action groups // are allowed or ignored @@ -124,7 +124,7 @@ export default ( mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions( + const buildActions = createBuildActions( diff, doMapActions, copyEmptyArrayProps diff --git a/packages/sync-actions/src/discount-codes.ts b/packages/sync-actions/src/discount-codes.ts index 363ba8ba4..94f843c18 100644 --- a/packages/sync-actions/src/discount-codes.ts +++ b/packages/sync-actions/src/discount-codes.ts @@ -1,4 +1,7 @@ -import { DiscountCodeUpdateAction } from '@commercetools/platform-sdk' +import { + DiscountCode, + DiscountCodeUpdateAction, +} from '@commercetools/platform-sdk' import { ActionGroup, SyncActionConfig } from '@commercetools/sdk-client-v2' import { actionsMapBase } from './discount-codes-actions' import { SyncAction } from './types/update-actions' @@ -28,7 +31,7 @@ function createDiscountCodesMapActions(mapActionGroup, syncActionConfig) { export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { // actionGroupList contains information about which action groups // are allowed or ignored @@ -45,6 +48,9 @@ export default ( mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions(diff, doMapActions) + const buildActions = createBuildActions< + DiscountCode, + DiscountCodeUpdateAction + >(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/inventories.ts b/packages/sync-actions/src/inventories.ts index 9fa73882b..4514ea411 100644 --- a/packages/sync-actions/src/inventories.ts +++ b/packages/sync-actions/src/inventories.ts @@ -1,4 +1,7 @@ -import { InventoryEntryUpdateAction } from '@commercetools/platform-sdk' +import { + InventoryEntry, + InventoryEntryUpdateAction, +} from '@commercetools/platform-sdk' import type { ActionGroup, SyncActionConfig, @@ -50,7 +53,7 @@ function createInventoryMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { // actionGroupList contains information about which action groups // are allowed or ignored @@ -67,6 +70,9 @@ export default ( mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions(diff, doMapActions) + const buildActions = createBuildActions< + InventoryEntry, + InventoryEntryUpdateAction + >(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/orders.ts b/packages/sync-actions/src/orders.ts index 28933d8bb..ca36617b8 100644 --- a/packages/sync-actions/src/orders.ts +++ b/packages/sync-actions/src/orders.ts @@ -1,4 +1,10 @@ -import { OrderUpdateAction } from '@commercetools/platform-sdk' +import { + CustomFields, + OrderUpdateAction, + ReturnInfo, + ShippingInfo, + StagedOrderUpdateAction, +} from '@commercetools/platform-sdk' import type { ActionGroup, SyncActionConfig, @@ -86,10 +92,19 @@ function createOrderMapActions( } } +export type OrderSync = { + orderState: string + paymentState: string + shipmentState: string + shippingInfo: ShippingInfo + returnInfo: Array + custom: CustomFields +} + export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { // actionGroupList contains information about which action groups // are allowed or ignored @@ -103,6 +118,9 @@ export default ( // It will return an empty array for ignored action groups const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createOrderMapActions(mapActionGroup, syncActionConfig) - const buildActions = createBuildActions(diff, doMapActions) + const buildActions = createBuildActions( + diff, + doMapActions + ) return { buildActions } } diff --git a/packages/sync-actions/src/product-discounts.ts b/packages/sync-actions/src/product-discounts.ts index 11b33d511..989605e61 100644 --- a/packages/sync-actions/src/product-discounts.ts +++ b/packages/sync-actions/src/product-discounts.ts @@ -1,4 +1,7 @@ -import { ProductDiscountUpdateAction } from '@commercetools/platform-sdk' +import { + ProductDiscount, + ProductDiscountUpdateAction, +} from '@commercetools/platform-sdk' import { ActionGroup, SyncActionConfig } from '@commercetools/sdk-client-v2' import { actionsMapBase } from './product-discounts-actions' import { SyncAction } from './types/update-actions' @@ -25,12 +28,15 @@ function createProductDiscountsMapActions(mapActionGroup, syncActionConfig) { export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createProductDiscountsMapActions( mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions(diff, doMapActions) + const buildActions = createBuildActions< + ProductDiscount, + ProductDiscountUpdateAction + >(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/product-selections.ts b/packages/sync-actions/src/product-selections.ts index 99a1d27c9..b00a3f9a3 100644 --- a/packages/sync-actions/src/product-selections.ts +++ b/packages/sync-actions/src/product-selections.ts @@ -1,4 +1,7 @@ -import { ProductSelectionUpdateAction } from '@commercetools/platform-sdk' +import { + ProductSelection, + ProductSelectionUpdateAction, +} from '@commercetools/platform-sdk' import type { ActionGroup, UpdateAction } from '@commercetools/sdk-client-v2' import { actionsMapBase } from './product-selections-actions' import { SyncAction } from './types/update-actions' @@ -40,15 +43,14 @@ function createProductSelectionsMapActions( export default ( actionGroupList?: Array -): SyncAction => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createProductSelectionsMapActions(mapActionGroup) const onBeforeApplyingDiff = null - const buildActions = createBuildActions( - diff, - doMapActions, - onBeforeApplyingDiff - ) + const buildActions = createBuildActions< + ProductSelection, + ProductSelectionUpdateAction + >(diff, doMapActions, onBeforeApplyingDiff) return { buildActions } } diff --git a/packages/sync-actions/src/product-types-actions.ts b/packages/sync-actions/src/product-types-actions.ts index db147d1cd..d0dda3cf1 100644 --- a/packages/sync-actions/src/product-types-actions.ts +++ b/packages/sync-actions/src/product-types-actions.ts @@ -1,9 +1,9 @@ +import { LocalizedString } from '@commercetools/platform-sdk' import { deepEqual } from 'fast-equals' import { buildBaseAttributesActions, createIsEmptyValue, } from './utils/common-actions' -import { LocalizedString } from '@commercetools/platform-sdk' export const baseActionsList = [ { action: 'changeName', key: 'name' }, diff --git a/packages/sync-actions/src/product-types.ts b/packages/sync-actions/src/product-types.ts index 8a05d4b51..9a26050a7 100644 --- a/packages/sync-actions/src/product-types.ts +++ b/packages/sync-actions/src/product-types.ts @@ -1,15 +1,17 @@ -import { ProductTypeUpdateAction } from '@commercetools/platform-sdk' +import { + ProductType, + ProductTypeUpdateAction, +} from '@commercetools/platform-sdk' import type { ActionGroup, SyncActionConfig as BaseSyncActionConfig, UpdateAction, } from '@commercetools/sdk-client-v2' import * as productTypeActions from './product-types-actions' -import { SyncAction } from './types/update-actions' +import { NestedValues } from './product-types-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' -import { NestedValues } from './product-types-actions' type SyncActionConfig = { withHints?: boolean } & BaseSyncActionConfig @@ -57,14 +59,14 @@ export type ProductTypeConfig = { export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +) => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createProductTypeMapActions( mapActionGroup, syncActionConfig ) const onBeforeApplyingDiff = null - const buildActions = createBuildActions( + const buildActions = createBuildActions( diff, doMapActions, onBeforeApplyingDiff, diff --git a/packages/sync-actions/src/products.ts b/packages/sync-actions/src/products.ts index 7c41fe4c7..8f3271a9e 100644 --- a/packages/sync-actions/src/products.ts +++ b/packages/sync-actions/src/products.ts @@ -1,4 +1,4 @@ -import { ProductUpdateAction } from '@commercetools/platform-sdk' +import { ProductData, ProductUpdateAction } from '@commercetools/platform-sdk' import type { ActionGroup, SyncActionConfig, @@ -25,6 +25,7 @@ import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' import findMatchingPairs from './utils/find-matching-pairs' +import exp from 'constants' const actionGroups = [ 'base', @@ -186,14 +187,16 @@ function moveMasterVariantsIntoVariants(before: any, now: any): Array { ] } +export type ProductSync = { key: string; id: string } & ProductData + export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createProductMapActions(mapActionGroup, syncActionConfig) - const buildActions = createBuildActions( + const buildActions = createBuildActions( diff, doMapActions, moveMasterVariantsIntoVariants diff --git a/packages/sync-actions/src/projects.ts b/packages/sync-actions/src/projects.ts index 4933e881d..6d9fdb6c1 100644 --- a/packages/sync-actions/src/projects.ts +++ b/packages/sync-actions/src/projects.ts @@ -1,10 +1,11 @@ -import { ProjectUpdateAction } from '@commercetools/platform-sdk' +import { Project, ProjectUpdateAction } from '@commercetools/platform-sdk' import { ActionGroup, SyncActionConfig } from '@commercetools/sdk-client-v2' import { actionsMapBase } from './projects-actions' import { SyncAction } from './types/update-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' +import { MessagesConfigurationDraft } from '@commercetools/platform-sdk' export const actionGroups = ['base'] @@ -22,15 +23,22 @@ function createChannelsMapActions(mapActionGroup, syncActionConfig) { } } +export type ProjectSync = { + messagesConfiguration: MessagesConfigurationDraft +} & Project + export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createChannelsMapActions( mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions(diff, doMapActions) + const buildActions = createBuildActions( + diff, + doMapActions + ) return { buildActions } } diff --git a/packages/sync-actions/src/quote-requests.ts b/packages/sync-actions/src/quote-requests.ts index eeb943b45..087afb27f 100644 --- a/packages/sync-actions/src/quote-requests.ts +++ b/packages/sync-actions/src/quote-requests.ts @@ -1,4 +1,7 @@ -import { QuoteRequestUpdateAction } from '@commercetools/platform-sdk' +import { + QuoteRequest, + QuoteRequestUpdateAction, +} from '@commercetools/platform-sdk' import type { ActionGroup, SyncActionConfig, @@ -46,14 +49,17 @@ function createQuoteRequestsMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createQuoteRequestsMapActions( mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions(diff, doMapActions) + const buildActions = createBuildActions< + QuoteRequest, + QuoteRequestUpdateAction + >(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/quotes.ts b/packages/sync-actions/src/quotes.ts index a9238c4de..be7190cd0 100644 --- a/packages/sync-actions/src/quotes.ts +++ b/packages/sync-actions/src/quotes.ts @@ -1,4 +1,4 @@ -import { QuoteUpdateAction } from '@commercetools/platform-sdk' +import { Quote, QuoteUpdateAction } from '@commercetools/platform-sdk' import type { ActionGroup, SyncActionConfig, @@ -46,11 +46,14 @@ function createQuotesMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createQuotesMapActions(mapActionGroup, syncActionConfig) - const buildActions = createBuildActions(diff, doMapActions) + const buildActions = createBuildActions( + diff, + doMapActions + ) return { buildActions } } diff --git a/packages/sync-actions/src/shipping-methods.ts b/packages/sync-actions/src/shipping-methods.ts index bf537a11d..1859aa440 100644 --- a/packages/sync-actions/src/shipping-methods.ts +++ b/packages/sync-actions/src/shipping-methods.ts @@ -1,4 +1,7 @@ -import { ShippingMethodUpdateAction } from '@commercetools/platform-sdk' +import { + ShippingMethod, + ShippingMethodUpdateAction, +} from '@commercetools/platform-sdk' import type { ActionGroup, SyncActionConfig, @@ -49,7 +52,7 @@ function createShippingMethodsMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { // actionGroupList contains information about which action groups // are allowed or ignored @@ -66,6 +69,9 @@ export default ( mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions(diff, doMapActions) + const buildActions = createBuildActions< + ShippingMethod, + ShippingMethodUpdateAction + >(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/staged-quotes.ts b/packages/sync-actions/src/staged-quotes.ts index 517d09b71..388523b96 100644 --- a/packages/sync-actions/src/staged-quotes.ts +++ b/packages/sync-actions/src/staged-quotes.ts @@ -1,4 +1,8 @@ -import { StagedQuoteUpdateAction } from '@commercetools/platform-sdk' +import { + CustomFields, + StagedQuote, + StagedQuoteUpdateAction, +} from '@commercetools/platform-sdk' import type { ActionGroup, SyncActionConfig, @@ -43,17 +47,25 @@ function createStagedQuotesMapActions( } } +export type StagedQuoteSync = { + stagedQuoteState: string + custom: CustomFields +} & StagedQuote + export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createStagedQuotesMapActions( mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions(diff, doMapActions) + const buildActions = createBuildActions< + StagedQuoteSync, + StagedQuoteUpdateAction + >(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/states.ts b/packages/sync-actions/src/states.ts index 54635be10..429d76de1 100644 --- a/packages/sync-actions/src/states.ts +++ b/packages/sync-actions/src/states.ts @@ -1,4 +1,4 @@ -import { StateUpdateAction } from '@commercetools/platform-sdk' +import { State, StateUpdateAction } from '@commercetools/platform-sdk' import type { ActionGroup, SyncActionConfig, @@ -62,9 +62,12 @@ function createStatesMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createStatesMapActions(mapActionGroup, syncActionConfig) - const buildActions = createBuildActions(diff, doMapActions) + const buildActions = createBuildActions( + diff, + doMapActions + ) return { buildActions } } diff --git a/packages/sync-actions/src/stores.ts b/packages/sync-actions/src/stores.ts index a78ba7b8c..f8d47ae92 100644 --- a/packages/sync-actions/src/stores.ts +++ b/packages/sync-actions/src/stores.ts @@ -1,4 +1,4 @@ -import { StoreUpdateAction } from '@commercetools/platform-sdk' +import { Store, StoreUpdateAction } from '@commercetools/platform-sdk' import type { ActionGroup, UpdateAction } from '@commercetools/sdk-client-v2' import { actionsMapBase } from './stores-actions' import { SyncAction } from './types/update-actions' @@ -40,11 +40,11 @@ function createStoresMapActions( export default ( actionGroupList?: Array -): SyncAction => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createStoresMapActions(mapActionGroup) const onBeforeApplyingDiff = null - const buildActions = createBuildActions( + const buildActions = createBuildActions( diff, doMapActions, onBeforeApplyingDiff diff --git a/packages/sync-actions/src/tax-categories.ts b/packages/sync-actions/src/tax-categories.ts index a65a13291..91684d0d3 100644 --- a/packages/sync-actions/src/tax-categories.ts +++ b/packages/sync-actions/src/tax-categories.ts @@ -1,4 +1,7 @@ -import { TaxCategoryUpdateAction } from '@commercetools/platform-sdk' +import { + TaxCategory, + TaxCategoryUpdateAction, +} from '@commercetools/platform-sdk' import type { ActionGroup, SyncActionConfig, @@ -45,7 +48,7 @@ function createTaxCategoriesMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { // config contains information about which action groups // are allowed or ignored @@ -62,6 +65,9 @@ export default ( mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions(diff, doMapActions) + const buildActions = createBuildActions( + diff, + doMapActions + ) return { buildActions } } diff --git a/packages/sync-actions/src/types.ts b/packages/sync-actions/src/types.ts index 1f5d672be..240c3daaf 100644 --- a/packages/sync-actions/src/types.ts +++ b/packages/sync-actions/src/types.ts @@ -1,5 +1,7 @@ +import { Type, TypeUpdateAction } from '@commercetools/platform-sdk/src' import { SyncActionConfig } from '@commercetools/sdk-client-v2' import { actionsMapBase, actionsMapFieldDefinitions } from './types-actions' +import { SyncAction } from './types/update-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' @@ -38,10 +40,13 @@ function createTypeMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -) => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createTypeMapActions(mapActionGroup, syncActionConfig) - const buildActions = createBuildActions(diff, doMapActions) + const buildActions = createBuildActions( + diff, + doMapActions + ) return { buildActions } } diff --git a/packages/sync-actions/src/types/update-actions.ts b/packages/sync-actions/src/types/update-actions.ts index 0654d171e..5f6b66f5e 100644 --- a/packages/sync-actions/src/types/update-actions.ts +++ b/packages/sync-actions/src/types/update-actions.ts @@ -1,5 +1,19 @@ import { UpdateAction } from '@commercetools/sdk-client-v2' -export type SyncAction = { - buildActions: (now: any, before: any, config?: S) => Array +export type SyncAction< + R extends object | undefined, + S extends UpdateAction, + T = {}, +> = { + buildActions: ( + now: DeepPartial, + before: DeepPartial, + config?: T + ) => Array } + +export type DeepPartial = T extends object + ? { + [P in keyof T]?: DeepPartial + } + : T diff --git a/packages/sync-actions/src/utils/create-build-actions.ts b/packages/sync-actions/src/utils/create-build-actions.ts index a3eab4ed6..c03becb09 100644 --- a/packages/sync-actions/src/utils/create-build-actions.ts +++ b/packages/sync-actions/src/utils/create-build-actions.ts @@ -1,4 +1,6 @@ +import { UpdateAction } from '@commercetools/sdk-client-v2' import { deepEqual } from 'fast-equals' +import { DeepPartial } from '../types/update-actions' function applyOnBeforeDiff(before, now, fn?: (before, now) => Array) { return fn && typeof fn === 'function' ? fn(before, now) : [before, now] @@ -66,13 +68,17 @@ function injectMissingPriceIds(nextVariants, previousVariants) { }) } -export default function createBuildActions( +export default function createBuildActions( differ, doMapActions, - onBeforeDiff?: (before, now) => Array, + onBeforeDiff?: (before: DeepPartial, now: DeepPartial) => Array, buildActionsConfig: any = {} ) { - return function buildActions(now, before, options = {}) { + return function buildActions( + now: DeepPartial, + before: DeepPartial, + options = {} + ): Array { if (!now || !before) throw new Error( 'Missing either `newObj` or `oldObj` ' + diff --git a/packages/sync-actions/src/zones.ts b/packages/sync-actions/src/zones.ts index 545d7809d..272ea3793 100644 --- a/packages/sync-actions/src/zones.ts +++ b/packages/sync-actions/src/zones.ts @@ -1,4 +1,4 @@ -import { ZoneUpdateAction } from '@commercetools/platform-sdk' +import { Zone, ZoneUpdateAction } from '@commercetools/platform-sdk' import type { ActionGroup, SyncActionConfig, @@ -46,7 +46,7 @@ function createZonesMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { // config contains information about which action groups // are allowed or ignored @@ -60,6 +60,9 @@ export default ( // It will return an empty array for ignored action groups const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createZonesMapActions(mapActionGroup, syncActionConfig) - const buildActions = createBuildActions(diff, doMapActions) + const buildActions = createBuildActions( + diff, + doMapActions + ) return { buildActions } } diff --git a/packages/sync-actions/test/attribute-groups-sync.spec.ts b/packages/sync-actions/test/attribute-groups-sync.spec.ts index 4de9b02b2..b267766dd 100644 --- a/packages/sync-actions/test/attribute-groups-sync.spec.ts +++ b/packages/sync-actions/test/attribute-groups-sync.spec.ts @@ -14,17 +14,17 @@ describe('Exports', () => { }) describe('Actions', () => { - let attributeGroupSync: SyncAction + let attributeGroupSync = attributeGroupSyncFn() beforeEach(() => { attributeGroupSync = attributeGroupSyncFn() }) test('should build `changeName` action', () => { const before = { - name: 'John', + name: { 'en-GB': 'John' }, } const now = { - name: 'Robert', + name: { 'en-GB': 'Robert' }, } const actual = attributeGroupSync.buildActions(now, before) @@ -34,10 +34,10 @@ describe('Actions', () => { test('should build `setDescription` action', () => { const before = { - description: 'some description', + description: { 'en-GB': 'some description' }, } const now = { - description: 'some updated description', + description: { 'en-GB': 'some updated description' }, } const actual = attributeGroupSync.buildActions(now, before) diff --git a/packages/sync-actions/test/cart-discounts-sync.spec.ts b/packages/sync-actions/test/cart-discounts-sync.spec.ts index cdfce4ef7..d73d6a3e1 100644 --- a/packages/sync-actions/test/cart-discounts-sync.spec.ts +++ b/packages/sync-actions/test/cart-discounts-sync.spec.ts @@ -1,7 +1,10 @@ import cartDiscountsSyncFn, { actionGroups } from '../src/cart-discounts' import { baseActionsList } from '../src/cart-discounts-actions' -import { SyncAction } from '../src/types/update-actions' -import { CartDiscountUpdateAction } from '@commercetools/platform-sdk/src' +import { DeepPartial, SyncAction } from '../src/types/update-actions' +import { + CartDiscountDraft, + CartDiscountUpdateAction, +} from '@commercetools/platform-sdk/src' describe('Cart Discounts Exports', () => { test('action group list', () => { @@ -111,7 +114,7 @@ describe('Cart Discounts Exports', () => { }) describe('Cart Discounts Actions', () => { - let cartDiscountsSync: SyncAction + let cartDiscountsSync = cartDiscountsSyncFn() beforeEach(() => { cartDiscountsSync = cartDiscountsSyncFn() }) @@ -193,14 +196,14 @@ describe('Cart Discounts Actions', () => { }) test('should build the `changeValue` action', () => { - const before = { + const before: DeepPartial = { value: { type: 'relative', permyriad: 100, }, } - const now = { + const now: DeepPartial = { value: { type: 'relative', permyriad: 200, @@ -240,14 +243,14 @@ describe('Cart Discounts Actions', () => { }) test('should build the `changeTarget` action', () => { - const before = { + const before: DeepPartial = { target: { type: 'customLineItems', predicate: 'sku="sku-a"', }, } - const now = { + const now: DeepPartial = { target: { type: 'lineItems', predicate: 'sku="sku-b"', @@ -368,7 +371,7 @@ describe('Cart Discounts Actions', () => { describe('custom fields', () => { test('should build `setCustomType` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -379,7 +382,7 @@ describe('Cart Discounts Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', @@ -397,7 +400,7 @@ describe('Cart Discounts Actions', () => { }) test('should build `setCustomField` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -408,7 +411,7 @@ describe('Cart Discounts Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', diff --git a/packages/sync-actions/test/category-sync.spec.ts b/packages/sync-actions/test/category-sync.spec.ts index 236fd62fb..f06ce14ab 100644 --- a/packages/sync-actions/test/category-sync.spec.ts +++ b/packages/sync-actions/test/category-sync.spec.ts @@ -1,11 +1,15 @@ import categorySyncFn, { actionGroups } from '../src/categories' -import { SyncAction } from '../src/types/update-actions' +import { DeepPartial, SyncAction } from '../src/types/update-actions' import { baseActionsList, metaActionsList, referenceActionsList, } from '../src/category-actions' -import { CategoryUpdateAction } from '@commercetools/platform-sdk/src' +import { + CartDiscountDraft, + CategoryDraft, + CategoryUpdateAction, +} from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -45,14 +49,14 @@ describe('Exports', () => { }) describe('Actions', () => { - let categorySync: SyncAction + let categorySync = categorySyncFn() beforeEach(() => { categorySync = categorySyncFn() }) describe('custom fields', () => { test('should build `setCustomType` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -63,7 +67,7 @@ describe('Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', @@ -81,7 +85,7 @@ describe('Actions', () => { }) test('should build `setCustomField` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -92,7 +96,7 @@ describe('Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', diff --git a/packages/sync-actions/test/channels-sync-.spec.ts b/packages/sync-actions/test/channels-sync-.spec.ts index ad48d4701..8e41a37df 100644 --- a/packages/sync-actions/test/channels-sync-.spec.ts +++ b/packages/sync-actions/test/channels-sync-.spec.ts @@ -1,7 +1,11 @@ import createChannelsSync, { actionGroups } from '../src/channels' import { baseActionsList } from '../src/channels-actions' -import { SyncAction } from '../src/types/update-actions' -import { ChannelUpdateAction } from '@commercetools/platform-sdk/src' +import { DeepPartial, SyncAction } from '../src/types/update-actions' +import { + CategoryDraft, + ChannelDraft, + ChannelUpdateAction, +} from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -68,7 +72,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let channelsSync: SyncAction + let channelsSync = createChannelsSync() beforeEach(() => { channelsSync = createChannelsSync() }) @@ -87,8 +91,10 @@ describe('Actions', () => { }) test('should build `changeName` action', () => { - const before = { name: 'nameBefore' } - const now = { name: 'nameAfter' } + const before = { + name: { 'en-GB': 'nameBefore' }, + } + const now = { name: { 'en-GB': 'nameAfter' } } const actual = channelsSync.buildActions(now, before) const expected = [ { @@ -100,8 +106,8 @@ describe('Actions', () => { }) test('should build `changeDescription` action', () => { - const before = { description: 'descriptionBefore' } - const now = { description: 'descriptionAfter' } + const before = { description: { 'en-GB': 'descriptionBefore' } } + const now = { description: { 'en-GB': 'descriptionAfter' } } const actual = channelsSync.buildActions(now, before) const expected = [ { @@ -113,8 +119,10 @@ describe('Actions', () => { }) test('should build `setAddress` action', () => { - const before = { address: 'addressBefore' } - const now = { address: 'addressAfter' } + const before: DeepPartial = { + address: { country: 'addressBefore' }, + } + const now = { address: { country: 'addressAfter' } } const actual = channelsSync.buildActions(now, before) const expected = [ { @@ -126,8 +134,12 @@ describe('Actions', () => { }) test('should build `setGeoLocation` action', () => { - const before = { geoLocation: 'geoLocationBefore' } - const now = { geoLocation: 'geoLocationAfter' } + const before: DeepPartial = { + geoLocation: { type: 'Point', coordinates: [123] }, + } + const now: DeepPartial = { + geoLocation: { type: 'Point', coordinates: [456] }, + } const actual = channelsSync.buildActions(now, before) const expected = [ { @@ -153,7 +165,7 @@ describe('Actions', () => { describe('custom fields', () => { test('should build `setCustomType` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -164,7 +176,7 @@ describe('Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', @@ -182,7 +194,7 @@ describe('Actions', () => { }) test('should build `setCustomField` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -193,7 +205,7 @@ describe('Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', diff --git a/packages/sync-actions/test/customer-group-sync.spec.ts b/packages/sync-actions/test/customer-group-sync.spec.ts index a9485f3e7..af110661a 100644 --- a/packages/sync-actions/test/customer-group-sync.spec.ts +++ b/packages/sync-actions/test/customer-group-sync.spec.ts @@ -1,7 +1,11 @@ import customerGroupSyncFn, { actionGroups } from '../src/customer-group' import { baseActionsList } from '../src/customer-group-actions' -import { SyncAction } from '../src/types/update-actions' -import { CustomerGroupUpdateAction } from '@commercetools/platform-sdk/src' +import { DeepPartial, SyncAction } from '../src/types/update-actions' +import { + CustomerGroup, + CustomerGroupDraft, + CustomerGroupUpdateAction, +} from '@commercetools/platform-sdk/src' describe('Customer Groups Exports', () => { test('action group list', () => { @@ -29,24 +33,24 @@ describe('Customer Groups Exports', () => { }) describe('Customer Groups Actions', () => { - let customerGroupSync: SyncAction + let customerGroupSync = customerGroupSyncFn() beforeEach(() => { customerGroupSync = customerGroupSyncFn() }) test('should build the `changeName` action', () => { - const before = { - name: { en: 'en-name-before', de: 'de-name-before' }, + const before: DeepPartial = { + name: 'en-name-before', } - const now = { - name: { en: 'en-name-now', de: 'de-name-now' }, + const now: DeepPartial = { + name: 'en-name-now', } const expected = [ { action: 'changeName', - name: { en: 'en-name-now', de: 'de-name-now' }, + name: 'en-name-now', }, ] const actual = customerGroupSync.buildActions(now, before) @@ -74,7 +78,7 @@ describe('Customer Groups Actions', () => { describe('custom fields', () => { test('should build `setCustomType` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -85,7 +89,7 @@ describe('Customer Groups Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', @@ -103,7 +107,7 @@ describe('Customer Groups Actions', () => { }) test('should build `setCustomField` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -114,7 +118,7 @@ describe('Customer Groups Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', diff --git a/packages/sync-actions/test/customer-sync.spec.ts b/packages/sync-actions/test/customer-sync.spec.ts index cab1c2210..98a5f4e76 100644 --- a/packages/sync-actions/test/customer-sync.spec.ts +++ b/packages/sync-actions/test/customer-sync.spec.ts @@ -4,8 +4,8 @@ import { setDefaultBaseActionsList, referenceActionsList, } from '../src/customer-actions' -import { SyncAction } from '../src/types/update-actions' -import { CustomerUpdateAction } from '@commercetools/platform-sdk/src' +import { DeepPartial } from '../src/types/update-actions' +import { Customer } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -66,7 +66,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let customerSync: SyncAction + let customerSync = customerSyncFn() beforeEach(() => { customerSync = customerSyncFn() }) @@ -98,7 +98,7 @@ describe('Actions', () => { }) test('should build `setDefaultBillingAddress` action', () => { - const before = { + const before: DeepPartial = { defaultBillingAddressId: 'abc123', } const now = { @@ -380,11 +380,10 @@ describe('Actions', () => { }) test('should build `setCustomerGroup` action with key', () => { - const before = {} - const now = { + const before: DeepPartial = {} + const now: DeepPartial = { customerGroup: { typeId: 'customer-group', - key: 'foo-customer-group', }, } const actual = customerSync.buildActions(now, before) @@ -399,7 +398,7 @@ describe('Actions', () => { describe('custom fields', () => { test('should build `setCustomType` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -410,7 +409,7 @@ describe('Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', @@ -428,7 +427,7 @@ describe('Actions', () => { }) test('should build `setCustomField` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -439,7 +438,7 @@ describe('Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', @@ -462,7 +461,7 @@ describe('Actions', () => { }) test('should build `setStores` action', () => { - const before = { + const before: DeepPartial = { stores: [ { typeId: 'store', @@ -470,7 +469,7 @@ describe('Actions', () => { }, ], } - const now = { + const now: DeepPartial = { stores: [ { typeId: 'store', @@ -518,7 +517,7 @@ describe('Actions', () => { }) test('should build not throw error for empty array', () => { - const before = { + const before: DeepPartial = { stores: [ { typeId: 'store', diff --git a/packages/sync-actions/test/discount-codes-sync.spec.ts b/packages/sync-actions/test/discount-codes-sync.spec.ts index 5dbc7548e..328e14be6 100644 --- a/packages/sync-actions/test/discount-codes-sync.spec.ts +++ b/packages/sync-actions/test/discount-codes-sync.spec.ts @@ -1,7 +1,7 @@ import discountCodesSyncFn, { actionGroups } from '../src/discount-codes' import { baseActionsList } from '../src/discount-codes-actions' -import { SyncAction } from '../src/types/update-actions' -import { DiscountCodeUpdateAction } from '@commercetools/platform-sdk/src' +import { DeepPartial } from '../src/types/update-actions' +import { DiscountCodeDraft } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -86,7 +86,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let discountCodesSync: SyncAction + let discountCodesSync = discountCodesSyncFn() beforeEach(() => { discountCodesSync = discountCodesSyncFn() }) @@ -180,34 +180,34 @@ describe('Actions', () => { }) test('should build `changeCartDiscounts` action', () => { - const before = { + const before: DeepPartial = { cartDiscounts: [ { - typeId: 'previous-cart-discount', + typeId: 'cart-discount', id: 'previous-cart-discount-id', }, { - typeId: 'another-previous-cart-discount', + typeId: 'cart-discount', id: 'another-previous-cart-discount-id', }, ], } - const now = { + const now: DeepPartial = { cartDiscounts: [ { - typeId: 'previous-cart-discount', + typeId: 'cart-discount', id: 'previous-cart-discount-id', }, { - typeId: 'new-cart-discount-1', + typeId: 'cart-discount', id: 'new-cart-discount-id-1', }, { - typeId: 'new-cart-discount-2', + typeId: 'cart-discount', id: 'new-cart-discount-id-2', }, { - typeId: 'another-new-cart-discount-2', + typeId: 'cart-discount', id: 'another-new-cart-discount-id-2', }, ], @@ -219,19 +219,19 @@ describe('Actions', () => { action: 'changeCartDiscounts', cartDiscounts: [ { - typeId: 'previous-cart-discount', + typeId: 'cart-discount', id: 'previous-cart-discount-id', }, { - typeId: 'new-cart-discount-1', + typeId: 'cart-discount', id: 'new-cart-discount-id-1', }, { - typeId: 'new-cart-discount-2', + typeId: 'cart-discount', id: 'new-cart-discount-id-2', }, { - typeId: 'another-new-cart-discount-2', + typeId: 'cart-discount', id: 'another-new-cart-discount-id-2', }, ], @@ -321,7 +321,7 @@ describe('Actions', () => { describe('custom fields', () => { test('should build `setCustomType` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -332,7 +332,7 @@ describe('Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', @@ -350,7 +350,7 @@ describe('Actions', () => { }) test('should build `setCustomField` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -361,7 +361,7 @@ describe('Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', diff --git a/packages/sync-actions/test/inventory-sync.spec.ts b/packages/sync-actions/test/inventory-sync.spec.ts index 1890aa687..566f05916 100644 --- a/packages/sync-actions/test/inventory-sync.spec.ts +++ b/packages/sync-actions/test/inventory-sync.spec.ts @@ -1,7 +1,10 @@ import inventorySyncFn, { actionGroups } from '../src/inventories' import { baseActionsList, referenceActionsList } from '../src/inventory-actions' import { SyncAction } from '../src/types/update-actions' -import { InventoryEntryUpdateAction } from '@commercetools/platform-sdk/src' +import { + InventoryEntryDraft, + InventoryEntryUpdateAction, +} from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -28,7 +31,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let inventorySync: SyncAction + let inventorySync = inventorySyncFn() beforeEach(() => { inventorySync = inventorySyncFn() }) @@ -48,7 +51,7 @@ describe('Actions', () => { describe('custom fields', () => { test('should build `setCustomType` action', () => { - const before = { + const before: Partial = { custom: { type: { typeId: 'type', @@ -59,7 +62,7 @@ describe('Actions', () => { }, }, } - const now = { + const now: Partial = { custom: { type: { typeId: 'type', @@ -77,7 +80,7 @@ describe('Actions', () => { }) test('should build `setCustomField` action', () => { - const before = { + const before: Partial = { custom: { type: { typeId: 'type', @@ -88,7 +91,7 @@ describe('Actions', () => { }, }, } - const now = { + const now: Partial = { custom: { type: { typeId: 'type', diff --git a/packages/sync-actions/test/order-sync.spec.ts b/packages/sync-actions/test/order-sync.spec.ts index 99d9a403b..8365e5662 100644 --- a/packages/sync-actions/test/order-sync.spec.ts +++ b/packages/sync-actions/test/order-sync.spec.ts @@ -1,8 +1,11 @@ import { performance } from 'perf_hooks' -import orderSyncFn, { actionGroups } from '../src/orders' +import orderSyncFn, { actionGroups, OrderSync } from '../src/orders' import { baseActionsList } from '../src/order-actions' -import { SyncAction } from '../src/types/update-actions' -import { OrderUpdateAction } from '@commercetools/platform-sdk/src' +import { DeepPartial, SyncAction } from '../src/types/update-actions' +import { + OrderEditDraft, + OrderUpdateAction, +} from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -19,14 +22,14 @@ describe('Exports', () => { }) describe('Actions', () => { - let orderSync: SyncAction + let orderSync = orderSyncFn() beforeEach(() => { orderSync = orderSyncFn() }) describe('base', () => { test('should build *state actions', () => { - const before = { + const before: DeepPartial = { orderState: 'Open', paymentState: 'Pending', shipmentState: 'Ready', @@ -49,18 +52,18 @@ describe('Actions', () => { describe('deliveries', () => { test('should build `addDelivery` action', () => { - const before = { + const before: DeepPartial = { shippingInfo: { deliveries: [], }, } - const now = { + const now: DeepPartial = { shippingInfo: { deliveries: [ { items: [ - { id: 'li-1', qty: 1 }, - { id: 'li-2', qty: 2 }, + { id: 'li-1', quantity: 1 }, + { id: 'li-2', quantity: 2 }, ], parcels: [ { @@ -306,7 +309,7 @@ describe('Actions', () => { }) test('should create remove `parcel` action', () => { - const before = { + const before: DeepPartial = { shippingInfo: { deliveries: [ { @@ -330,7 +333,7 @@ describe('Actions', () => { }, } - const now = { + const now: DeepPartial = { shippingInfo: { deliveries: [ { @@ -355,11 +358,11 @@ describe('Actions', () => { describe('returnInfo', () => { test('should not build `returnInfo` action if items are not set', () => { - const before = { + const before: DeepPartial = { returnInfo: [], } - const now = { + const now: DeepPartial = { returnInfo: [ { returnTrackingId: 'tracking-id-1', @@ -378,7 +381,7 @@ describe('Actions', () => { returnInfo: [], } - const now = { + const now: DeepPartial = { returnInfo: [ { returnTrackingId: 'tracking-id-1', @@ -841,12 +844,12 @@ describe('Actions', () => { }) describe('custom fields', () => { - let orderSync: SyncAction + let orderSync = orderSyncFn() beforeEach(() => { orderSync = orderSyncFn() }) test('should build `setCustomType` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -857,7 +860,7 @@ describe('custom fields', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', @@ -873,7 +876,7 @@ describe('custom fields', () => { expect(actual).toEqual(expected) }) test('should build `setCustomField` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -884,7 +887,7 @@ describe('custom fields', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', diff --git a/packages/sync-actions/test/product-discounts-sync.spec.ts b/packages/sync-actions/test/product-discounts-sync.spec.ts index b60761f8f..5fa50da0d 100644 --- a/packages/sync-actions/test/product-discounts-sync.spec.ts +++ b/packages/sync-actions/test/product-discounts-sync.spec.ts @@ -1,7 +1,7 @@ import productDiscountsSyncFn, { actionGroups } from '../src/product-discounts' import { baseActionsList } from '../src/product-discounts-actions' -import { SyncAction } from '../src/types/update-actions' -import { ProductDiscountUpdateAction } from '@commercetools/platform-sdk/src' +import { DeepPartial } from '../src/types/update-actions' +import { ProductDiscountDraft } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -78,7 +78,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let productDiscountsSync: SyncAction + let productDiscountsSync = productDiscountsSyncFn() beforeEach(() => { productDiscountsSync = productDiscountsSyncFn() }) @@ -160,14 +160,14 @@ describe('Actions', () => { }) test('should build the `changeValue` action', () => { - const before = { + const before: DeepPartial = { value: { type: 'relative', permyriad: 100, }, } - const now = { + const now: DeepPartial = { value: { type: 'relative', permyriad: 200, diff --git a/packages/sync-actions/test/product-selections-sync.spec.ts b/packages/sync-actions/test/product-selections-sync.spec.ts index 25399d195..5928b3ca3 100644 --- a/packages/sync-actions/test/product-selections-sync.spec.ts +++ b/packages/sync-actions/test/product-selections-sync.spec.ts @@ -2,8 +2,11 @@ import { baseActionsList } from '../src/product-selections-actions' import productSelectionsSyncFn, { actionGroups, } from '../src/product-selections' -import { SyncAction } from '../src/types/update-actions' -import { ProductSelectionUpdateAction } from '@commercetools/platform-sdk/src' +import { DeepPartial, SyncAction } from '../src/types/update-actions' +import { + ProductSelectionDraft, + ProductSelectionUpdateAction, +} from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -19,7 +22,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let productSelectionsSync: SyncAction + let productSelectionsSync = productSelectionsSyncFn() beforeEach(() => { productSelectionsSync = productSelectionsSyncFn() }) @@ -52,7 +55,7 @@ describe('Actions', () => { describe('custom fields', () => { test('should build `setCustomType` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -63,7 +66,7 @@ describe('Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', @@ -81,7 +84,7 @@ describe('Actions', () => { }) test('should build `setCustomField` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -92,7 +95,7 @@ describe('Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', diff --git a/packages/sync-actions/test/product-sync-base.spec.ts b/packages/sync-actions/test/product-sync-base.spec.ts index 4581ee373..8ad55582a 100644 --- a/packages/sync-actions/test/product-sync-base.spec.ts +++ b/packages/sync-actions/test/product-sync-base.spec.ts @@ -1,12 +1,16 @@ import clone from '../src/utils/clone' -import productsSyncFn, { actionGroups } from '../src/products' +import productsSyncFn, { actionGroups, ProductSync } from '../src/products' import { baseActionsList, metaActionsList, referenceActionsList, } from '../src/product-actions' -import { SyncAction } from '../src/types/update-actions' -import { ProductUpdateAction } from '@commercetools/platform-sdk/src' +import { DeepPartial, SyncAction } from '../src/types/update-actions' +import { + ProductData, + ProductDraft, + ProductUpdateAction, +} from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -52,7 +56,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let productsSync: SyncAction + let productsSync = productsSyncFn() beforeEach(() => { productsSync = productsSyncFn() }) @@ -91,7 +95,7 @@ describe('Actions', () => { test('should build `setKey` action', () => { const before = { key: 'unique-key-1' } - const now = { key: 'unique-key-2' } + const now: Partial = { key: 'unique-key-2' } const actions = productsSync.buildActions(now, before) expect(actions).toEqual([{ action: 'setKey', ...now }]) @@ -137,7 +141,7 @@ describe('Actions', () => { test('should build `setSearchKeywords` action', () => { /* eslint-disable max-len */ - const before = { + const before: DeepPartial = { searchKeywords: { en: [ { text: 'Multi tool' }, @@ -157,7 +161,7 @@ describe('Actions', () => { ], }, } - const now = { + const now: DeepPartial = { searchKeywords: { en: [ { @@ -189,7 +193,7 @@ describe('Actions', () => { test('should build no actions if searchKeywords did not change', () => { /* eslint-disable max-len */ - const before = { + const before: DeepPartial = { name: { en: 'Car', de: 'Auto' }, searchKeywords: { en: [ diff --git a/packages/sync-actions/test/product-sync-images.spec.ts b/packages/sync-actions/test/product-sync-images.spec.ts index b2ffa446b..17c0f4a62 100644 --- a/packages/sync-actions/test/product-sync-images.spec.ts +++ b/packages/sync-actions/test/product-sync-images.spec.ts @@ -1,10 +1,9 @@ -import { SyncAction } from '../src/types/update-actions' -import productsSyncFn from '../src/products' -import { ProductUpdateAction } from '@commercetools/platform-sdk/src' +import { DeepPartial, SyncAction } from '../src/types/update-actions' +import productsSyncFn, { ProductSync } from '../src/products' /* eslint-disable max-len */ describe('Actions', () => { - let productsSync: SyncAction + let productsSync = productsSyncFn() beforeEach(() => { productsSync = productsSyncFn() }) @@ -469,14 +468,12 @@ describe('Actions', () => { describe('without images', () => { test('should not build actions if images are not set', () => { - const before = { - id: '123-abc', - masterVariant: { id: 1, images: [] }, + const before: DeepPartial = { + masterVariant: { images: [] }, variants: [], } - const now = { - id: '456-def', - masterVariant: { id: 1 }, + const now: DeepPartial = { + masterVariant: {}, variants: [], } diff --git a/packages/sync-actions/test/product-sync-prices.spec.ts b/packages/sync-actions/test/product-sync-prices.spec.ts index 14dcac0fa..29395b567 100644 --- a/packages/sync-actions/test/product-sync-prices.spec.ts +++ b/packages/sync-actions/test/product-sync-prices.spec.ts @@ -1,22 +1,22 @@ -import { SyncAction } from '../src/types/update-actions' -import productsSyncFn from '../src/products' -import { ProductUpdateAction } from '@commercetools/platform-sdk/src' +import { DeepPartial } from '../src/types/update-actions' +import productsSyncFn, { ProductSync } from '../src/products' +import { DiscountedPriceDraft } from '@commercetools/platform-sdk/src' /* eslint-disable max-len */ describe('Actions', () => { - let productsSync: SyncAction + let productsSync = productsSyncFn() beforeEach(() => { productsSync = productsSyncFn() }) describe('with `priceID`', () => { - const discounted = { + const discounted: DiscountedPriceDraft = { value: { centAmount: 4000, currencyCode: 'EUR' }, discount: { typeId: 'product-discount', id: 'pd1' }, } const validFrom = new Date().toISOString() - const before = { + const before: DeepPartial = { id: '123', masterVariant: { id: 1, @@ -66,7 +66,7 @@ describe('Actions', () => { ], } - const now = { + const now: DeepPartial = { id: '123', masterVariant: { id: 1, @@ -226,7 +226,7 @@ describe('Actions', () => { }) test('should generate PriceCustom actions before changePrice action', () => { - const before = { + const before: DeepPartial = { id: '123', masterVariant: { prices: [ @@ -253,7 +253,7 @@ describe('Actions', () => { }, } - const now = { + const now: DeepPartial = { id: '123', masterVariant: { prices: [ @@ -322,11 +322,11 @@ describe('Actions', () => { describe('without `priceID`', () => { let actions - const dateNow = new Date() - const twoWeeksFromNow = new Date(Date.now() + 12096e5) // two weeks from now - const threeWeeksFromNow = new Date(Date.now() + 12096e5 * 1.5) + const dateNow = new Date().toISOString() + const twoWeeksFromNow = new Date(Date.now() + 12096e5).toISOString() // two weeks from now + const threeWeeksFromNow = new Date(Date.now() + 12096e5 * 1.5).toISOString() - const before = { + const before: DeepPartial = { id: '123-abc', masterVariant: { id: 1, @@ -438,7 +438,7 @@ describe('Actions', () => { ], }, } - const now = { + let now: DeepPartial = { id: '456-def', masterVariant: { id: 1, @@ -553,9 +553,13 @@ describe('Actions', () => { } beforeEach(() => { - now.masterVariant.prices = now.masterVariant.prices.sort( - () => Math.random() - 0.5 - ) + now = { + masterVariant: { + prices: now.masterVariant.prices.sort(() => Math.random() - 0.5), + ...now.masterVariant, + }, + ...now, + } actions = productsSync.buildActions(now, before) }) @@ -723,9 +727,8 @@ describe('Actions', () => { }) test('should remove a price without id', () => { - const oldProduct = { + const oldProduct: DeepPartial = { id: '123', - version: 1, masterVariant: { id: 1, sku: 'v1', @@ -765,9 +768,8 @@ describe('Actions', () => { }, variants: [], } - const newProduct = { + const newProduct: DeepPartial = { id: '123', - version: 1, masterVariant: { id: 1, sku: 'v1', @@ -806,9 +808,8 @@ describe('Actions', () => { }) test('should handle missing optional fields', () => { - const oldProduct = { + const oldProduct: DeepPartial = { id: '123', - version: 1, masterVariant: { id: 1, sku: 'v1', @@ -828,9 +829,8 @@ describe('Actions', () => { }, variants: [], } - const newProduct = { + const newProduct: DeepPartial = { id: '123', - version: 1, masterVariant: { id: 1, sku: 'v1', @@ -853,9 +853,8 @@ describe('Actions', () => { }) test('should sync when optional fields are different', () => { - const oldProduct = { + const oldProduct: DeepPartial = { id: '123', - version: 1, masterVariant: { id: 1, sku: 'v1', @@ -875,9 +874,8 @@ describe('Actions', () => { }, variants: [], } - const newProduct = { + const newProduct: DeepPartial = { id: '123', - version: 1, masterVariant: { id: 1, sku: 'v1', @@ -919,13 +917,8 @@ describe('Actions', () => { describe('without `country`', () => { let actions - const before = { + const before: DeepPartial = { id: '81400c95-1de9-4431-9abd-a3eb8e0884d5', - version: 1, - productType: { - typeId: 'product-type', - id: 'c538376f-b565-4cb7-ac29-49b88b7f2acf', - }, name: { de: 'abcd', }, @@ -995,13 +988,8 @@ describe('Actions', () => { ], } - const now = { + const now: DeepPartial = { id: '81400c95-1de9-4431-9abd-a3eb8e0884d5', - version: 1, - productType: { - typeId: 'product-type', - id: 'c538376f-b565-4cb7-ac29-49b88b7f2acf', - }, name: { de: 'abcd', }, @@ -1076,30 +1064,30 @@ describe('Actions', () => { }) describe('with read only prices', () => { - const before = { + const before: Readonly> = { id: '123', masterVariant: { id: 1, - prices: Object.freeze([ + prices: [ { id: '111', value: { currencyCode: 'EUR', centAmount: 1000 }, }, - ]), + ], }, } - const now = { + const now: Readonly> = { id: '123', masterVariant: { id: 1, - prices: Object.freeze([ + prices: [ { id: '111', value: { currencyCode: 'EUR', centAmount: 2000 }, country: 'US', }, - ]), + ], }, } diff --git a/packages/sync-actions/test/product-sync-variants.spec.ts b/packages/sync-actions/test/product-sync-variants.spec.ts index 80e93b601..4d63a82cf 100644 --- a/packages/sync-actions/test/product-sync-variants.spec.ts +++ b/packages/sync-actions/test/product-sync-variants.spec.ts @@ -1,10 +1,10 @@ -import { SyncAction } from '../src/types/update-actions' -import productsSyncFn from '../src/products' -import { ProductUpdateAction } from '@commercetools/platform-sdk/src' +import { DeepPartial, SyncAction } from '../src/types/update-actions' +import productsSyncFn, { ProductSync } from '../src/products' +import { Asset } from '@commercetools/platform-sdk/src' /* eslint-disable max-len */ describe('Actions', () => { - let productsSync: SyncAction + let productsSync = productsSyncFn() beforeEach(() => { productsSync = productsSyncFn() }) @@ -881,21 +881,16 @@ describe('Actions', () => { test('should ignore set sku', () => { // Case when sku is not set, and the new value is empty or null - const before = { - id: '123', - masterVariant: { - id: 1, - }, - variants: [{ id: 2 }], + const before: DeepPartial = { + masterVariant: {}, + variants: [{}], } - const now = { - id: '123', + const now: DeepPartial = { masterVariant: { - id: 1, sku: '', }, - variants: [{ id: 2, sku: null }], + variants: [{ sku: null }], } const actions = productsSync.buildActions(now, before) @@ -904,16 +899,14 @@ describe('Actions', () => { test('should ignore set key', () => { // Case when key is not set, and the new value is empty or null - const before = { - id: '123', + const before: DeepPartial = { masterVariant: { id: 1, }, variants: [{ id: 2 }], } - const now = { - id: '123', + const now: DeepPartial = { masterVariant: { id: 1, key: '', @@ -927,8 +920,7 @@ describe('Actions', () => { test('should ignore set sku if the sku was and still is empty', () => { // Case when sku is not set, and the new value is empty or null - const before = { - id: '123', + const before: DeepPartial = { masterVariant: { id: 1, sku: '', @@ -936,8 +928,7 @@ describe('Actions', () => { variants: [{ id: 2 }], } - const now = { - id: '123', + const now: DeepPartial = { masterVariant: { id: 1, sku: '', @@ -951,7 +942,7 @@ describe('Actions', () => { test('should ignore set key if the key was and still is empty', () => { // Case when key is not set, and the new value is empty or null - const before = { + const before: DeepPartial = { id: '123', masterVariant: { id: 1, @@ -960,7 +951,7 @@ describe('Actions', () => { variants: [{ id: 2 }], } - const now = { + const now: DeepPartial = { id: '123', masterVariant: { id: 1, @@ -1540,7 +1531,7 @@ describe('Actions', () => { }) test('should build "setAssetKey", "changeAssetName", "setAssetDescription", "setAssetSources", "setAssetTags", "setAssetCustomType" actions', () => { - const initialAsset = { + const initialAsset: Asset = { id: 'xyz', key: 'asset-key', name: { @@ -1567,7 +1558,7 @@ describe('Actions', () => { }, } - const changedAsset = { + const changedAsset: Asset = { id: 'xyz', key: 'update-asset-key', name: { @@ -1594,7 +1585,7 @@ describe('Actions', () => { }, } - const before = { + const before: DeepPartial = { variants: [ { id: 1, @@ -1602,7 +1593,7 @@ describe('Actions', () => { }, ], } - const now = { + const now: DeepPartial = { variants: [ { id: 1, @@ -1659,7 +1650,7 @@ describe('Actions', () => { }) test('should build "setAssetKey", "changeAssetName" and "setAssetCustomField" ', () => { - const initialAsset = { + const initialAsset: DeepPartial = { id: 'xyz', key: 'asset-key', name: { @@ -1675,7 +1666,7 @@ describe('Actions', () => { }, }, } - const changedAsset = { + const changedAsset: DeepPartial = { id: 'xyz', key: 'asset-key-two', name: { @@ -1691,7 +1682,7 @@ describe('Actions', () => { }, }, } - const before = { + const before: DeepPartial = { variants: [ { id: 1, @@ -1699,7 +1690,7 @@ describe('Actions', () => { }, ], } - const now = { + const now: DeepPartial = { variants: [ { id: 1, diff --git a/packages/sync-actions/test/product-types-sync-attribute-hints.spec.ts b/packages/sync-actions/test/product-types-sync-attribute-hints.spec.ts index e07e91960..9c0e40641 100644 --- a/packages/sync-actions/test/product-types-sync-attribute-hints.spec.ts +++ b/packages/sync-actions/test/product-types-sync-attribute-hints.spec.ts @@ -1,5 +1,4 @@ -import createSyncProductTypes, { ProductTypeConfig } from '../src/product-types' -import { SyncAction } from '../src/types/update-actions' +import createSyncProductTypes from '../src/product-types' import { ProductTypeUpdateAction } from '@commercetools/platform-sdk/src' import { AttributeEnumValues } from '../src/product-types-actions' @@ -47,7 +46,7 @@ const createAttributeEnumDraftItem = ( describe('product type hints', () => { let updateActions: Array - let sync: SyncAction + let sync = createSyncProductTypes([]) beforeEach(() => { sync = createSyncProductTypes([]) }) diff --git a/packages/sync-actions/test/product-types-sync-base.spec.ts b/packages/sync-actions/test/product-types-sync-base.spec.ts index fa83ed0e0..ec069243e 100644 --- a/packages/sync-actions/test/product-types-sync-base.spec.ts +++ b/packages/sync-actions/test/product-types-sync-base.spec.ts @@ -1,11 +1,17 @@ import clone from '../src/utils/clone' -import createSyncProductTypes, { actionGroups } from '../src/product-types' +import createSyncProductTypes, { + actionGroups, + ProductTypeConfig, +} from '../src/product-types' import { baseActionsList, generateBaseFieldsUpdateActions, } from '../src/product-types-actions' -import { SyncAction } from '../src/types/update-actions' -import { ProductTypeUpdateAction } from '@commercetools/platform-sdk/src' +import { DeepPartial, SyncAction } from '../src/types/update-actions' +import { + ProductTypeDraft, + ProductTypeUpdateAction, +} from '@commercetools/platform-sdk/src' describe('ProductTypes sync', () => { test('action group list', () => { @@ -23,10 +29,10 @@ describe('ProductTypes sync', () => { }) describe('Actions', () => { - let productTypesSync: SyncAction + let productTypesSync = createSyncProductTypes() let updateActions: Array - let before - let now + let before: DeepPartial + let now: DeepPartial beforeEach(() => { productTypesSync = createSyncProductTypes() }) diff --git a/packages/sync-actions/test/projects-sync.spec.ts b/packages/sync-actions/test/projects-sync.spec.ts index 0ac75cd74..b08721c87 100644 --- a/packages/sync-actions/test/projects-sync.spec.ts +++ b/packages/sync-actions/test/projects-sync.spec.ts @@ -1,7 +1,7 @@ -import createProjectsSync, { actionGroups } from '../src/projects' +import createProjectsSync, { actionGroups, ProjectSync } from '../src/projects' import { baseActionsList } from '../src/projects-actions' -import { SyncAction } from '../src/types/update-actions' -import { ProjectUpdateAction } from '@commercetools/platform-sdk/src' +import { DeepPartial } from '../src/types/update-actions' +import { Project } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -70,7 +70,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let projectsSync: SyncAction + let projectsSync = createProjectsSync() beforeEach(() => { projectsSync = createProjectsSync() }) @@ -129,7 +129,7 @@ describe('Actions', () => { describe('setShippingRateInputType', () => { describe('given `shippingRateInputType` is of type `CartClassification`', () => { - const before = { + const before: DeepPartial = { shippingRateInputType: { type: 'CartClassification', values: [ @@ -140,7 +140,7 @@ describe('Actions', () => { }, } describe('given a value of `values` changes', () => { - const now = { + const now: DeepPartial = { shippingRateInputType: { type: 'CartClassification', values: [ @@ -163,7 +163,7 @@ describe('Actions', () => { }) }) describe('given type changes to `CartValue`', () => { - let now = { + let now: DeepPartial = { shippingRateInputType: { type: 'CartValue', }, @@ -203,8 +203,12 @@ describe('Actions', () => { }) test('should build `changeMessagesConfiguration` action', () => { - const before = { messagesConfiguration: { type: 'some-config' } } - const now = { messagesConfiguration: { type: 'some-other-config' } } + const before: DeepPartial = { + messagesConfiguration: { enabled: false }, + } + const now: DeepPartial = { + messagesConfiguration: { enabled: true }, + } const actual = projectsSync.buildActions(now, before) const expected = [ { diff --git a/packages/sync-actions/test/quote-requests-sync.spec.ts b/packages/sync-actions/test/quote-requests-sync.spec.ts index b40c1f826..4ed45ce63 100644 --- a/packages/sync-actions/test/quote-requests-sync.spec.ts +++ b/packages/sync-actions/test/quote-requests-sync.spec.ts @@ -1,7 +1,10 @@ import createQuoteRequestsSync, { actionGroups } from '../src/quote-requests' import { baseActionsList } from '../src/quote-requests-actions' -import { SyncAction } from '../src/types/update-actions' -import { QuoteRequestUpdateAction } from '@commercetools/platform-sdk/src' +import { DeepPartial, SyncAction } from '../src/types/update-actions' +import { + QuoteRequest, + QuoteRequestUpdateAction, +} from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -26,7 +29,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let quoteRequestsSync: SyncAction + let quoteRequestsSync = createQuoteRequestsSync() beforeEach(() => { quoteRequestsSync = createQuoteRequestsSync() }) @@ -45,13 +48,13 @@ describe('Actions', () => { }) test('should build `transitionState` action', () => { - const before = { + const before: DeepPartial = { state: { typeId: 'state', id: 'sid1', }, } - const now = { + const now: DeepPartial = { state: { typeId: 'state', id: 'sid2', @@ -68,7 +71,7 @@ describe('Actions', () => { }) test('should build `setCustomType` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -79,7 +82,7 @@ describe('Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', @@ -96,7 +99,7 @@ describe('Actions', () => { }) test('should build `setCustomField` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -107,7 +110,7 @@ describe('Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', diff --git a/packages/sync-actions/test/quotes-sync.spec.ts b/packages/sync-actions/test/quotes-sync.spec.ts index 191d5bf43..2253e22ef 100644 --- a/packages/sync-actions/test/quotes-sync.spec.ts +++ b/packages/sync-actions/test/quotes-sync.spec.ts @@ -1,7 +1,11 @@ import createQuotesSync, { actionGroups } from '../src/quotes' import { baseActionsList } from '../src/quotes-actions' -import { SyncAction } from '../src/types/update-actions' -import { QuoteUpdateAction } from '@commercetools/platform-sdk/src' +import { DeepPartial, SyncAction } from '../src/types/update-actions' +import { + Quote, + QuoteDraft, + QuoteUpdateAction, +} from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -34,14 +38,14 @@ describe('Exports', () => { }) describe('Actions', () => { - let quotesSync: SyncAction + let quotesSync = createQuotesSync() beforeEach(() => { quotesSync = createQuotesSync() }) test('should build `changeQuoteState` action', () => { - const before = { quoteState: 'Pending' } - const now = { quoteState: 'Approved' } + const before: DeepPartial = { quoteState: 'Pending' } + const now: DeepPartial = { quoteState: 'Approved' } const actual = quotesSync.buildActions(now, before) const expected = [ { @@ -53,8 +57,8 @@ describe('Actions', () => { }) test('should build `requestQuoteRenegotiation` action', () => { - const before = { buyerComment: '' } - const now = { buyerComment: 'give me a 10% discount' } + const before: DeepPartial = { buyerComment: '' } + const now: DeepPartial = { buyerComment: 'give me a 10% discount' } const actual = quotesSync.buildActions(now, before) const expected = [ { @@ -66,13 +70,13 @@ describe('Actions', () => { }) test('should build `transitionState` action', () => { - const before = { + const before: DeepPartial = { state: { typeId: 'state', id: 'sid1', }, } - const now = { + const now: DeepPartial = { state: { typeId: 'state', id: 'sid2', @@ -89,7 +93,7 @@ describe('Actions', () => { }) test('should build `setCustomType` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -100,7 +104,7 @@ describe('Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', @@ -117,7 +121,7 @@ describe('Actions', () => { }) test('should build `setCustomField` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -128,7 +132,7 @@ describe('Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', diff --git a/packages/sync-actions/test/shipping-methods.spec.ts b/packages/sync-actions/test/shipping-methods.spec.ts index ca62ed67e..626157a4a 100644 --- a/packages/sync-actions/test/shipping-methods.spec.ts +++ b/packages/sync-actions/test/shipping-methods.spec.ts @@ -1,7 +1,10 @@ import shippingMethodsSyncFn, { actionGroups } from '../src/shipping-methods' import { baseActionsList } from '../src/shipping-methods-actions' -import { SyncAction } from '../src/types/update-actions' -import { ShippingMethodUpdateAction } from '@commercetools/platform-sdk/src' +import { DeepPartial, SyncAction } from '../src/types/update-actions' +import { + ShippingMethodDraft, + ShippingMethodUpdateAction, +} from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -23,7 +26,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let shippingMethodsSync: SyncAction + let shippingMethodsSync = shippingMethodsSyncFn() beforeEach(() => { shippingMethodsSync = shippingMethodsSyncFn() }) @@ -163,7 +166,7 @@ describe('Actions', () => { }) test('should build `setPredicate` action', () => { - const before = { + const before: Partial = { predicate: 'id is defined', } const now = { @@ -181,8 +184,12 @@ describe('Actions', () => { }) test('should build `changeTaxCategory` action', () => { - const before = { taxCategory: { typeId: 'taxCategory', id: 'id1' } } - const now = { taxCategory: { typeId: 'taxCategory', id: 'id2' } } + const before: Partial = { + taxCategory: { typeId: 'tax-category', id: 'id1' }, + } + const now: Partial = { + taxCategory: { typeId: 'tax-category', id: 'id2' }, + } const actual = shippingMethodsSync.buildActions(now, before) const expected = [ @@ -194,10 +201,10 @@ describe('Actions', () => { describe('`addZone`', () => { test('should build `addZone` action with one zone', () => { - const before = { + const before: DeepPartial = { zoneRates: [{ zone: { typeId: 'zone', id: 'z1' } }], } - const now = { + const now: DeepPartial = { zoneRates: [ { zone: { typeId: 'zone', id: 'z1' } }, { zone: { typeId: 'zone', id: 'z2' } }, @@ -210,10 +217,10 @@ describe('Actions', () => { }) test('should build `addZone` action with multiple zones', () => { - const before = { + const before: DeepPartial = { zoneRates: [{ zone: { typeId: 'zone', id: 'z1' } }], } - const now = { + const now: DeepPartial = { zoneRates: [ { zone: { typeId: 'zone', id: 'z1' } }, { zone: { typeId: 'zone', id: 'z3' } }, @@ -234,13 +241,13 @@ describe('Actions', () => { describe('`removeZone`', () => { test('should build `removeZone` removing the last zone item', () => { - const before = { + const before: DeepPartial = { zoneRates: [ { zone: { typeId: 'zone', id: 'z1' } }, { zone: { typeId: 'zone', id: 'z2' } }, ], } - const now = { + const now: DeepPartial = { zoneRates: [{ zone: { typeId: 'zone', id: 'z1' } }], } @@ -252,14 +259,14 @@ describe('Actions', () => { }) test('should build `removeZone` removing all existing zones', () => { - const before = { + const before: DeepPartial = { zoneRates: [ { zone: { typeId: 'zone', id: 'z1' } }, { zone: { typeId: 'zone', id: 'z2' } }, { zone: { typeId: 'zone', id: 'z3' } }, ], } - const now = { + const now: DeepPartial = { zoneRates: [], } @@ -275,7 +282,7 @@ describe('Actions', () => { describe('`addShippingRate`', () => { test('should build `addShippingRate` action with one shipping rate', () => { - const before = { + const before: DeepPartial = { zoneRates: [ { zone: { typeId: 'zone', id: 'z1' }, @@ -283,7 +290,7 @@ describe('Actions', () => { }, ], } - const now = { + const now: DeepPartial = { zoneRates: [ { zone: { typeId: 'zone', id: 'z1' }, @@ -306,10 +313,10 @@ describe('Actions', () => { }) test('should build `addShippingRate` action with multiple shipping rate', () => { - const before = { + const before: DeepPartial = { zoneRates: [{ zone: { typeId: 'zone', id: 'z1' }, shippingRates: [] }], } - const now = { + const now: DeepPartial = { zoneRates: [ { zone: { typeId: 'zone', id: 'z1' }, @@ -341,7 +348,7 @@ describe('Actions', () => { describe('`removeShippingRate`', () => { test('should build `removeShippingRate` removing one shippingRate', () => { - const before = { + const before: DeepPartial = { zoneRates: [ { zone: { typeId: 'zone', id: 'z1' }, @@ -352,7 +359,7 @@ describe('Actions', () => { }, ], } - const now = { + const now: DeepPartial = { zoneRates: [ { zone: { typeId: 'zone', id: 'z1' }, @@ -375,7 +382,7 @@ describe('Actions', () => { }) test('should build `removeShippingRate` removing all existing zones', () => { - const before = { + const before: DeepPartial = { zoneRates: [ { zone: { typeId: 'zone', id: 'z1' }, @@ -386,7 +393,7 @@ describe('Actions', () => { }, ], } - const now = { + const now: DeepPartial = { zoneRates: [ { zone: { typeId: 'zone', id: 'z1' }, @@ -414,14 +421,14 @@ describe('Actions', () => { describe('Swap zones (create one + delete one)', () => { test('should build `removeZone` and `addZone` when swaping zones', () => { - const before = { + const before: DeepPartial = { zoneRates: [ { zone: { typeId: 'zone', id: 'z1' } }, { zone: { typeId: 'zone', id: 'z2' } }, { zone: { typeId: 'zone', id: 'z3' } }, ], } - const now = { + const now: DeepPartial = { zoneRates: [ { zone: { typeId: 'zone', id: 'z4' } }, { zone: { typeId: 'zone', id: 'z5' } }, @@ -444,7 +451,7 @@ describe('Actions', () => { describe('Swap shippingRates (create one + delete one)', () => { test('should build `removeShippingRate` and `addShippingRate` when swaping zones', () => { - const before = { + const before: DeepPartial = { zoneRates: [ { zone: { typeId: 'zone', id: 'z1' }, @@ -455,7 +462,7 @@ describe('Actions', () => { }, ], } - const now = { + const now: DeepPartial = { zoneRates: [ { zone: { typeId: 'zone', id: 'z1' }, @@ -486,7 +493,7 @@ describe('Actions', () => { describe('Multiple actions between zones and shippingRates', () => { test('should build different actions for updating zones and shippingRates', () => { - const before = { + const before: DeepPartial = { zoneRates: [ { zone: { typeId: 'zone', id: 'z1' }, @@ -497,7 +504,7 @@ describe('Actions', () => { }, ], } - const now = { + const now: DeepPartial = { zoneRates: [ { zone: { typeId: 'zone', id: 'z1' }, @@ -530,7 +537,7 @@ describe('Actions', () => { describe('When adding a new zoneRate with zone and shippingRates (fixed rates)', () => { it('should build different actions for adding zone and shippingRates', () => { - const before = { + const before: DeepPartial = { zoneRates: [ { zone: { typeId: 'zone', id: 'z1' }, @@ -541,7 +548,7 @@ describe('Actions', () => { }, ], } - const now = { + const now: DeepPartial = { zoneRates: [ { zone: { typeId: 'zone', id: 'z1' }, @@ -551,7 +558,7 @@ describe('Actions', () => { ], }, { - zone: { typeId: 'zone 2', id: 'z2' }, + zone: { typeId: 'zone', id: 'z2' }, shippingRates: [ { price: { currencyCode: 'EUR', centAmount: 1000 } }, { price: { currencyCode: 'USD', centAmount: 1000 } }, @@ -580,7 +587,7 @@ describe('Actions', () => { describe('custom fields', () => { test('should build `setCustomType` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -591,7 +598,7 @@ describe('Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', @@ -608,7 +615,7 @@ describe('Actions', () => { }) test('should build `setCustomField` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -619,7 +626,7 @@ describe('Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', diff --git a/packages/sync-actions/test/staged-quotes-sync.spec.ts b/packages/sync-actions/test/staged-quotes-sync.spec.ts index c873f5df5..d8fcc24d1 100644 --- a/packages/sync-actions/test/staged-quotes-sync.spec.ts +++ b/packages/sync-actions/test/staged-quotes-sync.spec.ts @@ -1,6 +1,9 @@ -import createStagedQuotesSync, { actionGroups } from '../src/staged-quotes' +import createStagedQuotesSync, { + actionGroups, + StagedQuoteSync, +} from '../src/staged-quotes' import { baseActionsList } from '../src/staged-quotes-actions' -import { SyncAction } from '../src/types/update-actions' +import { DeepPartial, SyncAction } from '../src/types/update-actions' import { StagedQuoteUpdateAction } from '@commercetools/platform-sdk/src' describe('Exports', () => { @@ -40,7 +43,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let stagedQuotesSync: SyncAction + let stagedQuotesSync = createStagedQuotesSync() beforeEach(() => { stagedQuotesSync = createStagedQuotesSync() }) @@ -87,13 +90,13 @@ describe('Actions', () => { }) test('should build `transitionState` action', () => { - const before = { + const before: DeepPartial = { state: { typeId: 'state', id: 'sid1', }, } - const now = { + const now: DeepPartial = { state: { typeId: 'state', id: 'sid2', @@ -110,7 +113,7 @@ describe('Actions', () => { }) test('should build `setCustomType` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -121,7 +124,7 @@ describe('Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', @@ -138,7 +141,7 @@ describe('Actions', () => { }) test('should build `setCustomField` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -149,7 +152,7 @@ describe('Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', diff --git a/packages/sync-actions/test/states-sync.spec.ts b/packages/sync-actions/test/states-sync.spec.ts index 046052865..ae9469c61 100644 --- a/packages/sync-actions/test/states-sync.spec.ts +++ b/packages/sync-actions/test/states-sync.spec.ts @@ -1,7 +1,11 @@ import statesSyncFn, { actionGroups } from '../src/states' import { baseActionsList } from '../src/state-actions' -import { SyncAction } from '../src/types/update-actions' -import { StateUpdateAction } from '@commercetools/platform-sdk/src' +import { DeepPartial, SyncAction } from '../src/types/update-actions' +import { + StateDraft, + StateUpdateAction, + ZoneDraft, +} from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -68,7 +72,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let statesSync: SyncAction + let statesSync = statesSyncFn() beforeEach(() => { statesSync = statesSyncFn() }) @@ -149,7 +153,7 @@ describe('Actions', () => { }) test('should build `setTransitions` action', () => { - const before = { + const before: DeepPartial = { key: 'state-1', transitions: [ { @@ -162,7 +166,7 @@ describe('Actions', () => { }, ], } - const now = { + const now: DeepPartial = { key: 'state-1', transitions: [ { diff --git a/packages/sync-actions/test/stores-sync.spec.ts b/packages/sync-actions/test/stores-sync.spec.ts index a9ac3ed0c..b7df26d81 100644 --- a/packages/sync-actions/test/stores-sync.spec.ts +++ b/packages/sync-actions/test/stores-sync.spec.ts @@ -1,7 +1,7 @@ import storesSyncFn, { actionGroups } from '../src/stores' import { baseActionsList } from '../src/stores-actions' -import { SyncAction } from '../src/types/update-actions' -import { StoreUpdateAction } from '@commercetools/platform-sdk/src' +import { DeepPartial, SyncAction } from '../src/types/update-actions' +import { Store, StoreUpdateAction } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -19,7 +19,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let storesSync: SyncAction + let storesSync = storesSyncFn() beforeEach(() => { storesSync = storesSyncFn() }) @@ -51,7 +51,7 @@ describe('Actions', () => { }) test('should build `setDistributionsChannels` action', () => { - const before = { + const before: DeepPartial = { distributionChannels: [ { typeId: 'channel', @@ -59,7 +59,7 @@ describe('Actions', () => { }, ], } - const now = { + const now: DeepPartial = { distributionChannels: [ { typeId: 'channel', @@ -67,7 +67,7 @@ describe('Actions', () => { }, { typeId: 'channel', - key: 'pd-002', + id: 'pd-002', }, ], } @@ -81,7 +81,7 @@ describe('Actions', () => { ]) }) test('should build `setSupplyChannels` action', () => { - const before = { + const before: DeepPartial = { supplyChannels: [ { typeId: 'channel', @@ -89,7 +89,7 @@ describe('Actions', () => { }, ], } - const now = { + const now: DeepPartial = { supplyChannels: [ { typeId: 'channel', @@ -97,7 +97,7 @@ describe('Actions', () => { }, { typeId: 'channel', - key: 'inventory-supply-002', + id: 'inventory-supply-002', }, ], } @@ -113,7 +113,7 @@ describe('Actions', () => { describe('custom fields', () => { test('should build `setCustomType` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -124,7 +124,7 @@ describe('Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', @@ -142,7 +142,7 @@ describe('Actions', () => { }) test('should build `setCustomField` action', () => { - const before = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -153,7 +153,7 @@ describe('Actions', () => { }, }, } - const now = { + const now: DeepPartial = { custom: { type: { typeId: 'type', diff --git a/packages/sync-actions/test/tax-categories-sync.spec.ts b/packages/sync-actions/test/tax-categories-sync.spec.ts index 10facd935..745019583 100644 --- a/packages/sync-actions/test/tax-categories-sync.spec.ts +++ b/packages/sync-actions/test/tax-categories-sync.spec.ts @@ -1,7 +1,10 @@ import taxCategorySyncFn, { actionGroups } from '../src/tax-categories' import { baseActionsList } from '../src/tax-categories-actions' -import { SyncAction } from '../src/types/update-actions' -import { TaxCategoryUpdateAction } from '@commercetools/platform-sdk/src' +import { DeepPartial, SyncAction } from '../src/types/update-actions' +import { + TaxCategory, + TaxCategoryUpdateAction, +} from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -18,7 +21,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let taxCategorySync: SyncAction + let taxCategorySync = taxCategorySyncFn() beforeEach(() => { taxCategorySync = taxCategorySyncFn() }) @@ -55,9 +58,9 @@ describe('Actions', () => { }) test('should build `addTaxRate` action', () => { - const before = { addresses: [] } - const now = { - rates: [{ name: '5% US', amount: '0.05' }], + const before: DeepPartial = {} + const now: DeepPartial = { + rates: [{ name: '5% US', amount: 5 }], } const actual = taxCategorySync.buildActions(now, before) @@ -66,21 +69,21 @@ describe('Actions', () => { }) test('should build `replaceTaxRate` action', () => { - const before = { + const before: DeepPartial = { rates: [ { id: 'taxRate-1', name: '5% US', - amount: '0.05', + amount: 5, }, ], } - const now = { + const now: DeepPartial = { rates: [ { id: 'taxRate-1', name: '11% US', - amount: '0.11', + amount: 11, }, ], } @@ -113,31 +116,31 @@ describe('Actions', () => { }) test('should build complex mixed actions (1)', () => { - const before = { + const before: DeepPartial = { rates: [ { id: 'taxRate-1', name: '11% US', - amount: '0.11', + amount: 11, }, { id: 'taxRate-2', name: '8% DE', - amount: '0.08', + amount: 8, }, { id: 'taxRate-3', name: '21% ES', - amount: '0.21', + amount: 21, }, ], } - const now = { + const now: DeepPartial = { rates: [ { id: 'taxRate-1', name: '11% US', - amount: '0.11', + amount: 11, country: 'US', }, // REMOVED RATE 2 @@ -145,13 +148,13 @@ describe('Actions', () => { // UNCHANGED RATE 3 id: 'taxRate-3', name: '21% ES', - amount: '0.21', + amount: 21, }, { // ADD NEW RATE id: 'taxRate-4', name: '15% FR', - amount: '0.15', + amount: 15, }, ], } @@ -161,7 +164,7 @@ describe('Actions', () => { { action: 'replaceTaxRate', taxRate: { - amount: '0.11', + amount: 11, country: 'US', // added country to an existing rate id: 'taxRate-1', name: '11% US', @@ -171,7 +174,7 @@ describe('Actions', () => { { action: 'removeTaxRate', taxRateId: 'taxRate-2' }, // removed second tax rate { action: 'addTaxRate', - taxRate: { amount: '0.15', id: 'taxRate-4', name: '15% FR' }, // adds new tax rate + taxRate: { amount: 15, id: 'taxRate-4', name: '15% FR' }, // adds new tax rate }, ] expect(actual).toEqual(expected) @@ -183,17 +186,17 @@ describe('Actions', () => { { id: 'taxRate-1', name: '11% US', - amount: '0.11', + amount: 11, }, { id: 'taxRate-2', name: '8% DE', - amount: '0.08', + amount: 8, }, { id: 'taxRate-3', name: '21% ES', - amount: '0.21', + amount: 21, }, ], } @@ -206,13 +209,13 @@ describe('Actions', () => { id: 'taxRate-3', name: '21% ES', state: 'NY', - amount: '0.21', + amount: 21, }, { // ADD NEW RATE id: 'taxRate-4', name: '15% FR', - amount: '0.15', + amount: 15, }, ], } @@ -222,7 +225,7 @@ describe('Actions', () => { { action: 'replaceTaxRate', taxRate: { - amount: '0.21', + amount: 21, id: 'taxRate-3', name: '21% ES', state: 'NY', @@ -233,7 +236,7 @@ describe('Actions', () => { { action: 'removeTaxRate', taxRateId: 'taxRate-2' }, // removed second tax rate { action: 'addTaxRate', - taxRate: { amount: '0.15', id: 'taxRate-4', name: '15% FR' }, // adds new tax rate + taxRate: { amount: 15, id: 'taxRate-4', name: '15% FR' }, // adds new tax rate }, ] diff --git a/packages/sync-actions/test/types-sync-base.spec.ts b/packages/sync-actions/test/types-sync-base.spec.ts index 59c797618..6c0dc61ca 100644 --- a/packages/sync-actions/test/types-sync-base.spec.ts +++ b/packages/sync-actions/test/types-sync-base.spec.ts @@ -3,6 +3,7 @@ import createSyncTypes, { actionGroups } from '../src/types' import { baseActionsList } from '../src/types-actions' import { SyncAction } from '../src/types/update-actions' import { TypeUpdateAction } from '@commercetools/platform-sdk/src' +import typesSyncFn from '../src/types' describe('Exports', () => { test('action group list', () => { @@ -19,7 +20,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let typesSync: SyncAction + let typesSync = typesSyncFn() let updateActions: Array let before let now diff --git a/packages/sync-actions/test/types-sync-enums.spec.ts b/packages/sync-actions/test/types-sync-enums.spec.ts index 980388755..2ef4a8718 100644 --- a/packages/sync-actions/test/types-sync-enums.spec.ts +++ b/packages/sync-actions/test/types-sync-enums.spec.ts @@ -11,7 +11,7 @@ const createTestType = (custom) => ({ describe('Actions', () => { let before let now - let typesSync: SyncAction + let typesSync = typesSyncFn() let updateActions: Array beforeEach(() => { typesSync = typesSyncFn() diff --git a/packages/sync-actions/test/types-sync-fields.spec.ts b/packages/sync-actions/test/types-sync-fields.spec.ts index 89de63ea2..b0cffc5db 100644 --- a/packages/sync-actions/test/types-sync-fields.spec.ts +++ b/packages/sync-actions/test/types-sync-fields.spec.ts @@ -9,7 +9,7 @@ const createTestType = (custom) => ({ }) describe('Actions', () => { - let typesSync: SyncAction + let typesSync = typesSyncFn() let updateActions: Array let before let now diff --git a/packages/sync-actions/test/zones.spec.ts b/packages/sync-actions/test/zones.spec.ts index b407fdc29..287dbebdf 100644 --- a/packages/sync-actions/test/zones.spec.ts +++ b/packages/sync-actions/test/zones.spec.ts @@ -1,7 +1,5 @@ import zonesSyncFn, { actionGroups } from '../src/zones' import { baseActionsList } from '../src/zones-actions' -import { SyncAction } from '../src/types/update-actions' -import { ZoneUpdateAction } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -18,7 +16,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let zonesSync: SyncAction + let zonesSync = zonesSyncFn() beforeEach(() => { zonesSync = zonesSyncFn() }) From a9c8834796d1cdb895b13189a0c68f1c892c16e4 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Wed, 8 Nov 2023 18:08:57 +0100 Subject: [PATCH 19/33] feat(migrate): imports --- packages/sync-actions/src/product-actions.ts | 1 + packages/sync-actions/src/products.ts | 1 - packages/sync-actions/src/projects.ts | 7 +++++-- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/sync-actions/src/product-actions.ts b/packages/sync-actions/src/product-actions.ts index 4a1ea6b65..caacd7b80 100644 --- a/packages/sync-actions/src/product-actions.ts +++ b/packages/sync-actions/src/product-actions.ts @@ -433,6 +433,7 @@ function _buildVariantChangeAssetOrderAction( } return [changeAssetOrderAction] } + function _buildVariantAssetsActions(diffAssets, oldVariant, newVariant) { const assetActions = [] diff --git a/packages/sync-actions/src/products.ts b/packages/sync-actions/src/products.ts index 8f3271a9e..f226b1c93 100644 --- a/packages/sync-actions/src/products.ts +++ b/packages/sync-actions/src/products.ts @@ -25,7 +25,6 @@ import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' import findMatchingPairs from './utils/find-matching-pairs' -import exp from 'constants' const actionGroups = [ 'base', diff --git a/packages/sync-actions/src/projects.ts b/packages/sync-actions/src/projects.ts index 6d9fdb6c1..334f4d97e 100644 --- a/packages/sync-actions/src/projects.ts +++ b/packages/sync-actions/src/projects.ts @@ -1,11 +1,14 @@ -import { Project, ProjectUpdateAction } from '@commercetools/platform-sdk' +import { + MessagesConfigurationDraft, + Project, + ProjectUpdateAction, +} from '@commercetools/platform-sdk' import { ActionGroup, SyncActionConfig } from '@commercetools/sdk-client-v2' import { actionsMapBase } from './projects-actions' import { SyncAction } from './types/update-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' -import { MessagesConfigurationDraft } from '@commercetools/platform-sdk' export const actionGroups = ['base'] From 1c1f7be4ba6043b467956a0492fb0699dd90a9b4 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Wed, 8 Nov 2023 19:02:48 +0100 Subject: [PATCH 20/33] feat(migrate): imports --- .../test/attribute-groups-sync.spec.ts | 2 -- .../test/cart-discounts-sync.spec.ts | 7 ++---- .../sync-actions/test/category-sync.spec.ts | 8 ++----- .../sync-actions/test/channels-sync-.spec.ts | 8 ++----- .../test/customer-group-sync.spec.ts | 3 +-- .../sync-actions/test/inventory-sync.spec.ts | 6 +---- packages/sync-actions/test/order-sync.spec.ts | 22 ++++++++----------- .../test/product-selections-sync.spec.ts | 7 ++---- .../test/product-sync-base.spec.ts | 8 ++----- .../test/product-sync-images.spec.ts | 2 +- .../test/product-sync-variants.spec.ts | 2 +- .../test/product-types-sync-base.spec.ts | 7 ++---- .../test/quote-requests-sync.spec.ts | 7 ++---- .../sync-actions/test/quotes-sync.spec.ts | 8 ++----- .../test/shipping-methods.spec.ts | 7 ++---- .../test/staged-quotes-sync.spec.ts | 3 +-- .../sync-actions/test/states-sync.spec.ts | 10 +++------ .../sync-actions/test/stores-sync.spec.ts | 4 ++-- .../test/tax-categories-sync.spec.ts | 7 ++---- .../sync-actions/test/types-sync-base.spec.ts | 1 - .../test/types-sync-enums.spec.ts | 1 - .../test/types-sync-fields.spec.ts | 3 +-- 22 files changed, 40 insertions(+), 93 deletions(-) diff --git a/packages/sync-actions/test/attribute-groups-sync.spec.ts b/packages/sync-actions/test/attribute-groups-sync.spec.ts index b267766dd..b08b7f732 100644 --- a/packages/sync-actions/test/attribute-groups-sync.spec.ts +++ b/packages/sync-actions/test/attribute-groups-sync.spec.ts @@ -1,7 +1,5 @@ import attributeGroupSyncFn from '../src/attribute-groups' import { baseActionsList } from '../src/attribute-groups-actions' -import { AttributeGroupUpdateAction } from '@commercetools/platform-sdk/src' -import { SyncAction } from '../src/types/update-actions' describe('Exports', () => { test('correctly define base actions list', () => { diff --git a/packages/sync-actions/test/cart-discounts-sync.spec.ts b/packages/sync-actions/test/cart-discounts-sync.spec.ts index d73d6a3e1..be5eef2de 100644 --- a/packages/sync-actions/test/cart-discounts-sync.spec.ts +++ b/packages/sync-actions/test/cart-discounts-sync.spec.ts @@ -1,10 +1,7 @@ import cartDiscountsSyncFn, { actionGroups } from '../src/cart-discounts' import { baseActionsList } from '../src/cart-discounts-actions' -import { DeepPartial, SyncAction } from '../src/types/update-actions' -import { - CartDiscountDraft, - CartDiscountUpdateAction, -} from '@commercetools/platform-sdk/src' +import { DeepPartial } from '../src/types/update-actions' +import { CartDiscountDraft } from '@commercetools/platform-sdk/src' describe('Cart Discounts Exports', () => { test('action group list', () => { diff --git a/packages/sync-actions/test/category-sync.spec.ts b/packages/sync-actions/test/category-sync.spec.ts index f06ce14ab..e408be32d 100644 --- a/packages/sync-actions/test/category-sync.spec.ts +++ b/packages/sync-actions/test/category-sync.spec.ts @@ -1,15 +1,11 @@ import categorySyncFn, { actionGroups } from '../src/categories' -import { DeepPartial, SyncAction } from '../src/types/update-actions' +import { DeepPartial } from '../src/types/update-actions' import { baseActionsList, metaActionsList, referenceActionsList, } from '../src/category-actions' -import { - CartDiscountDraft, - CategoryDraft, - CategoryUpdateAction, -} from '@commercetools/platform-sdk/src' +import { CategoryDraft } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { diff --git a/packages/sync-actions/test/channels-sync-.spec.ts b/packages/sync-actions/test/channels-sync-.spec.ts index 8e41a37df..b0413e36b 100644 --- a/packages/sync-actions/test/channels-sync-.spec.ts +++ b/packages/sync-actions/test/channels-sync-.spec.ts @@ -1,11 +1,7 @@ import createChannelsSync, { actionGroups } from '../src/channels' import { baseActionsList } from '../src/channels-actions' -import { DeepPartial, SyncAction } from '../src/types/update-actions' -import { - CategoryDraft, - ChannelDraft, - ChannelUpdateAction, -} from '@commercetools/platform-sdk/src' +import { DeepPartial } from '../src/types/update-actions' +import { ChannelDraft } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { diff --git a/packages/sync-actions/test/customer-group-sync.spec.ts b/packages/sync-actions/test/customer-group-sync.spec.ts index af110661a..6aeb75d83 100644 --- a/packages/sync-actions/test/customer-group-sync.spec.ts +++ b/packages/sync-actions/test/customer-group-sync.spec.ts @@ -1,10 +1,9 @@ import customerGroupSyncFn, { actionGroups } from '../src/customer-group' import { baseActionsList } from '../src/customer-group-actions' -import { DeepPartial, SyncAction } from '../src/types/update-actions' +import { DeepPartial } from '../src/types/update-actions' import { CustomerGroup, CustomerGroupDraft, - CustomerGroupUpdateAction, } from '@commercetools/platform-sdk/src' describe('Customer Groups Exports', () => { diff --git a/packages/sync-actions/test/inventory-sync.spec.ts b/packages/sync-actions/test/inventory-sync.spec.ts index 566f05916..5f77d6830 100644 --- a/packages/sync-actions/test/inventory-sync.spec.ts +++ b/packages/sync-actions/test/inventory-sync.spec.ts @@ -1,10 +1,6 @@ import inventorySyncFn, { actionGroups } from '../src/inventories' import { baseActionsList, referenceActionsList } from '../src/inventory-actions' -import { SyncAction } from '../src/types/update-actions' -import { - InventoryEntryDraft, - InventoryEntryUpdateAction, -} from '@commercetools/platform-sdk/src' +import { InventoryEntryDraft } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { diff --git a/packages/sync-actions/test/order-sync.spec.ts b/packages/sync-actions/test/order-sync.spec.ts index 8365e5662..c0a09bb06 100644 --- a/packages/sync-actions/test/order-sync.spec.ts +++ b/packages/sync-actions/test/order-sync.spec.ts @@ -1,11 +1,7 @@ import { performance } from 'perf_hooks' import orderSyncFn, { actionGroups, OrderSync } from '../src/orders' import { baseActionsList } from '../src/order-actions' -import { DeepPartial, SyncAction } from '../src/types/update-actions' -import { - OrderEditDraft, - OrderUpdateAction, -} from '@commercetools/platform-sdk/src' +import { DeepPartial } from '../src/types/update-actions' describe('Exports', () => { test('action group list', () => { @@ -194,11 +190,11 @@ describe('Actions', () => { shippingInfo: { deliveries: Array(100) .fill(null) - .map((a, index) => ({ + .map((_a, index) => ({ parcels: [], items: Array(50) .fill(null) - .map((b, index2) => { + .map((_b, index2) => { return { id: `id-${index}-${index2}`, qty: 1, @@ -211,11 +207,11 @@ describe('Actions', () => { shippingInfo: { deliveries: Array(100) .fill(null) - .map((a, index) => ({ + .map((_a, index) => ({ parcels: [], items: Array(50) .fill(null) - .map((b, index2) => { + .map((_b, index2) => { return { id: `id-${index}-${index2}`, qty: 2, @@ -804,10 +800,10 @@ describe('Actions', () => { const before = { returnInfo: Array(100) .fill(null) - .map((a, index) => ({ + .map((_a, index) => ({ items: Array(50) .fill(null) - .map((b, index2) => { + .map((_b, index2) => { return { id: `id-${index}-${index2}`, shipmentState: 'Returned', @@ -819,10 +815,10 @@ describe('Actions', () => { const now = { returnInfo: Array(100) .fill(null) - .map((a, index) => ({ + .map((_a, index) => ({ items: Array(50) .fill(null) - .map((b, index2) => { + .map((_b, index2) => { return { id: `id-${index}-${index2}`, shipmentState: 'Returned', diff --git a/packages/sync-actions/test/product-selections-sync.spec.ts b/packages/sync-actions/test/product-selections-sync.spec.ts index 5928b3ca3..0b2045055 100644 --- a/packages/sync-actions/test/product-selections-sync.spec.ts +++ b/packages/sync-actions/test/product-selections-sync.spec.ts @@ -2,11 +2,8 @@ import { baseActionsList } from '../src/product-selections-actions' import productSelectionsSyncFn, { actionGroups, } from '../src/product-selections' -import { DeepPartial, SyncAction } from '../src/types/update-actions' -import { - ProductSelectionDraft, - ProductSelectionUpdateAction, -} from '@commercetools/platform-sdk/src' +import { DeepPartial } from '../src/types/update-actions' +import { ProductSelectionDraft } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { diff --git a/packages/sync-actions/test/product-sync-base.spec.ts b/packages/sync-actions/test/product-sync-base.spec.ts index 8ad55582a..7f8b5ba22 100644 --- a/packages/sync-actions/test/product-sync-base.spec.ts +++ b/packages/sync-actions/test/product-sync-base.spec.ts @@ -5,12 +5,8 @@ import { metaActionsList, referenceActionsList, } from '../src/product-actions' -import { DeepPartial, SyncAction } from '../src/types/update-actions' -import { - ProductData, - ProductDraft, - ProductUpdateAction, -} from '@commercetools/platform-sdk/src' +import { DeepPartial } from '../src/types/update-actions' +import { ProductDraft } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { diff --git a/packages/sync-actions/test/product-sync-images.spec.ts b/packages/sync-actions/test/product-sync-images.spec.ts index 17c0f4a62..36b309286 100644 --- a/packages/sync-actions/test/product-sync-images.spec.ts +++ b/packages/sync-actions/test/product-sync-images.spec.ts @@ -1,4 +1,4 @@ -import { DeepPartial, SyncAction } from '../src/types/update-actions' +import { DeepPartial } from '../src/types/update-actions' import productsSyncFn, { ProductSync } from '../src/products' /* eslint-disable max-len */ diff --git a/packages/sync-actions/test/product-sync-variants.spec.ts b/packages/sync-actions/test/product-sync-variants.spec.ts index 4d63a82cf..ab2983df5 100644 --- a/packages/sync-actions/test/product-sync-variants.spec.ts +++ b/packages/sync-actions/test/product-sync-variants.spec.ts @@ -1,4 +1,4 @@ -import { DeepPartial, SyncAction } from '../src/types/update-actions' +import { DeepPartial } from '../src/types/update-actions' import productsSyncFn, { ProductSync } from '../src/products' import { Asset } from '@commercetools/platform-sdk/src' diff --git a/packages/sync-actions/test/product-types-sync-base.spec.ts b/packages/sync-actions/test/product-types-sync-base.spec.ts index ec069243e..2209578c4 100644 --- a/packages/sync-actions/test/product-types-sync-base.spec.ts +++ b/packages/sync-actions/test/product-types-sync-base.spec.ts @@ -1,13 +1,10 @@ import clone from '../src/utils/clone' -import createSyncProductTypes, { - actionGroups, - ProductTypeConfig, -} from '../src/product-types' +import createSyncProductTypes, { actionGroups } from '../src/product-types' import { baseActionsList, generateBaseFieldsUpdateActions, } from '../src/product-types-actions' -import { DeepPartial, SyncAction } from '../src/types/update-actions' +import { DeepPartial } from '../src/types/update-actions' import { ProductTypeDraft, ProductTypeUpdateAction, diff --git a/packages/sync-actions/test/quote-requests-sync.spec.ts b/packages/sync-actions/test/quote-requests-sync.spec.ts index 4ed45ce63..c434a870f 100644 --- a/packages/sync-actions/test/quote-requests-sync.spec.ts +++ b/packages/sync-actions/test/quote-requests-sync.spec.ts @@ -1,10 +1,7 @@ import createQuoteRequestsSync, { actionGroups } from '../src/quote-requests' import { baseActionsList } from '../src/quote-requests-actions' -import { DeepPartial, SyncAction } from '../src/types/update-actions' -import { - QuoteRequest, - QuoteRequestUpdateAction, -} from '@commercetools/platform-sdk/src' +import { DeepPartial } from '../src/types/update-actions' +import { QuoteRequest } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { diff --git a/packages/sync-actions/test/quotes-sync.spec.ts b/packages/sync-actions/test/quotes-sync.spec.ts index 2253e22ef..ae0dcc068 100644 --- a/packages/sync-actions/test/quotes-sync.spec.ts +++ b/packages/sync-actions/test/quotes-sync.spec.ts @@ -1,11 +1,7 @@ import createQuotesSync, { actionGroups } from '../src/quotes' import { baseActionsList } from '../src/quotes-actions' -import { DeepPartial, SyncAction } from '../src/types/update-actions' -import { - Quote, - QuoteDraft, - QuoteUpdateAction, -} from '@commercetools/platform-sdk/src' +import { DeepPartial } from '../src/types/update-actions' +import { Quote } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { diff --git a/packages/sync-actions/test/shipping-methods.spec.ts b/packages/sync-actions/test/shipping-methods.spec.ts index 626157a4a..f8d32beb6 100644 --- a/packages/sync-actions/test/shipping-methods.spec.ts +++ b/packages/sync-actions/test/shipping-methods.spec.ts @@ -1,10 +1,7 @@ import shippingMethodsSyncFn, { actionGroups } from '../src/shipping-methods' import { baseActionsList } from '../src/shipping-methods-actions' -import { DeepPartial, SyncAction } from '../src/types/update-actions' -import { - ShippingMethodDraft, - ShippingMethodUpdateAction, -} from '@commercetools/platform-sdk/src' +import { DeepPartial } from '../src/types/update-actions' +import { ShippingMethodDraft } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { diff --git a/packages/sync-actions/test/staged-quotes-sync.spec.ts b/packages/sync-actions/test/staged-quotes-sync.spec.ts index d8fcc24d1..64c162560 100644 --- a/packages/sync-actions/test/staged-quotes-sync.spec.ts +++ b/packages/sync-actions/test/staged-quotes-sync.spec.ts @@ -3,8 +3,7 @@ import createStagedQuotesSync, { StagedQuoteSync, } from '../src/staged-quotes' import { baseActionsList } from '../src/staged-quotes-actions' -import { DeepPartial, SyncAction } from '../src/types/update-actions' -import { StagedQuoteUpdateAction } from '@commercetools/platform-sdk/src' +import { DeepPartial } from '../src/types/update-actions' describe('Exports', () => { test('action group list', () => { diff --git a/packages/sync-actions/test/states-sync.spec.ts b/packages/sync-actions/test/states-sync.spec.ts index ae9469c61..552bfd911 100644 --- a/packages/sync-actions/test/states-sync.spec.ts +++ b/packages/sync-actions/test/states-sync.spec.ts @@ -1,11 +1,7 @@ import statesSyncFn, { actionGroups } from '../src/states' import { baseActionsList } from '../src/state-actions' -import { DeepPartial, SyncAction } from '../src/types/update-actions' -import { - StateDraft, - StateUpdateAction, - ZoneDraft, -} from '@commercetools/platform-sdk/src' +import { DeepPartial } from '../src/types/update-actions' +import { StateDraft } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { @@ -238,7 +234,7 @@ describe('Actions', () => { test('should build the `removeRoles` and `addRoles` actions', () => { // This is necessary because there is currently no way to differentiate - // between `setRoles` action and `addRoles || removeRoles` actions so we + // between `setRoles` action and `addRoles || removeRoles` actions, so we // simply replace the roles that need to be replaced with add and remove const before = { key: 'state-1', diff --git a/packages/sync-actions/test/stores-sync.spec.ts b/packages/sync-actions/test/stores-sync.spec.ts index b7df26d81..1fd391e4c 100644 --- a/packages/sync-actions/test/stores-sync.spec.ts +++ b/packages/sync-actions/test/stores-sync.spec.ts @@ -1,7 +1,7 @@ import storesSyncFn, { actionGroups } from '../src/stores' import { baseActionsList } from '../src/stores-actions' -import { DeepPartial, SyncAction } from '../src/types/update-actions' -import { Store, StoreUpdateAction } from '@commercetools/platform-sdk/src' +import { DeepPartial } from '../src/types/update-actions' +import { Store } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { diff --git a/packages/sync-actions/test/tax-categories-sync.spec.ts b/packages/sync-actions/test/tax-categories-sync.spec.ts index 745019583..64ead49f7 100644 --- a/packages/sync-actions/test/tax-categories-sync.spec.ts +++ b/packages/sync-actions/test/tax-categories-sync.spec.ts @@ -1,10 +1,7 @@ import taxCategorySyncFn, { actionGroups } from '../src/tax-categories' import { baseActionsList } from '../src/tax-categories-actions' -import { DeepPartial, SyncAction } from '../src/types/update-actions' -import { - TaxCategory, - TaxCategoryUpdateAction, -} from '@commercetools/platform-sdk/src' +import { DeepPartial } from '../src/types/update-actions' +import { TaxCategory } from '@commercetools/platform-sdk/src' describe('Exports', () => { test('action group list', () => { diff --git a/packages/sync-actions/test/types-sync-base.spec.ts b/packages/sync-actions/test/types-sync-base.spec.ts index 6c0dc61ca..684c1a66d 100644 --- a/packages/sync-actions/test/types-sync-base.spec.ts +++ b/packages/sync-actions/test/types-sync-base.spec.ts @@ -1,7 +1,6 @@ import clone from '../src/utils/clone' import createSyncTypes, { actionGroups } from '../src/types' import { baseActionsList } from '../src/types-actions' -import { SyncAction } from '../src/types/update-actions' import { TypeUpdateAction } from '@commercetools/platform-sdk/src' import typesSyncFn from '../src/types' diff --git a/packages/sync-actions/test/types-sync-enums.spec.ts b/packages/sync-actions/test/types-sync-enums.spec.ts index 2ef4a8718..26a4e7df8 100644 --- a/packages/sync-actions/test/types-sync-enums.spec.ts +++ b/packages/sync-actions/test/types-sync-enums.spec.ts @@ -1,5 +1,4 @@ import typesSyncFn from '../src/types' -import { SyncAction } from '../src/types/update-actions' import { TypeUpdateAction } from '@commercetools/platform-sdk/src' const createTestType = (custom) => ({ diff --git a/packages/sync-actions/test/types-sync-fields.spec.ts b/packages/sync-actions/test/types-sync-fields.spec.ts index b0cffc5db..7b35f0d30 100644 --- a/packages/sync-actions/test/types-sync-fields.spec.ts +++ b/packages/sync-actions/test/types-sync-fields.spec.ts @@ -1,5 +1,4 @@ import typesSyncFn from '../src/types' -import { SyncAction } from '../src/types/update-actions' import { TypeUpdateAction } from '@commercetools/platform-sdk/src' const createTestType = (custom) => ({ @@ -380,7 +379,7 @@ describe('Actions', () => { /** * there is no update action for fieldDefinition -> required, * so this field is immutable and unchangeable. - * in case of changing it, this were throwing `Cannot read properties of undefined` cause its nested field. + * in case of changing it, this is throwing `Cannot read properties of undefined` cause its nested field. * below test is making sure this field is ignored and without any internal package errors. */ describe('should ignore changes in required field in fieldDefinition', () => { From b588f4e146ad43e6957bcc861ebd5e7124926c7e Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Thu, 9 Nov 2023 08:48:28 +0100 Subject: [PATCH 21/33] feat(migrate): adding types to create-map-action-group.ts --- .../src/utils/create-map-action-group.ts | 12 ++++++++---- .../test/utils/create-map-action-group.spec.ts | 15 +++++++++++---- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/packages/sync-actions/src/utils/create-map-action-group.ts b/packages/sync-actions/src/utils/create-map-action-group.ts index f42940091..a4cf8bb24 100644 --- a/packages/sync-actions/src/utils/create-map-action-group.ts +++ b/packages/sync-actions/src/utils/create-map-action-group.ts @@ -5,17 +5,21 @@ // { type: 'prices', group: 'allow' }, // { type: 'variants', group: 'ignore' }, // ] -export default function createMapActionGroup(actionGroups = []) { - return function mapActionGroup(type, fn) { +import { ActionGroup } from '@commercetools/sdk-client-v2' + +export default function createMapActionGroup( + actionGroups: Array = [] +) { + return function mapActionGroup(type: string, fn: () => any) { if (!Object.keys(actionGroups).length) return fn() const found = actionGroups.find((c) => c.type === type) if (!found) return [] // Keep `black` for backwards compatibility. - if (found.group === 'ignore' || found.group === 'black') return [] + if (found.group === 'ignore' || (found as any).group === 'black') return [] // Keep `white` for backwards compatibility. - if (found.group === 'allow' || found.group === 'white') return fn() + if (found.group === 'allow' || (found as any).group === 'white') return fn() throw new Error( `Action group '${found.group}' not supported. Use either "allow" or "ignore".` diff --git a/packages/sync-actions/test/utils/create-map-action-group.spec.ts b/packages/sync-actions/test/utils/create-map-action-group.spec.ts index 5e3de8d77..5beec488b 100644 --- a/packages/sync-actions/test/utils/create-map-action-group.spec.ts +++ b/packages/sync-actions/test/utils/create-map-action-group.spec.ts @@ -1,4 +1,5 @@ import createMapActionGroup from '../../src/utils/create-map-action-group' +import { ActionGroup } from '@commercetools/sdk-client-v2' describe('createMapActionGroup', () => { describe('without actionGroups', () => { @@ -18,7 +19,9 @@ describe('createMapActionGroup', () => { describe('with found `actionGroup` (type)', () => { describe('with `group` being `allow`', () => { const fn = jest.fn() - const actionGroups = [{ type: 'base', group: 'allow' }] + const actionGroups: Array = [ + { type: 'base', group: 'allow' }, + ] let mapActionGroup beforeEach(() => { @@ -33,7 +36,9 @@ describe('createMapActionGroup', () => { describe('with `group` being `ignore`', () => { const fn = jest.fn() - const actionGroups = [{ type: 'base', group: 'ignore' }] + const actionGroups: Array = [ + { type: 'base', group: 'ignore' }, + ] let mapActionGroup beforeEach(() => { @@ -52,7 +57,9 @@ describe('createMapActionGroup', () => { let mapActionGroup beforeEach(() => { - mapActionGroup = createMapActionGroup(actionGroups) + mapActionGroup = createMapActionGroup( + actionGroups as Array + ) }) test('should throw an error', () => { @@ -74,7 +81,7 @@ describe('createMapActionGroup', () => { describe('with non found `actionGroup` (type)', () => { const fn = jest.fn() - const actionGroups = [{ type: 'base', group: 'allow' }] + const actionGroups: Array = [{ type: 'base', group: 'allow' }] let mapActionGroup beforeEach(() => { From afc777487d709a002f1e53c83843e57373bea844 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Thu, 9 Nov 2023 13:51:50 +0100 Subject: [PATCH 22/33] feat(migrate): more types --- packages/sync-actions/src/assets-actions.ts | 41 ---- .../src/attribute-groups-actions.ts | 22 +- packages/sync-actions/src/attribute-groups.ts | 31 ++- .../src/cart-discounts-actions.ts | 13 +- packages/sync-actions/src/cart-discounts.ts | 18 +- packages/sync-actions/src/categories.ts | 45 ++-- packages/sync-actions/src/category-actions.ts | 19 +- .../src/category-assets-actions.ts | 45 ++++ packages/sync-actions/src/channels-actions.ts | 13 +- packages/sync-actions/src/channels.ts | 18 +- packages/sync-actions/src/customer-actions.ts | 57 ++++-- .../src/customer-group-actions.ts | 13 +- packages/sync-actions/src/customer-group.ts | 18 +- packages/sync-actions/src/customers.ts | 62 +++--- .../src/discount-codes-actions.ts | 13 +- packages/sync-actions/src/discount-codes.ts | 18 +- packages/sync-actions/src/inventories.ts | 33 ++- .../sync-actions/src/inventory-actions.ts | 15 +- packages/sync-actions/src/order-actions.ts | 51 +++-- packages/sync-actions/src/orders.ts | 47 ++--- packages/sync-actions/src/prices-actions.ts | 13 +- packages/sync-actions/src/prices.ts | 26 +-- packages/sync-actions/src/product-actions.ts | 192 +++++++++++------- .../src/product-discounts-actions.ts | 13 +- .../sync-actions/src/product-discounts.ts | 18 +- .../src/product-selections-actions.ts | 6 +- .../sync-actions/src/product-selections.ts | 2 +- .../sync-actions/src/product-types-actions.ts | 27 ++- packages/sync-actions/src/product-types.ts | 45 ++-- packages/sync-actions/src/products.ts | 103 ++++------ packages/sync-actions/src/projects-actions.ts | 13 +- packages/sync-actions/src/projects.ts | 18 +- .../src/quote-requests-actions.ts | 13 +- packages/sync-actions/src/quote-requests.ts | 28 +-- packages/sync-actions/src/quotes-actions.ts | 13 +- packages/sync-actions/src/quotes.ts | 28 +-- .../src/shipping-methods-actions.ts | 20 +- packages/sync-actions/src/shipping-methods.ts | 33 ++- .../sync-actions/src/staged-quotes-actions.ts | 13 +- packages/sync-actions/src/staged-quotes.ts | 28 +-- packages/sync-actions/src/state-actions.ts | 15 +- packages/sync-actions/src/states.ts | 43 ++-- packages/sync-actions/src/stores-actions.ts | 6 +- packages/sync-actions/src/stores.ts | 2 +- .../src/tax-categories-actions.ts | 15 +- packages/sync-actions/src/tax-categories.ts | 31 +-- packages/sync-actions/src/types-actions.ts | 47 ++--- packages/sync-actions/src/types.ts | 27 +-- .../src/utils/action-map-custom.ts | 21 +- packages/sync-actions/src/utils/clone.ts | 2 +- .../src/utils/combine-validity-actions.ts | 9 +- .../sync-actions/src/utils/common-actions.ts | 39 ++-- .../src/utils/copy-empty-array-props.ts | 5 +- .../src/utils/create-build-actions.ts | 28 ++- .../src/utils/create-build-array-actions.ts | 52 ++++- .../src/utils/create-map-action-group.ts | 28 ++- .../sync-actions/src/utils/diffpatcher.ts | 8 +- .../src/utils/extract-matching-pairs.ts | 7 +- .../src/utils/find-matching-pairs.ts | 10 +- packages/sync-actions/src/zones-actions.ts | 20 +- packages/sync-actions/src/zones.ts | 32 ++- 61 files changed, 851 insertions(+), 840 deletions(-) delete mode 100644 packages/sync-actions/src/assets-actions.ts create mode 100644 packages/sync-actions/src/category-assets-actions.ts diff --git a/packages/sync-actions/src/assets-actions.ts b/packages/sync-actions/src/assets-actions.ts deleted file mode 100644 index 749a87c9e..000000000 --- a/packages/sync-actions/src/assets-actions.ts +++ /dev/null @@ -1,41 +0,0 @@ -import createBuildArrayActions, { - ADD_ACTIONS, - CHANGE_ACTIONS, - REMOVE_ACTIONS, -} from './utils/create-build-array-actions' - -function toAssetIdentifier(asset) { - const assetIdentifier = asset.id - ? { assetId: asset.id } - : { assetKey: asset.key } - return assetIdentifier -} - -export default function actionsMapAssets(diff, oldObj, newObj) { - const handler = createBuildArrayActions('assets', { - [ADD_ACTIONS]: (newAsset) => ({ - action: 'addAsset', - asset: newAsset, - }), - [REMOVE_ACTIONS]: (oldAsset) => ({ - action: 'removeAsset', - ...toAssetIdentifier(oldAsset), - }), - [CHANGE_ACTIONS]: (oldAsset, newAsset) => - // here we could use more atomic update actions (e.g. changeAssetName) - // but for now we use the simpler approach to first remove and then - // re-add the asset - which reduces the code complexity - [ - { - action: 'removeAsset', - ...toAssetIdentifier(oldAsset), - }, - { - action: 'addAsset', - asset: newAsset, - }, - ], - }) - - return handler(diff, oldObj, newObj) -} diff --git a/packages/sync-actions/src/attribute-groups-actions.ts b/packages/sync-actions/src/attribute-groups-actions.ts index 036a70603..27d324a64 100644 --- a/packages/sync-actions/src/attribute-groups-actions.ts +++ b/packages/sync-actions/src/attribute-groups-actions.ts @@ -4,32 +4,32 @@ import createBuildArrayActions, { CHANGE_ACTIONS, REMOVE_ACTIONS, } from './utils/create-build-array-actions' +import { UpdateAction } from '@commercetools/sdk-client-v2' +import { ActionMapBase } from './utils/create-map-action-group' +import { AttributeReference } from '@commercetools/platform-sdk/src' -const hasAttribute = (attributes, newValue) => - attributes.some((attribute) => attribute.key === newValue.key) +const hasAttribute = ( + attributes: Array, + newValue: AttributeReference +) => attributes.some((attribute) => attribute.key === newValue.key) -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'changeName', key: 'name' }, { action: 'setKey', key: 'key' }, { action: 'setDescription', key: 'description' }, ] -export function actionsMapBase( - diff, - oldObj, - newObj, - config: { shouldOmitEmptyString?: boolean } = {} -) { +export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, oldObj, newObj, - shouldOmitEmptyString: config.shouldOmitEmptyString, + shouldOmitEmptyString: config?.shouldOmitEmptyString, }) } -export function actionsMapAttributes(diff, oldObj, newObj) { +export function actionsMapAttributes(diff: any, oldObj: any, newObj: any) { const handler = createBuildArrayActions('attributes', { [ADD_ACTIONS]: (newAttribute) => ({ action: 'addAttribute', diff --git a/packages/sync-actions/src/attribute-groups.ts b/packages/sync-actions/src/attribute-groups.ts index 556296a08..20314b85f 100644 --- a/packages/sync-actions/src/attribute-groups.ts +++ b/packages/sync-actions/src/attribute-groups.ts @@ -13,33 +13,26 @@ import { } from './attribute-groups-actions' import { SyncAction } from './types/update-actions' import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import createMapActionGroup, { + MapActionGroup, + MapActionResult, +} from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' function createAttributeGroupsMapActions( - mapActionGroup: ( - type: string, - fn: () => Array - ) => Array, + mapActionGroup: MapActionGroup, syncActionConfig?: SyncActionConfig -): (diff: any, newObj: any, oldObj: any) => Array { - return function doMapActions( - diff: any, - newObj: any, - oldObj: any - ): Array { - const allActions = [] +): MapActionResult { + return function doMapActions(diff, newObj, oldObj) { + const allActions: Array> = [] allActions.push( - mapActionGroup( - 'base', - (): Array => - actionsMapBase(diff, oldObj, newObj, syncActionConfig) + mapActionGroup('base', () => + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) allActions.push( - mapActionGroup( - 'attributes', - (): Array => actionsMapAttributes(diff, oldObj, newObj) + mapActionGroup('attributes', () => + actionsMapAttributes(diff, oldObj, newObj) ).flat() ) return allActions.flat() diff --git a/packages/sync-actions/src/cart-discounts-actions.ts b/packages/sync-actions/src/cart-discounts-actions.ts index 7ef4e27be..281ec3481 100644 --- a/packages/sync-actions/src/cart-discounts-actions.ts +++ b/packages/sync-actions/src/cart-discounts-actions.ts @@ -1,6 +1,8 @@ import { buildBaseAttributesActions } from './utils/common-actions' +import { ActionMapBase } from './utils/create-map-action-group' +import { UpdateAction } from '@commercetools/sdk-client-v2' -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'changeIsActive', key: 'isActive' }, { action: 'changeName', key: 'name' }, { action: 'changeCartPredicate', key: 'cartPredicate' }, @@ -15,17 +17,12 @@ export const baseActionsList = [ { action: 'setKey', key: 'key' }, ] -export function actionsMapBase( - diff, - oldObj, - newObj, - config: { shouldOmitEmptyString?: boolean } = {} -) { +export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, oldObj, newObj, - shouldOmitEmptyString: config.shouldOmitEmptyString, + shouldOmitEmptyString: config?.shouldOmitEmptyString, }) } diff --git a/packages/sync-actions/src/cart-discounts.ts b/packages/sync-actions/src/cart-discounts.ts index 9c769c6d5..f56ea83a9 100644 --- a/packages/sync-actions/src/cart-discounts.ts +++ b/packages/sync-actions/src/cart-discounts.ts @@ -2,20 +2,30 @@ import { CartDiscount, CartDiscountUpdateAction, } from '@commercetools/platform-sdk' -import { ActionGroup, SyncActionConfig } from '@commercetools/sdk-client-v2' +import { + ActionGroup, + SyncActionConfig, + UpdateAction, +} from '@commercetools/sdk-client-v2' import { actionsMapBase } from './cart-discounts-actions' import { SyncAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import combineValidityActions from './utils/combine-validity-actions' import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import createMapActionGroup, { + MapActionGroup, + MapActionResult, +} from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'custom'] -function createCartDiscountsMapActions(mapActionGroup, syncActionConfig) { +function createCartDiscountsMapActions( + mapActionGroup: MapActionGroup, + syncActionConfig?: SyncActionConfig +): MapActionResult { return function doMapActions(diff, newObj, oldObj) { - const allActions = [] + const allActions: Array> = [] allActions.push( mapActionGroup('base', () => diff --git a/packages/sync-actions/src/categories.ts b/packages/sync-actions/src/categories.ts index adf36bcce..3ff1d3666 100644 --- a/packages/sync-actions/src/categories.ts +++ b/packages/sync-actions/src/categories.ts @@ -4,7 +4,7 @@ import type { SyncActionConfig, UpdateAction, } from '@commercetools/sdk-client-v2' -import actionsMapAssets from './assets-actions' +import actionsMapAssets from './category-assets-actions' import { actionsMapBase, actionsMapMeta, @@ -14,56 +14,43 @@ import { SyncAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import copyEmptyArrayProps from './utils/copy-empty-array-props' import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import createMapActionGroup, { + MapActionGroup, + MapActionResult, +} from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'references', 'meta', 'custom', 'assets'] function createCategoryMapActions( - mapActionGroup: Function, + mapActionGroup: MapActionGroup, syncActionConfig?: SyncActionConfig -): (diff: any, newObj: any, oldObj: any) => Array { - return function doMapActions( - diff: any, - newObj: any, - oldObj: any /* , options */ - ): Array { - const allActions = [] +): MapActionResult { + return function doMapActions(diff, newObj, oldObj) { + const allActions: Array> = [] allActions.push( - mapActionGroup( - 'base', - (): Array => - actionsMapBase(diff, oldObj, newObj, syncActionConfig) + mapActionGroup('base', () => + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) allActions.push( - mapActionGroup( - 'references', - (): Array => actionsMapReferences(diff, oldObj, newObj) + mapActionGroup('references', () => + actionsMapReferences(diff, oldObj, newObj) ) ) allActions.push( - mapActionGroup( - 'meta', - (): Array => actionsMapMeta(diff, oldObj, newObj) - ) + mapActionGroup('meta', () => actionsMapMeta(diff, oldObj, newObj)) ) allActions.push( - mapActionGroup( - 'custom', - (): Array => actionsMapCustom(diff, newObj, oldObj) - ) + mapActionGroup('custom', () => actionsMapCustom(diff, newObj, oldObj)) ) allActions.push( - mapActionGroup( - 'assets', - (): Array => actionsMapAssets(diff, oldObj, newObj) - ) + mapActionGroup('assets', () => actionsMapAssets(diff, oldObj, newObj)) ) return allActions.flat() diff --git a/packages/sync-actions/src/category-actions.ts b/packages/sync-actions/src/category-actions.ts index 0e23ee5fd..1dc981917 100644 --- a/packages/sync-actions/src/category-actions.ts +++ b/packages/sync-actions/src/category-actions.ts @@ -2,8 +2,10 @@ import { buildBaseAttributesActions, buildReferenceActions, } from './utils/common-actions' +import { ActionMapBase } from './utils/create-map-action-group' +import { UpdateAction } from '@commercetools/sdk-client-v2' -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'changeName', key: 'name' }, { action: 'changeSlug', key: 'slug' }, { action: 'setDescription', key: 'description' }, @@ -12,7 +14,7 @@ export const baseActionsList = [ { action: 'setKey', key: 'key' }, ] -export const metaActionsList = [ +export const metaActionsList: Array = [ { action: 'setMetaTitle', key: 'metaTitle' }, { action: 'setMetaKeywords', key: 'metaKeywords' }, { action: 'setMetaDescription', key: 'metaDescription' }, @@ -24,22 +26,17 @@ export const referenceActionsList = [{ action: 'changeParent', key: 'parent' }] * SYNC FUNCTIONS */ -export function actionsMapBase( - diff, - oldObj, - newObj, - config: { shouldOmitEmptyString?: boolean } = {} -) { +export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, oldObj, newObj, - shouldOmitEmptyString: config.shouldOmitEmptyString, + shouldOmitEmptyString: config?.shouldOmitEmptyString, }) } -export function actionsMapReferences(diff, oldObj, newObj) { +export function actionsMapReferences(diff: any, oldObj: any, newObj: any) { return buildReferenceActions({ actions: referenceActionsList, diff, @@ -48,7 +45,7 @@ export function actionsMapReferences(diff, oldObj, newObj) { }) } -export function actionsMapMeta(diff, oldObj, newObj) { +export function actionsMapMeta(diff: any, oldObj: any, newObj: any) { return buildBaseAttributesActions({ actions: metaActionsList, diff, diff --git a/packages/sync-actions/src/category-assets-actions.ts b/packages/sync-actions/src/category-assets-actions.ts new file mode 100644 index 000000000..e59fd7a9e --- /dev/null +++ b/packages/sync-actions/src/category-assets-actions.ts @@ -0,0 +1,45 @@ +import createBuildArrayActions, { + ADD_ACTIONS, + CHANGE_ACTIONS, + REMOVE_ACTIONS, +} from './utils/create-build-array-actions' +import { + CategoryAddAssetAction, + CategoryRemoveAssetAction, +} from '@commercetools/platform-sdk' +import { UpdateAction } from '@commercetools/sdk-client-v2' + +function toAssetIdentifier(asset: { id?: string; key?: string }) { + return asset.id ? { assetId: asset.id } : { assetKey: asset.key } +} + +export default function actionsMapAssets(diff: any, oldObj: any, newObj: any) { + const handler = createBuildArrayActions('assets', { + [ADD_ACTIONS]: (newAsset): CategoryAddAssetAction => ({ + action: 'addAsset', + asset: newAsset, + }), + [REMOVE_ACTIONS]: (oldAsset): CategoryRemoveAssetAction => ({ + action: 'removeAsset', + ...toAssetIdentifier(oldAsset), + }), + [CHANGE_ACTIONS]: (oldAsset, newAsset): Array => + // here we could use more atomic update actions (e.g. changeAssetName) + // but for now we use the simpler approach to first remove and then + // re-add the asset - which reduces the code complexity + { + return [ + { + action: 'removeAsset', + ...toAssetIdentifier(oldAsset), + }, + { + action: 'addAsset', + asset: newAsset, + }, + ] + }, + }) + + return handler(diff, oldObj, newObj) +} diff --git a/packages/sync-actions/src/channels-actions.ts b/packages/sync-actions/src/channels-actions.ts index 2459c4e02..a45e529e7 100644 --- a/packages/sync-actions/src/channels-actions.ts +++ b/packages/sync-actions/src/channels-actions.ts @@ -1,6 +1,8 @@ import { buildBaseAttributesActions } from './utils/common-actions' +import { UpdateAction } from '@commercetools/sdk-client-v2' +import { ActionMapBase } from './utils/create-map-action-group' -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'changeKey', key: 'key' }, { action: 'changeName', key: 'name' }, { action: 'changeDescription', key: 'description' }, @@ -9,17 +11,12 @@ export const baseActionsList = [ { action: 'setRoles', key: 'roles' }, ] -export function actionsMapBase( - diff, - oldObj, - newObj, - config: { shouldOmitEmptyString?: boolean } = {} -) { +export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, oldObj, newObj, - shouldOmitEmptyString: config.shouldOmitEmptyString, + shouldOmitEmptyString: config?.shouldOmitEmptyString, }) } diff --git a/packages/sync-actions/src/channels.ts b/packages/sync-actions/src/channels.ts index 18f90d307..d1d552606 100644 --- a/packages/sync-actions/src/channels.ts +++ b/packages/sync-actions/src/channels.ts @@ -1,17 +1,27 @@ import { Channel, ChannelUpdateAction } from '@commercetools/platform-sdk' -import { ActionGroup, SyncActionConfig } from '@commercetools/sdk-client-v2' +import { + ActionGroup, + SyncActionConfig, + UpdateAction, +} from '@commercetools/sdk-client-v2' import { actionsMapBase } from './channels-actions' import { SyncAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import createMapActionGroup, { + MapActionGroup, + MapActionResult, +} from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'custom'] -function createChannelsMapActions(mapActionGroup, syncActionConfig) { +function createChannelsMapActions( + mapActionGroup: MapActionGroup, + syncActionConfig?: SyncActionConfig +): MapActionResult { return function doMapActions(diff, newObj, oldObj) { - const allActions = [] + const allActions: Array> = [] allActions.push( mapActionGroup('base', () => diff --git a/packages/sync-actions/src/customer-actions.ts b/packages/sync-actions/src/customer-actions.ts index a21f7bcbc..4477886a2 100644 --- a/packages/sync-actions/src/customer-actions.ts +++ b/packages/sync-actions/src/customer-actions.ts @@ -10,10 +10,12 @@ import createBuildArrayActions, { REMOVE_ACTIONS, } from './utils/create-build-array-actions' import { patch } from './utils/diffpatcher' +import { ActionMapBase } from './utils/create-map-action-group' +import { UpdateAction } from '@commercetools/sdk-client-v2' const isEmptyValue = createIsEmptyValue([undefined, null, '']) -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'setSalutation', key: 'salutation' }, { action: 'changeEmail', key: 'email' }, { action: 'setFirstName', key: 'firstName' }, @@ -33,7 +35,7 @@ export const baseActionsList = [ { action: 'setKey', key: 'key' }, ] -export const setDefaultBaseActionsList = [ +export const setDefaultBaseActionsList: Array = [ { action: 'setDefaultBillingAddress', key: 'defaultBillingAddressId', @@ -62,37 +64,32 @@ export const authenticationModeActionsList = [ * SYNC FUNCTIONS */ -export function actionsMapBase( - diff, - oldObj, - newObj, - config: { shouldOmitEmptyString?: boolean } = {} -) { +export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, oldObj, newObj, - shouldOmitEmptyString: config.shouldOmitEmptyString, + shouldOmitEmptyString: config?.shouldOmitEmptyString, }) } -export function actionsMapSetDefaultBase( +export const actionsMapSetDefaultBase: ActionMapBase = ( diff, oldObj, newObj, - config: { shouldOmitEmptyString?: boolean } = {} -) { + config +) => { return buildBaseAttributesActions({ actions: setDefaultBaseActionsList, diff, oldObj, newObj, - shouldOmitEmptyString: config.shouldOmitEmptyString, + shouldOmitEmptyString: config?.shouldOmitEmptyString, }) } -export function actionsMapReferences(diff, oldObj, newObj) { +export function actionsMapReferences(diff: any, oldObj: any, newObj: any) { return buildReferenceActions({ actions: referenceActionsList, diff, @@ -101,7 +98,7 @@ export function actionsMapReferences(diff, oldObj, newObj) { }) } -export function actionsMapAddresses(diff, oldObj, newObj) { +export function actionsMapAddresses(diff: any, oldObj: any, newObj: any) { const handler = createBuildArrayActions('addresses', { [ADD_ACTIONS]: (newObject) => ({ action: 'addAddress', @@ -121,7 +118,11 @@ export function actionsMapAddresses(diff, oldObj, newObj) { return handler(diff, oldObj, newObj) } -export function actionsMapBillingAddresses(diff, oldObj, newObj) { +export function actionsMapBillingAddresses( + diff: any, + oldObj: any, + newObj: any +) { const handler = createBuildArrayActions('billingAddressIds', { [ADD_ACTIONS]: (addressId) => ({ action: 'addBillingAddressId', @@ -136,7 +137,11 @@ export function actionsMapBillingAddresses(diff, oldObj, newObj) { return handler(diff, oldObj, newObj) } -export function actionsMapShippingAddresses(diff, oldObj, newObj) { +export function actionsMapShippingAddresses( + diff: any, + oldObj: any, + newObj: any +) { const handler = createBuildArrayActions('shippingAddressIds', { [ADD_ACTIONS]: (addressId) => ({ action: 'addShippingAddressId', @@ -151,7 +156,11 @@ export function actionsMapShippingAddresses(diff, oldObj, newObj) { return handler(diff, oldObj, newObj) } -export function actionsMapAuthenticationModes(diff, oldObj, newObj) { +export function actionsMapAuthenticationModes( + diff: any, + oldObj: any, + newObj: any +) { // eslint-disable-next-line no-use-before-define return buildAuthenticationModeActions({ actions: authenticationModeActionsList, @@ -161,7 +170,17 @@ export function actionsMapAuthenticationModes(diff, oldObj, newObj) { }) } -function buildAuthenticationModeActions({ actions, diff, oldObj, newObj }) { +function buildAuthenticationModeActions({ + actions, + diff, + oldObj, + newObj, +}: { + actions: Array + diff: any + oldObj: any + newObj: any +}) { return actions .map((item) => { const key = item.key diff --git a/packages/sync-actions/src/customer-group-actions.ts b/packages/sync-actions/src/customer-group-actions.ts index 7e687e580..5197f4fe0 100644 --- a/packages/sync-actions/src/customer-group-actions.ts +++ b/packages/sync-actions/src/customer-group-actions.ts @@ -1,21 +1,18 @@ import { buildBaseAttributesActions } from './utils/common-actions' +import { ActionMapBase } from './utils/create-map-action-group' +import { UpdateAction } from '@commercetools/sdk-client-v2' -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'changeName', key: 'name' }, { action: 'setKey', key: 'key' }, ] -export function actionsMapBase( - diff, - oldObj, - newObj, - config: { shouldOmitEmptyString?: boolean } = {} -) { +export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, oldObj, newObj, - shouldOmitEmptyString: config.shouldOmitEmptyString, + shouldOmitEmptyString: config?.shouldOmitEmptyString, }) } diff --git a/packages/sync-actions/src/customer-group.ts b/packages/sync-actions/src/customer-group.ts index ee940e2a7..49173b1f4 100644 --- a/packages/sync-actions/src/customer-group.ts +++ b/packages/sync-actions/src/customer-group.ts @@ -2,19 +2,29 @@ import { CustomerGroup, CustomerGroupUpdateAction, } from '@commercetools/platform-sdk' -import { ActionGroup, SyncActionConfig } from '@commercetools/sdk-client-v2' +import { + ActionGroup, + SyncActionConfig, + UpdateAction, +} from '@commercetools/sdk-client-v2' import { actionsMapBase } from './customer-group-actions' import { SyncAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import createMapActionGroup, { + MapActionGroup, + MapActionResult, +} from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'custom'] -function createCustomerGroupMapActions(mapActionGroup, syncActionConfig) { +function createCustomerGroupMapActions( + mapActionGroup: MapActionGroup, + syncActionConfig?: SyncActionConfig +): MapActionResult { return function doMapActions(diff, newObj, oldObj) { - const allActions = [] + const allActions: Array> = [] allActions.push( mapActionGroup('base', () => diff --git a/packages/sync-actions/src/customers.ts b/packages/sync-actions/src/customers.ts index a13807778..f184729f1 100644 --- a/packages/sync-actions/src/customers.ts +++ b/packages/sync-actions/src/customers.ts @@ -17,7 +17,10 @@ import { SyncAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import copyEmptyArrayProps from './utils/copy-empty-array-props' import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import createMapActionGroup, { + MapActionGroup, + MapActionResult, +} from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' export const actionGroups = [ @@ -29,74 +32,55 @@ export const actionGroups = [ ] function createCustomerMapActions( - mapActionGroup: Function, + mapActionGroup: MapActionGroup, syncActionConfig?: SyncActionConfig -): (diff: any, newObj: any, oldObj: any) => Array { - return function doMapActions( - diff: any, - newObj: any, - oldObj: any /* , options */ - ): Array { - const allActions = [] +): MapActionResult { + return function doMapActions(diff, newObj, oldObj) { + const allActions: Array> = [] allActions.push( - mapActionGroup( - 'base', - (): Array => - actionsMapBase(diff, oldObj, newObj, syncActionConfig) + mapActionGroup('base', () => + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) allActions.push( - mapActionGroup( - 'references', - (): Array => actionsMapReferences(diff, oldObj, newObj) + mapActionGroup('references', () => + actionsMapReferences(diff, oldObj, newObj) ) ) allActions.push( - mapActionGroup( - 'addresses', - (): Array => actionsMapAddresses(diff, oldObj, newObj) + mapActionGroup('addresses', () => + actionsMapAddresses(diff, oldObj, newObj) ) ) allActions.push( - mapActionGroup( - 'base', - (): Array => - actionsMapSetDefaultBase(diff, oldObj, newObj, syncActionConfig) + mapActionGroup('base', () => + actionsMapSetDefaultBase(diff, oldObj, newObj, syncActionConfig) ) ) allActions.push( - mapActionGroup( - 'billingAddressIds', - (): Array => - actionsMapBillingAddresses(diff, oldObj, newObj) + mapActionGroup('billingAddressIds', () => + actionsMapBillingAddresses(diff, oldObj, newObj) ) ) allActions.push( - mapActionGroup( - 'shippingAddressIds', - (): Array => - actionsMapShippingAddresses(diff, oldObj, newObj) + mapActionGroup('shippingAddressIds', () => + actionsMapShippingAddresses(diff, oldObj, newObj) ) ) allActions.push( - mapActionGroup( - 'custom', - (): Array => actionsMapCustom(diff, newObj, oldObj) - ) + mapActionGroup('custom', () => actionsMapCustom(diff, newObj, oldObj)) ) allActions.push( - mapActionGroup( - 'authenticationModes', - (): Array => - actionsMapAuthenticationModes(diff, oldObj, newObj) + mapActionGroup('authenticationModes', () => + actionsMapAuthenticationModes(diff, oldObj, newObj) ) ) diff --git a/packages/sync-actions/src/discount-codes-actions.ts b/packages/sync-actions/src/discount-codes-actions.ts index ba39d2565..203d05974 100644 --- a/packages/sync-actions/src/discount-codes-actions.ts +++ b/packages/sync-actions/src/discount-codes-actions.ts @@ -1,6 +1,8 @@ import { buildBaseAttributesActions } from './utils/common-actions' +import { ActionMapBase } from './utils/create-map-action-group' +import { UpdateAction } from '@commercetools/sdk-client-v2' -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'changeIsActive', key: 'isActive' }, { action: 'setName', key: 'name' }, { action: 'setDescription', key: 'description' }, @@ -16,17 +18,12 @@ export const baseActionsList = [ { action: 'changeGroups', key: 'groups' }, ] -export function actionsMapBase( - diff, - oldObj, - newObj, - config: { shouldOmitEmptyString?: boolean } = {} -) { +export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, oldObj, newObj, - shouldOmitEmptyString: config.shouldOmitEmptyString, + shouldOmitEmptyString: config?.shouldOmitEmptyString, }) } diff --git a/packages/sync-actions/src/discount-codes.ts b/packages/sync-actions/src/discount-codes.ts index 94f843c18..8870e005f 100644 --- a/packages/sync-actions/src/discount-codes.ts +++ b/packages/sync-actions/src/discount-codes.ts @@ -2,20 +2,30 @@ import { DiscountCode, DiscountCodeUpdateAction, } from '@commercetools/platform-sdk' -import { ActionGroup, SyncActionConfig } from '@commercetools/sdk-client-v2' +import { + ActionGroup, + SyncActionConfig, + UpdateAction, +} from '@commercetools/sdk-client-v2' import { actionsMapBase } from './discount-codes-actions' import { SyncAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import combineValidityActions from './utils/combine-validity-actions' import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import createMapActionGroup, { + MapActionGroup, + MapActionResult, +} from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'custom'] -function createDiscountCodesMapActions(mapActionGroup, syncActionConfig) { +function createDiscountCodesMapActions( + mapActionGroup: MapActionGroup, + syncActionConfig?: SyncActionConfig +): MapActionResult { return function doMapActions(diff, newObj, oldObj) { - const allActions = [] + const allActions: Array> = [] allActions.push( mapActionGroup('base', () => actionsMapBase(diff, oldObj, newObj, syncActionConfig) diff --git a/packages/sync-actions/src/inventories.ts b/packages/sync-actions/src/inventories.ts index 4514ea411..36a340fbb 100644 --- a/packages/sync-actions/src/inventories.ts +++ b/packages/sync-actions/src/inventories.ts @@ -11,40 +11,33 @@ import { actionsMapBase, actionsMapReferences } from './inventory-actions' import { SyncAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import createMapActionGroup, { + MapActionGroup, + MapActionResult, +} from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'references'] function createInventoryMapActions( - mapActionGroup: Function, + mapActionGroup: MapActionGroup, syncActionConfig?: SyncActionConfig -): (diff: any, newObj: any, oldObj: any) => Array { - return function doMapActions( - diff: any, - newObj: any, - oldObj: any /* , options */ - ): Array { - const allActions = [] +): MapActionResult { + return function doMapActions(diff, newObj, oldObj) { + const allActions: Array> = [] allActions.push( - mapActionGroup( - 'base', - (): Array => - actionsMapBase(diff, oldObj, newObj, syncActionConfig) + mapActionGroup('base', () => + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) allActions.push( - mapActionGroup( - 'references', - (): Array => actionsMapReferences(diff, oldObj, newObj) + mapActionGroup('references', () => + actionsMapReferences(diff, oldObj, newObj) ) ) allActions.push( - mapActionGroup( - 'custom', - (): Array => actionsMapCustom(diff, newObj, oldObj) - ) + mapActionGroup('custom', () => actionsMapCustom(diff, newObj, oldObj)) ) return allActions.flat() } diff --git a/packages/sync-actions/src/inventory-actions.ts b/packages/sync-actions/src/inventory-actions.ts index 2c200cf2c..a0e7ff0a2 100644 --- a/packages/sync-actions/src/inventory-actions.ts +++ b/packages/sync-actions/src/inventory-actions.ts @@ -2,8 +2,10 @@ import { buildBaseAttributesActions, buildReferenceActions, } from './utils/common-actions' +import { ActionMapBase } from './utils/create-map-action-group' +import { UpdateAction } from '@commercetools/sdk-client-v2' -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'changeQuantity', key: 'quantityOnStock', actionKey: 'quantity' }, { action: 'setRestockableInDays', key: 'restockableInDays' }, { action: 'setExpectedDelivery', key: 'expectedDelivery' }, @@ -17,22 +19,17 @@ export const referenceActionsList = [ * SYNC FUNCTIONS */ -export function actionsMapBase( - diff, - oldObj, - newObj, - config: { shouldOmitEmptyString?: boolean } = {} -) { +export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, oldObj, newObj, - shouldOmitEmptyString: config.shouldOmitEmptyString, + shouldOmitEmptyString: config?.shouldOmitEmptyString, }) } -export function actionsMapReferences(diff, oldObj, newObj) { +export function actionsMapReferences(diff: any, oldObj: any, newObj: any) { return buildReferenceActions({ actions: referenceActionsList, diff, diff --git a/packages/sync-actions/src/order-actions.ts b/packages/sync-actions/src/order-actions.ts index be0312fdd..f3cabcb30 100644 --- a/packages/sync-actions/src/order-actions.ts +++ b/packages/sync-actions/src/order-actions.ts @@ -6,17 +6,19 @@ import createBuildArrayActions, { import { getDeltaValue } from './utils/diffpatcher' import extractMatchingPairs from './utils/extract-matching-pairs' import findMatchingPairs from './utils/find-matching-pairs' +import { ActionMapBase } from './utils/create-map-action-group' +import { UpdateAction } from '@commercetools/sdk-client-v2' const REGEX_NUMBER = new RegExp(/^\d+$/) const REGEX_UNDERSCORE_NUMBER = new RegExp(/^_\d+$/) -const isAddAction = (key, resource) => +const isAddAction = (key: string, resource: any) => REGEX_NUMBER.test(key) && Array.isArray(resource) && resource.length -const isRemoveAction = (key, resource) => +const isRemoveAction = (key: string, resource: any) => REGEX_UNDERSCORE_NUMBER.test(key) && Number(resource[2]) === 0 -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'changeOrderState', key: 'orderState' }, { action: 'changePaymentState', key: 'paymentState' }, { action: 'changeShipmentState', key: 'shipmentState' }, @@ -26,22 +28,17 @@ export const baseActionsList = [ * SYNC FUNCTIONS */ -export function actionsMapBase( - diff, - oldObj, - newObj, - config: { shouldOmitEmptyString?: boolean } = {} -) { +export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, oldObj, newObj, - shouldOmitEmptyString: config.shouldOmitEmptyString, + shouldOmitEmptyString: config?.shouldOmitEmptyString, }) } -export function actionsMapDeliveries(diff, oldObj, newObj) { +export function actionsMapDeliveries(diff: any, oldObj: any, newObj: any) { const deliveriesDiff = diff.shippingInfo if (!deliveriesDiff) return [] @@ -57,12 +54,12 @@ export function actionsMapDeliveries(diff, oldObj, newObj) { } function _buildDeliveryParcelsAction( - diffedParcels, + diffedParcels: any, oldDelivery: any = {}, newDelivery: any = {} ) { - const addParcelActions = [] - const removeParcelActions = [] + const addParcelActions: Array = [] + const removeParcelActions: Array = [] // generate a hashMap to be able to reference the right image from both ends const matchingParcelPairs = findMatchingPairs( @@ -99,7 +96,7 @@ function _buildDeliveryParcelsAction( return [addParcelActions, removeParcelActions] } -function _buildDeliveryItemsAction(diffedItems, newDelivery: any = {}) { +function _buildDeliveryItemsAction(diffedItems: any, newDelivery: any = {}) { const setDeliveryItemsAction: Array = [] // If there is a diff it means that there were changes (update, adds or removes) // over the items, which means that `setDeliveryItems` change has happened over @@ -117,10 +114,10 @@ function _buildDeliveryItemsAction(diffedItems, newDelivery: any = {}) { } export function actionsMapParcels( - diff: { shippingInfo: { deliveries: { any } } }, - oldObj, - newObj, - deliveryHashMap + diff: { shippingInfo: { deliveries: { [key: string]: any } } }, + oldObj: any, + newObj: any, + deliveryHashMap: any ) { const shippingInfo = diff.shippingInfo if (!shippingInfo) return [] @@ -128,8 +125,8 @@ export function actionsMapParcels( const deliveries = shippingInfo.deliveries if (!deliveries) return [] - let addParcelActions = [] - let removeParcelActions = [] + let addParcelActions: Array = [] + let removeParcelActions: Array = [] if (deliveries) Object.entries(deliveries).forEach(([key, delivery]) => { @@ -156,10 +153,10 @@ export function actionsMapParcels( } export function actionsMapDeliveryItems( - diff: { shippingInfo: { deliveries: { any } } }, - oldObj, - newObj, - deliveryHashMap + diff: { shippingInfo: { deliveries: { [key: string]: any } } }, + oldObj: any, + newObj: any, + deliveryHashMap: any ) { const shippingInfo = diff.shippingInfo if (!shippingInfo) return [] @@ -167,7 +164,7 @@ export function actionsMapDeliveryItems( const deliveries = shippingInfo.deliveries if (!deliveries) return [] - let setDeliveryItemsActions = [] + let setDeliveryItemsActions: Array = [] Object.entries(deliveries).forEach(([key, delivery]) => { const { newObj: newDelivery } = extractMatchingPairs( @@ -190,7 +187,7 @@ export function actionsMapDeliveryItems( return setDeliveryItemsActions } -export function actionsMapReturnsInfo(diff, oldObj, newObj) { +export function actionsMapReturnsInfo(diff: any, oldObj: any, newObj: any) { const returnInfoDiff = diff.returnInfo if (!returnInfoDiff) return [] diff --git a/packages/sync-actions/src/orders.ts b/packages/sync-actions/src/orders.ts index ca36617b8..6ebd35fc3 100644 --- a/packages/sync-actions/src/orders.ts +++ b/packages/sync-actions/src/orders.ts @@ -20,23 +20,22 @@ import { import { SyncAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import createMapActionGroup, { + MapActionGroup, + MapActionResult, +} from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' import findMatchingPairs from './utils/find-matching-pairs' export const actionGroups = ['base', 'deliveries'] function createOrderMapActions( - mapActionGroup: Function, + mapActionGroup: MapActionGroup, syncActionConfig?: SyncActionConfig -): (diff: any, newObj: any, oldObj: any) => Array { - return function doMapActions( - diff: any, - newObj: any, - oldObj: any /* , options */ - ): Array { - const allActions = [] - let deliveryHashMap +): MapActionResult { + return function doMapActions(diff, newObj, oldObj) { + const allActions: Array> = [] + let deliveryHashMap: any if (diff.shippingInfo && diff.shippingInfo.deliveries) { deliveryHashMap = findMatchingPairs( @@ -47,40 +46,32 @@ function createOrderMapActions( } allActions.push( - mapActionGroup( - 'base', - (): Array => - actionsMapBase(diff, oldObj, newObj, syncActionConfig) + mapActionGroup('base', () => + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) allActions.push( - mapActionGroup( - 'deliveries', - (): Array => actionsMapDeliveries(diff, oldObj, newObj) + mapActionGroup('deliveries', () => + actionsMapDeliveries(diff, oldObj, newObj) ) ) allActions.push( - mapActionGroup( - 'parcels', - (): Array => - actionsMapParcels(diff, oldObj, newObj, deliveryHashMap) + mapActionGroup('parcels', () => + actionsMapParcels(diff, oldObj, newObj, deliveryHashMap) ) ) allActions.push( - mapActionGroup( - 'items', - (): Array => - actionsMapDeliveryItems(diff, oldObj, newObj, deliveryHashMap) + mapActionGroup('items', () => + actionsMapDeliveryItems(diff, oldObj, newObj, deliveryHashMap) ) ) allActions.push( - mapActionGroup( - 'returnInfo', - (): Array => actionsMapReturnsInfo(diff, oldObj, newObj) + mapActionGroup('returnInfo', () => + actionsMapReturnsInfo(diff, oldObj, newObj) ).flat() ) diff --git a/packages/sync-actions/src/prices-actions.ts b/packages/sync-actions/src/prices-actions.ts index 5d2b61b38..af1b3c18d 100644 --- a/packages/sync-actions/src/prices-actions.ts +++ b/packages/sync-actions/src/prices-actions.ts @@ -1,6 +1,8 @@ import { buildBaseAttributesActions } from './utils/common-actions' +import { ActionMapBase } from './utils/create-map-action-group' +import { UpdateAction } from '@commercetools/sdk-client-v2' -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'changeValue', key: 'value' }, { action: 'setDiscountedPrice', key: 'discounted' }, // TODO: Later add more accurate actions `addPriceTier`, `removePriceTier` @@ -11,17 +13,12 @@ export const baseActionsList = [ { action: 'changeActive', key: 'active' }, ] -export function actionsMapBase( - diff, - oldObj, - newObj, - config: { shouldOmitEmptyString?: boolean } = {} -) { +export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, oldObj, newObj, - shouldOmitEmptyString: config.shouldOmitEmptyString, + shouldOmitEmptyString: config?.shouldOmitEmptyString, }) } diff --git a/packages/sync-actions/src/prices.ts b/packages/sync-actions/src/prices.ts index 4f6c77372..98e4231e2 100644 --- a/packages/sync-actions/src/prices.ts +++ b/packages/sync-actions/src/prices.ts @@ -8,29 +8,25 @@ import { actionsMapBase } from './prices-actions' import actionsMapCustom from './utils/action-map-custom' import combineValidityActions from './utils/combine-validity-actions' import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import createMapActionGroup, { + MapActionGroup, + MapActionResult, +} from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' const actionGroups = ['base', 'custom'] function createPriceMapActions( - mapActionGroup: Function, + mapActionGroup: MapActionGroup, syncActionConfig?: SyncActionConfig -): (diff: any, newObj: any, oldObj: any, options: any) => Array { - return function doMapActions( - diff: any, - newObj: any, - oldObj: any - ): Array { - const baseActions = mapActionGroup( - 'base', - (): Array => - actionsMapBase(diff, oldObj, newObj, syncActionConfig) +): MapActionResult { + return function doMapActions(diff, newObj, oldObj) { + const baseActions = mapActionGroup('base', () => + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) - const customActions = mapActionGroup( - 'custom', - (): Array => actionsMapCustom(diff, newObj, oldObj) + const customActions = mapActionGroup('custom', () => + actionsMapCustom(diff, newObj, oldObj) ) return combineValidityActions([...baseActions, ...customActions]) diff --git a/packages/sync-actions/src/product-actions.ts b/packages/sync-actions/src/product-actions.ts index caacd7b80..d57a4d25c 100644 --- a/packages/sync-actions/src/product-actions.ts +++ b/packages/sync-actions/src/product-actions.ts @@ -1,4 +1,7 @@ -import { ProductVariant } from '@commercetools/platform-sdk/src' +import { + ProductAddToCategoryAction, + ProductVariant, +} from '@commercetools/platform-sdk/src' import actionsMapCustom from './utils/action-map-custom' import { buildBaseAttributesActions, @@ -11,11 +14,18 @@ import createBuildArrayActions, { import { getDeltaValue } from './utils/diffpatcher' import extractMatchingPairs from './utils/extract-matching-pairs' import findMatchingPairs from './utils/find-matching-pairs' +import { + Asset, + ProductRemoveFromCategoryAction, +} from '@commercetools/platform-sdk' +import { SyncActionConfig } from '@commercetools/sdk-client-v2/src' +import { UpdateAction } from '@commercetools/sdk-client-v2' +import { ActionMapBase } from './utils/create-map-action-group' const REGEX_NUMBER = new RegExp(/^\d+$/) const REGEX_UNDERSCORE_NUMBER = new RegExp(/^_\d+$/) -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'changeName', key: 'name' }, { action: 'changeSlug', key: 'slug' }, { action: 'setDescription', key: 'description' }, @@ -47,19 +57,19 @@ export const referenceActionsList = [ * HELPER FUNCTIONS */ -const getIsAddAction = (key, resource) => +const getIsAddAction = (key: string, resource: any) => REGEX_NUMBER.test(key) && Array.isArray(resource) && resource.length -const getIsUpdateAction = (key, resource) => +const getIsUpdateAction = (key: string, resource: any) => REGEX_NUMBER.test(key) && Object.keys(resource).length -const getIsRemoveAction = (key, resource) => +const getIsRemoveAction = (key: string, resource: any) => REGEX_UNDERSCORE_NUMBER.test(key) && Number(resource[2]) === 0 -const getIsItemMovedAction = (key, resource) => +const getIsItemMovedAction = (key: string, resource: any) => REGEX_UNDERSCORE_NUMBER.test(key) && Number(resource[2]) === 3 -function _buildSkuActions(variantDiff, oldVariant) { +function _buildSkuActions(variantDiff: any, oldVariant: any) { if ({}.hasOwnProperty.call(variantDiff, 'sku')) { const newValue = getDeltaValue(variantDiff.sku) if (!newValue && !oldVariant.sku) return null @@ -73,7 +83,7 @@ function _buildSkuActions(variantDiff, oldVariant) { return null } -function _buildKeyActions(variantDiff, oldVariant) { +function _buildKeyActions(variantDiff: any, oldVariant: any) { if ({}.hasOwnProperty.call(variantDiff, 'key')) { const newValue = getDeltaValue(variantDiff.key) if (!newValue && !oldVariant.key) return null @@ -87,7 +97,11 @@ function _buildKeyActions(variantDiff, oldVariant) { return null } -function _buildNewSetAttributeAction(id, el, sameForAllAttributeNames) { +function _buildNewSetAttributeAction( + id: any, + el: any, + sameForAllAttributeNames: Array +) { const attributeName = el && el.name if (!attributeName) return undefined @@ -107,10 +121,10 @@ function _buildNewSetAttributeAction(id, el, sameForAllAttributeNames) { } function _buildSetAttributeAction( - diffedValue, - oldVariant, - attribute, - sameForAllAttributeNames + diffedValue: any, + oldVariant: any, + attribute: any, + sameForAllAttributeNames: Array ) { if (!attribute) return undefined @@ -122,7 +136,7 @@ function _buildSetAttributeAction( // Used as original object for patching long diff text const oldAttribute = - oldVariant.attributes.find((a) => a.name === attribute.name) || {} + oldVariant.attributes.find((a: any) => a.name === attribute.name) || {} if (sameForAllAttributeNames.indexOf(attribute.name) !== -1) { action = { ...action, action: 'setAttributeInAllVariants' } @@ -179,7 +193,7 @@ function _buildVariantImagesAction( oldVariant: any = {}, newVariant: any = {} ) { - const actions = [] + const actions: Array = [] // generate a hashMap to be able to reference the right image from both ends const matchingImagePairs = findMatchingPairs( diffedImages, @@ -254,14 +268,14 @@ function _buildVariantImagesAction( } function _buildVariantPricesAction( - diffedPrices, + diffedPrices: any, oldVariant: any = {}, newVariant: any = {}, enableDiscounted = false ) { - const addPriceActions = [] - const changePriceActions = [] - const removePriceActions = [] + const addPriceActions: Array = [] + const changePriceActions: Array = [] + const removePriceActions: Array = [] // generate a hashMap to be able to reference the right image from both ends const matchingPricePairs = findMatchingPairs( @@ -279,7 +293,7 @@ function _buildVariantPricesAction( ) if (getIsAddAction(key, price)) { // Remove read-only fields - const patchedPrice = (price as any).map((p) => { + const patchedPrice = (price as any).map((p: any) => { const shallowClone = { ...p } if (enableDiscounted !== true) delete shallowClone.discounted return shallowClone @@ -325,12 +339,12 @@ function _buildVariantPricesAction( } function _buildVariantAttributesActions( - attributes, - oldVariant, - newVariant, - sameForAllAttributeNames + attributes: any, + oldVariant: any, + newVariant: any, + sameForAllAttributeNames: Array ) { - const actions = [] + const actions: Array = [] if (!attributes) return actions attributes && @@ -393,22 +407,22 @@ function _buildVariantAttributesActions( return actions } -function toAssetIdentifier(asset) { +function toAssetIdentifier(asset: Asset) { const assetIdentifier = asset.id ? { assetId: asset.id } : { assetKey: asset.key } return assetIdentifier } -function toVariantIdentifier(variant) { +function toVariantIdentifier(variant: ProductVariant) { const { id, sku } = variant return id ? { variantId: id } : { sku } } function _buildVariantChangeAssetOrderAction( - diffAssets, - oldVariant, - newVariant + diffAssets: any, + oldVariant: any, + newVariant: any ) { const isAssetOrderChanged = Object.entries(diffAssets).find((entry) => getIsItemMovedAction(entry[0], entry[1]) @@ -416,15 +430,15 @@ function _buildVariantChangeAssetOrderAction( if (!isAssetOrderChanged) { return [] } - const assetIdsBefore = oldVariant.assets.map((_) => _.id) + const assetIdsBefore = oldVariant.assets.map((value: any) => value.id) const assetIdsCurrent = newVariant.assets - .map((_) => _.id) - .filter((_) => _ !== undefined) - const assetIdsToKeep = assetIdsCurrent.filter((value) => + .map((value: any) => value.id) + .filter((value: any) => value !== undefined) + const assetIdsToKeep = assetIdsCurrent.filter((value: any) => assetIdsBefore.includes(value) ) const assetIdsToRemove = assetIdsBefore.filter( - (item) => !assetIdsToKeep.includes(item) + (item: any) => !assetIdsToKeep.includes(item) ) const changeAssetOrderAction = { action: 'changeAssetOrder', @@ -434,8 +448,12 @@ function _buildVariantChangeAssetOrderAction( return [changeAssetOrderAction] } -function _buildVariantAssetsActions(diffAssets, oldVariant, newVariant) { - const assetActions = [] +function _buildVariantAssetsActions( + diffAssets: any, + oldVariant: any, + newVariant: any +) { + const assetActions: Array = [] // generate a hashMap to be able to reference the right asset from both ends const matchingAssetPairs = findMatchingPairs( @@ -524,22 +542,17 @@ function _buildVariantAssetsActions(diffAssets, oldVariant, newVariant) { * SYNC FUNCTIONS */ -export function actionsMapBase( - diff, - oldObj, - newObj, - config: { shouldOmitEmptyString?: boolean } = {} -) { +export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, oldObj, newObj, - shouldOmitEmptyString: config.shouldOmitEmptyString, + shouldOmitEmptyString: config?.shouldOmitEmptyString, }) } -export function actionsMapMeta(diff, oldObj, newObj) { +export function actionsMapMeta(diff: any, oldObj: any, newObj: any) { return buildBaseAttributesActions({ actions: metaActionsList, diff, @@ -548,9 +561,9 @@ export function actionsMapMeta(diff, oldObj, newObj) { }) } -export function actionsMapAddVariants(diff, oldObj, newObj) { +export function actionsMapAddVariants(diff: any, oldObj: any, newObj: any) { const handler = createBuildArrayActions('variants', { - [ADD_ACTIONS]: (newObject) => ({ + [ADD_ACTIONS]: (newObject: any) => ({ ...newObject, action: 'addVariant', }), @@ -558,9 +571,9 @@ export function actionsMapAddVariants(diff, oldObj, newObj) { return handler(diff, oldObj, newObj) } -export function actionsMapRemoveVariants(diff, oldObj, newObj) { +export function actionsMapRemoveVariants(diff: any, oldObj: any, newObj: any) { const handler = createBuildArrayActions('variants', { - [REMOVE_ACTIONS]: ({ id }) => ({ + [REMOVE_ACTIONS]: ({ id }: { id: string }) => ({ action: 'removeVariant', id, }), @@ -568,7 +581,7 @@ export function actionsMapRemoveVariants(diff, oldObj, newObj) { return handler(diff, oldObj, newObj) } -export function actionsMapReferences(diff, oldObj, newObj) { +export function actionsMapReferences(diff: any, oldObj: any, newObj: any) { return buildReferenceActions({ actions: referenceActionsList, diff, @@ -577,12 +590,15 @@ export function actionsMapReferences(diff, oldObj, newObj) { }) } -export function actionsMapCategories(diff) { - const actions = [] +export function actionsMapCategories(diff: { + categories?: { [key: string]: any } + [key: string]: any +}): Array { + const actions: Array = [] if (!diff.categories) return actions - const addToCategoryActions = [] - const removeFromCategoryActions = [] + const addToCategoryActions: Array = [] + const removeFromCategoryActions: Array = [] Object.entries(diff.categories).forEach(([key, category]) => { if (Array.isArray(category)) { @@ -602,10 +618,10 @@ export function actionsMapCategories(diff) { }) // Make sure `removeFromCategory` actions come first - return removeFromCategoryActions.concat(addToCategoryActions) + return [...removeFromCategoryActions, ...addToCategoryActions] } -export function actionsMapCategoryOrderHints(diff) { +export function actionsMapCategoryOrderHints(diff: any) { if (!diff.categoryOrderHints) return [] // Ignore this pattern as its means no changes happened [{},0,0] if (Array.isArray(diff.categoryOrderHints)) return [] @@ -631,8 +647,13 @@ export function actionsMapCategoryOrderHints(diff) { }) } -export function actionsMapAssets(diff, oldObj, newObj, variantHashMap) { - let allAssetsActions = [] +export function actionsMapAssets( + diff: any, + oldObj: any, + newObj: any, + variantHashMap: any +) { + let allAssetsActions: Array = [] const { variants } = diff @@ -664,13 +685,13 @@ export function actionsMapAssets(diff, oldObj, newObj, variantHashMap) { } export function actionsMapAttributes( - diff, - oldObj, - newObj, - sameForAllAttributeNames = [], - variantHashMap + diff: any, + oldObj: any, + newObj: any, + sameForAllAttributeNames: Array = [], + variantHashMap: any ) { - let actions = [] + let actions: Array = [] const { variants } = diff if (variants) @@ -713,8 +734,13 @@ export function actionsMapAttributes( ) } -export function actionsMapImages(diff, oldObj, newObj, variantHashMap) { - let actions = [] +export function actionsMapImages( + diff: any, + oldObj: any, + newObj: any, + variantHashMap: any +) { + let actions: Array = [] const { variants } = diff if (variants) Object.entries(variants as { [key: string]: ProductVariant }).forEach( @@ -740,15 +766,15 @@ export function actionsMapImages(diff, oldObj, newObj, variantHashMap) { } export function actionsMapPrices( - diff, - oldObj, - newObj, - variantHashMap, - enableDiscounted + diff: any, + oldObj: any, + newObj: any, + variantHashMap: any, + enableDiscounted: any ) { - let addPriceActions = [] - let changePriceActions = [] - let removePriceActions = [] + let addPriceActions: Array = [] + let changePriceActions: Array = [] + let removePriceActions: Array = [] const { variants } = diff @@ -781,8 +807,13 @@ export function actionsMapPrices( return changePriceActions.concat(removePriceActions).concat(addPriceActions) } -export function actionsMapPricesCustom(diff, oldObj, newObj, variantHashMap) { - let actions = [] +export function actionsMapPricesCustom( + diff: any, + oldObj: any, + newObj: any, + variantHashMap: any +) { + let actions: Array = [] const { variants } = diff @@ -842,12 +873,15 @@ export function actionsMapPricesCustom(diff, oldObj, newObj, variantHashMap) { return actions } -export function actionsMapMasterVariant(oldObj, newObj) { - const createChangeMasterVariantAction = (variantId) => ({ +export function actionsMapMasterVariant( + oldObj: any, + newObj: any +): Array { + const createChangeMasterVariantAction = (variantId: string) => ({ action: 'changeMasterVariant', variantId, }) - const extractMasterVariantId = (fromObj) => { + const extractMasterVariantId = (fromObj: any) => { const variants = Array.isArray(fromObj.variants) ? fromObj.variants : [] return variants[0] ? variants[0].id : undefined diff --git a/packages/sync-actions/src/product-discounts-actions.ts b/packages/sync-actions/src/product-discounts-actions.ts index 38f7fd72c..1f612e693 100644 --- a/packages/sync-actions/src/product-discounts-actions.ts +++ b/packages/sync-actions/src/product-discounts-actions.ts @@ -1,6 +1,8 @@ import { buildBaseAttributesActions } from './utils/common-actions' +import { ActionMapBase } from './utils/create-map-action-group' +import { UpdateAction } from '@commercetools/sdk-client-v2' -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'changeIsActive', key: 'isActive' }, { action: 'changeName', key: 'name' }, { action: 'changePredicate', key: 'predicate' }, @@ -12,17 +14,12 @@ export const baseActionsList = [ { action: 'setKey', key: 'key' }, ] -export function actionsMapBase( - diff, - oldObj, - newObj, - config: { shouldOmitEmptyString?: boolean } = {} -) { +export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, oldObj, newObj, - shouldOmitEmptyString: config.shouldOmitEmptyString, + shouldOmitEmptyString: config?.shouldOmitEmptyString, }) } diff --git a/packages/sync-actions/src/product-discounts.ts b/packages/sync-actions/src/product-discounts.ts index 989605e61..ac37b21ff 100644 --- a/packages/sync-actions/src/product-discounts.ts +++ b/packages/sync-actions/src/product-discounts.ts @@ -2,19 +2,29 @@ import { ProductDiscount, ProductDiscountUpdateAction, } from '@commercetools/platform-sdk' -import { ActionGroup, SyncActionConfig } from '@commercetools/sdk-client-v2' +import { + ActionGroup, + SyncActionConfig, + UpdateAction, +} from '@commercetools/sdk-client-v2' import { actionsMapBase } from './product-discounts-actions' import { SyncAction } from './types/update-actions' import combineValidityActions from './utils/combine-validity-actions' import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import createMapActionGroup, { + MapActionGroup, + MapActionResult, +} from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' export const actionGroups = ['base'] -function createProductDiscountsMapActions(mapActionGroup, syncActionConfig) { +function createProductDiscountsMapActions( + mapActionGroup: MapActionGroup, + syncActionConfig?: SyncActionConfig +): MapActionResult { return function doMapActions(diff, newObj, oldObj) { - const allActions = [] + const allActions: Array> = [] allActions.push( mapActionGroup('base', () => diff --git a/packages/sync-actions/src/product-selections-actions.ts b/packages/sync-actions/src/product-selections-actions.ts index abeae9464..938c1c2d7 100644 --- a/packages/sync-actions/src/product-selections-actions.ts +++ b/packages/sync-actions/src/product-selections-actions.ts @@ -1,11 +1,13 @@ import { buildBaseAttributesActions } from './utils/common-actions' +import { ActionMapBase } from './utils/create-map-action-group' +import { UpdateAction } from '@commercetools/sdk-client-v2' -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'changeName', key: 'name' }, { action: 'setKey', key: 'key' }, ] -export function actionsMapBase(diff, oldObj, newObj) { +export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, diff --git a/packages/sync-actions/src/product-selections.ts b/packages/sync-actions/src/product-selections.ts index b00a3f9a3..ded29b91e 100644 --- a/packages/sync-actions/src/product-selections.ts +++ b/packages/sync-actions/src/product-selections.ts @@ -46,7 +46,7 @@ export default ( ): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createProductSelectionsMapActions(mapActionGroup) - const onBeforeApplyingDiff = null + const onBeforeApplyingDiff: any = null const buildActions = createBuildActions< ProductSelection, ProductSelectionUpdateAction diff --git a/packages/sync-actions/src/product-types-actions.ts b/packages/sync-actions/src/product-types-actions.ts index d0dda3cf1..11ad86e72 100644 --- a/packages/sync-actions/src/product-types-actions.ts +++ b/packages/sync-actions/src/product-types-actions.ts @@ -4,19 +4,16 @@ import { buildBaseAttributesActions, createIsEmptyValue, } from './utils/common-actions' +import { ActionMapBase } from './utils/create-map-action-group' +import { UpdateAction } from '@commercetools/sdk-client-v2' -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'changeName', key: 'name' }, { action: 'setKey', key: 'key' }, { action: 'changeDescription', key: 'description' }, ] -export function actionsMapBase( - diff, - previous, - next, - config: { shouldOmitEmptyString?: boolean } = {} -) { +export const actionsMapBase: ActionMapBase = (diff, previous, next, config) => { // when `diff` is undefined, then the underlying `buildActions` has returned any diff // which given in product-types would mean that `buildActions` has run with `nestedValuesChanges` applied // To allow continuation of update-action generation, we let this pass.. @@ -26,7 +23,7 @@ export function actionsMapBase( actions: baseActionsList, oldObj: previous, newObj: next, - shouldOmitEmptyString: config.shouldOmitEmptyString, + shouldOmitEmptyString: config?.shouldOmitEmptyString, }) } @@ -35,8 +32,8 @@ export function actionsMapBase( // which is an object consisting of flags which indicates different operations. // `generateBaseFieldsUpdateActions` only generate based on `previous` and `next`. export const generateBaseFieldsUpdateActions = ( - previous, - next, + previous: any, + next: any, actionDefinition: { [s: string]: { action: string; attributeName?: string } } ) => { const isEmpty = createIsEmptyValue([undefined, null, '']) @@ -284,9 +281,9 @@ const generateUpdateActionsForAttributeEnumValues = ( } const generateChangeAttributeOrderAction = ( - attrsOld = [], - attrsNew = [], - updateActions = [] + attrsOld: Array = [], + attrsNew: Array = [], + updateActions: Array = [] ) => { if (!attrsOld.length || !attrsNew.length) return null @@ -322,8 +319,8 @@ export type NestedValues = { } export const actionsMapForHints = ( nestedValuesChanges: NestedValues, - ptOld, - ptNew + ptOld: any, + ptNew: any ) => { const updateActions = [ ...generateUpdateActionsForAttributeDefinitions( diff --git a/packages/sync-actions/src/product-types.ts b/packages/sync-actions/src/product-types.ts index 9a26050a7..da8c76dc8 100644 --- a/packages/sync-actions/src/product-types.ts +++ b/packages/sync-actions/src/product-types.ts @@ -10,7 +10,10 @@ import type { import * as productTypeActions from './product-types-actions' import { NestedValues } from './product-types-actions' import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import createMapActionGroup, { + MapActionGroup, + MapActionResult, +} from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' type SyncActionConfig = { withHints?: boolean } & BaseSyncActionConfig @@ -18,44 +21,30 @@ type SyncActionConfig = { withHints?: boolean } & BaseSyncActionConfig const actionGroups = ['base'] function createProductTypeMapActions( - mapActionGroup: ( - type: string, - fn: () => Array - ) => Array, + mapActionGroup: MapActionGroup, syncActionConfig?: SyncActionConfig -): (diff: any, next: any, previous: any, options: any) => Array { - return function doMapActions( - diff: any, - next: any, - previous: any, - options: any - ): Array { +): MapActionResult { + return function doMapActions(diff, newObj, oldObj, options) { return [ // we support only base fields for the product type, // for attributes, applying hints would be recommended - mapActionGroup( - 'base', - (): Array => - productTypeActions.actionsMapBase( - diff, - previous, - next, - syncActionConfig - ) + mapActionGroup('base', () => + productTypeActions.actionsMapBase( + diff, + oldObj, + newObj, + syncActionConfig + ) ), productTypeActions.actionsMapForHints( options.nestedValuesChanges, - previous, - next + oldObj, + newObj ), ].flat() } } -export type ProductTypeConfig = { - nestedValuesChanges: NestedValues -} - export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig @@ -65,7 +54,7 @@ export default ( mapActionGroup, syncActionConfig ) - const onBeforeApplyingDiff = null + const onBeforeApplyingDiff: any = null const buildActions = createBuildActions( diff, doMapActions, diff --git a/packages/sync-actions/src/products.ts b/packages/sync-actions/src/products.ts index f226b1c93..806f69818 100644 --- a/packages/sync-actions/src/products.ts +++ b/packages/sync-actions/src/products.ts @@ -22,7 +22,10 @@ import { import { SyncAction } from './types/update-actions' import copyEmptyArrayProps from './utils/copy-empty-array-props' import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import createMapActionGroup, { + MapActionGroup, + MapActionResult, +} from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' import findMatchingPairs from './utils/find-matching-pairs' @@ -40,16 +43,11 @@ const actionGroups = [ ] function createProductMapActions( - mapActionGroup: Function, + mapActionGroup: MapActionGroup, syncActionConfig?: SyncActionConfig -): (diff: any, newObj: any, oldObj: any, options: any) => Array { - return function doMapActions( - diff: any, - newObj: any, - oldObj: any, - options: any = {} - ): Array { - const allActions = [] +): MapActionResult { + return function doMapActions(diff, newObj, oldObj, options) { + const allActions: Array> = [] const { sameForAllAttributeNames, enableDiscounted } = options const { publish, staged } = newObj @@ -60,107 +58,76 @@ function createProductMapActions( ) allActions.push( - mapActionGroup( - 'attributes', - (): Array => - actionsMapAttributes( - diff, - oldObj, - newObj, - sameForAllAttributeNames || [], - variantHashMap - ) + mapActionGroup('attributes', () => + actionsMapAttributes( + diff, + oldObj, + newObj, + sameForAllAttributeNames || [], + variantHashMap + ) ) ) allActions.push( - mapActionGroup( - 'variants', - (): Array => actionsMapAddVariants(diff, oldObj, newObj) + mapActionGroup('variants', () => + actionsMapAddVariants(diff, oldObj, newObj) ) ) allActions.push(actionsMapMasterVariant(oldObj, newObj)) allActions.push( - mapActionGroup( - 'variants', - (): Array => - actionsMapRemoveVariants(diff, oldObj, newObj) + mapActionGroup('variants', () => + actionsMapRemoveVariants(diff, oldObj, newObj) ) ) allActions.push( - mapActionGroup( - 'base', - (): Array => - actionsMapBase(diff, oldObj, newObj, syncActionConfig) + mapActionGroup('base', () => + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) allActions.push( - mapActionGroup( - 'meta', - (): Array => actionsMapMeta(diff, oldObj, newObj) - ) + mapActionGroup('meta', () => actionsMapMeta(diff, oldObj, newObj)) ) allActions.push( - mapActionGroup( - 'references', - (): Array => actionsMapReferences(diff, oldObj, newObj) + mapActionGroup('references', () => + actionsMapReferences(diff, oldObj, newObj) ) ) allActions.push( - mapActionGroup( - 'images', - (): Array => - actionsMapImages(diff, oldObj, newObj, variantHashMap) + mapActionGroup('images', () => + actionsMapImages(diff, oldObj, newObj, variantHashMap) ) ) allActions.push( - mapActionGroup( - 'pricesCustom', - (): Array => - actionsMapPricesCustom(diff, oldObj, newObj, variantHashMap) + mapActionGroup('pricesCustom', () => + actionsMapPricesCustom(diff, oldObj, newObj, variantHashMap) ) ) allActions.push( - mapActionGroup( - 'prices', - (): Array => - actionsMapPrices( - diff, - oldObj, - newObj, - variantHashMap, - enableDiscounted - ) + mapActionGroup('prices', () => + actionsMapPrices(diff, oldObj, newObj, variantHashMap, enableDiscounted) ) ) allActions.push( - mapActionGroup( - 'categories', - (): Array => actionsMapCategories(diff) - ) + mapActionGroup('categories', () => actionsMapCategories(diff)) ) allActions.push( - mapActionGroup( - 'categories', - (): Array => actionsMapCategoryOrderHints(diff) - ) + mapActionGroup('categories', () => actionsMapCategoryOrderHints(diff)) ) allActions.push( - mapActionGroup( - 'assets', - (): Array => - actionsMapAssets(diff, oldObj, newObj, variantHashMap) + mapActionGroup('assets', () => + actionsMapAssets(diff, oldObj, newObj, variantHashMap) ) ) diff --git a/packages/sync-actions/src/projects-actions.ts b/packages/sync-actions/src/projects-actions.ts index aa7423351..fd3e22735 100644 --- a/packages/sync-actions/src/projects-actions.ts +++ b/packages/sync-actions/src/projects-actions.ts @@ -1,6 +1,8 @@ import { buildBaseAttributesActions } from './utils/common-actions' +import { ActionMapBase } from './utils/create-map-action-group' +import { UpdateAction } from '@commercetools/sdk-client-v2' -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'changeName', key: 'name' }, { action: 'changeCurrencies', key: 'currencies' }, { action: 'changeCountries', key: 'countries' }, @@ -9,17 +11,12 @@ export const baseActionsList = [ { action: 'setShippingRateInputType', key: 'shippingRateInputType' }, ] -export function actionsMapBase( - diff, - oldObj, - newObj, - config: { shouldOmitEmptyString?: boolean } = {} -) { +export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, oldObj, newObj, - shouldOmitEmptyString: config.shouldOmitEmptyString, + shouldOmitEmptyString: config?.shouldOmitEmptyString, }) } diff --git a/packages/sync-actions/src/projects.ts b/packages/sync-actions/src/projects.ts index 334f4d97e..b571bb702 100644 --- a/packages/sync-actions/src/projects.ts +++ b/packages/sync-actions/src/projects.ts @@ -3,18 +3,28 @@ import { Project, ProjectUpdateAction, } from '@commercetools/platform-sdk' -import { ActionGroup, SyncActionConfig } from '@commercetools/sdk-client-v2' +import { + ActionGroup, + SyncActionConfig, + UpdateAction, +} from '@commercetools/sdk-client-v2' import { actionsMapBase } from './projects-actions' import { SyncAction } from './types/update-actions' import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import createMapActionGroup, { + MapActionGroup, + MapActionResult, +} from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' export const actionGroups = ['base'] -function createChannelsMapActions(mapActionGroup, syncActionConfig) { +function createChannelsMapActions( + mapActionGroup: MapActionGroup, + syncActionConfig?: SyncActionConfig +): MapActionResult { return function doMapActions(diff, newObj, oldObj) { - const allActions = [] + const allActions: Array> = [] allActions.push( mapActionGroup('base', () => diff --git a/packages/sync-actions/src/quote-requests-actions.ts b/packages/sync-actions/src/quote-requests-actions.ts index 045bb1d2a..9248317fe 100644 --- a/packages/sync-actions/src/quote-requests-actions.ts +++ b/packages/sync-actions/src/quote-requests-actions.ts @@ -1,21 +1,18 @@ import { buildBaseAttributesActions } from './utils/common-actions' +import { ActionMapBase } from './utils/create-map-action-group' +import { UpdateAction } from '@commercetools/sdk-client-v2' -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'changeQuoteRequestState', key: 'quoteRequestState' }, { action: 'transitionState', key: 'state' }, ] -export function actionsMapBase( - diff, - oldObj, - newObj, - config: { shouldOmitEmptyString?: boolean } = {} -) { +export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, oldObj, newObj, - shouldOmitEmptyString: config.shouldOmitEmptyString, + shouldOmitEmptyString: config?.shouldOmitEmptyString, }) } diff --git a/packages/sync-actions/src/quote-requests.ts b/packages/sync-actions/src/quote-requests.ts index 087afb27f..bd8e1f4b2 100644 --- a/packages/sync-actions/src/quote-requests.ts +++ b/packages/sync-actions/src/quote-requests.ts @@ -11,35 +11,29 @@ import { actionsMapBase } from './quote-requests-actions' import { SyncAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import createMapActionGroup, { + MapActionGroup, + MapActionResult, +} from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' const actionGroups = ['base', 'custom'] function createQuoteRequestsMapActions( - mapActionGroup: Function, + mapActionGroup: MapActionGroup, syncActionConfig?: SyncActionConfig -): (diff: any, newObj: any, oldObj: any, options: any) => Array { - return function doMapActions( - diff: any, - newObj: any, - oldObj: any - ): Array { - const allActions = [] +): MapActionResult { + return function doMapActions(diff, newObj, oldObj) { + const allActions: Array> = [] allActions.push( - mapActionGroup( - 'base', - (): Array => - actionsMapBase(diff, oldObj, newObj, syncActionConfig) + mapActionGroup('base', () => + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) allActions.push( - mapActionGroup( - 'custom', - (): Array => actionsMapCustom(diff, newObj, oldObj) - ) + mapActionGroup('custom', () => actionsMapCustom(diff, newObj, oldObj)) ) return allActions.flat() diff --git a/packages/sync-actions/src/quotes-actions.ts b/packages/sync-actions/src/quotes-actions.ts index a6881cc64..f5e772fa7 100644 --- a/packages/sync-actions/src/quotes-actions.ts +++ b/packages/sync-actions/src/quotes-actions.ts @@ -1,22 +1,19 @@ import { buildBaseAttributesActions } from './utils/common-actions' +import { ActionMapBase } from './utils/create-map-action-group' +import { UpdateAction } from '@commercetools/sdk-client-v2' -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'changeQuoteState', key: 'quoteState' }, { action: 'requestQuoteRenegotiation', key: 'buyerComment' }, { action: 'transitionState', key: 'state' }, ] -export function actionsMapBase( - diff, - oldObj, - newObj, - config: { shouldOmitEmptyString?: boolean } = {} -) { +export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, oldObj, newObj, - shouldOmitEmptyString: config.shouldOmitEmptyString, + shouldOmitEmptyString: config?.shouldOmitEmptyString, }) } diff --git a/packages/sync-actions/src/quotes.ts b/packages/sync-actions/src/quotes.ts index be7190cd0..e9bdb0d12 100644 --- a/packages/sync-actions/src/quotes.ts +++ b/packages/sync-actions/src/quotes.ts @@ -8,35 +8,29 @@ import { actionsMapBase } from './quotes-actions' import { SyncAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import createMapActionGroup, { + MapActionGroup, + MapActionResult, +} from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' const actionGroups = ['base', 'custom'] function createQuotesMapActions( - mapActionGroup: Function, + mapActionGroup: MapActionGroup, syncActionConfig?: SyncActionConfig -): (diff: any, newObj: any, oldObj: any, options: any) => Array { - return function doMapActions( - diff: any, - newObj: any, - oldObj: any - ): Array { - const allActions = [] +): MapActionResult { + return function doMapActions(diff, newObj, oldObj) { + const allActions: Array> = [] allActions.push( - mapActionGroup( - 'base', - (): Array => - actionsMapBase(diff, oldObj, newObj, syncActionConfig) + mapActionGroup('base', () => + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) allActions.push( - mapActionGroup( - 'custom', - (): Array => actionsMapCustom(diff, newObj, oldObj) - ) + mapActionGroup('custom', () => actionsMapCustom(diff, newObj, oldObj)) ) return allActions.flat() diff --git a/packages/sync-actions/src/shipping-methods-actions.ts b/packages/sync-actions/src/shipping-methods-actions.ts index bf299318f..d5b306388 100644 --- a/packages/sync-actions/src/shipping-methods-actions.ts +++ b/packages/sync-actions/src/shipping-methods-actions.ts @@ -4,8 +4,11 @@ import createBuildArrayActions, { CHANGE_ACTIONS, REMOVE_ACTIONS, } from './utils/create-build-array-actions' +import { ActionMapBase } from './utils/create-map-action-group' +import { UpdateAction } from '@commercetools/sdk-client-v2' +import { ZoneRate } from '@commercetools/platform-sdk' -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'setKey', key: 'key' }, { action: 'changeName', key: 'name' }, { action: 'setLocalizedName', key: 'localizedName' }, @@ -16,22 +19,17 @@ export const baseActionsList = [ { action: 'changeTaxCategory', key: 'taxCategory' }, ] -export function actionsMapBase( - diff, - oldObj, - newObj, - config: { shouldOmitEmptyString?: boolean } = {} -) { +export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, oldObj, newObj, - shouldOmitEmptyString: config.shouldOmitEmptyString, + shouldOmitEmptyString: config?.shouldOmitEmptyString, }) } -const addShippingRates = (newZoneRate) => +const addShippingRates = (newZoneRate: ZoneRate) => newZoneRate.shippingRates ? newZoneRate.shippingRates.map((shippingRate) => ({ action: 'addShippingRate', @@ -40,7 +38,7 @@ const addShippingRates = (newZoneRate) => })) : [] -function actionsMapZoneRatesShippingRates(diff, oldObj, newObj) { +function actionsMapZoneRatesShippingRates(diff: any, oldObj: any, newObj: any) { const handler = createBuildArrayActions('shippingRates', { [ADD_ACTIONS]: (newShippingRate) => ({ action: 'addShippingRate', @@ -69,7 +67,7 @@ function actionsMapZoneRatesShippingRates(diff, oldObj, newObj) { return handler(diff, oldObj, newObj) } -export function actionsMapZoneRates(diff, oldObj, newObj) { +export function actionsMapZoneRates(diff: any, oldObj: any, newObj: any) { const handler = createBuildArrayActions('zoneRates', { [ADD_ACTIONS]: (newZoneRate) => [ { diff --git a/packages/sync-actions/src/shipping-methods.ts b/packages/sync-actions/src/shipping-methods.ts index 1859aa440..c9d478edc 100644 --- a/packages/sync-actions/src/shipping-methods.ts +++ b/packages/sync-actions/src/shipping-methods.ts @@ -11,39 +11,32 @@ import { actionsMapBase, actionsMapZoneRates } from './shipping-methods-actions' import { SyncAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import createMapActionGroup, { + MapActionGroup, + MapActionResult, +} from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'zoneRates', 'custom'] function createShippingMethodsMapActions( - mapActionGroup: Function, + mapActionGroup: MapActionGroup, syncActionConfig?: SyncActionConfig -): (diff: any, newObj: any, oldObj: any) => Array { - return function doMapActions( - diff: any, - newObj: any, - oldObj: any - ): Array { - const allActions = [] +): MapActionResult { + return function doMapActions(diff, newObj, oldObj) { + const allActions: Array> = [] allActions.push( - mapActionGroup( - 'base', - (): Array => - actionsMapBase(diff, oldObj, newObj, syncActionConfig) + mapActionGroup('base', () => + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) allActions.push( - mapActionGroup( - 'zoneRates', - (): Array => actionsMapZoneRates(diff, oldObj, newObj) + mapActionGroup('zoneRates', () => + actionsMapZoneRates(diff, oldObj, newObj) ).flat() ) allActions.push( - mapActionGroup( - 'custom', - (): Array => actionsMapCustom(diff, newObj, oldObj) - ) + mapActionGroup('custom', () => actionsMapCustom(diff, newObj, oldObj)) ) return allActions.flat() } diff --git a/packages/sync-actions/src/staged-quotes-actions.ts b/packages/sync-actions/src/staged-quotes-actions.ts index b454b7708..deca4d90f 100644 --- a/packages/sync-actions/src/staged-quotes-actions.ts +++ b/packages/sync-actions/src/staged-quotes-actions.ts @@ -1,23 +1,20 @@ import { buildBaseAttributesActions } from './utils/common-actions' +import { ActionMapBase } from './utils/create-map-action-group' +import { UpdateAction } from '@commercetools/sdk-client-v2' -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'changeStagedQuoteState', key: 'stagedQuoteState' }, { action: 'setSellerComment', key: 'sellerComment' }, { action: 'setValidTo', key: 'validTo' }, { action: 'transitionState', key: 'state' }, ] -export function actionsMapBase( - diff, - oldObj, - newObj, - config: { shouldOmitEmptyString?: boolean } = {} -) { +export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, oldObj, newObj, - shouldOmitEmptyString: config.shouldOmitEmptyString, + shouldOmitEmptyString: config?.shouldOmitEmptyString, }) } diff --git a/packages/sync-actions/src/staged-quotes.ts b/packages/sync-actions/src/staged-quotes.ts index 388523b96..eceef819f 100644 --- a/packages/sync-actions/src/staged-quotes.ts +++ b/packages/sync-actions/src/staged-quotes.ts @@ -12,35 +12,29 @@ import { actionsMapBase } from './staged-quotes-actions' import { SyncAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import createMapActionGroup, { + MapActionGroup, + MapActionResult, +} from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' const actionGroups = ['base', 'custom'] function createStagedQuotesMapActions( - mapActionGroup: Function, + mapActionGroup: MapActionGroup, syncActionConfig?: SyncActionConfig -): (diff: any, newObj: any, oldObj: any, options: any) => Array { - return function doMapActions( - diff: any, - newObj: any, - oldObj: any - ): Array { - const allActions = [] +): MapActionResult { + return function doMapActions(diff, newObj, oldObj) { + const allActions: Array> = [] allActions.push( - mapActionGroup( - 'base', - (): Array => - actionsMapBase(diff, oldObj, newObj, syncActionConfig) + mapActionGroup('base', () => + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) allActions.push( - mapActionGroup( - 'custom', - (): Array => actionsMapCustom(diff, newObj, oldObj) - ) + mapActionGroup('custom', () => actionsMapCustom(diff, newObj, oldObj)) ) return allActions.flat() diff --git a/packages/sync-actions/src/state-actions.ts b/packages/sync-actions/src/state-actions.ts index 809f64bf3..6cc6322f9 100644 --- a/packages/sync-actions/src/state-actions.ts +++ b/packages/sync-actions/src/state-actions.ts @@ -3,8 +3,10 @@ import createBuildArrayActions, { ADD_ACTIONS, REMOVE_ACTIONS, } from './utils/create-build-array-actions' +import { ActionMapBase } from './utils/create-map-action-group' +import { UpdateAction } from '@commercetools/sdk-client-v2' -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'changeKey', key: 'key' }, { action: 'setName', key: 'name' }, { action: 'setDescription', key: 'description' }, @@ -13,22 +15,17 @@ export const baseActionsList = [ { action: 'setTransitions', key: 'transitions' }, ] -export function actionsMapBase( - diff, - oldObj, - newObj, - config: { shouldOmitEmptyString?: boolean } = {} -) { +export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, oldObj, newObj, - shouldOmitEmptyString: config.shouldOmitEmptyString, + shouldOmitEmptyString: config?.shouldOmitEmptyString, }) } -export function actionsMapRoles(diff, oldObj, newObj) { +export function actionsMapRoles(diff: any, oldObj: any, newObj: any) { const buildArrayActions = createBuildArrayActions('roles', { [ADD_ACTIONS]: (newRole) => ({ action: 'addRoles', diff --git a/packages/sync-actions/src/states.ts b/packages/sync-actions/src/states.ts index 429d76de1..0ec80be3d 100644 --- a/packages/sync-actions/src/states.ts +++ b/packages/sync-actions/src/states.ts @@ -7,20 +7,20 @@ import type { import { actionsMapBase, actionsMapRoles } from './state-actions' import { SyncAction } from './types/update-actions' import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import createMapActionGroup, { + MapActionGroup, + MapActionResult, +} from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' -type RoleUpdate = { - action: string - roles: string -} - export const actionGroups = ['base'] // This function groups `addRoles` and `removeRoles` actions to one array -function groupRoleActions([actions]: Array): Array { - const addActionRoles = [] - const removeActionRoles = [] +function groupRoleActions([actions]: Array< + Array +>): Array { + const addActionRoles: Array = [] + const removeActionRoles: Array = [] actions.forEach((action: UpdateAction) => { if (action.action === 'removeRoles') removeActionRoles.push(action.roles) if (action.action === 'addRoles') addActionRoles.push(action.roles) @@ -32,28 +32,19 @@ function groupRoleActions([actions]: Array): Array { } function createStatesMapActions( - mapActionGroup: Function, + mapActionGroup: MapActionGroup, syncActionConfig?: SyncActionConfig -): (diff: any, newObj: any, oldObj: any) => Array { - return function doMapActions( - diff: any, - newObj: any, - oldObj: any - ): Array { - const baseActions = [] - const roleActions = [] +): MapActionResult { + return function doMapActions(diff, newObj, oldObj) { + const baseActions: Array> = [] + const roleActions: Array> = [] baseActions.push( - mapActionGroup( - 'base', - (): Array => - actionsMapBase(diff, oldObj, newObj, syncActionConfig) + mapActionGroup('base', () => + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) roleActions.push( - mapActionGroup( - 'roles', - (): Array => actionsMapRoles(diff, oldObj, newObj) - ) + mapActionGroup('roles', () => actionsMapRoles(diff, oldObj, newObj)) ) return [...baseActions, ...groupRoleActions(roleActions)].flat() } diff --git a/packages/sync-actions/src/stores-actions.ts b/packages/sync-actions/src/stores-actions.ts index 7e1ad8a6a..bec2ee4d0 100644 --- a/packages/sync-actions/src/stores-actions.ts +++ b/packages/sync-actions/src/stores-actions.ts @@ -1,13 +1,15 @@ import { buildBaseAttributesActions } from './utils/common-actions' +import { ActionMapBase } from './utils/create-map-action-group' +import { UpdateAction } from '@commercetools/sdk-client-v2' -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'setName', key: 'name' }, { action: 'setLanguages', key: 'languages' }, { action: 'setDistributionChannels', key: 'distributionChannels' }, { action: 'setSupplyChannels', key: 'supplyChannels' }, ] -export function actionsMapBase(diff, oldObj, newObj) { +export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, diff --git a/packages/sync-actions/src/stores.ts b/packages/sync-actions/src/stores.ts index f8d47ae92..f0d5afbca 100644 --- a/packages/sync-actions/src/stores.ts +++ b/packages/sync-actions/src/stores.ts @@ -43,7 +43,7 @@ export default ( ): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createStoresMapActions(mapActionGroup) - const onBeforeApplyingDiff = null + const onBeforeApplyingDiff: any = null const buildActions = createBuildActions( diff, doMapActions, diff --git a/packages/sync-actions/src/tax-categories-actions.ts b/packages/sync-actions/src/tax-categories-actions.ts index 921b2e2f4..d9d12cb9c 100644 --- a/packages/sync-actions/src/tax-categories-actions.ts +++ b/packages/sync-actions/src/tax-categories-actions.ts @@ -4,29 +4,26 @@ import createBuildArrayActions, { CHANGE_ACTIONS, REMOVE_ACTIONS, } from './utils/create-build-array-actions' +import { ActionMapBase } from './utils/create-map-action-group' +import { UpdateAction } from '@commercetools/sdk-client-v2' -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'changeName', key: 'name' }, { action: 'setKey', key: 'key' }, { action: 'setDescription', key: 'description' }, ] -export function actionsMapBase( - diff, - oldObj, - newObj, - config: { shouldOmitEmptyString?: boolean } = {} -) { +export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, oldObj, newObj, - shouldOmitEmptyString: config.shouldOmitEmptyString, + shouldOmitEmptyString: config?.shouldOmitEmptyString, }) } -export function actionsMapRates(diff, oldObj, newObj) { +export function actionsMapRates(diff: any, oldObj: any, newObj: any) { const handler = createBuildArrayActions('rates', { [ADD_ACTIONS]: (newObject) => ({ action: 'addTaxRate', diff --git a/packages/sync-actions/src/tax-categories.ts b/packages/sync-actions/src/tax-categories.ts index 91684d0d3..6e97a265d 100644 --- a/packages/sync-actions/src/tax-categories.ts +++ b/packages/sync-actions/src/tax-categories.ts @@ -10,36 +10,27 @@ import type { import { actionsMapBase, actionsMapRates } from './tax-categories-actions' import { SyncAction } from './types/update-actions' import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import createMapActionGroup, { + MapActionGroup, + MapActionResult, +} from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'rates'] function createTaxCategoriesMapActions( - mapActionGroup: ( - type: string, - fn: () => Array - ) => Array, + mapActionGroup: MapActionGroup, syncActionConfig?: SyncActionConfig -): (diff: any, newObj: any, oldObj: any) => Array { - return function doMapActions( - diff: any, - newObj: any, - oldObj: any - ): Array { - const allActions = [] +): MapActionResult { + return function doMapActions(diff, newObj, oldObj) { + const allActions: Array> = [] allActions.push( - mapActionGroup( - 'base', - (): Array => - actionsMapBase(diff, oldObj, newObj, syncActionConfig) + mapActionGroup('base', () => + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) allActions.push( - mapActionGroup( - 'rates', - (): Array => actionsMapRates(diff, oldObj, newObj) - ) + mapActionGroup('rates', () => actionsMapRates(diff, oldObj, newObj)) ) return allActions.flat() } diff --git a/packages/sync-actions/src/types-actions.ts b/packages/sync-actions/src/types-actions.ts index 98c927ee7..ffeadd95e 100644 --- a/packages/sync-actions/src/types-actions.ts +++ b/packages/sync-actions/src/types-actions.ts @@ -6,39 +6,36 @@ import createBuildArrayActions, { } from './utils/create-build-array-actions' import { getDeltaValue } from './utils/diffpatcher' import extractMatchingPairs from './utils/extract-matching-pairs' +import { ActionMapBase } from './utils/create-map-action-group' +import { UpdateAction } from '@commercetools/sdk-client-v2' const REGEX_NUMBER = new RegExp(/^\d+$/) const REGEX_UNDERSCORE_NUMBER = new RegExp(/^_\d+$/) -const getIsChangedOperation = (key) => REGEX_NUMBER.test(key) -const getIsRemovedOperation = (key) => REGEX_UNDERSCORE_NUMBER.test(key) +const getIsChangedOperation = (key: string) => REGEX_NUMBER.test(key) +const getIsRemovedOperation = (key: string) => REGEX_UNDERSCORE_NUMBER.test(key) -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'changeKey', key: 'key' }, { action: 'changeName', key: 'name' }, { action: 'setDescription', key: 'description' }, ] -export function actionsMapBase( - diff, - oldObj, - newObj, - config: { shouldOmitEmptyString?: boolean } = {} -) { +export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, oldObj, newObj, - shouldOmitEmptyString: config.shouldOmitEmptyString, + shouldOmitEmptyString: config?.shouldOmitEmptyString, }) } function actionsMapEnums( - fieldName, - attributeType, - attributeDiff, - previous, - next + fieldName: any, + attributeType: any, + attributeDiff: any, + previous: any, + next: any ) { const addEnumActionName = attributeType === 'Enum' ? 'addEnumValue' : 'addLocalizedEnumValue' @@ -58,7 +55,7 @@ function actionsMapEnums( }), [CHANGE_ACTIONS]: (oldEnum, newEnum) => { const oldEnumInNext = next.values.find( - (nextEnum) => nextEnum.key === oldEnum.key + (nextEnum: any) => nextEnum.key === oldEnum.key ) // These `changeActions` would impose a nested structure among @@ -72,7 +69,7 @@ function actionsMapEnums( // check if the label is changed const foundPreviousEnum = previous.values.find( - (previousEnum) => previousEnum.key === newEnum.key + (previousEnum: any) => previousEnum.key === newEnum.key ) const isLabelEqual = deepEqual(foundPreviousEnum.label, newEnum.label) @@ -103,16 +100,16 @@ function actionsMapEnums( }, }) - const actions = [] + const actions: Array = [] // following lists are necessary to ensure that when we change the // order of enumValues, we generate one updateAction instead of one at a time. - let newEnumValuesOrder = [] + let newEnumValuesOrder: Array = [] buildArrayActions(attributeDiff, previous, next) .flat() .forEach((updateAction) => { if (updateAction.action === changeEnumOrderActionName) { - newEnumValuesOrder = next.values.map((enumValue) => enumValue.key) + newEnumValuesOrder = next.values.map((enumValue: any) => enumValue.key) } else actions.push(updateAction) }) @@ -132,11 +129,11 @@ function actionsMapEnums( export function actionsMapFieldDefinitions( fieldDefinitionsDiff: { [key: string]: any }, - previous, - next, - diffPaths + previous: any, + next: any, + diffPaths: any ) { - const actions = [] + const actions: Array = [] fieldDefinitionsDiff && Object.entries(fieldDefinitionsDiff).forEach(([diffKey, diffValue]) => { const extractedPairs = extractMatchingPairs( @@ -183,7 +180,7 @@ export function actionsMapFieldDefinitions( if (diffValue.length === 3 && diffValue[2] === 3) { actions.push({ action: 'changeFieldDefinitionOrder', - fieldNames: next.map((n) => n.name), + fieldNames: next.map((n: any) => n.name), }) } else { const deltaValue = getDeltaValue(diffValue) diff --git a/packages/sync-actions/src/types.ts b/packages/sync-actions/src/types.ts index 240c3daaf..bd59bd0c4 100644 --- a/packages/sync-actions/src/types.ts +++ b/packages/sync-actions/src/types.ts @@ -1,33 +1,36 @@ import { Type, TypeUpdateAction } from '@commercetools/platform-sdk/src' -import { SyncActionConfig } from '@commercetools/sdk-client-v2' +import { SyncActionConfig, UpdateAction } from '@commercetools/sdk-client-v2' import { actionsMapBase, actionsMapFieldDefinitions } from './types-actions' import { SyncAction } from './types/update-actions' import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import createMapActionGroup, { + MapActionGroup, + MapActionResult, +} from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' import findMatchingPairs from './utils/find-matching-pairs' const actionGroups = ['base', 'fieldDefinitions'] function createTypeMapActions( - mapActionGroup, - syncActionConfig: { shouldOmitEmptyString?: boolean } -) { - return function doMapActions(diff, next, previous) { - const allActions = [] + mapActionGroup: MapActionGroup, + syncActionConfig?: SyncActionConfig +): MapActionResult { + return function doMapActions(diff, newObj, oldObj) { + const allActions: Array> = [] allActions.push( mapActionGroup('base', () => - actionsMapBase(diff, previous, next, syncActionConfig) + actionsMapBase(diff, oldObj, newObj, syncActionConfig) ), mapActionGroup('fieldDefinitions', () => actionsMapFieldDefinitions( diff.fieldDefinitions, - previous.fieldDefinitions, - next.fieldDefinitions, + oldObj.fieldDefinitions, + newObj.fieldDefinitions, findMatchingPairs( diff.fieldDefinitions, - previous.fieldDefinitions, - next.fieldDefinitions, + oldObj.fieldDefinitions, + newObj.fieldDefinitions, 'name' ) ) diff --git a/packages/sync-actions/src/utils/action-map-custom.ts b/packages/sync-actions/src/utils/action-map-custom.ts index d61f6b2c5..b753bbaae 100644 --- a/packages/sync-actions/src/utils/action-map-custom.ts +++ b/packages/sync-actions/src/utils/action-map-custom.ts @@ -1,24 +1,27 @@ import { getDeltaValue } from './diffpatcher' +import { UpdateAction } from '@commercetools/sdk-client-v2' const Actions = { setCustomType: 'setCustomType', setCustomField: 'setCustomField', } -const hasSingleCustomFieldChanged = (diff) => Array.isArray(diff.custom) -const haveMultipleCustomFieldsChanged = (diff) => Boolean(diff.custom.fields) -const hasCustomTypeChanged = (diff) => Boolean(diff.custom.type) -const extractCustomType = (diff, previousObject) => +const hasSingleCustomFieldChanged = (diff: any) => Array.isArray(diff.custom) +const haveMultipleCustomFieldsChanged = (diff: any) => + Boolean(diff.custom.fields) +const hasCustomTypeChanged = (diff: any) => Boolean(diff.custom.type) +const extractCustomType = (diff: any, previousObject: any) => Array.isArray(diff.custom.type) ? getDeltaValue(diff.custom.type, previousObject) : diff.custom.type -const extractTypeId = (type, nextObject) => +const extractTypeId = (type: any, nextObject: any) => Array.isArray(type.id) ? getDeltaValue(type.id) : nextObject.custom.type.id -const extractTypeKey = (type, nextObject) => +const extractTypeKey = (type: any, nextObject: any) => Array.isArray(type.key) ? getDeltaValue(type.key) : nextObject.custom.type.key -const extractTypeFields = (diffedFields, nextFields) => +const extractTypeFields = (diffedFields: any, nextFields: any) => Array.isArray(diffedFields) ? getDeltaValue(diffedFields) : nextFields -const extractFieldValue = (newFields, fieldName) => newFields[fieldName] +const extractFieldValue = (newFields: any, fieldName: string) => + newFields[fieldName] export default function actionsMapCustom( diff: any, @@ -28,7 +31,7 @@ export default function actionsMapCustom( actions: {}, } ) { - const actions = [] + const actions: Array = [] const { actions: customPropsActions, ...options } = customProps const actionGroup = { ...Actions, ...customPropsActions } diff --git a/packages/sync-actions/src/utils/clone.ts b/packages/sync-actions/src/utils/clone.ts index c28a356f5..315a6ba74 100644 --- a/packages/sync-actions/src/utils/clone.ts +++ b/packages/sync-actions/src/utils/clone.ts @@ -1,4 +1,4 @@ -export default function clone(obj) { +export default function clone(obj: any) { return JSON.parse(JSON.stringify(obj)) } diff --git a/packages/sync-actions/src/utils/combine-validity-actions.ts b/packages/sync-actions/src/utils/combine-validity-actions.ts index 4cb6b7222..24fb3c459 100644 --- a/packages/sync-actions/src/utils/combine-validity-actions.ts +++ b/packages/sync-actions/src/utils/combine-validity-actions.ts @@ -1,8 +1,13 @@ +import { UpdateAction } from '@commercetools/sdk-client-v2' + const validityActions = ['setValidFrom', 'setValidUntil'] -const isValidityActions = (actionName) => validityActions.includes(actionName) +const isValidityActions = (actionName: string) => + validityActions.includes(actionName) -export default function combineValidityActions(actions = []) { +export default function combineValidityActions( + actions: Array = [] +) { const [setValidFromAction, setValidUntilAction] = actions.filter((item) => isValidityActions(item.action) ) diff --git a/packages/sync-actions/src/utils/common-actions.ts b/packages/sync-actions/src/utils/common-actions.ts index 8a170a685..a728083a8 100644 --- a/packages/sync-actions/src/utils/common-actions.ts +++ b/packages/sync-actions/src/utils/common-actions.ts @@ -1,22 +1,23 @@ import clone, { notEmpty } from './clone' import { getDeltaValue, patch } from './diffpatcher' +import { UpdateAction } from '@commercetools/sdk-client-v2' -const normalizeValue = (value) => +const normalizeValue = (value: any) => typeof value === 'string' ? value.trim() : value -export const createIsEmptyValue = (emptyValues) => (value) => +export const createIsEmptyValue = (emptyValues: Array) => (value: any) => emptyValues.some((emptyValue) => emptyValue === normalizeValue(value)) /** * Builds actions for simple object properties, given a list of actions * E.g. [{ action: `changeName`, key: 'name' }] * - * @param {Array} options.actions - a list of actions to be built + * @param {Array} actions - a list of actions to be built * based on the given property - * @param {Object} options.diff - the diff object - * @param {Object} options.oldObj - the object that needs to be updated - * @param {Object} options.newObj - the new representation of the object - * @param {Boolean} options.shouldOmitEmptyString - a flag to determine if we should treat an empty string a NON-value + * @param {Object} diff - the diff object + * @param {Object} oldObj - the object that needs to be updated + * @param {Object} newObj - the new representation of the object + * @param {Boolean} shouldOmitEmptyString - a flag to determine if we should treat an empty string a NON-value */ export function buildBaseAttributesActions({ actions, @@ -25,12 +26,12 @@ export function buildBaseAttributesActions({ newObj, shouldOmitEmptyString, }: { - actions: Array + actions: Array diff: any oldObj: any newObj: any shouldOmitEmptyString?: boolean -}) { +}): Array { const isEmptyValue = createIsEmptyValue( shouldOmitEmptyString ? [undefined, null, ''] : [undefined, null] ) @@ -70,13 +71,23 @@ export function buildBaseAttributesActions({ * Builds actions for simple reference objects, given a list of actions * E.g. [{ action: `setTaxCategory`, key: 'taxCategory' }] * - * @param {Array} options.actions - a list of actions to be built + * @param {Array} actions - a list of actions to be built * based on the given property - * @param {Object} options.diff - the diff object - * @param {Object} options.oldObj - the object that needs to be updated - * @param {Object} options.newObj - the new representation of the object + * @param {Object} diff - the diff object + * @param {Object} oldObj - the object that needs to be updated + * @param {Object} newObj - the new representation of the object */ -export function buildReferenceActions({ actions, diff, oldObj, newObj }) { +export function buildReferenceActions({ + actions, + diff, + oldObj, + newObj, +}: { + actions: Array + diff: any + oldObj: any + newObj: any +}): Array<{ action: string }> { return actions .map((item) => { const action = item.action diff --git a/packages/sync-actions/src/utils/copy-empty-array-props.ts b/packages/sync-actions/src/utils/copy-empty-array-props.ts index cc9f6a7b5..299e2981a 100644 --- a/packages/sync-actions/src/utils/copy-empty-array-props.ts +++ b/packages/sync-actions/src/utils/copy-empty-array-props.ts @@ -8,7 +8,10 @@ const CUSTOM = 'custom' * @param {Object} newObj * @returns {Array} Ordered Array [oldObj, newObj] */ -export default function copyEmptyArrayProps(oldObj = {}, newObj = {}) { +export default function copyEmptyArrayProps( + oldObj: any = {}, + newObj: any = {} +): Array { if (oldObj && newObj) { const nextObjectWithEmptyArray = Object.entries(oldObj).reduce( (merged, [key, value]) => { diff --git a/packages/sync-actions/src/utils/create-build-actions.ts b/packages/sync-actions/src/utils/create-build-actions.ts index c03becb09..31c558c43 100644 --- a/packages/sync-actions/src/utils/create-build-actions.ts +++ b/packages/sync-actions/src/utils/create-build-actions.ts @@ -1,12 +1,18 @@ import { UpdateAction } from '@commercetools/sdk-client-v2' import { deepEqual } from 'fast-equals' import { DeepPartial } from '../types/update-actions' +import { Price, ProductVariant } from '@commercetools/platform-sdk' +import { MapActionResult } from './create-map-action-group' -function applyOnBeforeDiff(before, now, fn?: (before, now) => Array) { +function applyOnBeforeDiff( + before: any, + now: any, + fn?: (before: any, now: any) => Array +) { return fn && typeof fn === 'function' ? fn(before, now) : [before, now] } -const createPriceComparator = (price) => ({ +const createPriceComparator = (price: Price) => ({ value: { currencyCode: price.value.currencyCode }, channel: price.channel, country: price.country, @@ -15,13 +21,16 @@ const createPriceComparator = (price) => ({ validUntil: price.validUntil, }) -function arePricesStructurallyEqual(oldPrice, newPrice) { +function arePricesStructurallyEqual(oldPrice: Price, newPrice: Price) { const oldPriceComparison = createPriceComparator(oldPrice) const newPriceComparison = createPriceComparator(newPrice) return deepEqual(newPriceComparison, oldPriceComparison) } -function extractPriceFromPreviousVariant(newPrice, previousVariant) { +function extractPriceFromPreviousVariant( + newPrice: Price, + previousVariant?: ProductVariant +) { if (!previousVariant) return null const price = previousVariant.prices.find((oldPrice) => arePricesStructurallyEqual(oldPrice, newPrice) @@ -29,7 +38,10 @@ function extractPriceFromPreviousVariant(newPrice, previousVariant) { return price || null } -function injectMissingPriceIds(nextVariants, previousVariants) { +function injectMissingPriceIds( + nextVariants: Array, + previousVariants: Array +) { return nextVariants.map((newVariant) => { const { prices, ...restOfVariant } = newVariant @@ -44,7 +56,7 @@ function injectMissingPriceIds(nextVariants, previousVariants) { return { ...restOfVariant, prices: prices.map((price) => { - const newPrice = { ...price } + let newPrice: any = { ...price } const oldPrice = extractPriceFromPreviousVariant(price, oldVariant) if (oldPrice) { @@ -69,8 +81,8 @@ function injectMissingPriceIds(nextVariants, previousVariants) { } export default function createBuildActions( - differ, - doMapActions, + differ: any, + doMapActions: any, onBeforeDiff?: (before: DeepPartial, now: DeepPartial) => Array, buildActionsConfig: any = {} ) { diff --git a/packages/sync-actions/src/utils/create-build-array-actions.ts b/packages/sync-actions/src/utils/create-build-array-actions.ts index b752b630c..526e7142f 100644 --- a/packages/sync-actions/src/utils/create-build-array-actions.ts +++ b/packages/sync-actions/src/utils/create-build-array-actions.ts @@ -1,3 +1,5 @@ +import { UpdateAction } from '@commercetools/sdk-client-v2' + const REGEX_NUMBER = new RegExp(/^\d+$/) const REGEX_UNDERSCORE_NUMBER = new RegExp(/^_\d+$/) @@ -17,7 +19,7 @@ export const CHANGE_ACTIONS = 'change' * @return {Boolean} Returns true if delta represents a create action, * false otherwise */ -function isCreateAction(obj, key) { +function isCreateAction(obj: { [key: string]: any }, key: string): boolean { return ( REGEX_NUMBER.test(key) && Array.isArray(obj[key]) && obj[key].length === 1 ) @@ -37,7 +39,7 @@ function isCreateAction(obj, key) { * @return {Boolean} Returns true if delta represents a change action, * false otherwise */ -function isChangeAction(obj, key) { +function isChangeAction(obj: any, key: string): boolean { return ( REGEX_NUMBER.test(key) && (typeof obj[key] === 'object' || typeof obj[key] === 'string') @@ -56,7 +58,7 @@ function isChangeAction(obj, key) { * @return {Boolean} Returns true if delta represents a remove action, * false otherwise */ -function isRemoveAction(obj, key) { +function isRemoveAction(obj: any, key: string): boolean { return ( REGEX_UNDERSCORE_NUMBER.test(key) && Array.isArray(obj[key]) && @@ -77,11 +79,29 @@ function isRemoveAction(obj, key) { * return an action object. * @return {Array} The generated array of actions */ -export default function createBuildArrayActions(key, config) { - return function buildArrayActions(diff, oldObj, newObj) { - const addActions = [] - const removeActions = [] - const changeActions = [] +export default function createBuildArrayActions( + key: string, + config: { + [ADD_ACTIONS]?: ( + newItem: any, + key?: number + ) => UpdateAction | Array + [REMOVE_ACTIONS]?: (oldItem: any, key?: number) => UpdateAction + [CHANGE_ACTIONS]?: ( + oldAsset: any, + newAsset: any, + key?: number + ) => UpdateAction | Array + } +) { + return function buildArrayActions( + diff: any, + oldObj: any, + newObj: any + ): Array { + let addActions: Array = [] + const removeActions: Array = [] + let changeActions: Array = [] if (diff[key]) { const arrayDelta = diff[key] @@ -95,7 +115,13 @@ export default function createBuildArrayActions(key, config) { parseInt(index, 10) ) - if (action) addActions.push(action) + if (action) { + if (Array.isArray(action)) { + addActions = addActions.concat(action) + } else { + addActions.push(action) + } + } } else if ( config[CHANGE_ACTIONS] && isChangeAction(arrayDelta, index) @@ -108,7 +134,13 @@ export default function createBuildArrayActions(key, config) { parseInt(index, 10) ) - if (action) changeActions.push(action) + if (action) { + if (Array.isArray(action)) { + changeActions = changeActions.concat(action) + } else { + changeActions.push(action) + } + } } else if ( config[REMOVE_ACTIONS] && isRemoveAction(arrayDelta, index) diff --git a/packages/sync-actions/src/utils/create-map-action-group.ts b/packages/sync-actions/src/utils/create-map-action-group.ts index a4cf8bb24..f22463966 100644 --- a/packages/sync-actions/src/utils/create-map-action-group.ts +++ b/packages/sync-actions/src/utils/create-map-action-group.ts @@ -5,12 +5,34 @@ // { type: 'prices', group: 'allow' }, // { type: 'variants', group: 'ignore' }, // ] -import { ActionGroup } from '@commercetools/sdk-client-v2' +import { ActionGroup, UpdateAction } from '@commercetools/sdk-client-v2' + +export type MapActionGroup = ( + type: string, + fn: () => Array +) => Array + +export type MapActionResult = ( + diff: any, + newObj: any, + oldObj: any, + config?: any +) => Array + +export type ActionMapBase = ( + diff: any, + oldObj: any, + newObj: any, + config?: { shouldOmitEmptyString?: boolean; [key: string]: any } +) => Array export default function createMapActionGroup( actionGroups: Array = [] -) { - return function mapActionGroup(type: string, fn: () => any) { +): MapActionGroup { + return function mapActionGroup( + type: string, + fn: () => Array + ): Array { if (!Object.keys(actionGroups).length) return fn() const found = actionGroups.find((c) => c.type === type) diff --git a/packages/sync-actions/src/utils/diffpatcher.ts b/packages/sync-actions/src/utils/diffpatcher.ts index 42dabb8ee..3530ebee8 100644 --- a/packages/sync-actions/src/utils/diffpatcher.ts +++ b/packages/sync-actions/src/utils/diffpatcher.ts @@ -3,7 +3,7 @@ // TODO create an issue here https://github.com/benjamine/jsondiffpatch/issues/new const DiffPatcher = require('jsondiffpatch').DiffPatcher -export function objectHash(obj, index) { +export function objectHash(obj: any, index: any) { const objIndex = `$$index:${index}` return typeof obj === 'object' && obj !== null ? obj.id || obj.name || obj.url || objIndex @@ -31,15 +31,15 @@ const diffpatcher = new DiffPatcher({ }, }) -export function diff(oldObj, newObj) { +export function diff(oldObj: any, newObj: any) { return diffpatcher.diff(oldObj, newObj) } -export function patch(obj, delta) { +export function patch(obj: any, delta: any) { return diffpatcher.patch(obj, delta) } -export function getDeltaValue(arr, originalObject?: any) { +export function getDeltaValue(arr: Array | any, originalObject?: any) { if (!Array.isArray(arr)) throw new Error('Expected array to extract delta value') diff --git a/packages/sync-actions/src/utils/extract-matching-pairs.ts b/packages/sync-actions/src/utils/extract-matching-pairs.ts index 2818eb54a..b871ff651 100644 --- a/packages/sync-actions/src/utils/extract-matching-pairs.ts +++ b/packages/sync-actions/src/utils/extract-matching-pairs.ts @@ -1,4 +1,9 @@ -export default function extractMatchingPairs(hashMap, key, before, now) { +export default function extractMatchingPairs( + hashMap: any, + key: string, + before: any, + now: any +) { let oldObjPos let newObjPos let oldObj diff --git a/packages/sync-actions/src/utils/find-matching-pairs.ts b/packages/sync-actions/src/utils/find-matching-pairs.ts index f1abbf8a3..9e7c75b49 100644 --- a/packages/sync-actions/src/utils/find-matching-pairs.ts +++ b/packages/sync-actions/src/utils/find-matching-pairs.ts @@ -1,7 +1,7 @@ const REGEX_NUMBER = new RegExp(/^\d+$/) const REGEX_UNDERSCORE_NUMBER = new RegExp(/^_\d+$/) -function preProcessCollection(collection = [], identifier = 'id') { +function preProcessCollection(collection: Array = [], identifier = 'id') { return collection.reduce( (acc, currentValue, currentIndex) => { acc.refByIndex[String(currentIndex)] = currentValue[identifier] @@ -17,10 +17,10 @@ function preProcessCollection(collection = [], identifier = 'id') { // creates a hash of a location of an item in collection1 and collection2 export default function findMatchingPairs( - diff, - before = [], - now = [], - identifier = 'id' + diff: any, + before: Array = [], + now: Array = [], + identifier: string = 'id' ) { const result = {} const { diff --git a/packages/sync-actions/src/zones-actions.ts b/packages/sync-actions/src/zones-actions.ts index 0fb10c257..a033ee7be 100644 --- a/packages/sync-actions/src/zones-actions.ts +++ b/packages/sync-actions/src/zones-actions.ts @@ -4,32 +4,30 @@ import createBuildArrayActions, { CHANGE_ACTIONS, REMOVE_ACTIONS, } from './utils/create-build-array-actions' +import { UpdateAction } from '@commercetools/sdk-client-v2' +import { ActionMapBase } from './utils/create-map-action-group' +import { Location } from '@commercetools/platform-sdk' -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'changeName', key: 'name' }, { action: 'setDescription', key: 'description' }, { action: 'setKey', key: 'key' }, ] -const hasLocation = (locations, otherLocation) => +const hasLocation = (locations: Array, otherLocation: Location) => locations.some((location) => location.country === otherLocation.country) -export function actionsMapBase( - diff, - oldObj, - newObj, - config: { shouldOmitEmptyString?: boolean } = {} -) { +export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, oldObj, newObj, - shouldOmitEmptyString: config.shouldOmitEmptyString, + shouldOmitEmptyString: config?.shouldOmitEmptyString, }) } -export function actionsMapLocations(diff, oldObj, newObj) { +export function actionsMapLocations(diff: any, oldObj: any, newObj: any) { const handler = createBuildArrayActions('locations', { [ADD_ACTIONS]: (newLocation) => ({ action: 'addLocation', @@ -44,7 +42,7 @@ export function actionsMapLocations(diff, oldObj, newObj) { } : null, [CHANGE_ACTIONS]: (oldLocation, newLocation) => { - const result = [] + const result: Array = [] // We only remove the location in case that the oldLocation is not // included in the new object diff --git a/packages/sync-actions/src/zones.ts b/packages/sync-actions/src/zones.ts index 272ea3793..fd82a153a 100644 --- a/packages/sync-actions/src/zones.ts +++ b/packages/sync-actions/src/zones.ts @@ -6,37 +6,29 @@ import type { } from '@commercetools/sdk-client-v2' import { SyncAction } from './types/update-actions' import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import createMapActionGroup, { + MapActionGroup, + MapActionResult, +} from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' import * as zonesActions from './zones-actions' export const actionGroups = ['base', 'locations'] function createZonesMapActions( - mapActionGroup: ( - type: string, - fn: () => Array - ) => Array, + mapActionGroup: MapActionGroup, syncActionConfig?: SyncActionConfig -): (diff: any, next: any, previous: any) => Array { - return function doMapActions( - diff: any, - newObj: any, - oldObj: any - ): Array { - const allActions = [] +): MapActionResult { + return function doMapActions(diff, newObj, oldObj) { + const allActions: Array> = [] allActions.push( - mapActionGroup( - 'base', - (): Array => - zonesActions.actionsMapBase(diff, oldObj, newObj, syncActionConfig) + mapActionGroup('base', () => + zonesActions.actionsMapBase(diff, oldObj, newObj, syncActionConfig) ) ) allActions.push( - mapActionGroup( - 'locations', - (): Array => - zonesActions.actionsMapLocations(diff, oldObj, newObj) + mapActionGroup('locations', () => + zonesActions.actionsMapLocations(diff, oldObj, newObj) ).flat() ) return allActions.flat() From 1ea94c89a564f8f2cc91485aacd3f642648e682e Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Thu, 9 Nov 2023 17:39:51 +0100 Subject: [PATCH 23/33] feat(migrate): latest version of jsondiffpatch --- packages/sync-actions/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/sync-actions/package.json b/packages/sync-actions/package.json index 9d1e394c0..72b6f8e07 100644 --- a/packages/sync-actions/package.json +++ b/packages/sync-actions/package.json @@ -24,7 +24,7 @@ }, "dependencies": { "fast-equals": "^2.0.0", - "jsondiffpatch": "^0.4.0" + "jsondiffpatch": "^0.5.0" }, "files": ["dist", "CHANGELOG.md"], "author": "Nicola Molinari (https://github.com/emmenko)", From 53afc44c9445cf523c0f328efc33af90168c3dd0 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Fri, 23 Aug 2024 18:11:01 +0200 Subject: [PATCH 24/33] chore: latest yarn.lock after rebase --- yarn.lock | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/yarn.lock b/yarn.lock index 1d9f4bde9..f15f0b427 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4282,6 +4282,14 @@ chalk@^2.1.0, chalk@^2.4.2: escape-string-regexp "^1.0.5" supports-color "^5.3.0" +chalk@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/chalk/-/chalk-3.0.0.tgz#3f73c2bf526591f574cc492c51e2456349f844e4" + integrity sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg== + dependencies: + ansi-styles "^4.1.0" + supports-color "^7.1.0" + chalk@^4.0.0, chalk@^4.1.0, chalk@^4.1.2: version "4.1.2" resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.2.tgz#aac4e2b7734a740867aeb16bf02aad556a1e7a01" @@ -4808,6 +4816,11 @@ detect-newline@^3.0.0: resolved "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz" integrity sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA== +diff-match-patch@^1.0.0: + version "1.0.5" + resolved "https://registry.yarnpkg.com/diff-match-patch/-/diff-match-patch-1.0.5.tgz#abb584d5f10cd1196dfc55aa03701592ae3f7b37" + integrity sha512-IayShXAgj/QMXgB0IWmKx+rOPuGMhqm5w6jvFxmVenXKIzRqTAAsbBPT3kWQeGANj3jGgvcvv4yK6SxqYmikgw== + diff-sequences@^29.6.3: version "29.6.3" resolved "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz" @@ -5221,6 +5234,11 @@ fast-deep-equal@^3.1.1, fast-deep-equal@^3.1.3: resolved "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz" integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q== +fast-equals@^2.0.0: + version "2.0.4" + resolved "https://registry.yarnpkg.com/fast-equals/-/fast-equals-2.0.4.tgz#3add9410585e2d7364c2deeb6a707beadb24b927" + integrity sha512-caj/ZmjHljPrZtbzJ3kfH5ia/k4mTJe/qSiXAGzxZWRZgsgDV0cvNaQULqUX8t0/JVlzzEdYOwCN5DmzTxoD4w== + fast-glob@^3.0.3, fast-glob@^3.2.11, fast-glob@^3.2.4, fast-glob@^3.2.9: version "3.3.2" resolved "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.2.tgz" @@ -6653,6 +6671,14 @@ jsonc-parser@^3.2.0: resolved "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.2.1.tgz" integrity sha512-AilxAyFOAcK5wA1+LeaySVBrHsGQvUFCDWXKpZjzaL0PqW+xfBOttn8GNtWKFWqneyMZj41MWF9Kl6iPWLwgOA== +jsondiffpatch@^0.5.0: + version "0.5.0" + resolved "https://registry.yarnpkg.com/jsondiffpatch/-/jsondiffpatch-0.5.0.tgz#f9795416022685a3ba7eced11a338c5cb0cf66f4" + integrity sha512-Quz3MvAwHxVYNXsOByL7xI5EB2WYOeFswqaHIA3qOK3isRWTxiplBEocmmru6XmxDB2L7jDNYtYA4FyimoAFEw== + dependencies: + chalk "^3.0.0" + diff-match-patch "^1.0.0" + jsonfile@^4.0.0: version "4.0.0" resolved "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz" From eb6438f419d107c912ebadb543675a2d22d60b1e Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Fri, 23 Aug 2024 18:42:37 +0200 Subject: [PATCH 25/33] feat(migrate): incorporate latest changes --- .../src/discount-codes-actions.ts | 1 + packages/sync-actions/src/projects-actions.ts | 9 ++ .../src/shipping-methods-actions.ts | 1 + .../test/discount-codes-sync.spec.ts | 29 ++++++ .../sync-actions/test/projects-sync.spec.ts | 94 +++++++++++++++++++ .../test/shipping-methods.spec.ts | 35 +++++++ 6 files changed, 169 insertions(+) diff --git a/packages/sync-actions/src/discount-codes-actions.ts b/packages/sync-actions/src/discount-codes-actions.ts index 203d05974..2b6ab8f61 100644 --- a/packages/sync-actions/src/discount-codes-actions.ts +++ b/packages/sync-actions/src/discount-codes-actions.ts @@ -6,6 +6,7 @@ export const baseActionsList: Array = [ { action: 'changeIsActive', key: 'isActive' }, { action: 'setName', key: 'name' }, { action: 'setDescription', key: 'description' }, + { action: 'setKey', key: 'key' }, { action: 'setCartPredicate', key: 'cartPredicate' }, { action: 'setMaxApplications', key: 'maxApplications' }, { diff --git a/packages/sync-actions/src/projects-actions.ts b/packages/sync-actions/src/projects-actions.ts index fd3e22735..a5776949c 100644 --- a/packages/sync-actions/src/projects-actions.ts +++ b/packages/sync-actions/src/projects-actions.ts @@ -9,6 +9,15 @@ export const baseActionsList: Array = [ { action: 'changeLanguages', key: 'languages' }, { action: 'changeMessagesConfiguration', key: 'messagesConfiguration' }, { action: 'setShippingRateInputType', key: 'shippingRateInputType' }, + { + action: 'changeMyBusinessUnitStatusOnCreation', + key: 'myBusinessUnitStatusOnCreation', + }, + { + action: 'setMyBusinessUnitAssociateRoleOnCreation', + key: 'myBusinessUnitAssociateRoleOnCreation', + }, + { action: 'changeCustomerSearchStatus', key: 'customerSearchStatus' }, ] export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { diff --git a/packages/sync-actions/src/shipping-methods-actions.ts b/packages/sync-actions/src/shipping-methods-actions.ts index d5b306388..c1b1dae9b 100644 --- a/packages/sync-actions/src/shipping-methods-actions.ts +++ b/packages/sync-actions/src/shipping-methods-actions.ts @@ -17,6 +17,7 @@ export const baseActionsList: Array = [ { action: 'changeIsDefault', key: 'isDefault' }, { action: 'setPredicate', key: 'predicate' }, { action: 'changeTaxCategory', key: 'taxCategory' }, + { action: 'changeActive', key: 'active' }, ] export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { diff --git a/packages/sync-actions/test/discount-codes-sync.spec.ts b/packages/sync-actions/test/discount-codes-sync.spec.ts index 328e14be6..7f8163adc 100644 --- a/packages/sync-actions/test/discount-codes-sync.spec.ts +++ b/packages/sync-actions/test/discount-codes-sync.spec.ts @@ -32,6 +32,17 @@ describe('Exports', () => { ) }) + test('should contain `setKey` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'setKey', + key: 'key', + }, + ]) + ) + }) + test('should contain `setMaxApplications` action', () => { expect(baseActionsList).toEqual( expect.arrayContaining([ @@ -140,6 +151,24 @@ describe('Actions', () => { expect(actual).toEqual(expected) }) + test('should build `setKey` action', () => { + const before = { + key: 'old-key', + } + const now = { + key: 'new-key', + } + + const actual = discountCodesSync.buildActions(now, before) + const expected = [ + { + action: 'setKey', + key: 'new-key', + }, + ] + expect(actual).toEqual(expected) + }) + test('should build `setCartPredicate` action', () => { const before = { cartPredicate: 'old-cart-predicate' } const now = { cartPredicate: 'new-cart-predicate' } diff --git a/packages/sync-actions/test/projects-sync.spec.ts b/packages/sync-actions/test/projects-sync.spec.ts index b08721c87..65122c1f5 100644 --- a/packages/sync-actions/test/projects-sync.spec.ts +++ b/packages/sync-actions/test/projects-sync.spec.ts @@ -66,6 +66,39 @@ describe('Exports', () => { ]) ) }) + + test('should contain `changeMyBusinessUnitStatusOnCreation` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'changeMyBusinessUnitStatusOnCreation', + key: 'myBusinessUnitStatusOnCreation', + }, + ]) + ) + }) + + test('should contain `setMyBusinessUnitAssociateRoleOnCreation` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'setMyBusinessUnitAssociateRoleOnCreation', + key: 'myBusinessUnitAssociateRoleOnCreation', + }, + ]) + ) + }) + + test('should contain `changeCustomerSearchStatus` action', () => { + expect(baseActionsList).toEqual( + expect.arrayContaining([ + { + action: 'changeCustomerSearchStatus', + key: 'customerSearchStatus', + }, + ]) + ) + }) }) }) @@ -218,4 +251,65 @@ describe('Actions', () => { ] expect(actual).toEqual(expected) }) + + test('should build `changeMyBusinessUnitStatusOnCreation` action', () => { + const before = { + myBusinessUnitStatusOnCreation: 'Active', + } + const now = { + myBusinessUnitStatusOnCreation: 'Deactive', + } + // @ts-ignore + const actual = projectsSync.buildActions(now, before) + const expected = [ + { + action: 'changeMyBusinessUnitStatusOnCreation', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `setMyBusinessUnitAssociateRoleOnCreation` action', () => { + const before = { + myBusinessUnitAssociateRoleOnCreation: { + typeId: 'associate-role', + key: 'old-role', + }, + } + const now = { + myBusinessUnitAssociateRoleOnCreation: { + typeId: 'associate-role', + key: 'new-role', + }, + } + // @ts-ignore + const actual = projectsSync.buildActions(now, before) + const expected = [ + { + action: 'setMyBusinessUnitAssociateRoleOnCreation', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) + + test('should build `changeCustomerSearchStatus` action', () => { + const before = { + customerSearchStatus: 'Activated', + } + const now = { + customerSearchStatus: 'Deactivated', + } + + // @ts-ignore + const actual = projectsSync.buildActions(now, before) + const expected = [ + { + action: 'changeCustomerSearchStatus', + ...now, + }, + ] + expect(actual).toEqual(expected) + }) }) diff --git a/packages/sync-actions/test/shipping-methods.spec.ts b/packages/sync-actions/test/shipping-methods.spec.ts index f8d32beb6..8a2375073 100644 --- a/packages/sync-actions/test/shipping-methods.spec.ts +++ b/packages/sync-actions/test/shipping-methods.spec.ts @@ -18,6 +18,7 @@ describe('Exports', () => { { action: 'changeIsDefault', key: 'isDefault' }, { action: 'setPredicate', key: 'predicate' }, { action: 'changeTaxCategory', key: 'taxCategory' }, + { action: 'changeActive', key: 'active' }, ]) }) }) @@ -60,6 +61,24 @@ describe('Actions', () => { expect(actual).toEqual(expected) }) + test('should build `changeActive` action', () => { + const before = { + active: false, + } + const now = { + active: true, + } + + const actual = shippingMethodsSync.buildActions(now, before) + const expected = [ + { + action: 'changeActive', + active: now.active, + }, + ] + expect(actual).toEqual(expected) + }) + test('should build `setLocalizedName` action', () => { const before = { localizedName: { @@ -170,6 +189,7 @@ describe('Actions', () => { predicate: 'id is not defined', } + // @ts-ignore const actual = shippingMethodsSync.buildActions(now, before) const expected = [ { @@ -188,6 +208,7 @@ describe('Actions', () => { taxCategory: { typeId: 'tax-category', id: 'id2' }, } + // @ts-ignore const actual = shippingMethodsSync.buildActions(now, before) const expected = [ { action: 'changeTaxCategory', taxCategory: now.taxCategory }, @@ -208,6 +229,7 @@ describe('Actions', () => { ], } + // @ts-ignore const actual = shippingMethodsSync.buildActions(now, before) const expected = [{ action: 'addZone', zone: now.zoneRates[1].zone }] expect(actual).toEqual(expected) @@ -226,6 +248,7 @@ describe('Actions', () => { ], } + // @ts-ignore const actual = shippingMethodsSync.buildActions(now, before) const expected = [ { action: 'addZone', zone: now.zoneRates[1].zone }, @@ -248,6 +271,7 @@ describe('Actions', () => { zoneRates: [{ zone: { typeId: 'zone', id: 'z1' } }], } + // @ts-ignore const actual = shippingMethodsSync.buildActions(now, before) const expected = [ { action: 'removeZone', zone: before.zoneRates[1].zone }, @@ -267,6 +291,7 @@ describe('Actions', () => { zoneRates: [], } + // @ts-ignore const actual = shippingMethodsSync.buildActions(now, before) const expected = [ { action: 'removeZone', zone: before.zoneRates[0].zone }, @@ -298,6 +323,7 @@ describe('Actions', () => { ], } + // @ts-ignore const actual = shippingMethodsSync.buildActions(now, before) const expected = [ { @@ -325,6 +351,7 @@ describe('Actions', () => { ], } + // @ts-ignore const actual = shippingMethodsSync.buildActions(now, before) const expected = [ { @@ -367,6 +394,7 @@ describe('Actions', () => { ], } + // @ts-ignore const actual = shippingMethodsSync.buildActions(now, before) const expected = [ { @@ -399,6 +427,7 @@ describe('Actions', () => { ], } + // @ts-ignore const actual = shippingMethodsSync.buildActions(now, before) const expected = [ { @@ -433,6 +462,7 @@ describe('Actions', () => { ], } + // @ts-ignore const actual = shippingMethodsSync.buildActions(now, before) const expected = [ { action: 'removeZone', zone: before.zoneRates[0].zone }, @@ -471,6 +501,7 @@ describe('Actions', () => { ], } + // @ts-ignore const actual = shippingMethodsSync.buildActions(now, before) const expected = [ { @@ -514,6 +545,7 @@ describe('Actions', () => { ], } + // @ts-ignore const actual = shippingMethodsSync.buildActions(now, before) const expected = [ { @@ -564,6 +596,7 @@ describe('Actions', () => { ], } + // @ts-ignore const actual = shippingMethodsSync.buildActions(now, before) const expected = [ { action: 'addZone', zone: now.zoneRates[1].zone }, @@ -606,6 +639,7 @@ describe('Actions', () => { }, }, } + // @ts-ignore const actual = shippingMethodsSync.buildActions(now, before) const expected = [{ action: 'setCustomType', ...now.custom }] expect(actual).toEqual(expected) @@ -634,6 +668,7 @@ describe('Actions', () => { }, }, } + // @ts-ignore const actual = shippingMethodsSync.buildActions(now, before) const expected = [ { From 86080edc927fb7bf91c41c1a4e1ab54c8f637142 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Thu, 29 Aug 2024 14:34:32 +0200 Subject: [PATCH 26/33] feat(migrate): incorporate latest changes and added types --- .../src/attribute-groups-actions.ts | 4 +- packages/sync-actions/src/categories.ts | 2 +- packages/sync-actions/src/category-actions.ts | 6 +- .../src/category-assets-actions.ts | 3 +- packages/sync-actions/src/customer-actions.ts | 37 ++-- .../sync-actions/src/inventory-actions.ts | 4 +- packages/sync-actions/src/order-actions.ts | 18 +- packages/sync-actions/src/product-actions.ts | 30 +-- .../sync-actions/src/product-selections.ts | 11 +- packages/sync-actions/src/projects-actions.ts | 45 ++++- packages/sync-actions/src/projects.ts | 40 ++-- .../src/shipping-methods-actions.ts | 6 +- packages/sync-actions/src/state-actions.ts | 4 +- packages/sync-actions/src/stores.ts | 11 +- .../src/tax-categories-actions.ts | 4 +- packages/sync-actions/src/types-actions.ts | 4 +- .../src/utils/action-map-custom.ts | 12 +- .../sync-actions/src/utils/common-actions.ts | 6 +- .../src/utils/create-build-actions.ts | 2 +- .../src/utils/create-build-array-actions.ts | 4 +- .../src/utils/create-map-action-group.ts | 11 +- .../sync-actions/src/utils/diffpatcher.ts | 5 +- .../src/utils/find-matching-pairs.ts | 4 +- packages/sync-actions/src/zones-actions.ts | 4 +- .../sync-actions/test/projects-sync.spec.ts | 184 +++++++++++------- .../test/utils/find-matching-pairs.spec.ts | 3 +- packages/sync-actions/tsconfig.json | 9 + 27 files changed, 297 insertions(+), 176 deletions(-) create mode 100644 packages/sync-actions/tsconfig.json diff --git a/packages/sync-actions/src/attribute-groups-actions.ts b/packages/sync-actions/src/attribute-groups-actions.ts index 27d324a64..31be18ebe 100644 --- a/packages/sync-actions/src/attribute-groups-actions.ts +++ b/packages/sync-actions/src/attribute-groups-actions.ts @@ -5,7 +5,7 @@ import createBuildArrayActions, { REMOVE_ACTIONS, } from './utils/create-build-array-actions' import { UpdateAction } from '@commercetools/sdk-client-v2' -import { ActionMapBase } from './utils/create-map-action-group' +import { ActionMap, ActionMapBase } from './utils/create-map-action-group' import { AttributeReference } from '@commercetools/platform-sdk/src' const hasAttribute = ( @@ -29,7 +29,7 @@ export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { }) } -export function actionsMapAttributes(diff: any, oldObj: any, newObj: any) { +export const actionsMapAttributes: ActionMap = (diff, oldObj, newObj) => { const handler = createBuildArrayActions('attributes', { [ADD_ACTIONS]: (newAttribute) => ({ action: 'addAttribute', diff --git a/packages/sync-actions/src/categories.ts b/packages/sync-actions/src/categories.ts index 3ff1d3666..8ca55b782 100644 --- a/packages/sync-actions/src/categories.ts +++ b/packages/sync-actions/src/categories.ts @@ -4,7 +4,7 @@ import type { SyncActionConfig, UpdateAction, } from '@commercetools/sdk-client-v2' -import actionsMapAssets from './category-assets-actions' +import { actionsMapAssets } from './category-assets-actions' import { actionsMapBase, actionsMapMeta, diff --git a/packages/sync-actions/src/category-actions.ts b/packages/sync-actions/src/category-actions.ts index 1dc981917..6b865b0c7 100644 --- a/packages/sync-actions/src/category-actions.ts +++ b/packages/sync-actions/src/category-actions.ts @@ -2,7 +2,7 @@ import { buildBaseAttributesActions, buildReferenceActions, } from './utils/common-actions' -import { ActionMapBase } from './utils/create-map-action-group' +import { ActionMap, ActionMapBase } from './utils/create-map-action-group' import { UpdateAction } from '@commercetools/sdk-client-v2' export const baseActionsList: Array = [ @@ -36,7 +36,7 @@ export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { }) } -export function actionsMapReferences(diff: any, oldObj: any, newObj: any) { +export const actionsMapReferences: ActionMap = (diff, oldObj, newObj) => { return buildReferenceActions({ actions: referenceActionsList, diff, @@ -45,7 +45,7 @@ export function actionsMapReferences(diff: any, oldObj: any, newObj: any) { }) } -export function actionsMapMeta(diff: any, oldObj: any, newObj: any) { +export const actionsMapMeta: ActionMap = (diff, oldObj, newObj) => { return buildBaseAttributesActions({ actions: metaActionsList, diff, diff --git a/packages/sync-actions/src/category-assets-actions.ts b/packages/sync-actions/src/category-assets-actions.ts index e59fd7a9e..739e01319 100644 --- a/packages/sync-actions/src/category-assets-actions.ts +++ b/packages/sync-actions/src/category-assets-actions.ts @@ -8,12 +8,13 @@ import { CategoryRemoveAssetAction, } from '@commercetools/platform-sdk' import { UpdateAction } from '@commercetools/sdk-client-v2' +import { ActionMap } from './utils/create-map-action-group' function toAssetIdentifier(asset: { id?: string; key?: string }) { return asset.id ? { assetId: asset.id } : { assetKey: asset.key } } -export default function actionsMapAssets(diff: any, oldObj: any, newObj: any) { +export const actionsMapAssets: ActionMap = (diff, oldObj, newObj) => { const handler = createBuildArrayActions('assets', { [ADD_ACTIONS]: (newAsset): CategoryAddAssetAction => ({ action: 'addAsset', diff --git a/packages/sync-actions/src/customer-actions.ts b/packages/sync-actions/src/customer-actions.ts index 4477886a2..d327acf09 100644 --- a/packages/sync-actions/src/customer-actions.ts +++ b/packages/sync-actions/src/customer-actions.ts @@ -9,8 +9,8 @@ import createBuildArrayActions, { CHANGE_ACTIONS, REMOVE_ACTIONS, } from './utils/create-build-array-actions' -import { patch } from './utils/diffpatcher' -import { ActionMapBase } from './utils/create-map-action-group' +import { Delta, patch } from './utils/diffpatcher' +import { ActionMap, ActionMapBase } from './utils/create-map-action-group' import { UpdateAction } from '@commercetools/sdk-client-v2' const isEmptyValue = createIsEmptyValue([undefined, null, '']) @@ -89,7 +89,7 @@ export const actionsMapSetDefaultBase: ActionMapBase = ( }) } -export function actionsMapReferences(diff: any, oldObj: any, newObj: any) { +export const actionsMapReferences: ActionMap = (diff, oldObj, newObj) => { return buildReferenceActions({ actions: referenceActionsList, diff, @@ -98,7 +98,7 @@ export function actionsMapReferences(diff: any, oldObj: any, newObj: any) { }) } -export function actionsMapAddresses(diff: any, oldObj: any, newObj: any) { +export const actionsMapAddresses: ActionMap = (diff, oldObj, newObj) => { const handler = createBuildArrayActions('addresses', { [ADD_ACTIONS]: (newObject) => ({ action: 'addAddress', @@ -118,11 +118,7 @@ export function actionsMapAddresses(diff: any, oldObj: any, newObj: any) { return handler(diff, oldObj, newObj) } -export function actionsMapBillingAddresses( - diff: any, - oldObj: any, - newObj: any -) { +export const actionsMapBillingAddresses: ActionMap = (diff, oldObj, newObj) => { const handler = createBuildArrayActions('billingAddressIds', { [ADD_ACTIONS]: (addressId) => ({ action: 'addBillingAddressId', @@ -137,11 +133,11 @@ export function actionsMapBillingAddresses( return handler(diff, oldObj, newObj) } -export function actionsMapShippingAddresses( - diff: any, - oldObj: any, - newObj: any -) { +export const actionsMapShippingAddresses: ActionMap = ( + diff, + oldObj, + newObj +) => { const handler = createBuildArrayActions('shippingAddressIds', { [ADD_ACTIONS]: (addressId) => ({ action: 'addShippingAddressId', @@ -156,12 +152,11 @@ export function actionsMapShippingAddresses( return handler(diff, oldObj, newObj) } -export function actionsMapAuthenticationModes( - diff: any, - oldObj: any, - newObj: any -) { - // eslint-disable-next-line no-use-before-define +export const actionsMapAuthenticationModes: ActionMap = ( + diff, + oldObj, + newObj +) => { return buildAuthenticationModeActions({ actions: authenticationModeActionsList, diff, @@ -177,7 +172,7 @@ function buildAuthenticationModeActions({ newObj, }: { actions: Array - diff: any + diff: Delta oldObj: any newObj: any }) { diff --git a/packages/sync-actions/src/inventory-actions.ts b/packages/sync-actions/src/inventory-actions.ts index a0e7ff0a2..5d2e4818e 100644 --- a/packages/sync-actions/src/inventory-actions.ts +++ b/packages/sync-actions/src/inventory-actions.ts @@ -2,7 +2,7 @@ import { buildBaseAttributesActions, buildReferenceActions, } from './utils/common-actions' -import { ActionMapBase } from './utils/create-map-action-group' +import { ActionMap, ActionMapBase } from './utils/create-map-action-group' import { UpdateAction } from '@commercetools/sdk-client-v2' export const baseActionsList: Array = [ @@ -29,7 +29,7 @@ export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { }) } -export function actionsMapReferences(diff: any, oldObj: any, newObj: any) { +export const actionsMapReferences: ActionMap = (diff, oldObj, newObj) => { return buildReferenceActions({ actions: referenceActionsList, diff, diff --git a/packages/sync-actions/src/order-actions.ts b/packages/sync-actions/src/order-actions.ts index f3cabcb30..7c85aa071 100644 --- a/packages/sync-actions/src/order-actions.ts +++ b/packages/sync-actions/src/order-actions.ts @@ -3,10 +3,10 @@ import createBuildArrayActions, { ADD_ACTIONS, CHANGE_ACTIONS, } from './utils/create-build-array-actions' -import { getDeltaValue } from './utils/diffpatcher' +import { Delta, getDeltaValue } from './utils/diffpatcher' import extractMatchingPairs from './utils/extract-matching-pairs' import findMatchingPairs from './utils/find-matching-pairs' -import { ActionMapBase } from './utils/create-map-action-group' +import { ActionMap, ActionMapBase } from './utils/create-map-action-group' import { UpdateAction } from '@commercetools/sdk-client-v2' const REGEX_NUMBER = new RegExp(/^\d+$/) @@ -38,7 +38,7 @@ export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { }) } -export function actionsMapDeliveries(diff: any, oldObj: any, newObj: any) { +export const actionsMapDeliveries: ActionMap = (diff, oldObj, newObj) => { const deliveriesDiff = diff.shippingInfo if (!deliveriesDiff) return [] @@ -54,7 +54,7 @@ export function actionsMapDeliveries(diff: any, oldObj: any, newObj: any) { } function _buildDeliveryParcelsAction( - diffedParcels: any, + diffedParcels: Delta, oldDelivery: any = {}, newDelivery: any = {} ) { @@ -114,7 +114,7 @@ function _buildDeliveryItemsAction(diffedItems: any, newDelivery: any = {}) { } export function actionsMapParcels( - diff: { shippingInfo: { deliveries: { [key: string]: any } } }, + diff: Delta | undefined, oldObj: any, newObj: any, deliveryHashMap: any @@ -139,7 +139,7 @@ export function actionsMapParcels( if (REGEX_UNDERSCORE_NUMBER.test(key) || REGEX_NUMBER.test(key)) { const [addParcelAction, removeParcelAction] = _buildDeliveryParcelsAction( - delivery.parcels, + (delivery as any).parcels, oldDelivery, newDelivery ) @@ -153,7 +153,7 @@ export function actionsMapParcels( } export function actionsMapDeliveryItems( - diff: { shippingInfo: { deliveries: { [key: string]: any } } }, + diff: Delta, oldObj: any, newObj: any, deliveryHashMap: any @@ -175,7 +175,7 @@ export function actionsMapDeliveryItems( ) if (REGEX_UNDERSCORE_NUMBER.test(key) || REGEX_NUMBER.test(key)) { const [setDeliveryItemsAction] = _buildDeliveryItemsAction( - delivery.items, + (delivery as any).items, newDelivery ) setDeliveryItemsActions = setDeliveryItemsActions.concat( @@ -187,7 +187,7 @@ export function actionsMapDeliveryItems( return setDeliveryItemsActions } -export function actionsMapReturnsInfo(diff: any, oldObj: any, newObj: any) { +export const actionsMapReturnsInfo: ActionMap = (diff, oldObj, newObj) => { const returnInfoDiff = diff.returnInfo if (!returnInfoDiff) return [] diff --git a/packages/sync-actions/src/product-actions.ts b/packages/sync-actions/src/product-actions.ts index d57a4d25c..b79c38f9b 100644 --- a/packages/sync-actions/src/product-actions.ts +++ b/packages/sync-actions/src/product-actions.ts @@ -11,7 +11,7 @@ import createBuildArrayActions, { ADD_ACTIONS, REMOVE_ACTIONS, } from './utils/create-build-array-actions' -import { getDeltaValue } from './utils/diffpatcher' +import { Delta, getDeltaValue } from './utils/diffpatcher' import extractMatchingPairs from './utils/extract-matching-pairs' import findMatchingPairs from './utils/find-matching-pairs' import { @@ -69,7 +69,7 @@ const getIsRemoveAction = (key: string, resource: any) => const getIsItemMovedAction = (key: string, resource: any) => REGEX_UNDERSCORE_NUMBER.test(key) && Number(resource[2]) === 3 -function _buildSkuActions(variantDiff: any, oldVariant: any) { +function _buildSkuActions(variantDiff: Delta, oldVariant: any) { if ({}.hasOwnProperty.call(variantDiff, 'sku')) { const newValue = getDeltaValue(variantDiff.sku) if (!newValue && !oldVariant.sku) return null @@ -83,7 +83,7 @@ function _buildSkuActions(variantDiff: any, oldVariant: any) { return null } -function _buildKeyActions(variantDiff: any, oldVariant: any) { +function _buildKeyActions(variantDiff: Delta, oldVariant: any) { if ({}.hasOwnProperty.call(variantDiff, 'key')) { const newValue = getDeltaValue(variantDiff.key) if (!newValue && !oldVariant.key) return null @@ -552,7 +552,7 @@ export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { }) } -export function actionsMapMeta(diff: any, oldObj: any, newObj: any) { +export function actionsMapMeta(diff: Delta, oldObj: any, newObj: any) { return buildBaseAttributesActions({ actions: metaActionsList, diff, @@ -561,7 +561,7 @@ export function actionsMapMeta(diff: any, oldObj: any, newObj: any) { }) } -export function actionsMapAddVariants(diff: any, oldObj: any, newObj: any) { +export function actionsMapAddVariants(diff: Delta, oldObj: any, newObj: any) { const handler = createBuildArrayActions('variants', { [ADD_ACTIONS]: (newObject: any) => ({ ...newObject, @@ -571,7 +571,11 @@ export function actionsMapAddVariants(diff: any, oldObj: any, newObj: any) { return handler(diff, oldObj, newObj) } -export function actionsMapRemoveVariants(diff: any, oldObj: any, newObj: any) { +export function actionsMapRemoveVariants( + diff: Delta, + oldObj: any, + newObj: any +) { const handler = createBuildArrayActions('variants', { [REMOVE_ACTIONS]: ({ id }: { id: string }) => ({ action: 'removeVariant', @@ -581,7 +585,7 @@ export function actionsMapRemoveVariants(diff: any, oldObj: any, newObj: any) { return handler(diff, oldObj, newObj) } -export function actionsMapReferences(diff: any, oldObj: any, newObj: any) { +export function actionsMapReferences(diff: Delta, oldObj: any, newObj: any) { return buildReferenceActions({ actions: referenceActionsList, diff, @@ -621,7 +625,7 @@ export function actionsMapCategories(diff: { return [...removeFromCategoryActions, ...addToCategoryActions] } -export function actionsMapCategoryOrderHints(diff: any) { +export function actionsMapCategoryOrderHints(diff: Delta) { if (!diff.categoryOrderHints) return [] // Ignore this pattern as its means no changes happened [{},0,0] if (Array.isArray(diff.categoryOrderHints)) return [] @@ -648,7 +652,7 @@ export function actionsMapCategoryOrderHints(diff: any) { } export function actionsMapAssets( - diff: any, + diff: Delta, oldObj: any, newObj: any, variantHashMap: any @@ -685,7 +689,7 @@ export function actionsMapAssets( } export function actionsMapAttributes( - diff: any, + diff: Delta, oldObj: any, newObj: any, sameForAllAttributeNames: Array = [], @@ -735,7 +739,7 @@ export function actionsMapAttributes( } export function actionsMapImages( - diff: any, + diff: Delta, oldObj: any, newObj: any, variantHashMap: any @@ -766,7 +770,7 @@ export function actionsMapImages( } export function actionsMapPrices( - diff: any, + diff: Delta, oldObj: any, newObj: any, variantHashMap: any, @@ -808,7 +812,7 @@ export function actionsMapPrices( } export function actionsMapPricesCustom( - diff: any, + diff: Delta, oldObj: any, newObj: any, variantHashMap: any diff --git a/packages/sync-actions/src/product-selections.ts b/packages/sync-actions/src/product-selections.ts index ded29b91e..c2603b9ca 100644 --- a/packages/sync-actions/src/product-selections.ts +++ b/packages/sync-actions/src/product-selections.ts @@ -8,7 +8,7 @@ import { SyncAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' -import { diff } from './utils/diffpatcher' +import { Delta, diff } from './utils/diffpatcher' export const actionGroups = ['base'] @@ -17,9 +17,14 @@ function createProductSelectionsMapActions( type: string, fn: () => Array ) => Array -): (diff: any, next: any, previous: any, options: any) => Array { +): ( + diff: Delta, + next: any, + previous: any, + options: any +) => Array { return function doMapActions( - diff: any, + diff: Delta, next: any, previous: any ): Array { diff --git a/packages/sync-actions/src/projects-actions.ts b/packages/sync-actions/src/projects-actions.ts index a5776949c..16449f2ce 100644 --- a/packages/sync-actions/src/projects-actions.ts +++ b/packages/sync-actions/src/projects-actions.ts @@ -1,31 +1,60 @@ import { buildBaseAttributesActions } from './utils/common-actions' -import { ActionMapBase } from './utils/create-map-action-group' -import { UpdateAction } from '@commercetools/sdk-client-v2' +import { ActionMap, ActionMapBase } from './utils/create-map-action-group' -export const baseActionsList: Array = [ +export const baseActionsList = [ { action: 'changeName', key: 'name' }, { action: 'changeCurrencies', key: 'currencies' }, { action: 'changeCountries', key: 'countries' }, { action: 'changeLanguages', key: 'languages' }, { action: 'changeMessagesConfiguration', key: 'messagesConfiguration' }, { action: 'setShippingRateInputType', key: 'shippingRateInputType' }, +] + +export const myBusinessUnitActionsList = [ { action: 'changeMyBusinessUnitStatusOnCreation', - key: 'myBusinessUnitStatusOnCreation', + key: 'status', }, { action: 'setMyBusinessUnitAssociateRoleOnCreation', - key: 'myBusinessUnitAssociateRoleOnCreation', + key: 'associateRole', + }, +] + +export const customerSearchActionsList = [ + { + action: 'changeCustomerSearchStatus', + key: 'status', }, - { action: 'changeCustomerSearchStatus', key: 'customerSearchStatus' }, ] -export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { +export const actionsMapBase: ActionMapBase = ( + diff, + oldObj, + newObj, + config = {} +) => { return buildBaseAttributesActions({ actions: baseActionsList, diff, oldObj, newObj, - shouldOmitEmptyString: config?.shouldOmitEmptyString, + shouldOmitEmptyString: config.shouldOmitEmptyString, }) } + +export const actionsMapBusinessUnit: ActionMap = (diff, oldObj, newObj) => + buildBaseAttributesActions({ + actions: myBusinessUnitActionsList, + diff, + oldObj, + newObj, + }) + +export const actionsMapCustomer: ActionMap = (diff, oldObj, newObj) => + buildBaseAttributesActions({ + actions: customerSearchActionsList, + diff, + oldObj, + newObj, + }) diff --git a/packages/sync-actions/src/projects.ts b/packages/sync-actions/src/projects.ts index b571bb702..5ac2dc405 100644 --- a/packages/sync-actions/src/projects.ts +++ b/packages/sync-actions/src/projects.ts @@ -1,30 +1,24 @@ +import createBuildActions from './utils/create-build-actions' +import createMapActionGroup from './utils/create-map-action-group' import { MessagesConfigurationDraft, Project, ProjectUpdateAction, } from '@commercetools/platform-sdk' import { - ActionGroup, - SyncActionConfig, - UpdateAction, -} from '@commercetools/sdk-client-v2' -import { actionsMapBase } from './projects-actions' -import { SyncAction } from './types/update-actions' -import createBuildActions from './utils/create-build-actions' -import createMapActionGroup, { - MapActionGroup, - MapActionResult, -} from './utils/create-map-action-group' + actionsMapBase, + actionsMapBusinessUnit, + actionsMapCustomer, +} from './projects-actions' import { diff } from './utils/diffpatcher' +import { ActionGroup, SyncActionConfig } from '@commercetools/sdk-client-v2' +import { SyncAction } from './types/update-actions' -export const actionGroups = ['base'] +export const actionGroups = ['base', 'myBusinessUnit', 'customerSearch'] -function createChannelsMapActions( - mapActionGroup: MapActionGroup, - syncActionConfig?: SyncActionConfig -): MapActionResult { +function createChannelsMapActions(mapActionGroup, syncActionConfig) { return function doMapActions(diff, newObj, oldObj) { - const allActions: Array> = [] + const allActions = [] allActions.push( mapActionGroup('base', () => @@ -32,6 +26,18 @@ function createChannelsMapActions( ) ) + allActions.push( + mapActionGroup('myBusinessUnit', () => + actionsMapBusinessUnit(diff, oldObj, newObj) + ) + ) + + allActions.push( + mapActionGroup('customerSearch', () => + actionsMapCustomer(diff, oldObj, newObj) + ) + ) + return allActions.flat() } } diff --git a/packages/sync-actions/src/shipping-methods-actions.ts b/packages/sync-actions/src/shipping-methods-actions.ts index c1b1dae9b..1a9c2df3e 100644 --- a/packages/sync-actions/src/shipping-methods-actions.ts +++ b/packages/sync-actions/src/shipping-methods-actions.ts @@ -4,7 +4,7 @@ import createBuildArrayActions, { CHANGE_ACTIONS, REMOVE_ACTIONS, } from './utils/create-build-array-actions' -import { ActionMapBase } from './utils/create-map-action-group' +import { ActionMap, ActionMapBase } from './utils/create-map-action-group' import { UpdateAction } from '@commercetools/sdk-client-v2' import { ZoneRate } from '@commercetools/platform-sdk' @@ -39,7 +39,7 @@ const addShippingRates = (newZoneRate: ZoneRate) => })) : [] -function actionsMapZoneRatesShippingRates(diff: any, oldObj: any, newObj: any) { +const actionsMapZoneRatesShippingRates: ActionMap = (diff, oldObj, newObj) => { const handler = createBuildArrayActions('shippingRates', { [ADD_ACTIONS]: (newShippingRate) => ({ action: 'addShippingRate', @@ -68,7 +68,7 @@ function actionsMapZoneRatesShippingRates(diff: any, oldObj: any, newObj: any) { return handler(diff, oldObj, newObj) } -export function actionsMapZoneRates(diff: any, oldObj: any, newObj: any) { +export const actionsMapZoneRates: ActionMap = (diff, oldObj, newObj) => { const handler = createBuildArrayActions('zoneRates', { [ADD_ACTIONS]: (newZoneRate) => [ { diff --git a/packages/sync-actions/src/state-actions.ts b/packages/sync-actions/src/state-actions.ts index 6cc6322f9..6e17cb00d 100644 --- a/packages/sync-actions/src/state-actions.ts +++ b/packages/sync-actions/src/state-actions.ts @@ -3,7 +3,7 @@ import createBuildArrayActions, { ADD_ACTIONS, REMOVE_ACTIONS, } from './utils/create-build-array-actions' -import { ActionMapBase } from './utils/create-map-action-group' +import { ActionMap, ActionMapBase } from './utils/create-map-action-group' import { UpdateAction } from '@commercetools/sdk-client-v2' export const baseActionsList: Array = [ @@ -25,7 +25,7 @@ export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { }) } -export function actionsMapRoles(diff: any, oldObj: any, newObj: any) { +export const actionsMapRoles: ActionMap = (diff, oldObj, newObj) => { const buildArrayActions = createBuildArrayActions('roles', { [ADD_ACTIONS]: (newRole) => ({ action: 'addRoles', diff --git a/packages/sync-actions/src/stores.ts b/packages/sync-actions/src/stores.ts index f0d5afbca..b29f761ae 100644 --- a/packages/sync-actions/src/stores.ts +++ b/packages/sync-actions/src/stores.ts @@ -5,7 +5,7 @@ import { SyncAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' -import { diff } from './utils/diffpatcher' +import { Delta, diff } from './utils/diffpatcher' export const actionGroups = ['base'] @@ -14,9 +14,14 @@ function createStoresMapActions( type: string, fn: () => Array ) => Array -): (diff: any, next: any, previous: any, options: any) => Array { +): ( + diff: Delta, + next: any, + previous: any, + options: any +) => Array { return function doMapActions( - diff: any, + diff, next: any, previous: any ): Array { diff --git a/packages/sync-actions/src/tax-categories-actions.ts b/packages/sync-actions/src/tax-categories-actions.ts index d9d12cb9c..e71270138 100644 --- a/packages/sync-actions/src/tax-categories-actions.ts +++ b/packages/sync-actions/src/tax-categories-actions.ts @@ -4,7 +4,7 @@ import createBuildArrayActions, { CHANGE_ACTIONS, REMOVE_ACTIONS, } from './utils/create-build-array-actions' -import { ActionMapBase } from './utils/create-map-action-group' +import { ActionMap, ActionMapBase } from './utils/create-map-action-group' import { UpdateAction } from '@commercetools/sdk-client-v2' export const baseActionsList: Array = [ @@ -23,7 +23,7 @@ export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { }) } -export function actionsMapRates(diff: any, oldObj: any, newObj: any) { +export const actionsMapRates: ActionMap = (diff, oldObj, newObj) => { const handler = createBuildArrayActions('rates', { [ADD_ACTIONS]: (newObject) => ({ action: 'addTaxRate', diff --git a/packages/sync-actions/src/types-actions.ts b/packages/sync-actions/src/types-actions.ts index ffeadd95e..bcdaa4ee8 100644 --- a/packages/sync-actions/src/types-actions.ts +++ b/packages/sync-actions/src/types-actions.ts @@ -4,7 +4,7 @@ import createBuildArrayActions, { ADD_ACTIONS, CHANGE_ACTIONS, } from './utils/create-build-array-actions' -import { getDeltaValue } from './utils/diffpatcher' +import { Delta, getDeltaValue } from './utils/diffpatcher' import extractMatchingPairs from './utils/extract-matching-pairs' import { ActionMapBase } from './utils/create-map-action-group' import { UpdateAction } from '@commercetools/sdk-client-v2' @@ -33,7 +33,7 @@ export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { function actionsMapEnums( fieldName: any, attributeType: any, - attributeDiff: any, + attributeDiff: Delta, previous: any, next: any ) { diff --git a/packages/sync-actions/src/utils/action-map-custom.ts b/packages/sync-actions/src/utils/action-map-custom.ts index b753bbaae..4996c065e 100644 --- a/packages/sync-actions/src/utils/action-map-custom.ts +++ b/packages/sync-actions/src/utils/action-map-custom.ts @@ -1,4 +1,4 @@ -import { getDeltaValue } from './diffpatcher' +import { Delta, getDeltaValue } from './diffpatcher' import { UpdateAction } from '@commercetools/sdk-client-v2' const Actions = { @@ -6,11 +6,11 @@ const Actions = { setCustomField: 'setCustomField', } -const hasSingleCustomFieldChanged = (diff: any) => Array.isArray(diff.custom) -const haveMultipleCustomFieldsChanged = (diff: any) => +const hasSingleCustomFieldChanged = (diff: Delta) => Array.isArray(diff.custom) +const haveMultipleCustomFieldsChanged = (diff: Delta) => Boolean(diff.custom.fields) -const hasCustomTypeChanged = (diff: any) => Boolean(diff.custom.type) -const extractCustomType = (diff: any, previousObject: any) => +const hasCustomTypeChanged = (diff: Delta) => Boolean(diff.custom.type) +const extractCustomType = (diff: Delta, previousObject: any) => Array.isArray(diff.custom.type) ? getDeltaValue(diff.custom.type, previousObject) : diff.custom.type @@ -24,7 +24,7 @@ const extractFieldValue = (newFields: any, fieldName: string) => newFields[fieldName] export default function actionsMapCustom( - diff: any, + diff: Delta, newObj: any, oldObj: any, customProps: { actions: any; priceId?: string } = { diff --git a/packages/sync-actions/src/utils/common-actions.ts b/packages/sync-actions/src/utils/common-actions.ts index a728083a8..3d243105e 100644 --- a/packages/sync-actions/src/utils/common-actions.ts +++ b/packages/sync-actions/src/utils/common-actions.ts @@ -1,5 +1,5 @@ import clone, { notEmpty } from './clone' -import { getDeltaValue, patch } from './diffpatcher' +import { Delta, getDeltaValue, patch } from './diffpatcher' import { UpdateAction } from '@commercetools/sdk-client-v2' const normalizeValue = (value: any) => @@ -27,7 +27,7 @@ export function buildBaseAttributesActions({ shouldOmitEmptyString, }: { actions: Array - diff: any + diff: Delta oldObj: any newObj: any shouldOmitEmptyString?: boolean @@ -84,7 +84,7 @@ export function buildReferenceActions({ newObj, }: { actions: Array - diff: any + diff: Delta oldObj: any newObj: any }): Array<{ action: string }> { diff --git a/packages/sync-actions/src/utils/create-build-actions.ts b/packages/sync-actions/src/utils/create-build-actions.ts index 31c558c43..2a3e5f328 100644 --- a/packages/sync-actions/src/utils/create-build-actions.ts +++ b/packages/sync-actions/src/utils/create-build-actions.ts @@ -81,7 +81,7 @@ function injectMissingPriceIds( } export default function createBuildActions( - differ: any, + differ: (oldObj: any, newObj: any) => any | undefined, doMapActions: any, onBeforeDiff?: (before: DeepPartial, now: DeepPartial) => Array, buildActionsConfig: any = {} diff --git a/packages/sync-actions/src/utils/create-build-array-actions.ts b/packages/sync-actions/src/utils/create-build-array-actions.ts index 526e7142f..397a4144f 100644 --- a/packages/sync-actions/src/utils/create-build-array-actions.ts +++ b/packages/sync-actions/src/utils/create-build-array-actions.ts @@ -1,4 +1,5 @@ import { UpdateAction } from '@commercetools/sdk-client-v2' +import { Delta } from './diffpatcher' const REGEX_NUMBER = new RegExp(/^\d+$/) const REGEX_UNDERSCORE_NUMBER = new RegExp(/^_\d+$/) @@ -77,7 +78,6 @@ function isRemoveAction(obj: any, key: string): boolean { * [ADD_ACTIONS, REMOVE_ACTIONS, CHANGE_ACTIONS], each of * which is a function. The function should accept the old + new arrays and * return an action object. - * @return {Array} The generated array of actions */ export default function createBuildArrayActions( key: string, @@ -95,7 +95,7 @@ export default function createBuildArrayActions( } ) { return function buildArrayActions( - diff: any, + diff: Delta, oldObj: any, newObj: any ): Array { diff --git a/packages/sync-actions/src/utils/create-map-action-group.ts b/packages/sync-actions/src/utils/create-map-action-group.ts index f22463966..899f48dc7 100644 --- a/packages/sync-actions/src/utils/create-map-action-group.ts +++ b/packages/sync-actions/src/utils/create-map-action-group.ts @@ -6,6 +6,7 @@ // { type: 'variants', group: 'ignore' }, // ] import { ActionGroup, UpdateAction } from '@commercetools/sdk-client-v2' +import { Delta } from './diffpatcher' export type MapActionGroup = ( type: string, @@ -13,14 +14,20 @@ export type MapActionGroup = ( ) => Array export type MapActionResult = ( - diff: any, + diff: Delta, newObj: any, oldObj: any, config?: any ) => Array +export type ActionMap = ( + diff: Delta, + oldObj: any, + newObj: any +) => Array + export type ActionMapBase = ( - diff: any, + diff: Delta, oldObj: any, newObj: any, config?: { shouldOmitEmptyString?: boolean; [key: string]: any } diff --git a/packages/sync-actions/src/utils/diffpatcher.ts b/packages/sync-actions/src/utils/diffpatcher.ts index 3530ebee8..3e63e73a6 100644 --- a/packages/sync-actions/src/utils/diffpatcher.ts +++ b/packages/sync-actions/src/utils/diffpatcher.ts @@ -2,6 +2,7 @@ // with es6 modules so we use require instead below // TODO create an issue here https://github.com/benjamine/jsondiffpatch/issues/new const DiffPatcher = require('jsondiffpatch').DiffPatcher +import { Delta as DiffDelta } from 'jsondiffpatch' export function objectHash(obj: any, index: any) { const objIndex = `$$index:${index}` @@ -31,7 +32,9 @@ const diffpatcher = new DiffPatcher({ }, }) -export function diff(oldObj: any, newObj: any) { +export type Delta = DiffDelta | undefined + +export function diff(oldObj: any, newObj: any): Delta { return diffpatcher.diff(oldObj, newObj) } diff --git a/packages/sync-actions/src/utils/find-matching-pairs.ts b/packages/sync-actions/src/utils/find-matching-pairs.ts index 9e7c75b49..8e9fb7a33 100644 --- a/packages/sync-actions/src/utils/find-matching-pairs.ts +++ b/packages/sync-actions/src/utils/find-matching-pairs.ts @@ -1,3 +1,5 @@ +import { Delta } from './diffpatcher' + const REGEX_NUMBER = new RegExp(/^\d+$/) const REGEX_UNDERSCORE_NUMBER = new RegExp(/^_\d+$/) @@ -17,7 +19,7 @@ function preProcessCollection(collection: Array = [], identifier = 'id') { // creates a hash of a location of an item in collection1 and collection2 export default function findMatchingPairs( - diff: any, + diff: Delta | undefined, before: Array = [], now: Array = [], identifier: string = 'id' diff --git a/packages/sync-actions/src/zones-actions.ts b/packages/sync-actions/src/zones-actions.ts index a033ee7be..8a6cff887 100644 --- a/packages/sync-actions/src/zones-actions.ts +++ b/packages/sync-actions/src/zones-actions.ts @@ -5,7 +5,7 @@ import createBuildArrayActions, { REMOVE_ACTIONS, } from './utils/create-build-array-actions' import { UpdateAction } from '@commercetools/sdk-client-v2' -import { ActionMapBase } from './utils/create-map-action-group' +import { ActionMap, ActionMapBase } from './utils/create-map-action-group' import { Location } from '@commercetools/platform-sdk' export const baseActionsList: Array = [ @@ -27,7 +27,7 @@ export const actionsMapBase: ActionMapBase = (diff, oldObj, newObj, config) => { }) } -export function actionsMapLocations(diff: any, oldObj: any, newObj: any) { +export const actionsMapLocations: ActionMap = (diff, oldObj, newObj) => { const handler = createBuildArrayActions('locations', { [ADD_ACTIONS]: (newLocation) => ({ action: 'addLocation', diff --git a/packages/sync-actions/test/projects-sync.spec.ts b/packages/sync-actions/test/projects-sync.spec.ts index 65122c1f5..a120e9c3f 100644 --- a/packages/sync-actions/test/projects-sync.spec.ts +++ b/packages/sync-actions/test/projects-sync.spec.ts @@ -1,11 +1,21 @@ import createProjectsSync, { actionGroups, ProjectSync } from '../src/projects' -import { baseActionsList } from '../src/projects-actions' +import { + baseActionsList, + myBusinessUnitActionsList, + customerSearchActionsList, +} from '../src/projects-actions' +import { ActionGroup } from '@commercetools/sdk-client-v2' import { DeepPartial } from '../src/types/update-actions' -import { Project } from '@commercetools/platform-sdk/src' +import { + Project, + ProjectUpdateAction, + SearchIndexingConfiguration, + SearchIndexingConfigurationValues, +} from '@commercetools/platform-sdk' describe('Exports', () => { test('action group list', () => { - expect(actionGroups).toEqual(['base']) + expect(actionGroups).toEqual(['base', 'myBusinessUnit', 'customerSearch']) }) describe('action list', () => { @@ -68,33 +78,33 @@ describe('Exports', () => { }) test('should contain `changeMyBusinessUnitStatusOnCreation` action', () => { - expect(baseActionsList).toEqual( + expect(myBusinessUnitActionsList).toEqual( expect.arrayContaining([ { action: 'changeMyBusinessUnitStatusOnCreation', - key: 'myBusinessUnitStatusOnCreation', + key: 'status', }, ]) ) }) test('should contain `setMyBusinessUnitAssociateRoleOnCreation` action', () => { - expect(baseActionsList).toEqual( + expect(myBusinessUnitActionsList).toEqual( expect.arrayContaining([ { action: 'setMyBusinessUnitAssociateRoleOnCreation', - key: 'myBusinessUnitAssociateRoleOnCreation', + key: 'associateRole', }, ]) ) }) test('should contain `changeCustomerSearchStatus` action', () => { - expect(baseActionsList).toEqual( + expect(customerSearchActionsList).toEqual( expect.arrayContaining([ { action: 'changeCustomerSearchStatus', - key: 'customerSearchStatus', + key: 'status', }, ]) ) @@ -109,52 +119,52 @@ describe('Actions', () => { }) test('should build `changeName` action', () => { - const before = { name: 'nameBefore' } - const now = { name: 'nameAfter' } + const before: DeepPartial = { name: 'nameBefore' } + const now: DeepPartial = { name: 'nameAfter' } const actual = projectsSync.buildActions(now, before) - const expected = [ + const expected: Array = [ { action: 'changeName', - ...now, + name: now.name, }, ] expect(actual).toEqual(expected) }) test('should build `changeCurrencies` action', () => { - const before = { currencies: ['EUR', 'Dollar'] } - const now = { currencies: ['EUR'] } + const before: DeepPartial = { currencies: ['EUR', 'Dollar'] } + const now: DeepPartial = { currencies: ['EUR'] } const actual = projectsSync.buildActions(now, before) - const expected = [ + const expected: Array = [ { action: 'changeCurrencies', - ...now, + currencies: now.currencies, }, ] expect(actual).toEqual(expected) }) test('should build `changeCountries` action', () => { - const before = { countries: ['Germany', 'Spain'] } - const now = { countries: ['Germany'] } + const before: DeepPartial = { countries: ['Germany', 'Spain'] } + const now: DeepPartial = { countries: ['Germany'] } const actual = projectsSync.buildActions(now, before) - const expected = [ + const expected: Array = [ { action: 'changeCountries', - ...now, + countries: now.countries, }, ] expect(actual).toEqual(expected) }) test('should build `changeLanguages` action', () => { - const before = { languages: ['German', 'Dutch'] } - const now = { languages: ['Dutch'] } + const before: DeepPartial = { languages: ['German', 'Dutch'] } + const now: DeepPartial = { languages: ['Dutch'] } const actual = projectsSync.buildActions(now, before) - const expected = [ + const expected: Array = [ { action: 'changeLanguages', - ...now, + languages: now.languages, }, ] expect(actual).toEqual(expected) @@ -162,7 +172,7 @@ describe('Actions', () => { describe('setShippingRateInputType', () => { describe('given `shippingRateInputType` is of type `CartClassification`', () => { - const before: DeepPartial = { + const before: DeepPartial = { shippingRateInputType: { type: 'CartClassification', values: [ @@ -173,7 +183,7 @@ describe('Actions', () => { }, } describe('given a value of `values` changes', () => { - const now: DeepPartial = { + const now: DeepPartial = { shippingRateInputType: { type: 'CartClassification', values: [ @@ -186,10 +196,17 @@ describe('Actions', () => { test('should build `setShippingRateInputType` action', () => { const actual = projectsSync.buildActions(now, before) - const expected = [ + const expected: Array = [ { action: 'setShippingRateInputType', - ...now, + shippingRateInputType: { + type: 'CartClassification', + values: [ + { key: 'Small', label: { en: 'Small', de: 'Klein' } }, + { key: 'Medium', label: { en: 'Medium', de: 'Mittel' } }, + { key: 'Big', label: { en: 'Big', de: 'Groß' } }, + ], + }, }, ] expect(actual).toEqual(expected) @@ -204,10 +221,12 @@ describe('Actions', () => { test('should build `setShippingRateInputType` action', () => { const actual = projectsSync.buildActions(now, before) - const expected = [ + const expected: Array = [ { action: 'setShippingRateInputType', - ...now, + shippingRateInputType: { + type: 'CartScore', + }, }, ] expect(actual).toEqual(expected) @@ -222,10 +241,12 @@ describe('Actions', () => { test('should build `setShippingRateInputType` action', () => { const actual = projectsSync.buildActions(now, before) - const expected = [ + const expected: Array = [ { action: 'setShippingRateInputType', - ...now, + shippingRateInputType: { + type: 'CartScore', + }, }, ] expect(actual).toEqual(expected) @@ -236,78 +257,111 @@ describe('Actions', () => { }) test('should build `changeMessagesConfiguration` action', () => { - const before: DeepPartial = { - messagesConfiguration: { enabled: false }, + const before: DeepPartial = { + messages: { + enabled: true, + deleteDaysAfterCreation: 20, + }, } - const now: DeepPartial = { - messagesConfiguration: { enabled: true }, + const now: DeepPartial = { + messages: { + enabled: false, + deleteDaysAfterCreation: 20, + }, } const actual = projectsSync.buildActions(now, before) - const expected = [ + const expected: Array = [ { action: 'changeMessagesConfiguration', - ...now, + messagesConfiguration: { enabled: false, deleteDaysAfterCreation: 20 }, }, ] expect(actual).toEqual(expected) }) test('should build `changeMyBusinessUnitStatusOnCreation` action', () => { - const before = { - myBusinessUnitStatusOnCreation: 'Active', + const actionGroupList: Array = [ + { type: 'base', group: 'allow' }, + { type: 'myBusinessUnit', group: 'allow' }, + { type: 'customerSearch', group: 'ignore' }, + ] + projectsSync = createProjectsSync(actionGroupList) + const before: DeepPartial = { + businessUnits: { myBusinessUnitStatusOnCreation: 'Active' }, } - const now = { - myBusinessUnitStatusOnCreation: 'Deactive', + const now: DeepPartial = { + businessUnits: { myBusinessUnitStatusOnCreation: 'Deactive' }, } - // @ts-ignore const actual = projectsSync.buildActions(now, before) - const expected = [ + const expected: Array = [ { action: 'changeMyBusinessUnitStatusOnCreation', - ...now, + status: 'Deactivated', }, ] expect(actual).toEqual(expected) }) test('should build `setMyBusinessUnitAssociateRoleOnCreation` action', () => { - const before = { - myBusinessUnitAssociateRoleOnCreation: { - typeId: 'associate-role', - key: 'old-role', + const before: DeepPartial = { + businessUnits: { + myBusinessUnitAssociateRoleOnCreation: { + typeId: 'associate-role', + key: 'old-role', + }, }, } - const now = { - myBusinessUnitAssociateRoleOnCreation: { - typeId: 'associate-role', - key: 'new-role', + const now: DeepPartial = { + businessUnits: { + myBusinessUnitAssociateRoleOnCreation: { + typeId: 'associate-role', + key: 'new-role', + }, }, } - // @ts-ignore const actual = projectsSync.buildActions(now, before) - const expected = [ + const expected: Array = [ { action: 'setMyBusinessUnitAssociateRoleOnCreation', - ...now, + associateRole: { + typeId: 'associate-role', + key: 'new-role', + }, }, ] expect(actual).toEqual(expected) }) test('should build `changeCustomerSearchStatus` action', () => { - const before = { - customerSearchStatus: 'Activated', + const actionGroupList: Array = [ + { type: 'base', group: 'allow' }, + { type: 'myBusinessUnit', group: 'ignore' }, + { type: 'customerSearch', group: 'allow' }, + ] + projectsSync = createProjectsSync(actionGroupList) + const before: DeepPartial< + Project & { + searchIndexing: SearchIndexingConfiguration & { + customers: SearchIndexingConfigurationValues + } + } + > = { + searchIndexing: { customers: { status: 'Activated' } }, } - const now = { - customerSearchStatus: 'Deactivated', + const now: DeepPartial< + Project & { + searchIndexing: SearchIndexingConfiguration & { + customers: SearchIndexingConfigurationValues + } + } + > = { + searchIndexing: { customers: { status: 'Deactivated' } }, } - - // @ts-ignore const actual = projectsSync.buildActions(now, before) - const expected = [ + const expected: Array = [ { action: 'changeCustomerSearchStatus', - ...now, + status: 'Deactivated', }, ] expect(actual).toEqual(expected) diff --git a/packages/sync-actions/test/utils/find-matching-pairs.spec.ts b/packages/sync-actions/test/utils/find-matching-pairs.spec.ts index 1e391c361..bb84e1210 100644 --- a/packages/sync-actions/test/utils/find-matching-pairs.spec.ts +++ b/packages/sync-actions/test/utils/find-matching-pairs.spec.ts @@ -1,7 +1,8 @@ import findMatchingPairs from '../../src/utils/find-matching-pairs' +import { Delta } from '../../src/utils/diffpatcher' describe('findMatchingPairs', () => { - let diff + let diff: Delta let newVariants let oldVariants beforeEach(() => { diff --git a/packages/sync-actions/tsconfig.json b/packages/sync-actions/tsconfig.json new file mode 100644 index 000000000..a318eeef5 --- /dev/null +++ b/packages/sync-actions/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "dist", + "noImplicitAny": true + }, + "include": ["src"] +} From c18fab6eae4914e7c9d96f7ca67785afcfdd7525 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Thu, 29 Aug 2024 17:16:40 +0200 Subject: [PATCH 27/33] feat(migrate): types for action --- packages/sync-actions/src/projects.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/sync-actions/src/projects.ts b/packages/sync-actions/src/projects.ts index 5ac2dc405..1300d82f3 100644 --- a/packages/sync-actions/src/projects.ts +++ b/packages/sync-actions/src/projects.ts @@ -1,5 +1,8 @@ import createBuildActions from './utils/create-build-actions' -import createMapActionGroup from './utils/create-map-action-group' +import createMapActionGroup, { + MapActionGroup, + MapActionResult, +} from './utils/create-map-action-group' import { MessagesConfigurationDraft, Project, @@ -16,7 +19,10 @@ import { SyncAction } from './types/update-actions' export const actionGroups = ['base', 'myBusinessUnit', 'customerSearch'] -function createChannelsMapActions(mapActionGroup, syncActionConfig) { +function createChannelsMapActions( + mapActionGroup: MapActionGroup, + syncActionConfig?: SyncActionConfig +): MapActionResult { return function doMapActions(diff, newObj, oldObj) { const allActions = [] From 121e1a5ceebade6597124e5c9147b3a6966308b3 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Fri, 30 Aug 2024 08:25:22 +0200 Subject: [PATCH 28/33] feat(fix): project action --- packages/sync-actions/src/projects-actions.ts | 46 +++++++++++++------ .../sync-actions/test/projects-sync.spec.ts | 11 +++-- 2 files changed, 40 insertions(+), 17 deletions(-) diff --git a/packages/sync-actions/src/projects-actions.ts b/packages/sync-actions/src/projects-actions.ts index 16449f2ce..656a0dcf5 100644 --- a/packages/sync-actions/src/projects-actions.ts +++ b/packages/sync-actions/src/projects-actions.ts @@ -6,18 +6,24 @@ export const baseActionsList = [ { action: 'changeCurrencies', key: 'currencies' }, { action: 'changeCountries', key: 'countries' }, { action: 'changeLanguages', key: 'languages' }, - { action: 'changeMessagesConfiguration', key: 'messagesConfiguration' }, + { + action: 'changeMessagesConfiguration', + actionKey: 'messagesConfiguration', + key: 'messages', + }, { action: 'setShippingRateInputType', key: 'shippingRateInputType' }, ] export const myBusinessUnitActionsList = [ { action: 'changeMyBusinessUnitStatusOnCreation', - key: 'status', + key: 'myBusinessUnitStatusOnCreation', + actionKey: 'status', }, { action: 'setMyBusinessUnitAssociateRoleOnCreation', - key: 'associateRole', + key: 'myBusinessUnitAssociateRoleOnCreation', + actionKey: 'associateRole', }, ] @@ -43,18 +49,32 @@ export const actionsMapBase: ActionMapBase = ( }) } -export const actionsMapBusinessUnit: ActionMap = (diff, oldObj, newObj) => - buildBaseAttributesActions({ +export const actionsMapBusinessUnit: ActionMap = (diff, oldObj, newObj) => { + const { businessUnits } = diff + if (!businessUnits) { + return [] + } + return buildBaseAttributesActions({ actions: myBusinessUnitActionsList, - diff, - oldObj, - newObj, + diff: businessUnits, + oldObj: oldObj.businessUnits, + newObj: newObj.businessUnits, }) +} -export const actionsMapCustomer: ActionMap = (diff, oldObj, newObj) => - buildBaseAttributesActions({ +export const actionsMapCustomer: ActionMap = (diff, oldObj, newObj) => { + const { searchIndexing } = diff + if (!searchIndexing) { + return [] + } + const { customers } = searchIndexing + if (!customers) { + return [] + } + return buildBaseAttributesActions({ actions: customerSearchActionsList, - diff, - oldObj, - newObj, + diff: customers, + oldObj: oldObj.searchIndexing.customers, + newObj: newObj.searchIndexing.customers, }) +} diff --git a/packages/sync-actions/test/projects-sync.spec.ts b/packages/sync-actions/test/projects-sync.spec.ts index a120e9c3f..fa352e6bb 100644 --- a/packages/sync-actions/test/projects-sync.spec.ts +++ b/packages/sync-actions/test/projects-sync.spec.ts @@ -60,7 +60,8 @@ describe('Exports', () => { expect.arrayContaining([ { action: 'changeMessagesConfiguration', - key: 'messagesConfiguration', + key: 'messages', + actionKey: 'messagesConfiguration', }, ]) ) @@ -82,7 +83,8 @@ describe('Exports', () => { expect.arrayContaining([ { action: 'changeMyBusinessUnitStatusOnCreation', - key: 'status', + key: 'myBusinessUnitStatusOnCreation', + actionKey: 'status', }, ]) ) @@ -93,7 +95,8 @@ describe('Exports', () => { expect.arrayContaining([ { action: 'setMyBusinessUnitAssociateRoleOnCreation', - key: 'associateRole', + key: 'myBusinessUnitAssociateRoleOnCreation', + actionKey: 'associateRole', }, ]) ) @@ -290,7 +293,7 @@ describe('Actions', () => { businessUnits: { myBusinessUnitStatusOnCreation: 'Active' }, } const now: DeepPartial = { - businessUnits: { myBusinessUnitStatusOnCreation: 'Deactive' }, + businessUnits: { myBusinessUnitStatusOnCreation: 'Deactivated' }, } const actual = projectsSync.buildActions(now, before) const expected: Array = [ From 26cf7d290422a1a007b68bf0e5d4ab125e39c210 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Fri, 30 Aug 2024 11:13:05 +0200 Subject: [PATCH 29/33] feat(fix): introducing types --- .../src/attribute-groups-actions.ts | 4 +- packages/sync-actions/src/attribute-groups.ts | 24 ++--- .../src/cart-discounts-actions.ts | 2 +- packages/sync-actions/src/cart-discounts.ts | 17 ++-- packages/sync-actions/src/categories.ts | 23 +++-- packages/sync-actions/src/category-actions.ts | 2 +- .../src/category-assets-actions.ts | 3 +- packages/sync-actions/src/channels-actions.ts | 2 +- packages/sync-actions/src/channels.ts | 17 ++-- packages/sync-actions/src/customer-actions.ts | 2 +- .../src/customer-group-actions.ts | 2 +- packages/sync-actions/src/customer-group.ts | 17 ++-- packages/sync-actions/src/customers.ts | 23 +++-- .../src/discount-codes-actions.ts | 2 +- packages/sync-actions/src/discount-codes.ts | 17 ++-- packages/sync-actions/src/index.ts | 2 + packages/sync-actions/src/inventories.ts | 19 ++-- .../sync-actions/src/inventory-actions.ts | 2 +- packages/sync-actions/src/order-actions.ts | 2 +- packages/sync-actions/src/orders.ts | 20 ++-- packages/sync-actions/src/prices-actions.ts | 2 +- packages/sync-actions/src/prices.ts | 30 +++--- packages/sync-actions/src/product-actions.ts | 5 +- .../src/product-discounts-actions.ts | 2 +- .../sync-actions/src/product-discounts.ts | 17 ++-- .../src/product-selections-actions.ts | 2 +- .../sync-actions/src/product-selections.ts | 3 +- .../sync-actions/src/product-types-actions.ts | 2 +- packages/sync-actions/src/product-types.ts | 21 ++-- packages/sync-actions/src/products.ts | 23 +++-- packages/sync-actions/src/projects.ts | 18 ++-- .../src/quote-requests-actions.ts | 2 +- packages/sync-actions/src/quote-requests.ts | 19 ++-- packages/sync-actions/src/quotes-actions.ts | 2 +- packages/sync-actions/src/quotes.ts | 19 ++-- .../src/shipping-methods-actions.ts | 2 +- packages/sync-actions/src/shipping-methods.ts | 19 ++-- .../sync-actions/src/staged-quotes-actions.ts | 2 +- packages/sync-actions/src/staged-quotes.ts | 19 ++-- packages/sync-actions/src/state-actions.ts | 2 +- packages/sync-actions/src/states.ts | 19 ++-- packages/sync-actions/src/stores-actions.ts | 2 +- packages/sync-actions/src/stores.ts | 3 +- .../src/tax-categories-actions.ts | 2 +- packages/sync-actions/src/tax-categories.ts | 19 ++-- packages/sync-actions/src/types-actions.ts | 2 +- packages/sync-actions/src/types.ts | 16 +-- .../sync-actions/src/types/update-actions.ts | 14 ++- .../src/utils/action-map-custom.ts | 3 +- .../src/utils/combine-validity-actions.ts | 2 +- .../sync-actions/src/utils/common-actions.ts | 2 +- .../src/utils/create-build-actions.ts | 4 +- .../src/utils/create-build-array-actions.ts | 3 +- .../src/utils/create-map-action-group.ts | 14 ++- packages/sync-actions/src/zones-actions.ts | 2 +- packages/sync-actions/src/zones.ts | 14 +-- packages/sync-actions/test/price-sync.spec.ts | 98 ++++++++++--------- 57 files changed, 316 insertions(+), 316 deletions(-) diff --git a/packages/sync-actions/src/attribute-groups-actions.ts b/packages/sync-actions/src/attribute-groups-actions.ts index 31be18ebe..8aff12b26 100644 --- a/packages/sync-actions/src/attribute-groups-actions.ts +++ b/packages/sync-actions/src/attribute-groups-actions.ts @@ -4,9 +4,9 @@ import createBuildArrayActions, { CHANGE_ACTIONS, REMOVE_ACTIONS, } from './utils/create-build-array-actions' -import { UpdateAction } from '@commercetools/sdk-client-v2' import { ActionMap, ActionMapBase } from './utils/create-map-action-group' -import { AttributeReference } from '@commercetools/platform-sdk/src' +import { AttributeReference } from '@commercetools/platform-sdk' +import { UpdateAction } from './types/update-actions' const hasAttribute = ( attributes: Array, diff --git a/packages/sync-actions/src/attribute-groups.ts b/packages/sync-actions/src/attribute-groups.ts index 20314b85f..6094b6ee9 100644 --- a/packages/sync-actions/src/attribute-groups.ts +++ b/packages/sync-actions/src/attribute-groups.ts @@ -2,27 +2,27 @@ import { AttributeGroup, AttributeGroupUpdateAction, } from '@commercetools/platform-sdk' -import type { - ActionGroup, - SyncActionConfig, - UpdateAction, -} from '@commercetools/sdk-client-v2' + import { actionsMapAttributes, actionsMapBase, } from './attribute-groups-actions' -import { SyncAction } from './types/update-actions' +import { + ActionGroup, + SyncAction, + SyncActionConfig, + UpdateAction, +} from './types/update-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup, { - MapActionGroup, - MapActionResult, + MapAction, } from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' -function createAttributeGroupsMapActions( - mapActionGroup: MapActionGroup, - syncActionConfig?: SyncActionConfig -): MapActionResult { +const createAttributeGroupsMapActions: MapAction = ( + mapActionGroup, + syncActionConfig +) => { return function doMapActions(diff, newObj, oldObj) { const allActions: Array> = [] allActions.push( diff --git a/packages/sync-actions/src/cart-discounts-actions.ts b/packages/sync-actions/src/cart-discounts-actions.ts index 281ec3481..323ab24d1 100644 --- a/packages/sync-actions/src/cart-discounts-actions.ts +++ b/packages/sync-actions/src/cart-discounts-actions.ts @@ -1,6 +1,6 @@ import { buildBaseAttributesActions } from './utils/common-actions' import { ActionMapBase } from './utils/create-map-action-group' -import { UpdateAction } from '@commercetools/sdk-client-v2' +import { UpdateAction } from './types/update-actions' export const baseActionsList: Array = [ { action: 'changeIsActive', key: 'isActive' }, diff --git a/packages/sync-actions/src/cart-discounts.ts b/packages/sync-actions/src/cart-discounts.ts index f56ea83a9..8201db209 100644 --- a/packages/sync-actions/src/cart-discounts.ts +++ b/packages/sync-actions/src/cart-discounts.ts @@ -2,28 +2,27 @@ import { CartDiscount, CartDiscountUpdateAction, } from '@commercetools/platform-sdk' +import { actionsMapBase } from './cart-discounts-actions' import { ActionGroup, + SyncAction, SyncActionConfig, UpdateAction, -} from '@commercetools/sdk-client-v2' -import { actionsMapBase } from './cart-discounts-actions' -import { SyncAction } from './types/update-actions' +} from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import combineValidityActions from './utils/combine-validity-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup, { - MapActionGroup, - MapActionResult, + MapAction, } from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'custom'] -function createCartDiscountsMapActions( - mapActionGroup: MapActionGroup, - syncActionConfig?: SyncActionConfig -): MapActionResult { +const createCartDiscountsMapActions: MapAction = ( + mapActionGroup, + syncActionConfig +) => { return function doMapActions(diff, newObj, oldObj) { const allActions: Array> = [] diff --git a/packages/sync-actions/src/categories.ts b/packages/sync-actions/src/categories.ts index 8ca55b782..35eecc79a 100644 --- a/packages/sync-actions/src/categories.ts +++ b/packages/sync-actions/src/categories.ts @@ -1,31 +1,30 @@ import { Category, CategoryUpdateAction } from '@commercetools/platform-sdk' -import type { - ActionGroup, - SyncActionConfig, - UpdateAction, -} from '@commercetools/sdk-client-v2' import { actionsMapAssets } from './category-assets-actions' import { actionsMapBase, actionsMapMeta, actionsMapReferences, } from './category-actions' -import { SyncAction } from './types/update-actions' +import { + SyncAction, + UpdateAction, + ActionGroup, + SyncActionConfig, +} from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import copyEmptyArrayProps from './utils/copy-empty-array-props' import createBuildActions from './utils/create-build-actions' import createMapActionGroup, { - MapActionGroup, - MapActionResult, + MapAction, } from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'references', 'meta', 'custom', 'assets'] -function createCategoryMapActions( - mapActionGroup: MapActionGroup, - syncActionConfig?: SyncActionConfig -): MapActionResult { +const createCategoryMapActions: MapAction = ( + mapActionGroup, + syncActionConfig +) => { return function doMapActions(diff, newObj, oldObj) { const allActions: Array> = [] diff --git a/packages/sync-actions/src/category-actions.ts b/packages/sync-actions/src/category-actions.ts index 6b865b0c7..2715d357d 100644 --- a/packages/sync-actions/src/category-actions.ts +++ b/packages/sync-actions/src/category-actions.ts @@ -3,7 +3,7 @@ import { buildReferenceActions, } from './utils/common-actions' import { ActionMap, ActionMapBase } from './utils/create-map-action-group' -import { UpdateAction } from '@commercetools/sdk-client-v2' +import { UpdateAction } from './types/update-actions' export const baseActionsList: Array = [ { action: 'changeName', key: 'name' }, diff --git a/packages/sync-actions/src/category-assets-actions.ts b/packages/sync-actions/src/category-assets-actions.ts index 739e01319..b0b1fe9e3 100644 --- a/packages/sync-actions/src/category-assets-actions.ts +++ b/packages/sync-actions/src/category-assets-actions.ts @@ -7,9 +7,10 @@ import { CategoryAddAssetAction, CategoryRemoveAssetAction, } from '@commercetools/platform-sdk' -import { UpdateAction } from '@commercetools/sdk-client-v2' import { ActionMap } from './utils/create-map-action-group' +import { UpdateAction } from './types/update-actions' + function toAssetIdentifier(asset: { id?: string; key?: string }) { return asset.id ? { assetId: asset.id } : { assetKey: asset.key } } diff --git a/packages/sync-actions/src/channels-actions.ts b/packages/sync-actions/src/channels-actions.ts index a45e529e7..ffd999729 100644 --- a/packages/sync-actions/src/channels-actions.ts +++ b/packages/sync-actions/src/channels-actions.ts @@ -1,6 +1,6 @@ import { buildBaseAttributesActions } from './utils/common-actions' -import { UpdateAction } from '@commercetools/sdk-client-v2' import { ActionMapBase } from './utils/create-map-action-group' +import { UpdateAction } from './types/update-actions' export const baseActionsList: Array = [ { action: 'changeKey', key: 'key' }, diff --git a/packages/sync-actions/src/channels.ts b/packages/sync-actions/src/channels.ts index d1d552606..401ada995 100644 --- a/packages/sync-actions/src/channels.ts +++ b/packages/sync-actions/src/channels.ts @@ -1,25 +1,24 @@ import { Channel, ChannelUpdateAction } from '@commercetools/platform-sdk' +import { actionsMapBase } from './channels-actions' import { ActionGroup, SyncActionConfig, + SyncAction, UpdateAction, -} from '@commercetools/sdk-client-v2' -import { actionsMapBase } from './channels-actions' -import { SyncAction } from './types/update-actions' +} from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup, { - MapActionGroup, - MapActionResult, + MapAction, } from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'custom'] -function createChannelsMapActions( - mapActionGroup: MapActionGroup, - syncActionConfig?: SyncActionConfig -): MapActionResult { +const createChannelsMapActions: MapAction = ( + mapActionGroup, + syncActionConfig +) => { return function doMapActions(diff, newObj, oldObj) { const allActions: Array> = [] diff --git a/packages/sync-actions/src/customer-actions.ts b/packages/sync-actions/src/customer-actions.ts index d327acf09..c98662a21 100644 --- a/packages/sync-actions/src/customer-actions.ts +++ b/packages/sync-actions/src/customer-actions.ts @@ -11,7 +11,7 @@ import createBuildArrayActions, { } from './utils/create-build-array-actions' import { Delta, patch } from './utils/diffpatcher' import { ActionMap, ActionMapBase } from './utils/create-map-action-group' -import { UpdateAction } from '@commercetools/sdk-client-v2' +import { UpdateAction } from './types/update-actions' const isEmptyValue = createIsEmptyValue([undefined, null, '']) diff --git a/packages/sync-actions/src/customer-group-actions.ts b/packages/sync-actions/src/customer-group-actions.ts index 5197f4fe0..44e33d826 100644 --- a/packages/sync-actions/src/customer-group-actions.ts +++ b/packages/sync-actions/src/customer-group-actions.ts @@ -1,6 +1,6 @@ import { buildBaseAttributesActions } from './utils/common-actions' import { ActionMapBase } from './utils/create-map-action-group' -import { UpdateAction } from '@commercetools/sdk-client-v2' +import { UpdateAction } from './types/update-actions' export const baseActionsList: Array = [ { action: 'changeName', key: 'name' }, diff --git a/packages/sync-actions/src/customer-group.ts b/packages/sync-actions/src/customer-group.ts index 49173b1f4..d517aca4f 100644 --- a/packages/sync-actions/src/customer-group.ts +++ b/packages/sync-actions/src/customer-group.ts @@ -2,27 +2,26 @@ import { CustomerGroup, CustomerGroupUpdateAction, } from '@commercetools/platform-sdk' +import { actionsMapBase } from './customer-group-actions' import { ActionGroup, SyncActionConfig, + SyncAction, UpdateAction, -} from '@commercetools/sdk-client-v2' -import { actionsMapBase } from './customer-group-actions' -import { SyncAction } from './types/update-actions' +} from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup, { - MapActionGroup, - MapActionResult, + MapAction, } from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'custom'] -function createCustomerGroupMapActions( - mapActionGroup: MapActionGroup, - syncActionConfig?: SyncActionConfig -): MapActionResult { +const createCustomerGroupMapActions: MapAction = ( + mapActionGroup, + syncActionConfig +) => { return function doMapActions(diff, newObj, oldObj) { const allActions: Array> = [] diff --git a/packages/sync-actions/src/customers.ts b/packages/sync-actions/src/customers.ts index f184729f1..530df0074 100644 --- a/packages/sync-actions/src/customers.ts +++ b/packages/sync-actions/src/customers.ts @@ -1,9 +1,4 @@ import { Customer, CustomerUpdateAction } from '@commercetools/platform-sdk' -import type { - ActionGroup, - SyncActionConfig, - UpdateAction, -} from '@commercetools/sdk-client-v2' import { actionsMapAddresses, actionsMapAuthenticationModes, @@ -13,13 +8,17 @@ import { actionsMapSetDefaultBase, actionsMapShippingAddresses, } from './customer-actions' -import { SyncAction } from './types/update-actions' +import { + ActionGroup, + SyncActionConfig, + SyncAction, + UpdateAction, +} from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import copyEmptyArrayProps from './utils/copy-empty-array-props' import createBuildActions from './utils/create-build-actions' import createMapActionGroup, { - MapActionGroup, - MapActionResult, + MapAction, } from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' @@ -31,10 +30,10 @@ export const actionGroups = [ 'authenticationModes', ] -function createCustomerMapActions( - mapActionGroup: MapActionGroup, - syncActionConfig?: SyncActionConfig -): MapActionResult { +const createCustomerMapActions: MapAction = ( + mapActionGroup, + syncActionConfig +) => { return function doMapActions(diff, newObj, oldObj) { const allActions: Array> = [] diff --git a/packages/sync-actions/src/discount-codes-actions.ts b/packages/sync-actions/src/discount-codes-actions.ts index 2b6ab8f61..8a5d836be 100644 --- a/packages/sync-actions/src/discount-codes-actions.ts +++ b/packages/sync-actions/src/discount-codes-actions.ts @@ -1,6 +1,6 @@ import { buildBaseAttributesActions } from './utils/common-actions' import { ActionMapBase } from './utils/create-map-action-group' -import { UpdateAction } from '@commercetools/sdk-client-v2' +import { UpdateAction } from './types/update-actions' export const baseActionsList: Array = [ { action: 'changeIsActive', key: 'isActive' }, diff --git a/packages/sync-actions/src/discount-codes.ts b/packages/sync-actions/src/discount-codes.ts index 8870e005f..6658ed485 100644 --- a/packages/sync-actions/src/discount-codes.ts +++ b/packages/sync-actions/src/discount-codes.ts @@ -2,28 +2,27 @@ import { DiscountCode, DiscountCodeUpdateAction, } from '@commercetools/platform-sdk' +import { actionsMapBase } from './discount-codes-actions' import { ActionGroup, SyncActionConfig, + SyncAction, UpdateAction, -} from '@commercetools/sdk-client-v2' -import { actionsMapBase } from './discount-codes-actions' -import { SyncAction } from './types/update-actions' +} from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import combineValidityActions from './utils/combine-validity-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup, { - MapActionGroup, - MapActionResult, + MapAction, } from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'custom'] -function createDiscountCodesMapActions( - mapActionGroup: MapActionGroup, - syncActionConfig?: SyncActionConfig -): MapActionResult { +const createDiscountCodesMapActions: MapAction = ( + mapActionGroup, + syncActionConfig +) => { return function doMapActions(diff, newObj, oldObj) { const allActions: Array> = [] allActions.push( diff --git a/packages/sync-actions/src/index.ts b/packages/sync-actions/src/index.ts index 423c2b327..b0008b097 100644 --- a/packages/sync-actions/src/index.ts +++ b/packages/sync-actions/src/index.ts @@ -19,3 +19,5 @@ export { default as createSyncStores } from './stores' export { default as createSyncTaxCategories } from './tax-categories' export { default as createSyncTypes } from './types' export { default as createSyncZones } from './zones' +export { type ActionGroup } from './types/update-actions' +export { type SyncActionConfig } from './types/update-actions' diff --git a/packages/sync-actions/src/inventories.ts b/packages/sync-actions/src/inventories.ts index 36a340fbb..bfbfab093 100644 --- a/packages/sync-actions/src/inventories.ts +++ b/packages/sync-actions/src/inventories.ts @@ -2,27 +2,26 @@ import { InventoryEntry, InventoryEntryUpdateAction, } from '@commercetools/platform-sdk' -import type { +import { actionsMapBase, actionsMapReferences } from './inventory-actions' +import { ActionGroup, SyncActionConfig, + SyncAction, UpdateAction, -} from '@commercetools/sdk-client-v2' -import { actionsMapBase, actionsMapReferences } from './inventory-actions' -import { SyncAction } from './types/update-actions' +} from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup, { - MapActionGroup, - MapActionResult, + MapAction, } from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'references'] -function createInventoryMapActions( - mapActionGroup: MapActionGroup, - syncActionConfig?: SyncActionConfig -): MapActionResult { +const createInventoryMapActions: MapAction = ( + mapActionGroup, + syncActionConfig +) => { return function doMapActions(diff, newObj, oldObj) { const allActions: Array> = [] allActions.push( diff --git a/packages/sync-actions/src/inventory-actions.ts b/packages/sync-actions/src/inventory-actions.ts index 5d2e4818e..27be7f391 100644 --- a/packages/sync-actions/src/inventory-actions.ts +++ b/packages/sync-actions/src/inventory-actions.ts @@ -3,7 +3,7 @@ import { buildReferenceActions, } from './utils/common-actions' import { ActionMap, ActionMapBase } from './utils/create-map-action-group' -import { UpdateAction } from '@commercetools/sdk-client-v2' +import { UpdateAction } from './types/update-actions' export const baseActionsList: Array = [ { action: 'changeQuantity', key: 'quantityOnStock', actionKey: 'quantity' }, diff --git a/packages/sync-actions/src/order-actions.ts b/packages/sync-actions/src/order-actions.ts index 7c85aa071..67483a71d 100644 --- a/packages/sync-actions/src/order-actions.ts +++ b/packages/sync-actions/src/order-actions.ts @@ -7,7 +7,7 @@ import { Delta, getDeltaValue } from './utils/diffpatcher' import extractMatchingPairs from './utils/extract-matching-pairs' import findMatchingPairs from './utils/find-matching-pairs' import { ActionMap, ActionMapBase } from './utils/create-map-action-group' -import { UpdateAction } from '@commercetools/sdk-client-v2' +import { UpdateAction } from './types/update-actions' const REGEX_NUMBER = new RegExp(/^\d+$/) const REGEX_UNDERSCORE_NUMBER = new RegExp(/^_\d+$/) diff --git a/packages/sync-actions/src/orders.ts b/packages/sync-actions/src/orders.ts index 6ebd35fc3..94edc9166 100644 --- a/packages/sync-actions/src/orders.ts +++ b/packages/sync-actions/src/orders.ts @@ -5,11 +5,6 @@ import { ShippingInfo, StagedOrderUpdateAction, } from '@commercetools/platform-sdk' -import type { - ActionGroup, - SyncActionConfig, - UpdateAction, -} from '@commercetools/sdk-client-v2' import { actionsMapBase, actionsMapDeliveries, @@ -17,22 +12,23 @@ import { actionsMapParcels, actionsMapReturnsInfo, } from './order-actions' -import { SyncAction } from './types/update-actions' +import { + ActionGroup, + SyncActionConfig, + SyncAction, + UpdateAction, +} from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup, { - MapActionGroup, - MapActionResult, + MapAction, } from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' import findMatchingPairs from './utils/find-matching-pairs' export const actionGroups = ['base', 'deliveries'] -function createOrderMapActions( - mapActionGroup: MapActionGroup, - syncActionConfig?: SyncActionConfig -): MapActionResult { +const createOrderMapActions: MapAction = (mapActionGroup, syncActionConfig) => { return function doMapActions(diff, newObj, oldObj) { const allActions: Array> = [] let deliveryHashMap: any diff --git a/packages/sync-actions/src/prices-actions.ts b/packages/sync-actions/src/prices-actions.ts index af1b3c18d..afc485fbd 100644 --- a/packages/sync-actions/src/prices-actions.ts +++ b/packages/sync-actions/src/prices-actions.ts @@ -1,6 +1,6 @@ import { buildBaseAttributesActions } from './utils/common-actions' import { ActionMapBase } from './utils/create-map-action-group' -import { UpdateAction } from '@commercetools/sdk-client-v2' +import { UpdateAction } from './types/update-actions' export const baseActionsList: Array = [ { action: 'changeValue', key: 'value' }, diff --git a/packages/sync-actions/src/prices.ts b/packages/sync-actions/src/prices.ts index 98e4231e2..7fde71316 100644 --- a/packages/sync-actions/src/prices.ts +++ b/packages/sync-actions/src/prices.ts @@ -1,25 +1,24 @@ -import type { - ActionGroup, - SyncAction, - SyncActionConfig, - UpdateAction, -} from '@commercetools/sdk-client-v2' import { actionsMapBase } from './prices-actions' import actionsMapCustom from './utils/action-map-custom' import combineValidityActions from './utils/combine-validity-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup, { - MapActionGroup, - MapActionResult, + MapAction, } from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' +import { + ActionGroup, + SyncAction, + SyncActionConfig, +} from './types/update-actions' +import { + StandalonePrice, + StandalonePriceUpdateAction, +} from '@commercetools/platform-sdk' const actionGroups = ['base', 'custom'] -function createPriceMapActions( - mapActionGroup: MapActionGroup, - syncActionConfig?: SyncActionConfig -): MapActionResult { +const createPriceMapActions: MapAction = (mapActionGroup, syncActionConfig) => { return function doMapActions(diff, newObj, oldObj) { const baseActions = mapActionGroup('base', () => actionsMapBase(diff, oldObj, newObj, syncActionConfig) @@ -36,11 +35,14 @@ function createPriceMapActions( export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createPriceMapActions(mapActionGroup, syncActionConfig) - const buildActions = createBuildActions(diff, doMapActions) + const buildActions = createBuildActions< + StandalonePrice, + StandalonePriceUpdateAction + >(diff, doMapActions) return { buildActions } } diff --git a/packages/sync-actions/src/product-actions.ts b/packages/sync-actions/src/product-actions.ts index b79c38f9b..15d81037b 100644 --- a/packages/sync-actions/src/product-actions.ts +++ b/packages/sync-actions/src/product-actions.ts @@ -18,9 +18,8 @@ import { Asset, ProductRemoveFromCategoryAction, } from '@commercetools/platform-sdk' -import { SyncActionConfig } from '@commercetools/sdk-client-v2/src' -import { UpdateAction } from '@commercetools/sdk-client-v2' import { ActionMapBase } from './utils/create-map-action-group' +import { UpdateAction } from './types/update-actions' const REGEX_NUMBER = new RegExp(/^\d+$/) const REGEX_UNDERSCORE_NUMBER = new RegExp(/^_\d+$/) @@ -34,7 +33,7 @@ export const baseActionsList: Array = [ { action: 'setPriceMode', key: 'priceMode' }, ] -export const baseAssetActionsList = [ +export const baseAssetActionsList: Array = [ { action: 'setAssetKey', key: 'key', actionKey: 'assetKey' }, { action: 'changeAssetName', key: 'name' }, { action: 'setAssetDescription', key: 'description' }, diff --git a/packages/sync-actions/src/product-discounts-actions.ts b/packages/sync-actions/src/product-discounts-actions.ts index 1f612e693..1fdf74dc5 100644 --- a/packages/sync-actions/src/product-discounts-actions.ts +++ b/packages/sync-actions/src/product-discounts-actions.ts @@ -1,6 +1,6 @@ import { buildBaseAttributesActions } from './utils/common-actions' import { ActionMapBase } from './utils/create-map-action-group' -import { UpdateAction } from '@commercetools/sdk-client-v2' +import { UpdateAction } from './types/update-actions' export const baseActionsList: Array = [ { action: 'changeIsActive', key: 'isActive' }, diff --git a/packages/sync-actions/src/product-discounts.ts b/packages/sync-actions/src/product-discounts.ts index ac37b21ff..5cf19a01c 100644 --- a/packages/sync-actions/src/product-discounts.ts +++ b/packages/sync-actions/src/product-discounts.ts @@ -2,27 +2,26 @@ import { ProductDiscount, ProductDiscountUpdateAction, } from '@commercetools/platform-sdk' +import { actionsMapBase } from './product-discounts-actions' import { ActionGroup, SyncActionConfig, + SyncAction, UpdateAction, -} from '@commercetools/sdk-client-v2' -import { actionsMapBase } from './product-discounts-actions' -import { SyncAction } from './types/update-actions' +} from './types/update-actions' import combineValidityActions from './utils/combine-validity-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup, { - MapActionGroup, - MapActionResult, + MapAction, } from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' export const actionGroups = ['base'] -function createProductDiscountsMapActions( - mapActionGroup: MapActionGroup, - syncActionConfig?: SyncActionConfig -): MapActionResult { +const createProductDiscountsMapActions: MapAction = ( + mapActionGroup, + syncActionConfig +) => { return function doMapActions(diff, newObj, oldObj) { const allActions: Array> = [] diff --git a/packages/sync-actions/src/product-selections-actions.ts b/packages/sync-actions/src/product-selections-actions.ts index 938c1c2d7..47aaf1f37 100644 --- a/packages/sync-actions/src/product-selections-actions.ts +++ b/packages/sync-actions/src/product-selections-actions.ts @@ -1,6 +1,6 @@ import { buildBaseAttributesActions } from './utils/common-actions' import { ActionMapBase } from './utils/create-map-action-group' -import { UpdateAction } from '@commercetools/sdk-client-v2' +import { UpdateAction } from './types/update-actions' export const baseActionsList: Array = [ { action: 'changeName', key: 'name' }, diff --git a/packages/sync-actions/src/product-selections.ts b/packages/sync-actions/src/product-selections.ts index c2603b9ca..b525939d6 100644 --- a/packages/sync-actions/src/product-selections.ts +++ b/packages/sync-actions/src/product-selections.ts @@ -2,9 +2,8 @@ import { ProductSelection, ProductSelectionUpdateAction, } from '@commercetools/platform-sdk' -import type { ActionGroup, UpdateAction } from '@commercetools/sdk-client-v2' import { actionsMapBase } from './product-selections-actions' -import { SyncAction } from './types/update-actions' +import { ActionGroup, SyncAction, UpdateAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' diff --git a/packages/sync-actions/src/product-types-actions.ts b/packages/sync-actions/src/product-types-actions.ts index 11ad86e72..a8dc01362 100644 --- a/packages/sync-actions/src/product-types-actions.ts +++ b/packages/sync-actions/src/product-types-actions.ts @@ -5,7 +5,7 @@ import { createIsEmptyValue, } from './utils/common-actions' import { ActionMapBase } from './utils/create-map-action-group' -import { UpdateAction } from '@commercetools/sdk-client-v2' +import { UpdateAction } from './types/update-actions' export const baseActionsList: Array = [ { action: 'changeName', key: 'name' }, diff --git a/packages/sync-actions/src/product-types.ts b/packages/sync-actions/src/product-types.ts index da8c76dc8..d400faf02 100644 --- a/packages/sync-actions/src/product-types.ts +++ b/packages/sync-actions/src/product-types.ts @@ -2,28 +2,25 @@ import { ProductType, ProductTypeUpdateAction, } from '@commercetools/platform-sdk' -import type { - ActionGroup, - SyncActionConfig as BaseSyncActionConfig, - UpdateAction, -} from '@commercetools/sdk-client-v2' import * as productTypeActions from './product-types-actions' -import { NestedValues } from './product-types-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup, { - MapActionGroup, - MapActionResult, + MapAction, } from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' +import { + ActionGroup, + SyncActionConfig as BaseSyncActionConfig, +} from './types/update-actions' type SyncActionConfig = { withHints?: boolean } & BaseSyncActionConfig const actionGroups = ['base'] -function createProductTypeMapActions( - mapActionGroup: MapActionGroup, - syncActionConfig?: SyncActionConfig -): MapActionResult { +const createProductTypeMapActions: MapAction = ( + mapActionGroup, + syncActionConfig +) => { return function doMapActions(diff, newObj, oldObj, options) { return [ // we support only base fields for the product type, diff --git a/packages/sync-actions/src/products.ts b/packages/sync-actions/src/products.ts index 806f69818..d03878fce 100644 --- a/packages/sync-actions/src/products.ts +++ b/packages/sync-actions/src/products.ts @@ -1,9 +1,4 @@ import { ProductData, ProductUpdateAction } from '@commercetools/platform-sdk' -import type { - ActionGroup, - SyncActionConfig, - UpdateAction, -} from '@commercetools/sdk-client-v2' import { actionsMapAddVariants, actionsMapAssets, @@ -19,12 +14,16 @@ import { actionsMapReferences, actionsMapRemoveVariants, } from './product-actions' -import { SyncAction } from './types/update-actions' +import { + ActionGroup, + SyncActionConfig, + SyncAction, + UpdateAction, +} from './types/update-actions' import copyEmptyArrayProps from './utils/copy-empty-array-props' import createBuildActions from './utils/create-build-actions' import createMapActionGroup, { - MapActionGroup, - MapActionResult, + MapAction, } from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' import findMatchingPairs from './utils/find-matching-pairs' @@ -42,10 +41,10 @@ const actionGroups = [ 'categoryOrderHints', ] -function createProductMapActions( - mapActionGroup: MapActionGroup, - syncActionConfig?: SyncActionConfig -): MapActionResult { +const createProductMapActions: MapAction = ( + mapActionGroup, + syncActionConfig +) => { return function doMapActions(diff, newObj, oldObj, options) { const allActions: Array> = [] const { sameForAllAttributeNames, enableDiscounted } = options diff --git a/packages/sync-actions/src/projects.ts b/packages/sync-actions/src/projects.ts index 1300d82f3..73b0133fd 100644 --- a/packages/sync-actions/src/projects.ts +++ b/packages/sync-actions/src/projects.ts @@ -1,7 +1,6 @@ import createBuildActions from './utils/create-build-actions' import createMapActionGroup, { - MapActionGroup, - MapActionResult, + MapAction, } from './utils/create-map-action-group' import { MessagesConfigurationDraft, @@ -14,15 +13,18 @@ import { actionsMapCustomer, } from './projects-actions' import { diff } from './utils/diffpatcher' -import { ActionGroup, SyncActionConfig } from '@commercetools/sdk-client-v2' -import { SyncAction } from './types/update-actions' +import { + ActionGroup, + SyncAction, + SyncActionConfig, +} from './types/update-actions' export const actionGroups = ['base', 'myBusinessUnit', 'customerSearch'] -function createChannelsMapActions( - mapActionGroup: MapActionGroup, - syncActionConfig?: SyncActionConfig -): MapActionResult { +const createChannelsMapActions: MapAction = ( + mapActionGroup, + syncActionConfig +) => { return function doMapActions(diff, newObj, oldObj) { const allActions = [] diff --git a/packages/sync-actions/src/quote-requests-actions.ts b/packages/sync-actions/src/quote-requests-actions.ts index 9248317fe..300804ad0 100644 --- a/packages/sync-actions/src/quote-requests-actions.ts +++ b/packages/sync-actions/src/quote-requests-actions.ts @@ -1,6 +1,6 @@ import { buildBaseAttributesActions } from './utils/common-actions' import { ActionMapBase } from './utils/create-map-action-group' -import { UpdateAction } from '@commercetools/sdk-client-v2' +import { UpdateAction } from './types/update-actions' export const baseActionsList: Array = [ { action: 'changeQuoteRequestState', key: 'quoteRequestState' }, diff --git a/packages/sync-actions/src/quote-requests.ts b/packages/sync-actions/src/quote-requests.ts index bd8e1f4b2..03312abda 100644 --- a/packages/sync-actions/src/quote-requests.ts +++ b/packages/sync-actions/src/quote-requests.ts @@ -2,27 +2,26 @@ import { QuoteRequest, QuoteRequestUpdateAction, } from '@commercetools/platform-sdk' -import type { +import { actionsMapBase } from './quote-requests-actions' +import { ActionGroup, SyncActionConfig, + SyncAction, UpdateAction, -} from '@commercetools/sdk-client-v2' -import { actionsMapBase } from './quote-requests-actions' -import { SyncAction } from './types/update-actions' +} from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup, { - MapActionGroup, - MapActionResult, + MapAction, } from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' const actionGroups = ['base', 'custom'] -function createQuoteRequestsMapActions( - mapActionGroup: MapActionGroup, - syncActionConfig?: SyncActionConfig -): MapActionResult { +const createQuoteRequestsMapActions: MapAction = ( + mapActionGroup, + syncActionConfig +) => { return function doMapActions(diff, newObj, oldObj) { const allActions: Array> = [] diff --git a/packages/sync-actions/src/quotes-actions.ts b/packages/sync-actions/src/quotes-actions.ts index f5e772fa7..2be2697b3 100644 --- a/packages/sync-actions/src/quotes-actions.ts +++ b/packages/sync-actions/src/quotes-actions.ts @@ -1,6 +1,6 @@ import { buildBaseAttributesActions } from './utils/common-actions' import { ActionMapBase } from './utils/create-map-action-group' -import { UpdateAction } from '@commercetools/sdk-client-v2' +import { UpdateAction } from './types/update-actions' export const baseActionsList: Array = [ { action: 'changeQuoteState', key: 'quoteState' }, diff --git a/packages/sync-actions/src/quotes.ts b/packages/sync-actions/src/quotes.ts index e9bdb0d12..92b3bd623 100644 --- a/packages/sync-actions/src/quotes.ts +++ b/packages/sync-actions/src/quotes.ts @@ -1,25 +1,24 @@ import { Quote, QuoteUpdateAction } from '@commercetools/platform-sdk' -import type { +import { actionsMapBase } from './quotes-actions' +import { ActionGroup, SyncActionConfig, + SyncAction, UpdateAction, -} from '@commercetools/sdk-client-v2' -import { actionsMapBase } from './quotes-actions' -import { SyncAction } from './types/update-actions' +} from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup, { - MapActionGroup, - MapActionResult, + MapAction, } from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' const actionGroups = ['base', 'custom'] -function createQuotesMapActions( - mapActionGroup: MapActionGroup, - syncActionConfig?: SyncActionConfig -): MapActionResult { +const createQuotesMapActions: MapAction = ( + mapActionGroup, + syncActionConfig +) => { return function doMapActions(diff, newObj, oldObj) { const allActions: Array> = [] diff --git a/packages/sync-actions/src/shipping-methods-actions.ts b/packages/sync-actions/src/shipping-methods-actions.ts index 1a9c2df3e..c4982b665 100644 --- a/packages/sync-actions/src/shipping-methods-actions.ts +++ b/packages/sync-actions/src/shipping-methods-actions.ts @@ -5,8 +5,8 @@ import createBuildArrayActions, { REMOVE_ACTIONS, } from './utils/create-build-array-actions' import { ActionMap, ActionMapBase } from './utils/create-map-action-group' -import { UpdateAction } from '@commercetools/sdk-client-v2' import { ZoneRate } from '@commercetools/platform-sdk' +import { UpdateAction } from './types/update-actions' export const baseActionsList: Array = [ { action: 'setKey', key: 'key' }, diff --git a/packages/sync-actions/src/shipping-methods.ts b/packages/sync-actions/src/shipping-methods.ts index c9d478edc..9d27565b6 100644 --- a/packages/sync-actions/src/shipping-methods.ts +++ b/packages/sync-actions/src/shipping-methods.ts @@ -2,27 +2,26 @@ import { ShippingMethod, ShippingMethodUpdateAction, } from '@commercetools/platform-sdk' -import type { +import { actionsMapBase, actionsMapZoneRates } from './shipping-methods-actions' +import { ActionGroup, SyncActionConfig, + SyncAction, UpdateAction, -} from '@commercetools/sdk-client-v2' -import { actionsMapBase, actionsMapZoneRates } from './shipping-methods-actions' -import { SyncAction } from './types/update-actions' +} from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup, { - MapActionGroup, - MapActionResult, + MapAction, } from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'zoneRates', 'custom'] -function createShippingMethodsMapActions( - mapActionGroup: MapActionGroup, - syncActionConfig?: SyncActionConfig -): MapActionResult { +const createShippingMethodsMapActions: MapAction = ( + mapActionGroup, + syncActionConfig +) => { return function doMapActions(diff, newObj, oldObj) { const allActions: Array> = [] allActions.push( diff --git a/packages/sync-actions/src/staged-quotes-actions.ts b/packages/sync-actions/src/staged-quotes-actions.ts index deca4d90f..578c95f57 100644 --- a/packages/sync-actions/src/staged-quotes-actions.ts +++ b/packages/sync-actions/src/staged-quotes-actions.ts @@ -1,6 +1,6 @@ import { buildBaseAttributesActions } from './utils/common-actions' import { ActionMapBase } from './utils/create-map-action-group' -import { UpdateAction } from '@commercetools/sdk-client-v2' +import { UpdateAction } from './types/update-actions' export const baseActionsList: Array = [ { action: 'changeStagedQuoteState', key: 'stagedQuoteState' }, diff --git a/packages/sync-actions/src/staged-quotes.ts b/packages/sync-actions/src/staged-quotes.ts index eceef819f..b37008146 100644 --- a/packages/sync-actions/src/staged-quotes.ts +++ b/packages/sync-actions/src/staged-quotes.ts @@ -3,27 +3,26 @@ import { StagedQuote, StagedQuoteUpdateAction, } from '@commercetools/platform-sdk' -import type { +import { actionsMapBase } from './staged-quotes-actions' +import { ActionGroup, SyncActionConfig, + SyncAction, UpdateAction, -} from '@commercetools/sdk-client-v2' -import { actionsMapBase } from './staged-quotes-actions' -import { SyncAction } from './types/update-actions' +} from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup, { - MapActionGroup, - MapActionResult, + MapAction, } from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' const actionGroups = ['base', 'custom'] -function createStagedQuotesMapActions( - mapActionGroup: MapActionGroup, - syncActionConfig?: SyncActionConfig -): MapActionResult { +const createStagedQuotesMapActions: MapAction = ( + mapActionGroup, + syncActionConfig +) => { return function doMapActions(diff, newObj, oldObj) { const allActions: Array> = [] diff --git a/packages/sync-actions/src/state-actions.ts b/packages/sync-actions/src/state-actions.ts index 6e17cb00d..20d270681 100644 --- a/packages/sync-actions/src/state-actions.ts +++ b/packages/sync-actions/src/state-actions.ts @@ -4,7 +4,7 @@ import createBuildArrayActions, { REMOVE_ACTIONS, } from './utils/create-build-array-actions' import { ActionMap, ActionMapBase } from './utils/create-map-action-group' -import { UpdateAction } from '@commercetools/sdk-client-v2' +import { UpdateAction } from './types/update-actions' export const baseActionsList: Array = [ { action: 'changeKey', key: 'key' }, diff --git a/packages/sync-actions/src/states.ts b/packages/sync-actions/src/states.ts index 0ec80be3d..9f6306f77 100644 --- a/packages/sync-actions/src/states.ts +++ b/packages/sync-actions/src/states.ts @@ -1,15 +1,14 @@ import { State, StateUpdateAction } from '@commercetools/platform-sdk' -import type { +import { actionsMapBase, actionsMapRoles } from './state-actions' +import { ActionGroup, SyncActionConfig, + SyncAction, UpdateAction, -} from '@commercetools/sdk-client-v2' -import { actionsMapBase, actionsMapRoles } from './state-actions' -import { SyncAction } from './types/update-actions' +} from './types/update-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup, { - MapActionGroup, - MapActionResult, + MapAction, } from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' @@ -31,10 +30,10 @@ function groupRoleActions([actions]: Array< ].filter((action: UpdateAction): number => action.roles.length) } -function createStatesMapActions( - mapActionGroup: MapActionGroup, - syncActionConfig?: SyncActionConfig -): MapActionResult { +const createStatesMapActions: MapAction = ( + mapActionGroup, + syncActionConfig +) => { return function doMapActions(diff, newObj, oldObj) { const baseActions: Array> = [] const roleActions: Array> = [] diff --git a/packages/sync-actions/src/stores-actions.ts b/packages/sync-actions/src/stores-actions.ts index bec2ee4d0..5aa8973c2 100644 --- a/packages/sync-actions/src/stores-actions.ts +++ b/packages/sync-actions/src/stores-actions.ts @@ -1,6 +1,6 @@ import { buildBaseAttributesActions } from './utils/common-actions' import { ActionMapBase } from './utils/create-map-action-group' -import { UpdateAction } from '@commercetools/sdk-client-v2' +import { UpdateAction } from './types/update-actions' export const baseActionsList: Array = [ { action: 'setName', key: 'name' }, diff --git a/packages/sync-actions/src/stores.ts b/packages/sync-actions/src/stores.ts index b29f761ae..99cf348b7 100644 --- a/packages/sync-actions/src/stores.ts +++ b/packages/sync-actions/src/stores.ts @@ -1,7 +1,6 @@ import { Store, StoreUpdateAction } from '@commercetools/platform-sdk' -import type { ActionGroup, UpdateAction } from '@commercetools/sdk-client-v2' import { actionsMapBase } from './stores-actions' -import { SyncAction } from './types/update-actions' +import { ActionGroup, SyncAction, UpdateAction } from './types/update-actions' import actionsMapCustom from './utils/action-map-custom' import createBuildActions from './utils/create-build-actions' import createMapActionGroup from './utils/create-map-action-group' diff --git a/packages/sync-actions/src/tax-categories-actions.ts b/packages/sync-actions/src/tax-categories-actions.ts index e71270138..658895e7c 100644 --- a/packages/sync-actions/src/tax-categories-actions.ts +++ b/packages/sync-actions/src/tax-categories-actions.ts @@ -5,7 +5,7 @@ import createBuildArrayActions, { REMOVE_ACTIONS, } from './utils/create-build-array-actions' import { ActionMap, ActionMapBase } from './utils/create-map-action-group' -import { UpdateAction } from '@commercetools/sdk-client-v2' +import { UpdateAction } from './types/update-actions' export const baseActionsList: Array = [ { action: 'changeName', key: 'name' }, diff --git a/packages/sync-actions/src/tax-categories.ts b/packages/sync-actions/src/tax-categories.ts index 6e97a265d..dc4190472 100644 --- a/packages/sync-actions/src/tax-categories.ts +++ b/packages/sync-actions/src/tax-categories.ts @@ -2,26 +2,25 @@ import { TaxCategory, TaxCategoryUpdateAction, } from '@commercetools/platform-sdk' -import type { +import { actionsMapBase, actionsMapRates } from './tax-categories-actions' +import { ActionGroup, SyncActionConfig, + SyncAction, UpdateAction, -} from '@commercetools/sdk-client-v2' -import { actionsMapBase, actionsMapRates } from './tax-categories-actions' -import { SyncAction } from './types/update-actions' +} from './types/update-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup, { - MapActionGroup, - MapActionResult, + MapAction, } from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' export const actionGroups = ['base', 'rates'] -function createTaxCategoriesMapActions( - mapActionGroup: MapActionGroup, - syncActionConfig?: SyncActionConfig -): MapActionResult { +const createTaxCategoriesMapActions: MapAction = ( + mapActionGroup, + syncActionConfig +) => { return function doMapActions(diff, newObj, oldObj) { const allActions: Array> = [] allActions.push( diff --git a/packages/sync-actions/src/types-actions.ts b/packages/sync-actions/src/types-actions.ts index bcdaa4ee8..693599cd5 100644 --- a/packages/sync-actions/src/types-actions.ts +++ b/packages/sync-actions/src/types-actions.ts @@ -7,7 +7,7 @@ import createBuildArrayActions, { import { Delta, getDeltaValue } from './utils/diffpatcher' import extractMatchingPairs from './utils/extract-matching-pairs' import { ActionMapBase } from './utils/create-map-action-group' -import { UpdateAction } from '@commercetools/sdk-client-v2' +import { UpdateAction } from './types/update-actions' const REGEX_NUMBER = new RegExp(/^\d+$/) const REGEX_UNDERSCORE_NUMBER = new RegExp(/^_\d+$/) diff --git a/packages/sync-actions/src/types.ts b/packages/sync-actions/src/types.ts index bd59bd0c4..1ad368be3 100644 --- a/packages/sync-actions/src/types.ts +++ b/packages/sync-actions/src/types.ts @@ -1,21 +1,21 @@ import { Type, TypeUpdateAction } from '@commercetools/platform-sdk/src' -import { SyncActionConfig, UpdateAction } from '@commercetools/sdk-client-v2' import { actionsMapBase, actionsMapFieldDefinitions } from './types-actions' -import { SyncAction } from './types/update-actions' +import { + ActionGroup, + SyncActionConfig, + SyncAction, + UpdateAction, +} from './types/update-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup, { - MapActionGroup, - MapActionResult, + MapAction, } from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' import findMatchingPairs from './utils/find-matching-pairs' const actionGroups = ['base', 'fieldDefinitions'] -function createTypeMapActions( - mapActionGroup: MapActionGroup, - syncActionConfig?: SyncActionConfig -): MapActionResult { +const createTypeMapActions: MapAction = (mapActionGroup, syncActionConfig) => { return function doMapActions(diff, newObj, oldObj) { const allActions: Array> = [] allActions.push( diff --git a/packages/sync-actions/src/types/update-actions.ts b/packages/sync-actions/src/types/update-actions.ts index 5f6b66f5e..97bdfda45 100644 --- a/packages/sync-actions/src/types/update-actions.ts +++ b/packages/sync-actions/src/types/update-actions.ts @@ -1,4 +1,8 @@ -import { UpdateAction } from '@commercetools/sdk-client-v2' +export type UpdateAction = { + action: string + [key: string]: any + actionKey?: string +} export type SyncAction< R extends object | undefined, @@ -17,3 +21,11 @@ export type DeepPartial = T extends object [P in keyof T]?: DeepPartial } : T +export type SyncActionConfig = { + shouldOmitEmptyString: boolean +} + +export type ActionGroup = { + type: string + group: 'ignore' | 'allow' +} diff --git a/packages/sync-actions/src/utils/action-map-custom.ts b/packages/sync-actions/src/utils/action-map-custom.ts index 4996c065e..7f08e9dc1 100644 --- a/packages/sync-actions/src/utils/action-map-custom.ts +++ b/packages/sync-actions/src/utils/action-map-custom.ts @@ -1,5 +1,6 @@ import { Delta, getDeltaValue } from './diffpatcher' -import { UpdateAction } from '@commercetools/sdk-client-v2' + +import { UpdateAction } from '../types/update-actions' const Actions = { setCustomType: 'setCustomType', diff --git a/packages/sync-actions/src/utils/combine-validity-actions.ts b/packages/sync-actions/src/utils/combine-validity-actions.ts index 24fb3c459..5ee088693 100644 --- a/packages/sync-actions/src/utils/combine-validity-actions.ts +++ b/packages/sync-actions/src/utils/combine-validity-actions.ts @@ -1,4 +1,4 @@ -import { UpdateAction } from '@commercetools/sdk-client-v2' +import { UpdateAction } from '../types/update-actions' const validityActions = ['setValidFrom', 'setValidUntil'] diff --git a/packages/sync-actions/src/utils/common-actions.ts b/packages/sync-actions/src/utils/common-actions.ts index 3d243105e..1ced8e0c7 100644 --- a/packages/sync-actions/src/utils/common-actions.ts +++ b/packages/sync-actions/src/utils/common-actions.ts @@ -1,6 +1,6 @@ import clone, { notEmpty } from './clone' import { Delta, getDeltaValue, patch } from './diffpatcher' -import { UpdateAction } from '@commercetools/sdk-client-v2' +import { UpdateAction } from '../types/update-actions' const normalizeValue = (value: any) => typeof value === 'string' ? value.trim() : value diff --git a/packages/sync-actions/src/utils/create-build-actions.ts b/packages/sync-actions/src/utils/create-build-actions.ts index 2a3e5f328..c7faaf6d2 100644 --- a/packages/sync-actions/src/utils/create-build-actions.ts +++ b/packages/sync-actions/src/utils/create-build-actions.ts @@ -1,8 +1,6 @@ -import { UpdateAction } from '@commercetools/sdk-client-v2' import { deepEqual } from 'fast-equals' -import { DeepPartial } from '../types/update-actions' +import { DeepPartial, UpdateAction } from '../types/update-actions' import { Price, ProductVariant } from '@commercetools/platform-sdk' -import { MapActionResult } from './create-map-action-group' function applyOnBeforeDiff( before: any, diff --git a/packages/sync-actions/src/utils/create-build-array-actions.ts b/packages/sync-actions/src/utils/create-build-array-actions.ts index 397a4144f..351362dcf 100644 --- a/packages/sync-actions/src/utils/create-build-array-actions.ts +++ b/packages/sync-actions/src/utils/create-build-array-actions.ts @@ -1,6 +1,7 @@ -import { UpdateAction } from '@commercetools/sdk-client-v2' import { Delta } from './diffpatcher' +import { UpdateAction } from '../types/update-actions' + const REGEX_NUMBER = new RegExp(/^\d+$/) const REGEX_UNDERSCORE_NUMBER = new RegExp(/^_\d+$/) diff --git a/packages/sync-actions/src/utils/create-map-action-group.ts b/packages/sync-actions/src/utils/create-map-action-group.ts index 899f48dc7..30b27c372 100644 --- a/packages/sync-actions/src/utils/create-map-action-group.ts +++ b/packages/sync-actions/src/utils/create-map-action-group.ts @@ -5,15 +5,23 @@ // { type: 'prices', group: 'allow' }, // { type: 'variants', group: 'ignore' }, // ] -import { ActionGroup, UpdateAction } from '@commercetools/sdk-client-v2' import { Delta } from './diffpatcher' -export type MapActionGroup = ( +import { + ActionGroup, + SyncActionConfig, + UpdateAction, +} from '../types/update-actions' + +type MapActionGroup = ( type: string, fn: () => Array ) => Array -export type MapActionResult = ( +export type MapAction = ( + mapActionGroup: MapActionGroup, + syncActionConfig?: SyncActionConfig +) => ( diff: Delta, newObj: any, oldObj: any, diff --git a/packages/sync-actions/src/zones-actions.ts b/packages/sync-actions/src/zones-actions.ts index 8a6cff887..978cd3040 100644 --- a/packages/sync-actions/src/zones-actions.ts +++ b/packages/sync-actions/src/zones-actions.ts @@ -4,9 +4,9 @@ import createBuildArrayActions, { CHANGE_ACTIONS, REMOVE_ACTIONS, } from './utils/create-build-array-actions' -import { UpdateAction } from '@commercetools/sdk-client-v2' import { ActionMap, ActionMapBase } from './utils/create-map-action-group' import { Location } from '@commercetools/platform-sdk' +import { UpdateAction } from './types/update-actions' export const baseActionsList: Array = [ { action: 'changeName', key: 'name' }, diff --git a/packages/sync-actions/src/zones.ts b/packages/sync-actions/src/zones.ts index fd82a153a..d9c984734 100644 --- a/packages/sync-actions/src/zones.ts +++ b/packages/sync-actions/src/zones.ts @@ -1,24 +1,20 @@ import { Zone, ZoneUpdateAction } from '@commercetools/platform-sdk' -import type { +import { ActionGroup, SyncActionConfig, + SyncAction, UpdateAction, -} from '@commercetools/sdk-client-v2' -import { SyncAction } from './types/update-actions' +} from './types/update-actions' import createBuildActions from './utils/create-build-actions' import createMapActionGroup, { - MapActionGroup, - MapActionResult, + MapAction, } from './utils/create-map-action-group' import { diff } from './utils/diffpatcher' import * as zonesActions from './zones-actions' export const actionGroups = ['base', 'locations'] -function createZonesMapActions( - mapActionGroup: MapActionGroup, - syncActionConfig?: SyncActionConfig -): MapActionResult { +const createZonesMapActions: MapAction = (mapActionGroup, syncActionConfig) => { return function doMapActions(diff, newObj, oldObj) { const allActions: Array> = [] allActions.push( diff --git a/packages/sync-actions/test/price-sync.spec.ts b/packages/sync-actions/test/price-sync.spec.ts index 66e4572d5..466d5cf07 100644 --- a/packages/sync-actions/test/price-sync.spec.ts +++ b/packages/sync-actions/test/price-sync.spec.ts @@ -1,9 +1,11 @@ import pricesSyncFn, { actionGroups } from '../src/prices' +import { DeepPartial } from '../src/types/update-actions' +import { StandalonePrice } from '@commercetools/platform-sdk' const pricesSync = pricesSyncFn() -const dateNow = new Date() -const twoWeeksFromNow = new Date(Date.now() + 12096e5) +const dateNow = new Date().toString() +const twoWeeksFromNow = new Date(Date.now() + 12096e5).toString() /* eslint-disable max-len */ describe('price actions', () => { @@ -12,14 +14,14 @@ describe('price actions', () => { }) test('should not build actions if prices are not set', () => { - const before = {} - const now = {} + const before: DeepPartial = {} + const now: DeepPartial = {} const actions = pricesSync.buildActions(now, before) expect(actions).toEqual([]) }) test('should not build actions if now price is not set', () => { - const before = { + const before: DeepPartial = { id: '9fe6610f', value: { type: 'centPrecision', @@ -28,13 +30,13 @@ describe('price actions', () => { fractionDigits: 2, }, } - const now = {} + const now: DeepPartial = {} const actions = pricesSync.buildActions(now, before) expect(actions).toEqual([]) }) test('should not build actions if there is no change', () => { - const before = { + const before: DeepPartial = { id: '9fe6610f', value: { type: 'centPrecision', @@ -57,7 +59,7 @@ describe('price actions', () => { }, } - const now = { + const now: DeepPartial = { id: '9fe6610f', value: { type: 'centPrecision', @@ -85,7 +87,7 @@ describe('price actions', () => { describe('changeValue', () => { test('should generate changeValue action', () => { - const before = { + const before: DeepPartial = { id: '9fe6610f', value: { type: 'centPrecision', @@ -95,7 +97,7 @@ describe('price actions', () => { }, } - const now = { + const now: DeepPartial = { id: '9fe6610f', value: { type: 'centPrecision', @@ -122,7 +124,7 @@ describe('price actions', () => { describe('setDiscountedPrice', () => { test('should build `setDiscountedPrice` action for newly discounted', () => { - const before = { + const before: DeepPartial = { id: '1010', value: { currencyCode: 'EGP', centAmount: 1000 }, country: 'UK', @@ -130,7 +132,7 @@ describe('price actions', () => { validUntil: twoWeeksFromNow, } - const now = { + const now: DeepPartial = { id: '1010', value: { currencyCode: 'EGP', centAmount: 1000 }, country: 'UK', @@ -158,7 +160,7 @@ describe('price actions', () => { }) test('should build `setDiscountedPrice` action for removed discounted', () => { - const before = { + const before: DeepPartial = { id: '1010', value: { currencyCode: 'EGP', centAmount: 1000 }, country: 'UK', @@ -170,7 +172,7 @@ describe('price actions', () => { }, } - const now = { + const now: DeepPartial = { id: '1010', value: { currencyCode: 'EGP', centAmount: 1000 }, country: 'UK', @@ -190,7 +192,7 @@ describe('price actions', () => { }) test('should build `setDiscountedPrice` action for changed value centAmount', () => { - const before = { + const before: DeepPartial = { id: '1010', value: { currencyCode: 'GBP', centAmount: 1000 }, country: 'UK', @@ -202,7 +204,7 @@ describe('price actions', () => { }, } - const now = { + const now: DeepPartial = { id: '1010', value: { currencyCode: 'GBP', centAmount: 1000 }, country: 'UK', @@ -232,8 +234,8 @@ describe('price actions', () => { describe('setPriceTiers', () => { test('should build `setPriceTiers` action if price tier are set', () => { - const before = {} - const now = { + const before: DeepPartial = {} + const now: DeepPartial = { id: '9fe6610f', value: { type: 'centPrecision', @@ -282,7 +284,7 @@ describe('price actions', () => { }) test('should build `setPriceTiers` action for price tier change', () => { - const before = { + const before: DeepPartial = { id: '9fe6610f', value: { type: 'centPrecision', @@ -302,7 +304,7 @@ describe('price actions', () => { }, ], } - const now = { + const now: DeepPartial = { id: '9fe6610f', value: { type: 'centPrecision', @@ -342,7 +344,7 @@ describe('price actions', () => { }) test('should build `setPriceTiers` action for removed price tier', () => { - const before = { + const before: DeepPartial = { id: '9fe6610f', value: { type: 'centPrecision', @@ -372,7 +374,7 @@ describe('price actions', () => { ], } - const now = { + const now: DeepPartial = { id: '9fe6610f', value: { type: 'centPrecision', @@ -413,7 +415,7 @@ describe('price actions', () => { }) test('should build `setPriceTiers` action when removed all price tier', () => { - const before = { + const before: DeepPartial = { id: '9fe6610f', value: { type: 'centPrecision', @@ -443,7 +445,7 @@ describe('price actions', () => { ], } - const now = { + const now: DeepPartial = { id: '9fe6610f', value: { type: 'centPrecision', @@ -464,7 +466,7 @@ describe('price actions', () => { }) test('should not build `setPriceTiers` action when price tiers on now and then are equal', () => { - const before = { + const before: DeepPartial = { id: '9fe6610f', value: { type: 'centPrecision', @@ -494,7 +496,7 @@ describe('price actions', () => { ], } - const now = { + const now: DeepPartial = { id: '9fe6610f', value: { type: 'centPrecision', @@ -533,12 +535,12 @@ describe('price actions', () => { test('should build `setKey` action', () => { const key = 'test-key' - const before = { + const before: DeepPartial = { id: '1010', key: undefined, } - const now = { + const now: DeepPartial = { id: '1010', key, } @@ -555,13 +557,13 @@ describe('price actions', () => { describe('setValidFrom', () => { test('should build `setValidFrom` action', () => { - const before = { + const before: DeepPartial = { id: '1010', validFrom: dateNow, validUntil: dateNow, } - const now = { + const now: DeepPartial = { id: '1010', validFrom: twoWeeksFromNow, validUntil: dateNow, @@ -579,13 +581,13 @@ describe('price actions', () => { describe('setValidUntil', () => { test('should build `setValidUntil` action', () => { - const before = { + const before: DeepPartial = { id: '1010', validFrom: dateNow, validUntil: dateNow, } - const now = { + const now: DeepPartial = { id: '1010', validFrom: dateNow, validUntil: twoWeeksFromNow, @@ -603,13 +605,13 @@ describe('price actions', () => { describe('setValidFromAndUntil', () => { it('should build `setValidFromAndUntil` action', () => { - const before = { + const before: DeepPartial = { id: '1010', validFrom: dateNow, validUntil: dateNow, } - const now = { + const now: DeepPartial = { id: '1010', validFrom: twoWeeksFromNow, validUntil: twoWeeksFromNow, @@ -628,12 +630,12 @@ describe('price actions', () => { describe('changeActive', () => { test('should build `changeActive` action', () => { - const before = { + const before: DeepPartial = { id: '1010', active: false, } - const now = { + const now: DeepPartial = { id: '1010', active: true, } @@ -650,7 +652,7 @@ describe('price actions', () => { describe('setCustomType', () => { test('should build `setCustomType` action without fields', () => { - const before = { + const before: DeepPartial = { id: '888', value: { currencyCode: 'GBP', centAmount: 1000 }, country: 'UK', @@ -658,7 +660,7 @@ describe('price actions', () => { validUntil: twoWeeksFromNow, } - const now = { + const now: DeepPartial = { id: '888', value: { currencyCode: 'GBP', centAmount: 1000 }, country: 'UK', @@ -685,7 +687,7 @@ describe('price actions', () => { }) test('should build `setCustomType` action', () => { - const before = { + const before: DeepPartial = { id: '999', value: { currencyCode: 'GBP', centAmount: 1000 }, country: 'UK', @@ -693,7 +695,7 @@ describe('price actions', () => { validUntil: twoWeeksFromNow, } - const now = { + const now: DeepPartial = { // set price custom type and field id: '999', value: { currencyCode: 'GBP', centAmount: 1000 }, @@ -727,7 +729,7 @@ describe('price actions', () => { }) test('should build `setCustomType` action which delete custom type', () => { - const before = { + const before: DeepPartial = { id: '1111', value: { currencyCode: 'GBP', centAmount: 1000 }, country: 'UK', @@ -744,7 +746,7 @@ describe('price actions', () => { }, } - const now = { + const now: DeepPartial = { // remove price custom field and type id: '1111', value: { currencyCode: 'GBP', centAmount: 1000 }, @@ -764,7 +766,7 @@ describe('price actions', () => { describe('setCustomField', () => { test('should generate `setCustomField` actions', () => { - const before = { + const before: DeepPartial = { value: { type: 'centPrecision', currencyCode: 'EUR', @@ -784,7 +786,7 @@ describe('price actions', () => { }, } - const now = { + const now: DeepPartial = { value: { type: 'centPrecision', currencyCode: 'EUR', @@ -820,7 +822,7 @@ describe('price actions', () => { }) test('should build `setCustomField` action', () => { - const before = { + const before: DeepPartial = { id: '1010', value: { currencyCode: 'GBP', centAmount: 1000 }, country: 'UK', @@ -837,7 +839,7 @@ describe('price actions', () => { }, } - const now = { + const now: DeepPartial = { id: '1010', value: { currencyCode: 'GBP', centAmount: 1000 }, country: 'UK', @@ -865,7 +867,7 @@ describe('price actions', () => { }) test('should build three `setCustomField` action', () => { - const before = { + const before: DeepPartial = { id: '1010', value: { currencyCode: 'GBP', centAmount: 1000 }, country: 'UK', @@ -885,7 +887,7 @@ describe('price actions', () => { }, } - const now = { + const now: DeepPartial = { id: '1010', value: { currencyCode: 'GBP', centAmount: 1000 }, country: 'UK', From 1d0a9a19f4608b31df3d21fcd629e6fdd085c8f4 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Fri, 30 Aug 2024 12:26:25 +0200 Subject: [PATCH 30/33] feat(fix): introducing types --- packages/sync-actions/src/category-actions.ts | 4 +++- packages/sync-actions/src/customer-actions.ts | 4 ++-- packages/sync-actions/src/inventory-actions.ts | 2 +- packages/sync-actions/src/product-actions.ts | 4 ++-- packages/sync-actions/src/projects-actions.ts | 7 ++++--- 5 files changed, 12 insertions(+), 9 deletions(-) diff --git a/packages/sync-actions/src/category-actions.ts b/packages/sync-actions/src/category-actions.ts index 2715d357d..f07e1727c 100644 --- a/packages/sync-actions/src/category-actions.ts +++ b/packages/sync-actions/src/category-actions.ts @@ -20,7 +20,9 @@ export const metaActionsList: Array = [ { action: 'setMetaDescription', key: 'metaDescription' }, ] -export const referenceActionsList = [{ action: 'changeParent', key: 'parent' }] +export const referenceActionsList: Array = [ + { action: 'changeParent', key: 'parent' }, +] /** * SYNC FUNCTIONS diff --git a/packages/sync-actions/src/customer-actions.ts b/packages/sync-actions/src/customer-actions.ts index c98662a21..442019ef8 100644 --- a/packages/sync-actions/src/customer-actions.ts +++ b/packages/sync-actions/src/customer-actions.ts @@ -48,11 +48,11 @@ export const setDefaultBaseActionsList: Array = [ }, ] -export const referenceActionsList = [ +export const referenceActionsList: Array = [ { action: 'setCustomerGroup', key: 'customerGroup' }, ] -export const authenticationModeActionsList = [ +export const authenticationModeActionsList: Array = [ { action: 'setAuthenticationMode', key: 'authenticationMode', diff --git a/packages/sync-actions/src/inventory-actions.ts b/packages/sync-actions/src/inventory-actions.ts index 27be7f391..b06428b98 100644 --- a/packages/sync-actions/src/inventory-actions.ts +++ b/packages/sync-actions/src/inventory-actions.ts @@ -11,7 +11,7 @@ export const baseActionsList: Array = [ { action: 'setExpectedDelivery', key: 'expectedDelivery' }, ] -export const referenceActionsList = [ +export const referenceActionsList: Array = [ { action: 'setSupplyChannel', key: 'supplyChannel' }, ] diff --git a/packages/sync-actions/src/product-actions.ts b/packages/sync-actions/src/product-actions.ts index 15d81037b..2840a034a 100644 --- a/packages/sync-actions/src/product-actions.ts +++ b/packages/sync-actions/src/product-actions.ts @@ -41,13 +41,13 @@ export const baseAssetActionsList: Array = [ { action: 'setAssetSources', key: 'sources' }, ] -export const metaActionsList = [ +export const metaActionsList: Array = [ { action: 'setMetaTitle', key: 'metaTitle' }, { action: 'setMetaDescription', key: 'metaDescription' }, { action: 'setMetaKeywords', key: 'metaKeywords' }, ] -export const referenceActionsList = [ +export const referenceActionsList: Array = [ { action: 'setTaxCategory', key: 'taxCategory' }, { action: 'transitionState', key: 'state' }, ] diff --git a/packages/sync-actions/src/projects-actions.ts b/packages/sync-actions/src/projects-actions.ts index 656a0dcf5..b81470bb3 100644 --- a/packages/sync-actions/src/projects-actions.ts +++ b/packages/sync-actions/src/projects-actions.ts @@ -1,7 +1,8 @@ import { buildBaseAttributesActions } from './utils/common-actions' import { ActionMap, ActionMapBase } from './utils/create-map-action-group' +import { UpdateAction } from './types/update-actions' -export const baseActionsList = [ +export const baseActionsList: Array = [ { action: 'changeName', key: 'name' }, { action: 'changeCurrencies', key: 'currencies' }, { action: 'changeCountries', key: 'countries' }, @@ -14,7 +15,7 @@ export const baseActionsList = [ { action: 'setShippingRateInputType', key: 'shippingRateInputType' }, ] -export const myBusinessUnitActionsList = [ +export const myBusinessUnitActionsList: Array = [ { action: 'changeMyBusinessUnitStatusOnCreation', key: 'myBusinessUnitStatusOnCreation', @@ -27,7 +28,7 @@ export const myBusinessUnitActionsList = [ }, ] -export const customerSearchActionsList = [ +export const customerSearchActionsList: Array = [ { action: 'changeCustomerSearchStatus', key: 'status', From daca08cd0b2886201fbc9b9de7cccf3dcd5a73bc Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Fri, 30 Aug 2024 13:09:12 +0200 Subject: [PATCH 31/33] feat(fix): introducing types --- packages/sync-actions/src/product-types-actions.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/sync-actions/src/product-types-actions.ts b/packages/sync-actions/src/product-types-actions.ts index a8dc01362..1bd63c470 100644 --- a/packages/sync-actions/src/product-types-actions.ts +++ b/packages/sync-actions/src/product-types-actions.ts @@ -206,7 +206,7 @@ const generateUpdateActionsForAttributeEnumValues = ( return [ ...Object.values( - removedAttributeEnumValues.reduce( + removedAttributeEnumValues.reduce<{ [key: string]: any }>( (nextEnumUpdateActions, removedAttributeEnumValue) => { const removedAttributeEnumValueOfSameAttributeName = nextEnumUpdateActions[ From 27c17da469c350216f9cd2977d355fdd8c376278 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Fri, 30 Aug 2024 14:32:58 +0200 Subject: [PATCH 32/33] feat(chore): removed unused --- packages/sync-actions/src/projects.ts | 11 ++++------- packages/sync-actions/test/projects-sync.spec.ts | 2 +- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/packages/sync-actions/src/projects.ts b/packages/sync-actions/src/projects.ts index 73b0133fd..c3f472f5b 100644 --- a/packages/sync-actions/src/projects.ts +++ b/packages/sync-actions/src/projects.ts @@ -17,6 +17,7 @@ import { ActionGroup, SyncAction, SyncActionConfig, + UpdateAction, } from './types/update-actions' export const actionGroups = ['base', 'myBusinessUnit', 'customerSearch'] @@ -26,7 +27,7 @@ const createChannelsMapActions: MapAction = ( syncActionConfig ) => { return function doMapActions(diff, newObj, oldObj) { - const allActions = [] + const allActions: Array> = [] allActions.push( mapActionGroup('base', () => @@ -50,20 +51,16 @@ const createChannelsMapActions: MapAction = ( } } -export type ProjectSync = { - messagesConfiguration: MessagesConfigurationDraft -} & Project - export default ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createChannelsMapActions( mapActionGroup, syncActionConfig ) - const buildActions = createBuildActions( + const buildActions = createBuildActions( diff, doMapActions ) diff --git a/packages/sync-actions/test/projects-sync.spec.ts b/packages/sync-actions/test/projects-sync.spec.ts index fa352e6bb..ee2ebfea1 100644 --- a/packages/sync-actions/test/projects-sync.spec.ts +++ b/packages/sync-actions/test/projects-sync.spec.ts @@ -1,4 +1,4 @@ -import createProjectsSync, { actionGroups, ProjectSync } from '../src/projects' +import createProjectsSync, { actionGroups } from '../src/projects' import { baseActionsList, myBusinessUnitActionsList, From b27864a0a98411ecf1416ab0e4fffa3d98d62dc9 Mon Sep 17 00:00:00 2001 From: Philipp Hofmann Date: Fri, 30 Aug 2024 14:56:04 +0200 Subject: [PATCH 33/33] feat(fix): proper exports --- packages/sync-actions/src/attribute-groups.ts | 2 +- packages/sync-actions/src/cart-discounts.ts | 2 +- packages/sync-actions/src/categories.ts | 2 +- packages/sync-actions/src/channels.ts | 2 +- packages/sync-actions/src/customer-group.ts | 2 +- packages/sync-actions/src/customers.ts | 2 +- packages/sync-actions/src/discount-codes.ts | 2 +- packages/sync-actions/src/index.ts | 45 ++++++++++--------- packages/sync-actions/src/inventories.ts | 2 +- packages/sync-actions/src/orders.ts | 7 +-- packages/sync-actions/src/prices.ts | 2 +- .../sync-actions/src/product-discounts.ts | 2 +- .../sync-actions/src/product-selections.ts | 2 +- packages/sync-actions/src/product-types.ts | 2 +- packages/sync-actions/src/products.ts | 2 +- packages/sync-actions/src/projects.ts | 2 +- packages/sync-actions/src/quote-requests.ts | 2 +- packages/sync-actions/src/quotes.ts | 2 +- packages/sync-actions/src/shipping-methods.ts | 2 +- packages/sync-actions/src/staged-quotes.ts | 2 +- packages/sync-actions/src/states.ts | 2 +- packages/sync-actions/src/stores.ts | 2 +- packages/sync-actions/src/tax-categories.ts | 2 +- packages/sync-actions/src/types.ts | 2 +- packages/sync-actions/src/zones.ts | 2 +- .../test/attribute-groups-sync.spec.ts | 6 +-- .../test/cart-discounts-sync.spec.ts | 6 +-- .../sync-actions/test/category-sync.spec.ts | 6 +-- .../sync-actions/test/channels-sync-.spec.ts | 6 +-- .../test/customer-group-sync.spec.ts | 6 +-- .../sync-actions/test/customer-sync.spec.ts | 6 +-- .../test/discount-codes-sync.spec.ts | 6 +-- .../sync-actions/test/inventory-sync.spec.ts | 6 +-- packages/sync-actions/test/order-sync.spec.ts | 35 ++++++++------- packages/sync-actions/test/price-sync.spec.ts | 4 +- .../test/product-discounts-sync.spec.ts | 9 ++-- .../test/product-selections-sync.spec.ts | 7 +-- .../test/product-sync-base.spec.ts | 6 +-- .../test/product-sync-images.spec.ts | 6 +-- .../test/product-sync-prices.spec.ts | 6 +-- .../test/product-sync-variants.spec.ts | 6 +-- ...product-types-sync-attribute-hints.spec.ts | 2 +- .../test/product-types-sync-base.spec.ts | 2 +- .../sync-actions/test/projects-sync.spec.ts | 10 ++--- .../test/quote-requests-sync.spec.ts | 6 +-- .../sync-actions/test/quotes-sync.spec.ts | 6 +-- .../test/shipping-methods.spec.ts | 9 ++-- .../test/staged-quotes-sync.spec.ts | 7 +-- .../sync-actions/test/states-sync.spec.ts | 6 +-- .../sync-actions/test/stores-sync.spec.ts | 6 +-- .../test/tax-categories-sync.spec.ts | 6 +-- .../sync-actions/test/types-sync-base.spec.ts | 5 +-- .../test/types-sync-enums.spec.ts | 6 +-- .../test/types-sync-fields.spec.ts | 6 +-- packages/sync-actions/test/zones.spec.ts | 6 +-- 55 files changed, 160 insertions(+), 148 deletions(-) diff --git a/packages/sync-actions/src/attribute-groups.ts b/packages/sync-actions/src/attribute-groups.ts index 6094b6ee9..9a037ae01 100644 --- a/packages/sync-actions/src/attribute-groups.ts +++ b/packages/sync-actions/src/attribute-groups.ts @@ -39,7 +39,7 @@ const createAttributeGroupsMapActions: MapAction = ( } } -export default ( +export const createSyncAttributeGroups = ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig ): SyncAction => { diff --git a/packages/sync-actions/src/cart-discounts.ts b/packages/sync-actions/src/cart-discounts.ts index 8201db209..f19a526be 100644 --- a/packages/sync-actions/src/cart-discounts.ts +++ b/packages/sync-actions/src/cart-discounts.ts @@ -40,7 +40,7 @@ const createCartDiscountsMapActions: MapAction = ( } } -export default ( +export const createSyncCartDiscounts = ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig ): SyncAction => { diff --git a/packages/sync-actions/src/categories.ts b/packages/sync-actions/src/categories.ts index 35eecc79a..2c7dddbce 100644 --- a/packages/sync-actions/src/categories.ts +++ b/packages/sync-actions/src/categories.ts @@ -56,7 +56,7 @@ const createCategoryMapActions: MapAction = ( } } -export default ( +export const createSyncCategories = ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig ): SyncAction => { diff --git a/packages/sync-actions/src/channels.ts b/packages/sync-actions/src/channels.ts index 401ada995..11df85aa3 100644 --- a/packages/sync-actions/src/channels.ts +++ b/packages/sync-actions/src/channels.ts @@ -36,7 +36,7 @@ const createChannelsMapActions: MapAction = ( } } -export default ( +export const createSyncChannels = ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig ): SyncAction => { diff --git a/packages/sync-actions/src/customer-group.ts b/packages/sync-actions/src/customer-group.ts index d517aca4f..677ef1e5b 100644 --- a/packages/sync-actions/src/customer-group.ts +++ b/packages/sync-actions/src/customer-group.ts @@ -39,7 +39,7 @@ const createCustomerGroupMapActions: MapAction = ( } } -export default ( +export const createSyncCustomerGroup = ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig ): SyncAction => { diff --git a/packages/sync-actions/src/customers.ts b/packages/sync-actions/src/customers.ts index 530df0074..4a1845259 100644 --- a/packages/sync-actions/src/customers.ts +++ b/packages/sync-actions/src/customers.ts @@ -87,7 +87,7 @@ const createCustomerMapActions: MapAction = ( } } -export default ( +export const createSyncCustomers = ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig ): SyncAction => { diff --git a/packages/sync-actions/src/discount-codes.ts b/packages/sync-actions/src/discount-codes.ts index 6658ed485..8daa85f01 100644 --- a/packages/sync-actions/src/discount-codes.ts +++ b/packages/sync-actions/src/discount-codes.ts @@ -37,7 +37,7 @@ const createDiscountCodesMapActions: MapAction = ( } } -export default ( +export const createSyncDiscountCodes = ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig ): SyncAction => { diff --git a/packages/sync-actions/src/index.ts b/packages/sync-actions/src/index.ts index b0008b097..fc3b85e74 100644 --- a/packages/sync-actions/src/index.ts +++ b/packages/sync-actions/src/index.ts @@ -1,23 +1,26 @@ -export { default as createSyncAttributeGroups } from './attribute-groups' -export { default as createSyncCartDiscounts } from './cart-discounts' -export { default as createSyncCategories } from './categories' -export { default as createSyncChannels } from './channels' -export { default as createSyncCustomerGroup } from './customer-group' -export { default as createSyncCustomers } from './customers' -export { default as createSyncDiscountCodes } from './discount-codes' -export { default as createSyncInventories } from './inventories' -export { default as createSyncOrders } from './orders' -export { default as createSyncStandalonePrices } from './prices' -export { default as createSyncProductDiscounts } from './product-discounts' -export { default as createSyncProductSelections } from './product-selections' -export { default as createSyncProductTypes } from './product-types' -export { default as createSyncProducts } from './products' -export { default as createSyncProjects } from './projects' -export { default as createSyncShippingMethods } from './shipping-methods' -export { default as createSyncStates } from './states' -export { default as createSyncStores } from './stores' -export { default as createSyncTaxCategories } from './tax-categories' -export { default as createSyncTypes } from './types' -export { default as createSyncZones } from './zones' +export { createSyncAttributeGroups } from './attribute-groups' +export { createSyncCartDiscounts } from './cart-discounts' +export { createSyncCategories } from './categories' +export { createSyncChannels } from './channels' +export { createSyncCustomerGroup } from './customer-group' +export { createSyncCustomers } from './customers' +export { createSyncDiscountCodes } from './discount-codes' +export { createSyncInventories } from './inventories' +export { createSyncOrders } from './orders' +export { createSyncStandalonePrices } from './prices' +export { createSyncProductDiscounts } from './product-discounts' +export { createSyncProductSelections } from './product-selections' +export { createSyncProductTypes } from './product-types' +export { createSyncProducts } from './products' +export { createSyncProjects } from './projects' +export { createSyncQuoteRequest } from './quote-requests' +export { createSyncQuote } from './quotes' +export { createSyncShippingMethods } from './shipping-methods' +export { createSyncStagedQuote } from './staged-quotes' +export { createSyncStates } from './states' +export { createSyncStores } from './stores' +export { createSyncTaxCategories } from './tax-categories' +export { createSyncTypes } from './types' +export { createSyncZones } from './zones' export { type ActionGroup } from './types/update-actions' export { type SyncActionConfig } from './types/update-actions' diff --git a/packages/sync-actions/src/inventories.ts b/packages/sync-actions/src/inventories.ts index bfbfab093..35d390502 100644 --- a/packages/sync-actions/src/inventories.ts +++ b/packages/sync-actions/src/inventories.ts @@ -42,7 +42,7 @@ const createInventoryMapActions: MapAction = ( } } -export default ( +export const createSyncInventories = ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig ): SyncAction => { diff --git a/packages/sync-actions/src/orders.ts b/packages/sync-actions/src/orders.ts index 94edc9166..63c2b013c 100644 --- a/packages/sync-actions/src/orders.ts +++ b/packages/sync-actions/src/orders.ts @@ -1,5 +1,6 @@ import { CustomFields, + Order, OrderUpdateAction, ReturnInfo, ShippingInfo, @@ -88,10 +89,10 @@ export type OrderSync = { custom: CustomFields } -export default ( +export const createSyncOrders = ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig -): SyncAction => { +): SyncAction => { // actionGroupList contains information about which action groups // are allowed or ignored @@ -105,7 +106,7 @@ export default ( // It will return an empty array for ignored action groups const mapActionGroup = createMapActionGroup(actionGroupList) const doMapActions = createOrderMapActions(mapActionGroup, syncActionConfig) - const buildActions = createBuildActions( + const buildActions = createBuildActions( diff, doMapActions ) diff --git a/packages/sync-actions/src/prices.ts b/packages/sync-actions/src/prices.ts index 7fde71316..44a479c62 100644 --- a/packages/sync-actions/src/prices.ts +++ b/packages/sync-actions/src/prices.ts @@ -32,7 +32,7 @@ const createPriceMapActions: MapAction = (mapActionGroup, syncActionConfig) => { } } -export default ( +export const createSyncStandalonePrices = ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig ): SyncAction => { diff --git a/packages/sync-actions/src/product-discounts.ts b/packages/sync-actions/src/product-discounts.ts index 5cf19a01c..1e0d8cacd 100644 --- a/packages/sync-actions/src/product-discounts.ts +++ b/packages/sync-actions/src/product-discounts.ts @@ -34,7 +34,7 @@ const createProductDiscountsMapActions: MapAction = ( } } -export default ( +export const createSyncProductDiscounts = ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig ): SyncAction => { diff --git a/packages/sync-actions/src/product-selections.ts b/packages/sync-actions/src/product-selections.ts index b525939d6..cb8b34b83 100644 --- a/packages/sync-actions/src/product-selections.ts +++ b/packages/sync-actions/src/product-selections.ts @@ -45,7 +45,7 @@ function createProductSelectionsMapActions( } } -export default ( +export const createSyncProductSelections = ( actionGroupList?: Array ): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) diff --git a/packages/sync-actions/src/product-types.ts b/packages/sync-actions/src/product-types.ts index d400faf02..5fb325d5a 100644 --- a/packages/sync-actions/src/product-types.ts +++ b/packages/sync-actions/src/product-types.ts @@ -42,7 +42,7 @@ const createProductTypeMapActions: MapAction = ( } } -export default ( +export const createSyncProductTypes = ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig ) => { diff --git a/packages/sync-actions/src/products.ts b/packages/sync-actions/src/products.ts index d03878fce..e29b213eb 100644 --- a/packages/sync-actions/src/products.ts +++ b/packages/sync-actions/src/products.ts @@ -154,7 +154,7 @@ function moveMasterVariantsIntoVariants(before: any, now: any): Array { export type ProductSync = { key: string; id: string } & ProductData -export default ( +export const createSyncProducts = ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig ): SyncAction => { diff --git a/packages/sync-actions/src/projects.ts b/packages/sync-actions/src/projects.ts index c3f472f5b..ba4097f30 100644 --- a/packages/sync-actions/src/projects.ts +++ b/packages/sync-actions/src/projects.ts @@ -51,7 +51,7 @@ const createChannelsMapActions: MapAction = ( } } -export default ( +export const createSyncProjects = ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig ): SyncAction => { diff --git a/packages/sync-actions/src/quote-requests.ts b/packages/sync-actions/src/quote-requests.ts index 03312abda..d2ae861da 100644 --- a/packages/sync-actions/src/quote-requests.ts +++ b/packages/sync-actions/src/quote-requests.ts @@ -39,7 +39,7 @@ const createQuoteRequestsMapActions: MapAction = ( } } -export default ( +export const createSyncQuoteRequest = ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig ): SyncAction => { diff --git a/packages/sync-actions/src/quotes.ts b/packages/sync-actions/src/quotes.ts index 92b3bd623..878830740 100644 --- a/packages/sync-actions/src/quotes.ts +++ b/packages/sync-actions/src/quotes.ts @@ -36,7 +36,7 @@ const createQuotesMapActions: MapAction = ( } } -export default ( +export const createSyncQuote = ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig ): SyncAction => { diff --git a/packages/sync-actions/src/shipping-methods.ts b/packages/sync-actions/src/shipping-methods.ts index 9d27565b6..3c2bbbfcd 100644 --- a/packages/sync-actions/src/shipping-methods.ts +++ b/packages/sync-actions/src/shipping-methods.ts @@ -41,7 +41,7 @@ const createShippingMethodsMapActions: MapAction = ( } } -export default ( +export const createSyncShippingMethods = ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig ): SyncAction => { diff --git a/packages/sync-actions/src/staged-quotes.ts b/packages/sync-actions/src/staged-quotes.ts index b37008146..ea17266f6 100644 --- a/packages/sync-actions/src/staged-quotes.ts +++ b/packages/sync-actions/src/staged-quotes.ts @@ -45,7 +45,7 @@ export type StagedQuoteSync = { custom: CustomFields } & StagedQuote -export default ( +export const createSyncStagedQuote = ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig ): SyncAction => { diff --git a/packages/sync-actions/src/states.ts b/packages/sync-actions/src/states.ts index 9f6306f77..76c76a1b3 100644 --- a/packages/sync-actions/src/states.ts +++ b/packages/sync-actions/src/states.ts @@ -49,7 +49,7 @@ const createStatesMapActions: MapAction = ( } } -export default ( +export const createSyncStates = ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig ): SyncAction => { diff --git a/packages/sync-actions/src/stores.ts b/packages/sync-actions/src/stores.ts index 99cf348b7..a02a52dd0 100644 --- a/packages/sync-actions/src/stores.ts +++ b/packages/sync-actions/src/stores.ts @@ -42,7 +42,7 @@ function createStoresMapActions( } } -export default ( +export const createSyncStores = ( actionGroupList?: Array ): SyncAction => { const mapActionGroup = createMapActionGroup(actionGroupList) diff --git a/packages/sync-actions/src/tax-categories.ts b/packages/sync-actions/src/tax-categories.ts index dc4190472..b8428ae78 100644 --- a/packages/sync-actions/src/tax-categories.ts +++ b/packages/sync-actions/src/tax-categories.ts @@ -35,7 +35,7 @@ const createTaxCategoriesMapActions: MapAction = ( } } -export default ( +export const createSyncTaxCategories = ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig ): SyncAction => { diff --git a/packages/sync-actions/src/types.ts b/packages/sync-actions/src/types.ts index 1ad368be3..2a72e8866 100644 --- a/packages/sync-actions/src/types.ts +++ b/packages/sync-actions/src/types.ts @@ -40,7 +40,7 @@ const createTypeMapActions: MapAction = (mapActionGroup, syncActionConfig) => { } } -export default ( +export const createSyncTypes = ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig ): SyncAction => { diff --git a/packages/sync-actions/src/zones.ts b/packages/sync-actions/src/zones.ts index d9c984734..2c6f4ad6d 100644 --- a/packages/sync-actions/src/zones.ts +++ b/packages/sync-actions/src/zones.ts @@ -31,7 +31,7 @@ const createZonesMapActions: MapAction = (mapActionGroup, syncActionConfig) => { } } -export default ( +export const createSyncZones = ( actionGroupList?: Array, syncActionConfig?: SyncActionConfig ): SyncAction => { diff --git a/packages/sync-actions/test/attribute-groups-sync.spec.ts b/packages/sync-actions/test/attribute-groups-sync.spec.ts index b08b7f732..ac49f9d02 100644 --- a/packages/sync-actions/test/attribute-groups-sync.spec.ts +++ b/packages/sync-actions/test/attribute-groups-sync.spec.ts @@ -1,4 +1,4 @@ -import attributeGroupSyncFn from '../src/attribute-groups' +import { createSyncAttributeGroups } from '../src' import { baseActionsList } from '../src/attribute-groups-actions' describe('Exports', () => { @@ -12,9 +12,9 @@ describe('Exports', () => { }) describe('Actions', () => { - let attributeGroupSync = attributeGroupSyncFn() + let attributeGroupSync = createSyncAttributeGroups() beforeEach(() => { - attributeGroupSync = attributeGroupSyncFn() + attributeGroupSync = createSyncAttributeGroups() }) test('should build `changeName` action', () => { diff --git a/packages/sync-actions/test/cart-discounts-sync.spec.ts b/packages/sync-actions/test/cart-discounts-sync.spec.ts index be5eef2de..52a4b5071 100644 --- a/packages/sync-actions/test/cart-discounts-sync.spec.ts +++ b/packages/sync-actions/test/cart-discounts-sync.spec.ts @@ -1,4 +1,4 @@ -import cartDiscountsSyncFn, { actionGroups } from '../src/cart-discounts' +import { actionGroups, createSyncCartDiscounts } from '../src/cart-discounts' import { baseActionsList } from '../src/cart-discounts-actions' import { DeepPartial } from '../src/types/update-actions' import { CartDiscountDraft } from '@commercetools/platform-sdk/src' @@ -111,9 +111,9 @@ describe('Cart Discounts Exports', () => { }) describe('Cart Discounts Actions', () => { - let cartDiscountsSync = cartDiscountsSyncFn() + let cartDiscountsSync = createSyncCartDiscounts() beforeEach(() => { - cartDiscountsSync = cartDiscountsSyncFn() + cartDiscountsSync = createSyncCartDiscounts() }) test('should build the `changeIsActive` action', () => { diff --git a/packages/sync-actions/test/category-sync.spec.ts b/packages/sync-actions/test/category-sync.spec.ts index e408be32d..5a2e50ecb 100644 --- a/packages/sync-actions/test/category-sync.spec.ts +++ b/packages/sync-actions/test/category-sync.spec.ts @@ -1,4 +1,4 @@ -import categorySyncFn, { actionGroups } from '../src/categories' +import { createSyncCategories, actionGroups } from '../src/categories' import { DeepPartial } from '../src/types/update-actions' import { baseActionsList, @@ -45,9 +45,9 @@ describe('Exports', () => { }) describe('Actions', () => { - let categorySync = categorySyncFn() + let categorySync = createSyncCategories() beforeEach(() => { - categorySync = categorySyncFn() + categorySync = createSyncCategories() }) describe('custom fields', () => { diff --git a/packages/sync-actions/test/channels-sync-.spec.ts b/packages/sync-actions/test/channels-sync-.spec.ts index b0413e36b..f2c891378 100644 --- a/packages/sync-actions/test/channels-sync-.spec.ts +++ b/packages/sync-actions/test/channels-sync-.spec.ts @@ -1,4 +1,4 @@ -import createChannelsSync, { actionGroups } from '../src/channels' +import { createSyncChannels, actionGroups } from '../src/channels' import { baseActionsList } from '../src/channels-actions' import { DeepPartial } from '../src/types/update-actions' import { ChannelDraft } from '@commercetools/platform-sdk/src' @@ -68,9 +68,9 @@ describe('Exports', () => { }) describe('Actions', () => { - let channelsSync = createChannelsSync() + let channelsSync = createSyncChannels() beforeEach(() => { - channelsSync = createChannelsSync() + channelsSync = createSyncChannels() }) test('should build `changeKey` action', () => { diff --git a/packages/sync-actions/test/customer-group-sync.spec.ts b/packages/sync-actions/test/customer-group-sync.spec.ts index 6aeb75d83..62ea48d26 100644 --- a/packages/sync-actions/test/customer-group-sync.spec.ts +++ b/packages/sync-actions/test/customer-group-sync.spec.ts @@ -1,4 +1,4 @@ -import customerGroupSyncFn, { actionGroups } from '../src/customer-group' +import { actionGroups, createSyncCustomerGroup } from '../src/customer-group' import { baseActionsList } from '../src/customer-group-actions' import { DeepPartial } from '../src/types/update-actions' import { @@ -32,9 +32,9 @@ describe('Customer Groups Exports', () => { }) describe('Customer Groups Actions', () => { - let customerGroupSync = customerGroupSyncFn() + let customerGroupSync = createSyncCustomerGroup() beforeEach(() => { - customerGroupSync = customerGroupSyncFn() + customerGroupSync = createSyncCustomerGroup() }) test('should build the `changeName` action', () => { diff --git a/packages/sync-actions/test/customer-sync.spec.ts b/packages/sync-actions/test/customer-sync.spec.ts index 98a5f4e76..4f7503c44 100644 --- a/packages/sync-actions/test/customer-sync.spec.ts +++ b/packages/sync-actions/test/customer-sync.spec.ts @@ -1,4 +1,4 @@ -import customerSyncFn, { actionGroups } from '../src/customers' +import { actionGroups, createSyncCustomers } from '../src/customers' import { baseActionsList, setDefaultBaseActionsList, @@ -66,9 +66,9 @@ describe('Exports', () => { }) describe('Actions', () => { - let customerSync = customerSyncFn() + let customerSync = createSyncCustomers() beforeEach(() => { - customerSync = customerSyncFn() + customerSync = createSyncCustomers() }) test('should build `setSalutation` action', () => { diff --git a/packages/sync-actions/test/discount-codes-sync.spec.ts b/packages/sync-actions/test/discount-codes-sync.spec.ts index 7f8163adc..a63d5c9a3 100644 --- a/packages/sync-actions/test/discount-codes-sync.spec.ts +++ b/packages/sync-actions/test/discount-codes-sync.spec.ts @@ -1,4 +1,4 @@ -import discountCodesSyncFn, { actionGroups } from '../src/discount-codes' +import { actionGroups, createSyncDiscountCodes } from '../src/discount-codes' import { baseActionsList } from '../src/discount-codes-actions' import { DeepPartial } from '../src/types/update-actions' import { DiscountCodeDraft } from '@commercetools/platform-sdk/src' @@ -97,9 +97,9 @@ describe('Exports', () => { }) describe('Actions', () => { - let discountCodesSync = discountCodesSyncFn() + let discountCodesSync = createSyncDiscountCodes() beforeEach(() => { - discountCodesSync = discountCodesSyncFn() + discountCodesSync = createSyncDiscountCodes() }) test('should build `changeIsActive` action', () => { diff --git a/packages/sync-actions/test/inventory-sync.spec.ts b/packages/sync-actions/test/inventory-sync.spec.ts index 5f77d6830..f42784d14 100644 --- a/packages/sync-actions/test/inventory-sync.spec.ts +++ b/packages/sync-actions/test/inventory-sync.spec.ts @@ -1,4 +1,4 @@ -import inventorySyncFn, { actionGroups } from '../src/inventories' +import { actionGroups, createSyncInventories } from '../src/inventories' import { baseActionsList, referenceActionsList } from '../src/inventory-actions' import { InventoryEntryDraft } from '@commercetools/platform-sdk/src' @@ -27,9 +27,9 @@ describe('Exports', () => { }) describe('Actions', () => { - let inventorySync = inventorySyncFn() + let inventorySync = createSyncInventories() beforeEach(() => { - inventorySync = inventorySyncFn() + inventorySync = createSyncInventories() }) test('should build `changeQuantity` action', () => { diff --git a/packages/sync-actions/test/order-sync.spec.ts b/packages/sync-actions/test/order-sync.spec.ts index c0a09bb06..bc3c482ca 100644 --- a/packages/sync-actions/test/order-sync.spec.ts +++ b/packages/sync-actions/test/order-sync.spec.ts @@ -1,7 +1,8 @@ import { performance } from 'perf_hooks' -import orderSyncFn, { actionGroups, OrderSync } from '../src/orders' +import { actionGroups, createSyncOrders } from '../src/orders' import { baseActionsList } from '../src/order-actions' import { DeepPartial } from '../src/types/update-actions' +import { Order } from '@commercetools/platform-sdk' describe('Exports', () => { test('action group list', () => { @@ -18,14 +19,14 @@ describe('Exports', () => { }) describe('Actions', () => { - let orderSync = orderSyncFn() + let orderSync = createSyncOrders() beforeEach(() => { - orderSync = orderSyncFn() + orderSync = createSyncOrders() }) describe('base', () => { test('should build *state actions', () => { - const before: DeepPartial = { + const before: DeepPartial = { orderState: 'Open', paymentState: 'Pending', shipmentState: 'Ready', @@ -48,12 +49,12 @@ describe('Actions', () => { describe('deliveries', () => { test('should build `addDelivery` action', () => { - const before: DeepPartial = { + const before: DeepPartial = { shippingInfo: { deliveries: [], }, } - const now: DeepPartial = { + const now: DeepPartial = { shippingInfo: { deliveries: [ { @@ -305,7 +306,7 @@ describe('Actions', () => { }) test('should create remove `parcel` action', () => { - const before: DeepPartial = { + const before: DeepPartial = { shippingInfo: { deliveries: [ { @@ -329,7 +330,7 @@ describe('Actions', () => { }, } - const now: DeepPartial = { + const now: DeepPartial = { shippingInfo: { deliveries: [ { @@ -354,11 +355,11 @@ describe('Actions', () => { describe('returnInfo', () => { test('should not build `returnInfo` action if items are not set', () => { - const before: DeepPartial = { + const before: DeepPartial = { returnInfo: [], } - const now: DeepPartial = { + const now: DeepPartial = { returnInfo: [ { returnTrackingId: 'tracking-id-1', @@ -377,7 +378,7 @@ describe('Actions', () => { returnInfo: [], } - const now: DeepPartial = { + const now: DeepPartial = { returnInfo: [ { returnTrackingId: 'tracking-id-1', @@ -840,12 +841,12 @@ describe('Actions', () => { }) describe('custom fields', () => { - let orderSync = orderSyncFn() + let orderSync = createSyncOrders() beforeEach(() => { - orderSync = orderSyncFn() + orderSync = createSyncOrders() }) test('should build `setCustomType` action', () => { - const before: DeepPartial = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -856,7 +857,7 @@ describe('custom fields', () => { }, }, } - const now: DeepPartial = { + const now: DeepPartial = { custom: { type: { typeId: 'type', @@ -872,7 +873,7 @@ describe('custom fields', () => { expect(actual).toEqual(expected) }) test('should build `setCustomField` action', () => { - const before: DeepPartial = { + const before: DeepPartial = { custom: { type: { typeId: 'type', @@ -883,7 +884,7 @@ describe('custom fields', () => { }, }, } - const now: DeepPartial = { + const now: DeepPartial = { custom: { type: { typeId: 'type', diff --git a/packages/sync-actions/test/price-sync.spec.ts b/packages/sync-actions/test/price-sync.spec.ts index 466d5cf07..29308aa2f 100644 --- a/packages/sync-actions/test/price-sync.spec.ts +++ b/packages/sync-actions/test/price-sync.spec.ts @@ -1,8 +1,8 @@ -import pricesSyncFn, { actionGroups } from '../src/prices' +import { actionGroups, createSyncStandalonePrices } from '../src/prices' import { DeepPartial } from '../src/types/update-actions' import { StandalonePrice } from '@commercetools/platform-sdk' -const pricesSync = pricesSyncFn() +const pricesSync = createSyncStandalonePrices() const dateNow = new Date().toString() const twoWeeksFromNow = new Date(Date.now() + 12096e5).toString() diff --git a/packages/sync-actions/test/product-discounts-sync.spec.ts b/packages/sync-actions/test/product-discounts-sync.spec.ts index 5fa50da0d..1572e5ca4 100644 --- a/packages/sync-actions/test/product-discounts-sync.spec.ts +++ b/packages/sync-actions/test/product-discounts-sync.spec.ts @@ -1,4 +1,7 @@ -import productDiscountsSyncFn, { actionGroups } from '../src/product-discounts' +import { + actionGroups, + createSyncProductDiscounts, +} from '../src/product-discounts' import { baseActionsList } from '../src/product-discounts-actions' import { DeepPartial } from '../src/types/update-actions' import { ProductDiscountDraft } from '@commercetools/platform-sdk/src' @@ -78,9 +81,9 @@ describe('Exports', () => { }) describe('Actions', () => { - let productDiscountsSync = productDiscountsSyncFn() + let productDiscountsSync = createSyncProductDiscounts() beforeEach(() => { - productDiscountsSync = productDiscountsSyncFn() + productDiscountsSync = createSyncProductDiscounts() }) test('should build the `changeIsActive` action', () => { diff --git a/packages/sync-actions/test/product-selections-sync.spec.ts b/packages/sync-actions/test/product-selections-sync.spec.ts index 0b2045055..ee554923b 100644 --- a/packages/sync-actions/test/product-selections-sync.spec.ts +++ b/packages/sync-actions/test/product-selections-sync.spec.ts @@ -1,6 +1,7 @@ import { baseActionsList } from '../src/product-selections-actions' -import productSelectionsSyncFn, { +import { actionGroups, + createSyncProductSelections, } from '../src/product-selections' import { DeepPartial } from '../src/types/update-actions' import { ProductSelectionDraft } from '@commercetools/platform-sdk/src' @@ -19,9 +20,9 @@ describe('Exports', () => { }) describe('Actions', () => { - let productSelectionsSync = productSelectionsSyncFn() + let productSelectionsSync = createSyncProductSelections() beforeEach(() => { - productSelectionsSync = productSelectionsSyncFn() + productSelectionsSync = createSyncProductSelections() }) test('should build `changeName` action', () => { diff --git a/packages/sync-actions/test/product-sync-base.spec.ts b/packages/sync-actions/test/product-sync-base.spec.ts index 7f8b5ba22..a68471b71 100644 --- a/packages/sync-actions/test/product-sync-base.spec.ts +++ b/packages/sync-actions/test/product-sync-base.spec.ts @@ -1,5 +1,5 @@ import clone from '../src/utils/clone' -import productsSyncFn, { actionGroups, ProductSync } from '../src/products' +import { actionGroups, createSyncProducts, ProductSync } from '../src/products' import { baseActionsList, metaActionsList, @@ -52,9 +52,9 @@ describe('Exports', () => { }) describe('Actions', () => { - let productsSync = productsSyncFn() + let productsSync = createSyncProducts() beforeEach(() => { - productsSync = productsSyncFn() + productsSync = createSyncProducts() }) test('should ensure given objects are not mutated', () => { diff --git a/packages/sync-actions/test/product-sync-images.spec.ts b/packages/sync-actions/test/product-sync-images.spec.ts index 36b309286..47f4a4866 100644 --- a/packages/sync-actions/test/product-sync-images.spec.ts +++ b/packages/sync-actions/test/product-sync-images.spec.ts @@ -1,11 +1,11 @@ import { DeepPartial } from '../src/types/update-actions' -import productsSyncFn, { ProductSync } from '../src/products' +import { createSyncProducts, ProductSync } from '../src/products' /* eslint-disable max-len */ describe('Actions', () => { - let productsSync = productsSyncFn() + let productsSync = createSyncProducts() beforeEach(() => { - productsSync = productsSyncFn() + productsSync = createSyncProducts() }) describe('with matching variant order', () => { diff --git a/packages/sync-actions/test/product-sync-prices.spec.ts b/packages/sync-actions/test/product-sync-prices.spec.ts index 29395b567..cf54386ea 100644 --- a/packages/sync-actions/test/product-sync-prices.spec.ts +++ b/packages/sync-actions/test/product-sync-prices.spec.ts @@ -1,12 +1,12 @@ import { DeepPartial } from '../src/types/update-actions' -import productsSyncFn, { ProductSync } from '../src/products' +import { createSyncProducts, ProductSync } from '../src/products' import { DiscountedPriceDraft } from '@commercetools/platform-sdk/src' /* eslint-disable max-len */ describe('Actions', () => { - let productsSync = productsSyncFn() + let productsSync = createSyncProducts() beforeEach(() => { - productsSync = productsSyncFn() + productsSync = createSyncProducts() }) describe('with `priceID`', () => { diff --git a/packages/sync-actions/test/product-sync-variants.spec.ts b/packages/sync-actions/test/product-sync-variants.spec.ts index ab2983df5..6b9acee51 100644 --- a/packages/sync-actions/test/product-sync-variants.spec.ts +++ b/packages/sync-actions/test/product-sync-variants.spec.ts @@ -1,12 +1,12 @@ import { DeepPartial } from '../src/types/update-actions' -import productsSyncFn, { ProductSync } from '../src/products' +import { createSyncProducts, ProductSync } from '../src/products' import { Asset } from '@commercetools/platform-sdk/src' /* eslint-disable max-len */ describe('Actions', () => { - let productsSync = productsSyncFn() + let productsSync = createSyncProducts() beforeEach(() => { - productsSync = productsSyncFn() + productsSync = createSyncProducts() }) test('should build attribute actions', () => { diff --git a/packages/sync-actions/test/product-types-sync-attribute-hints.spec.ts b/packages/sync-actions/test/product-types-sync-attribute-hints.spec.ts index 9c0e40641..393ec6bf1 100644 --- a/packages/sync-actions/test/product-types-sync-attribute-hints.spec.ts +++ b/packages/sync-actions/test/product-types-sync-attribute-hints.spec.ts @@ -1,4 +1,4 @@ -import createSyncProductTypes from '../src/product-types' +import { createSyncProductTypes } from '../src' import { ProductTypeUpdateAction } from '@commercetools/platform-sdk/src' import { AttributeEnumValues } from '../src/product-types-actions' diff --git a/packages/sync-actions/test/product-types-sync-base.spec.ts b/packages/sync-actions/test/product-types-sync-base.spec.ts index 2209578c4..ec05c3e00 100644 --- a/packages/sync-actions/test/product-types-sync-base.spec.ts +++ b/packages/sync-actions/test/product-types-sync-base.spec.ts @@ -1,5 +1,5 @@ import clone from '../src/utils/clone' -import createSyncProductTypes, { actionGroups } from '../src/product-types' +import { createSyncProductTypes, actionGroups } from '../src/product-types' import { baseActionsList, generateBaseFieldsUpdateActions, diff --git a/packages/sync-actions/test/projects-sync.spec.ts b/packages/sync-actions/test/projects-sync.spec.ts index ee2ebfea1..5279de9d8 100644 --- a/packages/sync-actions/test/projects-sync.spec.ts +++ b/packages/sync-actions/test/projects-sync.spec.ts @@ -1,4 +1,4 @@ -import createProjectsSync, { actionGroups } from '../src/projects' +import { actionGroups, createSyncProjects } from '../src/projects' import { baseActionsList, myBusinessUnitActionsList, @@ -116,9 +116,9 @@ describe('Exports', () => { }) describe('Actions', () => { - let projectsSync = createProjectsSync() + let projectsSync = createSyncProjects() beforeEach(() => { - projectsSync = createProjectsSync() + projectsSync = createSyncProjects() }) test('should build `changeName` action', () => { @@ -288,7 +288,7 @@ describe('Actions', () => { { type: 'myBusinessUnit', group: 'allow' }, { type: 'customerSearch', group: 'ignore' }, ] - projectsSync = createProjectsSync(actionGroupList) + projectsSync = createSyncProjects(actionGroupList) const before: DeepPartial = { businessUnits: { myBusinessUnitStatusOnCreation: 'Active' }, } @@ -341,7 +341,7 @@ describe('Actions', () => { { type: 'myBusinessUnit', group: 'ignore' }, { type: 'customerSearch', group: 'allow' }, ] - projectsSync = createProjectsSync(actionGroupList) + projectsSync = createSyncProjects(actionGroupList) const before: DeepPartial< Project & { searchIndexing: SearchIndexingConfiguration & { diff --git a/packages/sync-actions/test/quote-requests-sync.spec.ts b/packages/sync-actions/test/quote-requests-sync.spec.ts index c434a870f..95e26227a 100644 --- a/packages/sync-actions/test/quote-requests-sync.spec.ts +++ b/packages/sync-actions/test/quote-requests-sync.spec.ts @@ -1,4 +1,4 @@ -import createQuoteRequestsSync, { actionGroups } from '../src/quote-requests' +import { actionGroups, createSyncQuoteRequest } from '../src/quote-requests' import { baseActionsList } from '../src/quote-requests-actions' import { DeepPartial } from '../src/types/update-actions' import { QuoteRequest } from '@commercetools/platform-sdk/src' @@ -26,9 +26,9 @@ describe('Exports', () => { }) describe('Actions', () => { - let quoteRequestsSync = createQuoteRequestsSync() + let quoteRequestsSync = createSyncQuoteRequest() beforeEach(() => { - quoteRequestsSync = createQuoteRequestsSync() + quoteRequestsSync = createSyncQuoteRequest() }) test('should build `changeQuoteRequestState` action', () => { diff --git a/packages/sync-actions/test/quotes-sync.spec.ts b/packages/sync-actions/test/quotes-sync.spec.ts index ae0dcc068..d3decfd1d 100644 --- a/packages/sync-actions/test/quotes-sync.spec.ts +++ b/packages/sync-actions/test/quotes-sync.spec.ts @@ -1,4 +1,4 @@ -import createQuotesSync, { actionGroups } from '../src/quotes' +import { actionGroups, createSyncQuote } from '../src/quotes' import { baseActionsList } from '../src/quotes-actions' import { DeepPartial } from '../src/types/update-actions' import { Quote } from '@commercetools/platform-sdk/src' @@ -34,9 +34,9 @@ describe('Exports', () => { }) describe('Actions', () => { - let quotesSync = createQuotesSync() + let quotesSync = createSyncQuote() beforeEach(() => { - quotesSync = createQuotesSync() + quotesSync = createSyncQuote() }) test('should build `changeQuoteState` action', () => { diff --git a/packages/sync-actions/test/shipping-methods.spec.ts b/packages/sync-actions/test/shipping-methods.spec.ts index 8a2375073..efbf1018d 100644 --- a/packages/sync-actions/test/shipping-methods.spec.ts +++ b/packages/sync-actions/test/shipping-methods.spec.ts @@ -1,4 +1,7 @@ -import shippingMethodsSyncFn, { actionGroups } from '../src/shipping-methods' +import { + actionGroups, + createSyncShippingMethods, +} from '../src/shipping-methods' import { baseActionsList } from '../src/shipping-methods-actions' import { DeepPartial } from '../src/types/update-actions' import { ShippingMethodDraft } from '@commercetools/platform-sdk/src' @@ -24,9 +27,9 @@ describe('Exports', () => { }) describe('Actions', () => { - let shippingMethodsSync = shippingMethodsSyncFn() + let shippingMethodsSync = createSyncShippingMethods() beforeEach(() => { - shippingMethodsSync = shippingMethodsSyncFn() + shippingMethodsSync = createSyncShippingMethods() }) describe('base', () => { diff --git a/packages/sync-actions/test/staged-quotes-sync.spec.ts b/packages/sync-actions/test/staged-quotes-sync.spec.ts index 64c162560..93d0e7aab 100644 --- a/packages/sync-actions/test/staged-quotes-sync.spec.ts +++ b/packages/sync-actions/test/staged-quotes-sync.spec.ts @@ -1,5 +1,6 @@ -import createStagedQuotesSync, { +import { actionGroups, + createSyncStagedQuote, StagedQuoteSync, } from '../src/staged-quotes' import { baseActionsList } from '../src/staged-quotes-actions' @@ -42,9 +43,9 @@ describe('Exports', () => { }) describe('Actions', () => { - let stagedQuotesSync = createStagedQuotesSync() + let stagedQuotesSync = createSyncStagedQuote() beforeEach(() => { - stagedQuotesSync = createStagedQuotesSync() + stagedQuotesSync = createSyncStagedQuote() }) test('should build `changeQuoteState` action', () => { diff --git a/packages/sync-actions/test/states-sync.spec.ts b/packages/sync-actions/test/states-sync.spec.ts index 552bfd911..acac96670 100644 --- a/packages/sync-actions/test/states-sync.spec.ts +++ b/packages/sync-actions/test/states-sync.spec.ts @@ -1,4 +1,4 @@ -import statesSyncFn, { actionGroups } from '../src/states' +import { actionGroups, createSyncStates } from '../src/states' import { baseActionsList } from '../src/state-actions' import { DeepPartial } from '../src/types/update-actions' import { StateDraft } from '@commercetools/platform-sdk/src' @@ -68,9 +68,9 @@ describe('Exports', () => { }) describe('Actions', () => { - let statesSync = statesSyncFn() + let statesSync = createSyncStates() beforeEach(() => { - statesSync = statesSyncFn() + statesSync = createSyncStates() }) test('should build `setName` action', () => { diff --git a/packages/sync-actions/test/stores-sync.spec.ts b/packages/sync-actions/test/stores-sync.spec.ts index 1fd391e4c..17ecf3b14 100644 --- a/packages/sync-actions/test/stores-sync.spec.ts +++ b/packages/sync-actions/test/stores-sync.spec.ts @@ -1,4 +1,4 @@ -import storesSyncFn, { actionGroups } from '../src/stores' +import { actionGroups, createSyncStores } from '../src/stores' import { baseActionsList } from '../src/stores-actions' import { DeepPartial } from '../src/types/update-actions' import { Store } from '@commercetools/platform-sdk/src' @@ -19,9 +19,9 @@ describe('Exports', () => { }) describe('Actions', () => { - let storesSync = storesSyncFn() + let storesSync = createSyncStores() beforeEach(() => { - storesSync = storesSyncFn() + storesSync = createSyncStores() }) test('should build `setName` action', () => { diff --git a/packages/sync-actions/test/tax-categories-sync.spec.ts b/packages/sync-actions/test/tax-categories-sync.spec.ts index 64ead49f7..02e6331a8 100644 --- a/packages/sync-actions/test/tax-categories-sync.spec.ts +++ b/packages/sync-actions/test/tax-categories-sync.spec.ts @@ -1,4 +1,4 @@ -import taxCategorySyncFn, { actionGroups } from '../src/tax-categories' +import { actionGroups, createSyncTaxCategories } from '../src/tax-categories' import { baseActionsList } from '../src/tax-categories-actions' import { DeepPartial } from '../src/types/update-actions' import { TaxCategory } from '@commercetools/platform-sdk/src' @@ -18,9 +18,9 @@ describe('Exports', () => { }) describe('Actions', () => { - let taxCategorySync = taxCategorySyncFn() + let taxCategorySync = createSyncTaxCategories() beforeEach(() => { - taxCategorySync = taxCategorySyncFn() + taxCategorySync = createSyncTaxCategories() }) test('should build `changeName` action', () => { diff --git a/packages/sync-actions/test/types-sync-base.spec.ts b/packages/sync-actions/test/types-sync-base.spec.ts index 684c1a66d..9f2d88895 100644 --- a/packages/sync-actions/test/types-sync-base.spec.ts +++ b/packages/sync-actions/test/types-sync-base.spec.ts @@ -1,8 +1,7 @@ import clone from '../src/utils/clone' -import createSyncTypes, { actionGroups } from '../src/types' +import { actionGroups, createSyncTypes } from '../src/types' import { baseActionsList } from '../src/types-actions' import { TypeUpdateAction } from '@commercetools/platform-sdk/src' -import typesSyncFn from '../src/types' describe('Exports', () => { test('action group list', () => { @@ -19,7 +18,7 @@ describe('Exports', () => { }) describe('Actions', () => { - let typesSync = typesSyncFn() + let typesSync = createSyncTypes() let updateActions: Array let before let now diff --git a/packages/sync-actions/test/types-sync-enums.spec.ts b/packages/sync-actions/test/types-sync-enums.spec.ts index 26a4e7df8..6658bf074 100644 --- a/packages/sync-actions/test/types-sync-enums.spec.ts +++ b/packages/sync-actions/test/types-sync-enums.spec.ts @@ -1,4 +1,4 @@ -import typesSyncFn from '../src/types' +import { createSyncTypes } from '../src/types' import { TypeUpdateAction } from '@commercetools/platform-sdk/src' const createTestType = (custom) => ({ @@ -10,10 +10,10 @@ const createTestType = (custom) => ({ describe('Actions', () => { let before let now - let typesSync = typesSyncFn() + let typesSync = createSyncTypes() let updateActions: Array beforeEach(() => { - typesSync = typesSyncFn() + typesSync = createSyncTypes() }) describe('enum values', () => { describe('with new enum', () => { diff --git a/packages/sync-actions/test/types-sync-fields.spec.ts b/packages/sync-actions/test/types-sync-fields.spec.ts index 7b35f0d30..42c76ff01 100644 --- a/packages/sync-actions/test/types-sync-fields.spec.ts +++ b/packages/sync-actions/test/types-sync-fields.spec.ts @@ -1,4 +1,4 @@ -import typesSyncFn from '../src/types' +import { createSyncTypes } from '../src' import { TypeUpdateAction } from '@commercetools/platform-sdk/src' const createTestType = (custom) => ({ @@ -8,12 +8,12 @@ const createTestType = (custom) => ({ }) describe('Actions', () => { - let typesSync = typesSyncFn() + let typesSync = createSyncTypes() let updateActions: Array let before let now beforeEach(() => { - typesSync = typesSyncFn() + typesSync = createSyncTypes() }) describe('with new fields', () => { beforeEach(() => { diff --git a/packages/sync-actions/test/zones.spec.ts b/packages/sync-actions/test/zones.spec.ts index 287dbebdf..51aae55e6 100644 --- a/packages/sync-actions/test/zones.spec.ts +++ b/packages/sync-actions/test/zones.spec.ts @@ -1,4 +1,4 @@ -import zonesSyncFn, { actionGroups } from '../src/zones' +import { actionGroups, createSyncZones } from '../src/zones' import { baseActionsList } from '../src/zones-actions' describe('Exports', () => { @@ -16,9 +16,9 @@ describe('Exports', () => { }) describe('Actions', () => { - let zonesSync = zonesSyncFn() + let zonesSync = createSyncZones() beforeEach(() => { - zonesSync = zonesSyncFn() + zonesSync = createSyncZones() }) test('should build `changeName` action', () => {