|
1 | 1 | /* eslint-disable max-len */ |
2 | 2 | import forEach from 'lodash.foreach' |
3 | 3 | import uniqWith from 'lodash.uniqwith' |
| 4 | +import intersection from 'lodash.intersection' |
| 5 | +import without from 'lodash.without' |
4 | 6 | import * as diffpatcher from './utils/diffpatcher' |
5 | 7 | import extractMatchingPairs from './utils/extract-matching-pairs' |
6 | 8 | import actionsMapCustom from './utils/action-map-custom' |
@@ -58,6 +60,9 @@ const getIsUpdateAction = (key, resource) => |
58 | 60 | const getIsRemoveAction = (key, resource) => |
59 | 61 | REGEX_UNDERSCORE_NUMBER.test(key) && Number(resource[2]) === 0 |
60 | 62 |
|
| 63 | +const getIsItemMovedAction = (key, resource) => |
| 64 | + REGEX_UNDERSCORE_NUMBER.test(key) && Number(resource[2]) === 3 |
| 65 | + |
61 | 66 | function _buildSkuActions(variantDiff, oldVariant) { |
62 | 67 | if ({}.hasOwnProperty.call(variantDiff, 'sku')) { |
63 | 68 | const newValue = diffpatcher.getDeltaValue(variantDiff.sku) |
@@ -401,6 +406,30 @@ function toVariantIdentifier(variant) { |
401 | 406 | return id ? { variantId: id } : { sku } |
402 | 407 | } |
403 | 408 |
|
| 409 | +function _buildVariantChangeAssetOrderAction( |
| 410 | + diffAssets, |
| 411 | + oldVariant, |
| 412 | + newVariant |
| 413 | +) { |
| 414 | + const isAssetOrderChanged = Object.entries(diffAssets).find((entry) => |
| 415 | + getIsItemMovedAction(entry[0], entry[1]) |
| 416 | + ) |
| 417 | + if (!isAssetOrderChanged) { |
| 418 | + return [] |
| 419 | + } |
| 420 | + const assetIdsBefore = oldVariant.assets.map((_) => _.id) |
| 421 | + const assetIdsCurrent = newVariant.assets |
| 422 | + .map((_) => _.id) |
| 423 | + .filter((_) => _ !== undefined) |
| 424 | + const assetIdsToKeep = intersection(assetIdsCurrent, assetIdsBefore) |
| 425 | + const assetIdsToRemove = without(assetIdsBefore, ...assetIdsToKeep) |
| 426 | + const changeAssetOrderAction = { |
| 427 | + action: 'changeAssetOrder', |
| 428 | + assetOrder: assetIdsToKeep.concat(assetIdsToRemove), |
| 429 | + ...toVariantIdentifier(oldVariant), |
| 430 | + } |
| 431 | + return [changeAssetOrderAction] |
| 432 | +} |
404 | 433 | function _buildVariantAssetsActions(diffAssets, oldVariant, newVariant) { |
405 | 434 | const assetActions = [] |
406 | 435 |
|
@@ -478,7 +507,12 @@ function _buildVariantAssetsActions(diffAssets, oldVariant, newVariant) { |
478 | 507 | } |
479 | 508 | }) |
480 | 509 |
|
481 | | - return assetActions |
| 510 | + const changedAssetOrderAction = _buildVariantChangeAssetOrderAction( |
| 511 | + diffAssets, |
| 512 | + oldVariant, |
| 513 | + newVariant |
| 514 | + ) |
| 515 | + return [...changedAssetOrderAction, ...assetActions] |
482 | 516 | } |
483 | 517 |
|
484 | 518 | /** |
|
0 commit comments