UserCoupon.php 9.5 KB

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