123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- import shop from '../../api/shop'
- import nested from './nested'
- // initial state
- // shape: [{ id, quantity }]
- const state = () => ({
- items: [],
- checkoutStatus: null
- })
- // getters
- const getters = {
- cartProducts: (state, getters, rootState) => {
- return state.items.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 = {
- async checkout ({ commit, state }, products) {
- const savedCartItems = [...state.items]
- commit('setCheckoutStatus', null)
- // empty cart
- commit('setCartItems', { items: [] })
- try {
- await shop.buyProducts(products)
- commit('setCheckoutStatus', 'successful')
- } catch (e) {
- console.error(e)
- commit('setCheckoutStatus', 'failed')
- // rollback to the cart saved before sending the request
- commit('setCartItems', { items: savedCartItems })
- }
- },
- addProductToCart ({ state, commit }, product) {
- commit('setCheckoutStatus', null)
- if (product.inventory > 0) {
- const cartItem = state.items.find(item => item.id === product.id)
- if (!cartItem) {
- commit('pushProductToCart', { id: product.id })
- } else {
- commit('incrementItemQuantity', cartItem)
- }
- // remove 1 item from stock
- commit('products/decrementProductInventory', { id: product.id }, { root: true })
- }
- }
- }
- // mutations
- const mutations = {
- pushProductToCart (state, { id }) {
- state.items.push({
- id,
- quantity: 1
- })
- },
- incrementItemQuantity (state, { id }) {
- const cartItem = state.items.find(item => item.id === id)
- cartItem.quantity++
- },
- setCartItems (state, { items }) {
- state.items = items
- },
- setCheckoutStatus (state, status) {
- state.checkoutStatus = status
- }
- }
- export default {
- namespaced: true,
- state,
- getters,
- actions,
- mutations,
- modules: {
- nested
- }
- }
|