coupon.js 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import { fetchReceivedCouponCount, receiveCoupon, checkCouponAlert } from '@/services/api/coupon.js'
  2. const state = {
  3. expiredNum: 0, // 已过期
  4. unusedNum: 0, // 未使用
  5. usedNum: 0, // 已使用
  6. couponAlertType: 0, // 优惠券弹窗类型 0: 不弹出 1: 全部用户 2: 新人用户
  7. couponNoticeFlag: false // 新优惠券领取通知
  8. }
  9. const mutations = {
  10. //设置优惠券数量
  11. SET_COUPON_COUNT: (state, data) => {
  12. state.expiredNum = data.expiredNum
  13. state.unusedNum = data.unusedNum
  14. state.usedNum = data.usedNum
  15. },
  16. // 设置优惠券弹窗类型
  17. SET_COUPON_ALERT_TYPE: (state, data) => {
  18. typeof data === 'number' ? state.couponAlertType = data : state.couponAlertType++
  19. },
  20. // 设置新优惠券通知
  21. SET_COUPON_NITICE_FLAG: (state, data) => {
  22. state.couponNoticeFlag = data
  23. }
  24. }
  25. const actions = {
  26. // 领取优惠券
  27. async receiveCoupon({ rootGetters, dispatch }, { couponId, couponShareId }) {
  28. if (!rootGetters.userId) {
  29. const pages = getCurrentPages()
  30. const page = pages[pages.length - 1]
  31. uni.setStorageSync('LOGIN_REDIRECT_URL', page.$page.fullPath)
  32. uni.redirectTo({ url: '/pages/authorize/login-custom' })
  33. return Promise.reject('用户未登录')
  34. }
  35. try {
  36. const res = await receiveCoupon({ couponId, couponShareId, userId: rootGetters.userId })
  37. uni.showToast({
  38. icon: 'success',
  39. title: '领取成功'
  40. })
  41. await dispatch('initCouponCount')
  42. return res
  43. } catch (e) {
  44. console.log('领取优惠券失败')
  45. return Promise.reject(e)
  46. }
  47. },
  48. // 初始化已领取优惠券数量
  49. async initCouponCount({ commit, rootGetters }) {
  50. try {
  51. const res = await fetchReceivedCouponCount({ userId: rootGetters.userId })
  52. commit('SET_COUPON_COUNT', res.data)
  53. return res
  54. } catch (e) {
  55. console.log('初始化已领取优惠券数量失败')
  56. return Promise.reject(e)
  57. }
  58. },
  59. // 优惠券弹窗验证
  60. async checkCouponAlert({ commit, rootGetters }) {
  61. try {
  62. const result = await checkCouponAlert({ userId: rootGetters.userId })
  63. const { newUserCouponFlag, actCouponFlag, otherCouponFlag } = result.data
  64. // 活动优惠券弹窗(全部用户)
  65. if (actCouponFlag !== 0) {
  66. commit('SET_COUPON_ALERT_TYPE')
  67. }
  68. // 新用户优惠券弹窗(新用户)
  69. if (newUserCouponFlag !== 0) {
  70. commit('SET_COUPON_ALERT_TYPE')
  71. }
  72. // 其它优惠券弹窗(可领取优惠券弹窗)
  73. if (otherCouponFlag !== 0) {
  74. commit('SET_COUPON_NITICE_FLAG', true)
  75. setTimeout(() => {
  76. commit('SET_COUPON_NITICE_FLAG', false)
  77. }, 5000)
  78. }
  79. } catch (e) {
  80. console.log('优惠券弹窗校验失败')
  81. return Promise.reject(e)
  82. }
  83. }
  84. }
  85. export default {
  86. namespaced: true,
  87. state,
  88. mutations,
  89. actions
  90. }