|
@@ -10,18 +10,41 @@ const state = {
|
|
|
|
|
|
// getters
|
|
|
const getters = {
|
|
|
- checkoutStatus: state => state.checkoutStatus
|
|
|
+ checkoutStatus: state => state.checkoutStatus,
|
|
|
+
|
|
|
+ cartProducts: (state, getters, rootState) => {
|
|
|
+ return state.added.map(({ id, quantity }) => {
|
|
|
+ const product = rootState.products.all.find(product => product.id === id)
|
|
|
+ return {
|
|
|
+ title: product.title,
|
|
|
+ price: product.price,
|
|
|
+ quantity
|
|
|
+ }
|
|
|
+ })
|
|
|
+ },
|
|
|
+
|
|
|
+ cartTotalPrice: (state, getters) => {
|
|
|
+ return getters.cartProducts.reduce((total, product) => {
|
|
|
+ return total + product.price * product.quantity
|
|
|
+ }, 0)
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
// actions
|
|
|
const actions = {
|
|
|
checkout ({ commit, state }, products) {
|
|
|
const savedCartItems = [...state.added]
|
|
|
- commit(types.CHECKOUT_REQUEST)
|
|
|
+ commit(types.SET_CHECKOUT_STATUS, null)
|
|
|
+ // empty cart
|
|
|
+ commit(types.SET_CART_ITEMS, { items: [] })
|
|
|
shop.buyProducts(
|
|
|
products,
|
|
|
- () => commit(types.CHECKOUT_SUCCESS),
|
|
|
- () => commit(types.CHECKOUT_FAILURE, { savedCartItems })
|
|
|
+ () => commit(types.SET_CHECKOUT_STATUS, 'successful'),
|
|
|
+ () => {
|
|
|
+ commit(types.SET_CHECKOUT_STATUS, 'failed')
|
|
|
+ // rollback to the cart saved before sending the request
|
|
|
+ commit(types.SET_CART_ITEMS, { items: savedCartItems })
|
|
|
+ }
|
|
|
)
|
|
|
}
|
|
|
}
|
|
@@ -30,7 +53,7 @@ const actions = {
|
|
|
const mutations = {
|
|
|
[types.ADD_TO_CART] (state, { id }) {
|
|
|
state.checkoutStatus = null
|
|
|
- const record = state.added.find(p => p.id === id)
|
|
|
+ const record = state.added.find(product => product.id === id)
|
|
|
if (!record) {
|
|
|
state.added.push({
|
|
|
id,
|
|
@@ -41,20 +64,12 @@ const mutations = {
|
|
|
}
|
|
|
},
|
|
|
|
|
|
- [types.CHECKOUT_REQUEST] (state) {
|
|
|
- // clear cart
|
|
|
- state.added = []
|
|
|
- state.checkoutStatus = null
|
|
|
- },
|
|
|
-
|
|
|
- [types.CHECKOUT_SUCCESS] (state) {
|
|
|
- state.checkoutStatus = 'successful'
|
|
|
+ [types.SET_CART_ITEMS] (state, { items }) {
|
|
|
+ state.added = items
|
|
|
},
|
|
|
|
|
|
- [types.CHECKOUT_FAILURE] (state, { savedCartItems }) {
|
|
|
- // rollback to the cart saved before sending the request
|
|
|
- state.added = savedCartItems
|
|
|
- state.checkoutStatus = 'failed'
|
|
|
+ [types.SET_CHECKOUT_STATUS] (state, status) {
|
|
|
+ state.checkoutStatus = status
|
|
|
}
|
|
|
}
|
|
|
|