UserCoupon.php 9.7 KB

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