UserCoupon.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. }
  59. // 已过期的优惠券
  60. if ($params['dataType'] === 'isExpire') {
  61. $filter[] = ['is_expire', '=', 1];
  62. }
  63. // 已使用的优惠券
  64. if ($params['dataType'] === 'isUse') {
  65. $filter[] = ['is_use', '=', 1];
  66. }
  67. // 订单消费金额
  68. $params['amount'] > 0 && $filter[] = ['min_price', '<=', $params['amount']];
  69. return $filter;
  70. }
  71. /**
  72. * 获取用户优惠券总数量(可用)
  73. * @param int $userId
  74. * @return int
  75. */
  76. public function getCount(int $userId)
  77. {
  78. return $this->where('user_id', '=', $userId)
  79. ->where('is_use', '=', 0)
  80. ->where('is_expire', '=', 0)
  81. ->count();
  82. }
  83. /**
  84. * 获取用户优惠券ID集
  85. * @param $userId
  86. * @return array
  87. */
  88. public function getUserCouponIds(int $userId)
  89. {
  90. return $this->where('user_id', '=', $userId)->column('coupon_id');
  91. }
  92. /**
  93. * 领取优惠券
  94. * @param int $couponId 优惠券ID
  95. * @return bool
  96. * @throws BaseException
  97. */
  98. public function receive(int $couponId)
  99. {
  100. // 当前用户信息
  101. $userInfo = UserService::getCurrentLoginUser(true);
  102. // 获取优惠券信息
  103. $coupon = Coupon::detail($couponId);
  104. // 验证优惠券是否可领取
  105. if (!$this->checkReceive($userInfo, $coupon)) {
  106. return false;
  107. }
  108. // 添加领取记录
  109. return $this->add($userInfo, $coupon);
  110. }
  111. /**
  112. * 添加领取记录
  113. * @param $user
  114. * @param Coupon $coupon
  115. * @return bool
  116. */
  117. private function add($user, Coupon $coupon)
  118. {
  119. // 计算有效期
  120. if ($coupon['expire_type'] == ExpireTypeEnum::RECEIVE) {
  121. $startTime = time();
  122. $endTime = $startTime + ($coupon['expire_day'] * 86400);
  123. } else {
  124. $startTime = $coupon->getData('start_time');
  125. $endTime = $coupon->getData('end_time');
  126. }
  127. // 整理领取记录
  128. $data = [
  129. 'coupon_id' => $coupon['coupon_id'],
  130. 'name' => $coupon['name'],
  131. 'coupon_type' => $coupon['coupon_type'],
  132. 'reduce_price' => $coupon['reduce_price'],
  133. 'discount' => $coupon->getData('discount'),
  134. 'min_price' => $coupon['min_price'],
  135. 'expire_type' => $coupon['expire_type'],
  136. 'expire_day' => $coupon['expire_day'],
  137. 'start_time' => $startTime,
  138. 'end_time' => $endTime,
  139. 'apply_range' => $coupon['apply_range'],
  140. 'apply_range_config' => $coupon['apply_range_config'],
  141. 'user_id' => $user['user_id'],
  142. 'store_id' => self::$storeId
  143. ];
  144. // 事务处理
  145. return $this->transaction(function () use ($data, $coupon) {
  146. // 添加领取记录
  147. $status = $this->save($data);
  148. if ($status) {
  149. // 更新优惠券领取数量
  150. $coupon->setIncReceiveNum();
  151. }
  152. return $status;
  153. });
  154. }
  155. /**
  156. * 验证优惠券是否可领取
  157. * @param mixed $userInfo 当前登录用户信息
  158. * @param Coupon $coupon 优惠券详情
  159. * @return bool
  160. */
  161. private function checkReceive($userInfo, Coupon $coupon)
  162. {
  163. if (!$coupon) {
  164. $this->error = '优惠券不存在';
  165. return false;
  166. }
  167. if (!$coupon->checkReceive()) {
  168. $this->error = $coupon->getError();
  169. return false;
  170. }
  171. // 验证是否已领取
  172. $userCouponIds = $this->getUserCouponIds($userInfo['user_id']);
  173. if (in_array($coupon['coupon_id'], $userCouponIds)) {
  174. $this->error = '该优惠券已领取';
  175. return false;
  176. }
  177. return true;
  178. }
  179. /**
  180. * 订单结算优惠券列表
  181. * @param int $userId 用户id
  182. * @param float $orderPayPrice 订单商品总金额
  183. * @return array|mixed
  184. * @throws \think\db\exception\DbException
  185. */
  186. public static function getUserCouponList(int $userId, float $orderPayPrice)
  187. {
  188. // 获取用户可用的优惠券列表
  189. $list = (new static)->getList($userId, ['dataType' => 'isUsable', 'amount' => $orderPayPrice]);
  190. $data = [];
  191. foreach ($list as $coupon) {
  192. // 有效期范围内
  193. if ($coupon['start_time'] > time()) continue;
  194. $key = $coupon['user_coupon_id'];
  195. $data[$key] = [
  196. 'user_coupon_id' => $coupon['user_coupon_id'],
  197. 'name' => $coupon['name'],
  198. 'coupon_type' => $coupon['coupon_type'],
  199. 'reduce_price' => $coupon['reduce_price'],
  200. 'discount' => $coupon['discount'],
  201. 'min_price' => $coupon['min_price'],
  202. 'expire_type' => $coupon['expire_type'],
  203. 'start_time' => $coupon['start_time'],
  204. 'end_time' => $coupon['end_time'],
  205. 'apply_range' => $coupon['apply_range'],
  206. 'apply_range_config' => $coupon['apply_range_config']
  207. ];
  208. // 计算打折金额
  209. if ($coupon['coupon_type'] == 20) {
  210. $reducePrice = helper::bcmul($orderPayPrice, $coupon['discount'] / 10);
  211. $data[$key]['reduced_price'] = helper::bcsub($orderPayPrice, $reducePrice);
  212. } else
  213. $data[$key]['reduced_price'] = $coupon['reduce_price'];
  214. }
  215. // 根据折扣金额排序并返回
  216. return array_sort($data, 'reduced_price', true);
  217. }
  218. /**
  219. * 判断当前优惠券是否满足订单使用条件
  220. * @param $couponList
  221. * @param array $orderGoodsIds 订单商品ID集
  222. * @return mixed
  223. */
  224. public static function couponListApplyRange(array $couponList, array $orderGoodsIds)
  225. {
  226. // 名词解释(is_apply):允许用于抵扣当前订单
  227. foreach ($couponList as &$item) {
  228. if ($item['apply_range'] == ApplyRangeEnum::ALL) {
  229. // 1. 全部商品
  230. $item['is_apply'] = true;
  231. } elseif ($item['apply_range'] == ApplyRangeEnum::SOME) {
  232. // 2. 指定商品, 判断订单商品是否存在可用
  233. $applyGoodsIds = array_intersect($item['apply_range_config']['applyGoodsIds'], $orderGoodsIds);
  234. $item['is_apply'] = !empty($applyGoodsIds);
  235. } elseif ($item['apply_range'] == ApplyRangeEnum::EXCLUDE) {
  236. // 2. 排除商品, 判断订单商品是否全部都在排除行列
  237. $excludedGoodsIds = array_intersect($item['apply_range_config']['excludedGoodsIds'], $orderGoodsIds);
  238. $item['is_apply'] = count($excludedGoodsIds) != count($orderGoodsIds);
  239. }
  240. !$item['is_apply'] && $item['not_apply_info'] = '该优惠券不支持当前商品';
  241. }
  242. return $couponList;
  243. }
  244. }