diff --git a/src/app/cart/cart.component.js b/src/app/cart/cart.component.js index b38661072..9eef901ba 100644 --- a/src/app/cart/cart.component.js +++ b/src/app/cart/cart.component.js @@ -46,8 +46,18 @@ class CartController { } else { this.loading = true } + // Remember the order of the existing items in the cart + const orderByCode = this.cartData?.items?.map(item => item.code) || [] this.cartService.get() .subscribe(data => { + if (reload) { + // Sort the incoming cart to match the order of the previous cart, with new items at the top + // The code of recurring gifts have a suffix and look like 0123456_MON or 0123456_QUARTERLY. + // We will be able to maintain the order of items in the cart as long as the user doesn't + // change the frequency of a gift. The server prevents carts from containing multiple gifts + // with the same frequency and designation account, which would interfere with sorting. + data.items?.sort((item1, item2) => orderByCode.indexOf(item1.code) - orderByCode.indexOf(item2.code)) + } this.cartData = data this.setLoadCartVars(reload) }, @@ -97,7 +107,6 @@ class CartController { .configureProduct(item.code, item.config, true, item.uri) modal && modal.result .then(() => { - pull(this.cartData.items, item) this.loadCart(true) }, angular.noop) } diff --git a/src/app/cart/cart.component.spec.js b/src/app/cart/cart.component.spec.js index f1ca6132a..ca14206fe 100644 --- a/src/app/cart/cart.component.spec.js +++ b/src/app/cart/cart.component.spec.js @@ -73,6 +73,23 @@ describe('cart', () => { expect(self.controller.updating).toEqual(false) }) + it('should preserve the order', () => { + self.controller.cartService.get.mockReturnValue(Observable.of({ items: [{ code: '1' }, { code: '2' }, { code: '3' }] })) + self.controller.loadCart(true) + + self.controller.cartService.get.mockReturnValue(Observable.of({ items: [{ code: '3' }, { code: '2' }, { code: '1' }, { code: '4' }] })) + self.controller.loadCart(true) + + expect(self.controller.cartData).toEqual({ items: [{ code: '4' }, { code: '1' }, { code: '2' }, { code: '3' }] }) + }) + + it('should handle empty data', () => { + self.controller.cartService.get.mockReturnValue(Observable.of({})) + self.controller.loadCart(true) + + expect(self.controller.cartData).toEqual({}) + }) + it('should handle an error loading cart data', () => { self.controller.cartData = 'previous data' self.controller.cartService.get.mockReturnValue(Observable.throw('error')) @@ -178,7 +195,6 @@ describe('cart', () => { expect(self.controller.productModalService.configureProduct).toHaveBeenCalledWith('0123456', 'some config', true, 'uri1') expect(self.controller.loadCart).toHaveBeenCalledWith(true) - expect(self.controller.cartData.items).toEqual([{ uri: 'uri2' }]) }) }) diff --git a/src/app/cart/cart.tpl.html b/src/app/cart/cart.tpl.html index 7d8605774..3ed10cbc8 100644 --- a/src/app/cart/cart.tpl.html +++ b/src/app/cart/cart.tpl.html @@ -39,7 +39,7 @@