const state = { cartItems: [], cartTotal: 0, itemToDiscount: null } const getters = { cartItems (state) { return state.cartItems }, cartTotal (state, getters) { return state.cartTotal }, itemToDiscount (state) { return state.itemToDiscount } } const mutations = { setCart (state, payload) { state.cartItems = payload }, pushToCart (state, payload) { let productFound = state.cartItems.find(item => item.id === payload.id) if (productFound) { if (payload.quantity > 1) { if (productFound.quantity === payload.quantity) { productFound.quantity = productFound.quantity + 1 } else { productFound.quantity = payload.quantity } } else { productFound.quantity = productFound.quantity + payload.quantity } return } state.cartItems = [payload, ...state.cartItems] }, pullFromCart (state, payload) { let productFoundIndex = state.cartItems.findIndex(item => item.id === payload.item.id) if (state.cartItems[productFoundIndex].quantity === 1) { payload.mode = 'full' } if (payload.mode === 'partial') { if (payload.item.quantity !== -1) { state.cartItems[productFoundIndex].quantity = payload.item.quantity } else { state.cartItems[productFoundIndex].quantity = state.cartItems[productFoundIndex].quantity - 1 } } else { state.cartItems.splice(productFoundIndex, 1) } }, setCartTotal (state, payload) { state.cartTotal = payload }, setItemToDiscount (state, payload) { state.itemToDiscount = payload }, setItemPrice (state, payload) { let foundProduct = state.cartItems.find(item => item.id === state.itemToDiscount.id) foundProduct.price = payload }, resetPrice (state, payload) { let foundProduct = state.cartItems.find(item => item.id === payload.id) foundProduct.price = foundProduct.listPrice } } const actions = { addToCart ({ commit }, payload) { commit('pushToCart', payload) }, decreaseFromCart ({ commit }, payload) { commit('pullFromCart', { item: payload, mode: 'partial' }) }, undoPrice ({ commit }, payload) { commit('resetPrice', payload) }, changePrice ({ commit }, payload) { commit('setItemToDiscount', payload) }, applyPrice ({ commit }, payload) { if (payload) { commit('setItemPrice', payload) } commit('setItemToDiscount', null) }, removeFromCart ({ commit }, payload) { commit('pullFromCart', { item: payload, mode: 'full' }) }, changeCartTotal ({ commit, dispatch }, payload) { commit('setCartTotal', payload) dispatch('changeAmountToPay', payload) }, resetCart ({ commit }) { commit('setCart', []) commit('setCartTotal', 0) } } export default { state, getters, mutations, actions }