UserCoupon.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\api\model;
  13. use app\api\service\User as UserService;
  14. use app\common\exception\BaseException;
  15. use app\common\model\UserCoupon as UserCouponModel;
  16. use app\common\enum\coupon\ExpireType as ExpireTypeEnum;
  17. use app\common\enum\coupon\ApplyRange as ApplyRangeEnum;
  18. use app\common\library\helper;
  19. /**
  20. * 用户优惠券模型
  21. * Class UserCoupon
  22. * @package app\api\model
  23. */
  24. class UserCoupon extends UserCouponModel
  25. {
  26. /**
  27. * 获取用户优惠券列表
  28. * @param int $userId
  29. * @param array $param
  30. * @return \think\Paginator
  31. * @throws \think\db\exception\DbException
  32. */
  33. public function getList(int $userId, array $param)
  34. {
  35. $filter = $this->getFilter($param);
  36. return $this->where($filter)
  37. ->where('user_id', '=', $userId)
  38. ->paginate();
  39. }
  40. /**
  41. * 检索查询条件
  42. * @param array $param
  43. * @return array|mixed
  44. */
  45. private function getFilter(array $param = [])
  46. {
  47. // 设置默认查询参数
  48. $params = $this->setQueryDefaultValue($param, [
  49. 'dataType' => 'all', // all:全部 isUsable:可用的 isExpire:已过期 isUse:已使用
  50. 'amount' => null, // 订单消费金额
  51. ]);
  52. // 检索列表类型
  53. $filter = [];
  54. // 可用的优惠券
  55. if ($params['dataType'] === 'isUsable') {
  56. $filter[] = ['is_use', '=', 0];
  57. $filter[] = ['is_expire', '=', 0];
  58. $filter[] = ['start_time', '<=', time()];
  59. $filter[] = ['end_time', '>', time()];
  60. }
  61. // 已过期的优惠券
  62. if ($params['dataType'] === 'isExpire') {
  63. $filter[] = ['is_expire', '=', 1];
  64. }
  65. // 已使用的优惠券
  66. if ($params['dataType'] === 'isUse') {
  67. $filter[] = ['is_use', '=', 1];
  68. }
  69. // 订单消费金额
  70. $params['amount'] > 0 && $filter[] = ['min_price', '<=', $params['amount']];
  71. return $filter;
  72. }
  73. /**
  74. * 获取用户优惠券总数量(可用)
  75. * @param int $userId
  76. * @return int
  77. */
  78. public function getCount(int $userId)
  79. {
  80. return $this->where('user_id', '=', $userId)
  81. ->where('is_use', '=', 0)
  82. ->where('is_expire', '=', 0)
  83. ->count();
  84. }
  85. /**
  86. * 获取用户优惠券ID集
  87. * @param $userId
  88. * @return array
  89. */
  90. public function getUserCouponIds(int $userId)
  91. {
  92. return $this->where('user_id', '=', $userId)->column('coupon_id');
  93. }
  94. /**
  95. * 领取优惠券
  96. * @param int $couponId 优惠券ID
  97. * @return bool
  98. * @throws BaseException
  99. */
  100. public function receive(int $couponId)
  101. {
  102. // 当前用户信息
  103. $userInfo = UserService::getCurrentLoginUser(true);
  104. // 获取优惠券信息
  105. $coupon = Coupon::detail($couponId);
  106. // 验证优惠券是否可领取
  107. if (!$this->checkReceive($userInfo, $coupon)) {
  108. return false;
  109. }
  110. // 添加领取记录
  111. return $this->add($userInfo, $coupon);
  112. }
  113. /**
  114. * 添加领取记录
  115. * @param $user
  116. * @param Coupon $coupon
  117. * @return bool
  118. */
  119. private function add($user, Coupon $coupon)
  120. {
  121. // 计算有效期
  122. if ($coupon['expire_type'] == ExpireTypeEnum::RECEIVE) {
  123. $startTime = time();
  124. $endTime = $startTime + ($coupon['expire_day'] * 86400);
  125. } else {
  126. $startTime = $coupon->getData('start_time');
  127. $endTime = $coupon->getData('end_time');
  128. }
  129. // 整理领取记录
  130. $data = [
  131. 'coupon_id' => $coupon['coupon_id'],
  132. 'name' => $coupon['name'],
  133. 'coupon_type' => $coupon['coupon_type'],
  134. 'reduce_price' => $coupon['reduce_price'],
  135. 'discount' => $coupon['discount'],
  136. 'min_price' => $coupon['min_price'],
  137. 'expire_type' => $coupon['expire_type'],
  138. 'expire_day' => $coupon['expire_day'],
  139. 'start_time' => $startTime,
  140. 'end_time' => $endTime,
  141. 'apply_range' => $coupon['apply_range'],
  142. 'apply_range_config' => $coupon['apply_range_config'],
  143. 'user_id' => $user['user_id'],
  144. 'store_id' => self::$storeId
  145. ];
  146. // 事务处理
  147. return $this->transaction(function () use ($data, $coupon) {
  148. // 添加领取记录
  149. $status = $this->save($data);
  150. if ($status) {
  151. // 更新优惠券领取数量
  152. $coupon->setIncReceiveNum();
  153. }
  154. return $status;
  155. });
  156. }
  157. /**
  158. * 验证优惠券是否可领取
  159. * @param mixed $userInfo 当前登录用户信息
  160. * @param Coupon $coupon 优惠券详情
  161. * @return bool
  162. */
  163. private function checkReceive($userInfo, Coupon $coupon)
  164. {
  165. if (!$coupon) {
  166. $this->error = '优惠券不存在';
  167. return false;
  168. }
  169. if (!$coupon->checkReceive()) {
  170. $this->error = $coupon->getError();
  171. return false;
  172. }
  173. // 验证是否已领取
  174. $userCouponIds = $this->getUserCouponIds($userInfo['user_id']);
  175. if (in_array($coupon['coupon_id'], $userCouponIds)) {
  176. $this->error = '该优惠券已领取';
  177. return false;
  178. }
  179. return true;
  180. }
  181. /**
  182. * 订单结算优惠券列表
  183. * @param int $userId 用户id
  184. * @param float $orderPayPrice 订单商品总金额
  185. * @return array|mixed
  186. * @throws \think\db\exception\DbException
  187. */
  188. public static function getUserCouponList(int $userId, float $orderPayPrice)
  189. {
  190. // 获取用户可用的优惠券列表
  191. $list = (new static)->getList($userId, ['dataType' => 'isUsable', 'amount' => $orderPayPrice]);
  192. $data = [];
  193. foreach ($list as $coupon) {
  194. // 有效期范围内
  195. if ($coupon['start_time'] > time()) continue;
  196. $key = $coupon['user_coupon_id'];
  197. $data[$key] = [
  198. 'user_coupon_id' => $coupon['user_coupon_id'],
  199. 'name' => $coupon['name'],
  200. 'coupon_type' => $coupon['coupon_type'],
  201. 'reduce_price' => $coupon['reduce_price'],
  202. 'discount' => $coupon['discount'],
  203. 'min_price' => $coupon['min_price'],
  204. 'expire_type' => $coupon['expire_type'],
  205. 'start_time' => $coupon['start_time'],
  206. 'end_time' => $coupon['end_time'],
  207. 'apply_range' => $coupon['apply_range'],
  208. 'apply_range_config' => $coupon['apply_range_config']
  209. ];
  210. // 计算打折金额
  211. if ($coupon['coupon_type'] == 20) {
  212. $reducePrice = helper::bcmul($orderPayPrice, $coupon['discount'] / 10);
  213. $data[$key]['reduced_price'] = helper::bcsub($orderPayPrice, $reducePrice);
  214. } else
  215. $data[$key]['reduced_price'] = $coupon['reduce_price'];
  216. }
  217. // 根据折扣金额排序并返回
  218. return array_sort($data, 'reduced_price', true);
  219. }
  220. /**
  221. * 判断当前优惠券是否满足订单使用条件
  222. * @param $couponList
  223. * @param array $orderGoodsIds 订单商品ID集
  224. * @return mixed
  225. */
  226. public static function couponListApplyRange(array $couponList, array $orderGoodsIds)
  227. {
  228. // 名词解释(is_apply):允许用于抵扣当前订单
  229. foreach ($couponList as &$item) {
  230. if ($item['apply_range'] == ApplyRangeEnum::ALL) {
  231. // 1. 全部商品
  232. $item['is_apply'] = true;
  233. } elseif ($item['apply_range'] == ApplyRangeEnum::SOME) {
  234. // 2. 指定商品, 判断订单商品是否存在可用
  235. $applyGoodsIds = array_intersect($item['apply_range_config']['applyGoodsIds'], $orderGoodsIds);
  236. $item['is_apply'] = !empty($applyGoodsIds);
  237. } elseif ($item['apply_range'] == ApplyRangeEnum::EXCLUDE) {
  238. // 2. 排除商品, 判断订单商品是否全部都在排除行列
  239. $excludedGoodsIds = array_intersect($item['apply_range_config']['excludedGoodsIds'], $orderGoodsIds);
  240. $item['is_apply'] = count($excludedGoodsIds) != count($orderGoodsIds);
  241. }
  242. !$item['is_apply'] && $item['not_apply_info'] = '该优惠券不支持当前商品';
  243. }
  244. return $couponList;
  245. }
  246. }