|
@@ -1,5 +1,4 @@
|
|
import shop from '../../api/shop'
|
|
import shop from '../../api/shop'
|
|
-import * as types from '../mutation-types'
|
|
|
|
|
|
|
|
// initial state
|
|
// initial state
|
|
// shape: [{ id, quantity }]
|
|
// shape: [{ id, quantity }]
|
|
@@ -34,41 +33,54 @@ const getters = {
|
|
const actions = {
|
|
const actions = {
|
|
checkout ({ commit, state }, products) {
|
|
checkout ({ commit, state }, products) {
|
|
const savedCartItems = [...state.added]
|
|
const savedCartItems = [...state.added]
|
|
- commit(types.SET_CHECKOUT_STATUS, null)
|
|
|
|
|
|
+ commit('setCheckoutStatus', null)
|
|
// empty cart
|
|
// empty cart
|
|
- commit(types.SET_CART_ITEMS, { items: [] })
|
|
|
|
|
|
+ commit('setCartItems', { items: [] })
|
|
shop.buyProducts(
|
|
shop.buyProducts(
|
|
products,
|
|
products,
|
|
- () => commit(types.SET_CHECKOUT_STATUS, 'successful'),
|
|
|
|
|
|
+ () => commit('setCheckoutStatus', 'successful'),
|
|
() => {
|
|
() => {
|
|
- commit(types.SET_CHECKOUT_STATUS, 'failed')
|
|
|
|
|
|
+ commit('setCheckoutStatus', 'failed')
|
|
// rollback to the cart saved before sending the request
|
|
// rollback to the cart saved before sending the request
|
|
- commit(types.SET_CART_ITEMS, { items: savedCartItems })
|
|
|
|
|
|
+ commit('setCartItems', { items: savedCartItems })
|
|
}
|
|
}
|
|
)
|
|
)
|
|
|
|
+ },
|
|
|
|
+
|
|
|
|
+ addProductToCart ({ state, commit }, product) {
|
|
|
|
+ commit('setCheckoutStatus', null)
|
|
|
|
+ if (product.inventory > 0) {
|
|
|
|
+ const cartItem = state.added.find(item => item.id === product.id)
|
|
|
|
+ if (!cartItem) {
|
|
|
|
+ commit('pushProductToCart', { id: product.id })
|
|
|
|
+ } else {
|
|
|
|
+ commit('incrementItemQuantity', cartItem)
|
|
|
|
+ }
|
|
|
|
+ // remove 1 item from stock
|
|
|
|
+ commit('decrementProductInventory', { id: product.id })
|
|
|
|
+ }
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
// mutations
|
|
// mutations
|
|
const mutations = {
|
|
const mutations = {
|
|
- [types.ADD_TO_CART] (state, { id }) {
|
|
|
|
- state.checkoutStatus = null
|
|
|
|
- const record = state.added.find(product => product.id === id)
|
|
|
|
- if (!record) {
|
|
|
|
- state.added.push({
|
|
|
|
- id,
|
|
|
|
- quantity: 1
|
|
|
|
- })
|
|
|
|
- } else {
|
|
|
|
- record.quantity++
|
|
|
|
- }
|
|
|
|
|
|
+ pushProductToCart (state, { id }) {
|
|
|
|
+ state.added.push({
|
|
|
|
+ id,
|
|
|
|
+ quantity: 1
|
|
|
|
+ })
|
|
|
|
+ },
|
|
|
|
+
|
|
|
|
+ incrementItemQuantity (state, { id }) {
|
|
|
|
+ const cartItem = state.added.find(item => item.id === id)
|
|
|
|
+ cartItem.quantity++
|
|
},
|
|
},
|
|
|
|
|
|
- [types.SET_CART_ITEMS] (state, { items }) {
|
|
|
|
|
|
+ setCartItems (state, { items }) {
|
|
state.added = items
|
|
state.added = items
|
|
},
|
|
},
|
|
|
|
|
|
- [types.SET_CHECKOUT_STATUS] (state, status) {
|
|
|
|
|
|
+ setCheckoutStatus (state, status) {
|
|
state.checkoutStatus = status
|
|
state.checkoutStatus = status
|
|
}
|
|
}
|
|
}
|
|
}
|