import { Address } from '../common/address' ; import { Entity , Reduces } from '@boostercloud/framework-core' ; import { UUID } from '@boostercloud/framework-types' ; import { CartItemChanged } from '../events/cart-item-changed' ; import { ShippingAddressUpdated as UpdatedCartShippingAddress } from '../events/shipping-address-updated' ; import { CartItem } from '../common/cart-item' ; import { CartChecked } from '../events/cart-checked' ; import { beforeHookProductId } from '../constants' ; /**
 * A cart is a temporary object where users accumulate all the items they want to buy
 */ @ Entity ( { authorizeReadEvents : 'all' , } ) export class Cart { public constructor ( readonly id , readonly cartItems , public shippingAddress ? , public checks = 0 ) { } public getId ( ) { return this . id ; } @ Reduces ( CartItemChanged ) public static changeItem ( event , currentCart ) { if ( currentCart == null ) { currentCart = new Cart ( event . cartId , [ ] ) ; } currentCart . getId ( ) ; event . getProductId ( ) ; const current = currentCart . cartItems . find ( ( cartItem ) : boolean => cartItem . productId === event . productId ) ; if ( current && current . productId !== beforeHookProductId ) { current . quantity += event . quantity ; return currentCart ; } else { currentCart . cartItems . push ( { productId : event . productId , quantity : event . quantity , } ) ; return currentCart ; } } @ Reduces ( UpdatedCartShippingAddress ) public static updatedShippingAddress ( event , currentCart ) { if ( currentCart == null ) { currentCart = new Cart ( event . cartId , [ ] ) ; } currentCart . shippingAddress = event . address ; return currentCart ; } @ Reduces ( CartChecked ) public static checkCart ( event , currentCart ) { if ( currentCart == null ) { currentCart = new Cart ( event . cartId , [ ] ) ; } currentCart . checks += 1 ; return currentCart ; } }