UserCoupon.php 8.3 KB

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