123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- const state = {
- cart: [],
- total: 0,
- productToDiscount: null
- }
- const getters = {
- cartItems(state) {
- return state.cart
- },
- total(state) {
- return state.total
- },
- cartIsEmpty(state) {
- return state.cart.length !== 0
- },
- productToDiscount(state) {
- return state.productToDiscount
- }
- }
- const mutations = {
- addToCart(state, payload) {
- let finded = state.cart.find(item => item.id == payload.product.id)
- if (finded) {
- payload.product.qty = payload.product.qty + 1
- } else {
- state.cart = [payload.product, ...state.cart]
- }
- },
- subtractFromCart(state, payload) {
- let finded = state.cart.find(item => item.id == payload.product.id)
- finded.qty = finded.qty - 1
- },
- discountFromCart(state, payload) {
- state.productToDiscount = payload
- },
- applyDiscount(state, payload) {
- let finded = state.cart.find(item => item.id == state.productToDiscount.id)
- finded.price = state.productToDiscount.discount
- },
- removeFromCart(state, payload) {
- let findedIndex = state.cart.findIndex(item => item.id == payload.product.id)
- state.cart.splice(findedIndex, 1)
- },
- calculateTotal(state) {
- let sum = 0
- state.cart.forEach(item => {
- sum = sum + ((item.price || item.list_price) * (item.qty || 1))
- })
- state.total = sum
- }
- }
- const actions = {
- addToCart({ commit, dispatch }, payload) {
- commit('addToCart', {
- product: payload
- })
-
- commit('calculateTotal')
- // dispatch('setSelectedProduct', {
- // product: null
- // })
- },
- subtractFromCart({ commit, dispatch }, payload) {
- if (payload.qty > 1) {
- commit('subtractFromCart', {
- product: payload
- })
- } else {
- commit('removeFromCart', {
- product: payload
- })
- }
-
- commit('calculateTotal')
- },
- discountFromCart({ commit, dispatch }, payload) {
- if (payload && !payload.minimum_price && !payload.maximum_price) {
- dispatch('notify', 'No hay descuento para este producto')
- return
- }
- commit('discountFromCart', payload)
- },
- applyDiscount({ getters, commit, dispatch }, payload) {
- if(payload.apply) {
- let product = getters.productToDiscount
- if (product.priceApply < product.minimum_price || product.priceApply > product.maximum_price) {
- dispatch('notify', 'No se puede aplicar este descuento')
- return
- }
- commit('applyDiscount', product.id)
- commit('calculateTotal')
- }
- dispatch('discountFromCart', null)
- },
- removeFromCart({ commit, dispatch }, payload) {
- commit('removeFromCart', {
- product: payload
- })
-
- commit('calculateTotal')
- }
- }
- export default {
- state,
- getters,
- mutations,
- actions
- }
|