UserCoupon.php 9.5 KB

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