diff --git a/src/app/core/store/customer/basket/basket-items.effects.spec.ts b/src/app/core/store/customer/basket/basket-items.effects.spec.ts index 46c7c3fd94..52aba7ed25 100644 --- a/src/app/core/store/customer/basket/basket-items.effects.spec.ts +++ b/src/app/core/store/customer/basket/basket-items.effects.spec.ts @@ -70,15 +70,17 @@ describe('Basket Items Effects', () => { }); describe('addProductToBasket$', () => { - it('should accumulate AddProductToBasket to a single AddItemsToBasket action', () => { + it('should accumulate AddProductToBasket to a single action', () => { store$.dispatch(loadProductSuccess({ product: { sku: 'SKU1', packingUnit: 'pcs.' } as Product })); store$.dispatch(loadProductSuccess({ product: { sku: 'SKU2', packingUnit: 'pcs.' } as Product })); const action1 = addProductToBasket({ sku: 'SKU1', quantity: 1 }); const action2 = addProductToBasket({ sku: 'SKU2', quantity: 1 }); const completion = addItemsToBasket({ items: [ - { sku: 'SKU2', quantity: 2, unit: 'pcs.' }, - { sku: 'SKU1', quantity: 2, unit: 'pcs.' }, + { sku: 'SKU2', quantity: 1, unit: 'pcs.' }, + { sku: 'SKU1', quantity: 1, unit: 'pcs.' }, + { sku: 'SKU2', quantity: 1, unit: 'pcs.' }, + { sku: 'SKU1', quantity: 1, unit: 'pcs.' }, ], }); actions$ = hot(' -b-a-b-a--|', { a: action1, b: action2 }); diff --git a/src/app/core/store/customer/basket/basket-items.effects.ts b/src/app/core/store/customer/basket/basket-items.effects.ts index 67da9ebf51..b23482245d 100644 --- a/src/app/core/store/customer/basket/basket-items.effects.ts +++ b/src/app/core/store/customer/basket/basket-items.effects.ts @@ -12,8 +12,8 @@ import { map, mapTo, mergeMap, - reduce, switchMap, + toArray, window, withLatestFrom, } from 'rxjs/operators'; @@ -53,30 +53,19 @@ export class BasketItemsEffects { /** * Add a product to the current basket. - * Triggers the internal AddItemsToBasket action that handles the actual adding of the product to the basket. + * Triggers the internal action that handles the actual adding of the product to the basket. */ addProductToBasket$ = createEffect(() => this.actions$.pipe( ofType(addProductToBasket), mapToPayload(), + // add unit + withLatestFrom(this.store.pipe(select(getProductEntities))), + map(([val, entities]) => ({ ...val, unit: entities[val.sku] && entities[val.sku].packingUnit })), // accumulate all actions window(this.actions$.pipe(ofType(addProductToBasket), debounceTime(1000))), - mergeMap(window$ => - window$.pipe( - withLatestFrom(this.store.pipe(select(getProductEntities))), - // accumulate changes - reduce((acc, [val, entities]) => { - const element = acc.find(x => x.sku === val.sku); - if (element) { - element.quantity += val.quantity; - } else { - acc.push({ ...val, unit: entities[val.sku] && entities[val.sku].packingUnit }); - } - return acc; - }, []), - map(items => addItemsToBasket({ items })) - ) - ) + mergeMap(window$ => window$.pipe(toArray())), + map(items => addItemsToBasket({ items })) ) );