UserCoupon.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2024 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\api\model\Coupon as CouponModel;
  15. use app\common\model\UserCoupon as UserCouponModel;
  16. use app\common\enum\coupon\CouponType as CouponTypeEnum;
  17. use app\common\enum\coupon\ApplyRange as ApplyRangeEnum;
  18. use app\common\library\helper;
  19. use cores\exception\BaseException;
  20. /**
  21. * 用户优惠券模型
  22. * Class UserCoupon
  23. * @package app\api\model
  24. */
  25. class UserCoupon extends UserCouponModel
  26. {
  27. /**
  28. * 隐藏字段
  29. * @var array
  30. */
  31. protected $hidden = [
  32. 'store_id',
  33. 'create_time',
  34. 'update_time'
  35. ];
  36. /**
  37. * 获取用户优惠券列表 (分页)
  38. * @param int $userId
  39. * @param array $param
  40. * @return \think\Paginator
  41. * @throws \think\db\exception\DbException
  42. */
  43. public function getList(int $userId, array $param): \think\Paginator
  44. {
  45. $filter = $this->getFilter($param);
  46. return $this->where($filter)
  47. ->where('user_id', '=', $userId)
  48. ->paginate(15);
  49. }
  50. /**
  51. * 获取用户优惠券列表 (全部)
  52. * @param int $userId
  53. * @param array $param
  54. * @return UserCoupon[]|array|\think\Collection
  55. * @throws \think\db\exception\DataNotFoundException
  56. * @throws \think\db\exception\DbException
  57. * @throws \think\db\exception\ModelNotFoundException
  58. */
  59. public static function getAllList(int $userId, array $param)
  60. {
  61. $model = new static;
  62. $filter = $model->getFilter($param);
  63. return $model->where($filter)
  64. ->where('user_id', '=', $userId)
  65. ->select();
  66. }
  67. /**
  68. * 检索查询条件
  69. * @param array $param
  70. * @return array
  71. */
  72. private function getFilter(array $param = []): array
  73. {
  74. // 设置默认查询参数
  75. $params = $this->setQueryDefaultValue($param, [
  76. 'dataType' => 'all', // all:全部 isUsable:可用的 isExpire:已过期 isUse:已使用
  77. 'amount' => null, // 订单消费金额
  78. ]);
  79. // 检索列表类型
  80. $filter = [];
  81. // 可用的优惠券
  82. if ($params['dataType'] === 'isUsable') {
  83. $filter[] = ['is_use', '=', 0];
  84. $filter[] = ['is_expire', '=', 0];
  85. $filter[] = ['start_time', '<=', time()];
  86. $filter[] = ['end_time', '>', time()];
  87. }
  88. // 未使用的优惠券
  89. if ($params['dataType'] === 'isUnused') {
  90. $filter[] = ['is_use', '=', 0];
  91. $filter[] = ['is_expire', '=', 0];
  92. $filter[] = ['end_time', '>', time()];
  93. }
  94. // 已过期的优惠券
  95. if ($params['dataType'] === 'isExpire') {
  96. $filter[] = ['is_expire', '=', 1];
  97. }
  98. // 已使用的优惠券
  99. if ($params['dataType'] === 'isUse') {
  100. $filter[] = ['is_use', '=', 1];
  101. }
  102. // 订单消费金额
  103. $params['amount'] > 0 && $filter[] = ['min_price', '<=', $params['amount']];
  104. return $filter;
  105. }
  106. /**
  107. * 获取用户优惠券总数量(可用)
  108. * @param int $userId
  109. * @return int
  110. */
  111. public function getCount(int $userId): int
  112. {
  113. return $this->where('user_id', '=', $userId)
  114. ->where('is_use', '=', 0)
  115. ->where('is_expire', '=', 0)
  116. ->where('end_time', '>', time())
  117. ->count();
  118. }
  119. /**
  120. * 获取用户优惠券ID集
  121. * @param int $userId
  122. * @return array
  123. */
  124. public function getUserCouponIds(int $userId): array
  125. {
  126. return $this->where('user_id', '=', $userId)->column('coupon_id');
  127. }
  128. /**
  129. * 领取优惠券
  130. * @param int $couponId 优惠券ID
  131. * @return bool
  132. * @throws BaseException
  133. */
  134. public function receive(int $couponId): bool
  135. {
  136. // 当前用户ID
  137. $userId = UserService::getCurrentLoginUserId(true);
  138. // 获取优惠券信息
  139. $couponInfo = Coupon::detail($couponId);
  140. // 验证优惠券是否可领取
  141. if (!$this->checkReceive($userId, $couponInfo)) {
  142. return false;
  143. }
  144. // 添加领取记录
  145. return $this->add($userId, $couponInfo);
  146. }
  147. /**
  148. * 验证优惠券是否可领取
  149. * @param int $userId 当前用户ID
  150. * @param CouponModel $couponInfo 优惠券详情
  151. * @return bool
  152. */
  153. private function checkReceive(int $userId, CouponModel $couponInfo): bool
  154. {
  155. if (empty($couponInfo)) {
  156. $this->error = '当前优惠券不存在';
  157. return false;
  158. }
  159. // 验证优惠券状态是否可领取
  160. $model = new CouponModel;
  161. if (!$model->checkReceive($couponInfo)) {
  162. $this->error = $model->getError() ?: '优惠券状态不可领取';
  163. return false;
  164. }
  165. // 验证当前用户是否已领取
  166. if (static::checktUserCoupon($couponInfo['coupon_id'], $userId)) {
  167. $this->error = '当前用户已领取该优惠券';
  168. return false;
  169. }
  170. return true;
  171. }
  172. /**
  173. * 根据订单获取可用的优惠券列表 (用于订单结算台)
  174. * @param int $userId 用户id
  175. * @param float $orderPayPrice 订单商品总金额
  176. * @return array
  177. * @throws \think\db\exception\DbException
  178. */
  179. public static function getListByOrder(int $userId, float $orderPayPrice): array
  180. {
  181. // 判断订单商品总金额不能为1分
  182. if ($orderPayPrice <= 0.01) {
  183. return [];
  184. }
  185. // 获取用户可用的优惠券列表
  186. $list = static::getAllList($userId, ['dataType' => 'isUsable', 'amount' => $orderPayPrice]);
  187. $data = $list->isEmpty() ? [] : $list->toArray();
  188. foreach ($data as &$item) {
  189. // 计算最大能折扣的金额
  190. if ($item['coupon_type'] == CouponTypeEnum::DISCOUNT) {
  191. $reducePrice = helper::bcmul($orderPayPrice, $item['discount'] / 10);
  192. $item['reduced_price'] = helper::bcsub($orderPayPrice, $reducePrice);
  193. } else {
  194. $item['reduced_price'] = $item['reduce_price'];
  195. }
  196. }
  197. // 根据折扣金额排序并返回
  198. return !empty($data) ? array_sort($data, 'reduced_price', true) : [];
  199. }
  200. /**
  201. * 判断当前优惠券是否满足订单使用条件
  202. * @param array $couponList
  203. * @param array $orderGoodsIds 订单商品ID集
  204. * @return array
  205. */
  206. public static function couponListApplyRange(array $couponList, array $orderGoodsIds): array
  207. {
  208. // 名词解释(is_apply):允许用于抵扣当前订单
  209. foreach ($couponList as $key => &$item) {
  210. if ($item['apply_range'] == ApplyRangeEnum::ALL) {
  211. // 1. 全部商品
  212. $item['is_apply'] = true;
  213. } elseif ($item['apply_range'] == ApplyRangeEnum::SOME) {
  214. // 2. 指定商品, 判断订单商品是否存在可用
  215. $applyGoodsIds = array_intersect($item['apply_range_config']['goodsIds'], $orderGoodsIds);
  216. $item['is_apply'] = !empty($applyGoodsIds);
  217. } elseif ($item['apply_range'] == ApplyRangeEnum::EXCLUDE) {
  218. // 2. 排除商品, 判断订单商品是否全部都在排除行列
  219. $excludedGoodsIds = array_intersect($item['apply_range_config']['goodsIds'], $orderGoodsIds);
  220. $item['is_apply'] = count($excludedGoodsIds) != count($orderGoodsIds);
  221. }
  222. !$item['is_apply'] && $item['not_apply_info'] = '该优惠券不支持当前订单';
  223. // 此处改为: 将不支持的优惠券剔除
  224. if (!$item['is_apply']) {
  225. unset($couponList[$key]);
  226. }
  227. }
  228. return $couponList;
  229. }
  230. }