CouponLogic.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | likeshop100%开源免费商用商城系统
  4. // +----------------------------------------------------------------------
  5. // | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
  6. // | 开源版本可自由商用,可去除界面版权logo
  7. // | 商业版本务必购买商业授权,以免引起法律纠纷
  8. // | 禁止对系统程序代码以任何目的,任何形式的再发布
  9. // | gitee下载:https://gitee.com/likeshop_gitee
  10. // | github下载:https://github.com/likeshop-github
  11. // | 访问官网:https://www.likeshop.cn
  12. // | 访问社区:https://home.likeshop.cn
  13. // | 访问手册:http://doc.likeshop.cn
  14. // | 微信公众号:likeshop技术社区
  15. // | likeshop团队 版权所有 拥有最终解释权
  16. // +----------------------------------------------------------------------
  17. // | author: likeshopTeam
  18. // +----------------------------------------------------------------------
  19. namespace app\shopapi\logic;
  20. use app\common\enum\CouponEnum;
  21. use app\common\enum\FootprintEnum;
  22. use app\common\enum\YesNoEnum;
  23. use app\common\logic\DiscountLogic;
  24. use app\common\model\Cart;
  25. use app\common\model\Coupon;
  26. use app\common\model\CouponList;
  27. use app\common\model\Goods;
  28. use app\common\model\GoodsCategory;
  29. use app\common\model\GoodsCategoryIndex;
  30. use app\common\model\GoodsItem;
  31. use app\common\model\User;
  32. use app\common\service\TimeService;
  33. use Exception;
  34. class CouponLogic
  35. {
  36. /**
  37. * @notes 领取优惠券
  38. * @param $params
  39. * @param $user_id
  40. * @return bool|string
  41. * @author 张无忌
  42. * @date 2021/7/22 15:28
  43. */
  44. public static function receive($params, $user_id)
  45. {
  46. try {
  47. $user = User::findOrEmpty($user_id);
  48. if ($user->isEmpty()) {
  49. throw new Exception('请先登录');
  50. }
  51. // 汽泡足迹
  52. event('Footprint', ['type' => FootprintEnum::GET_COUPONS, 'user_id' => $user_id]);
  53. // 查询优惠券信息
  54. $coupon = (new Coupon())->findOrEmpty(intval($params['id']))->toArray();
  55. if (!$coupon or $coupon['status'] == CouponEnum::COUPON_STATUS_NOT) {
  56. throw new Exception('优惠券尚未开放领取,敬请期待');
  57. }
  58. if (!$coupon or $coupon['status'] == CouponEnum::COUPON_STATUS_END) {
  59. throw new Exception('领取失败,优惠券活动已结束');
  60. }
  61. if ($coupon['send_total_type'] == CouponEnum::SEND_TOTAL_TYPE_FIXED) {
  62. if ($coupon['send_total'] <= 0) {
  63. throw new Exception('领取失败,优惠券已抢光了');
  64. }
  65. $receiveTotal = (new CouponList())->where(['coupon_id'=>intval($params['id'])])->count();
  66. if ($receiveTotal >= $coupon['send_total']) {
  67. throw new Exception('领取失败,优惠券已抢光了');
  68. }
  69. }
  70. switch ($coupon['get_num_type']) {
  71. case CouponEnum::GET_NUM_TYPE_NOT:
  72. break;
  73. case CouponEnum::GET_NUM_TYPE_LIMIT:
  74. $total = (new CouponList())
  75. ->where('user_id', '=', $user_id)
  76. ->where('coupon_id', '=', $coupon['id'])
  77. ->count();
  78. if ($total >= $coupon['get_num']) {
  79. throw new Exception('领取失败,超过领取限制');
  80. }
  81. break;
  82. case CouponEnum::GET_NUM_TYPE_DAY:
  83. $total = (new CouponList())
  84. ->where('coupon_id', '=', $coupon['id'])
  85. ->where('user_id', '=', $user_id)
  86. ->where('create_time', '>=', TimeService::today()[0])
  87. ->where('create_time', '<=', TimeService::today()[1])
  88. ->count();
  89. if ($total >= $coupon['get_num']) {
  90. throw new Exception('领取失败,超过今天领取限制');
  91. }
  92. break;
  93. }
  94. // 计算出券最后可用时间
  95. $invalid_time = 0;
  96. switch ($coupon['use_time_type']) {
  97. case CouponEnum::USE_TIME_TYPE_FIXED:
  98. $invalid_time = $coupon['use_time_end'];
  99. break;
  100. case CouponEnum::USE_TIME_TYPE_TODAY:
  101. $invalid_time = time() + ($coupon['use_time'] * 86400);
  102. break;
  103. case CouponEnum::USE_TIME_TYPE_TOMORROW:
  104. $time = strtotime(date('Y-m-d', strtotime("+1 day")));
  105. $invalid_time = $time + ($coupon['use_time'] * 86400);
  106. }
  107. // 发放优惠券
  108. CouponList::create([
  109. 'channel' => 1,
  110. 'coupon_code' => create_code(),
  111. 'user_id' => $user_id,
  112. 'coupon_id' => $coupon['id'],
  113. 'order_id' => 0,
  114. 'status' => 0,
  115. 'use_time' => 0,
  116. 'invalid_time' => $invalid_time,
  117. 'create_time' => time()
  118. ]);
  119. return true;
  120. } catch (Exception $e) {
  121. return $e->getMessage();
  122. }
  123. }
  124. /**
  125. * @notes 获取商品优惠券
  126. * @param int $goodsId 商品id
  127. * @param int $userId 用户id
  128. * @return array
  129. * @author cjhao
  130. * @date 2021/8/27 15:12
  131. */
  132. public static function goodsCoupon(int $goodsId,int $userId = 0):array
  133. {
  134. $couponList = Coupon::where(['get_type'=>CouponEnum::GET_TYPE_USER,'status' => CouponEnum::COUPON_STATUS_CONDUCT])
  135. ->append([ 'use_time_text', 'use_time_text2', 'use_type', 'condition' ])
  136. ->select();
  137. $goodsCoupon = [];
  138. $myCouponIds = [];
  139. if($userId){
  140. $myCouponIds = CouponList::where(['user_id'=>$userId,'status'=>CouponEnum::USE_STATUS_NOT])
  141. ->column('coupon_id');
  142. }
  143. foreach ($couponList as $coupon){
  144. $couponId = false;
  145. //优惠券是否适合当前商品
  146. switch ($coupon->use_goods_type){
  147. case CouponEnum::USE_GOODS_TYPE_NOT:
  148. $couponId = true;
  149. break;
  150. case CouponEnum::USE_GOODS_TYPE_ALLOW:
  151. $useGoodsIds = $coupon->use_goods_ids;
  152. if(in_array($goodsId,$useGoodsIds)){
  153. $couponId = true;
  154. }
  155. break;
  156. case CouponEnum::USE_GOODS_TYPE_BAN:
  157. $useGoodsIds = $coupon->use_goods_ids;
  158. if(!in_array($goodsId,$useGoodsIds)){
  159. $couponId = true;
  160. }
  161. break;
  162. }
  163. if(CouponEnum::USE_TIME_TYPE_FIXED == $coupon->use_time_type && $coupon->use_time_end < time()){
  164. $couponId = false;
  165. }
  166. if($couponId){
  167. //使用条件
  168. $condition = $coupon['condition'];
  169. //
  170. $useScene = $coupon['use_type'];
  171. //使用时间
  172. $effectiveTime = $coupon['use_time_text2'];
  173. //优惠券是否已领取
  174. $isReceive = in_array($coupon->id, $myCouponIds) ? 1 : 0;
  175. $isAvailable = 0;
  176. //是否可领取
  177. switch ($coupon->get_num_type) {
  178. case CouponEnum::GET_NUM_TYPE_LIMIT:
  179. $total = CouponList::where(['coupon_id' => $coupon->id])
  180. ->where(['user_id' => $userId])
  181. ->count();
  182. $isAvailable = $total >= $coupon->get_num ? 1 : 0;
  183. break;
  184. case CouponEnum::GET_NUM_TYPE_DAY:
  185. $total = CouponList::where(['coupon_id' => $coupon->id])
  186. ->where(['user_id' =>$userId])
  187. ->where('create_time', '>=', TimeService::today()[0])
  188. ->where('create_time', '<=', TimeService::today()[1])
  189. ->count();
  190. $isAvailable = $total >= $coupon->get_num ? 1 : 0;
  191. break;
  192. }
  193. $goodsCoupon[] = [
  194. 'id' => $coupon->id,
  195. 'name' => $coupon->name,
  196. 'money' => $coupon->money,
  197. 'condition' => $condition,
  198. 'condition_type'=> $coupon->condition_type,
  199. 'condition_money' => $coupon->condition_money,
  200. 'discount_max_money' => $coupon->discount_max_money,
  201. 'discount_ratio' => $coupon->discount_ratio,
  202. 'use_scene' => $useScene,
  203. 'is_receive' => $isReceive,
  204. 'is_available' => $isAvailable,
  205. 'effective_time'=> $effectiveTime,
  206. ];
  207. }
  208. }
  209. return $goodsCoupon;
  210. }
  211. /**
  212. * @notes 结算页优惠券
  213. * @param $params
  214. * @return array
  215. * @author Tab
  216. * @date 2021/9/9 18:14
  217. */
  218. public static function orderCoupon($params)
  219. {
  220. // 处理购物车的情况
  221. if ($params['source'] == 2) {
  222. $params['goods'] = self::handleCart($params['cart_ids']);
  223. }
  224. // 计算订单金额
  225. $orderAmountResult = self::calcOrderAmount($params);
  226. // 查找用户未使用的券
  227. $where = [
  228. ['cl.user_id', '=', $params['user_id']],
  229. ['cl.status', '=', CouponEnum::USE_STATUS_NOT],
  230. ];
  231. $field = [
  232. // 领取时间
  233. 'cl.id',
  234. // 领取时间
  235. 'cl.create_time',
  236. // 领取时间
  237. 'cl.create_time',
  238. // 过期时间
  239. 'cl.invalid_time',
  240. // 券名称
  241. 'c.name',
  242. // 面额
  243. 'c.money',
  244. // 使用门槛
  245. 'c.condition_type',
  246. // 订单满多少金额可用
  247. 'c.condition_money',
  248. // 使用时间类型
  249. 'c.use_time_type',
  250. // 固定时间范围
  251. 'c.use_time_start',
  252. 'c.use_time_end',
  253. // 领取多少天后可用
  254. 'c.use_time',
  255. // 适用商品类型
  256. 'c.use_goods_type',
  257. 'c.use_goods_ids',
  258. 'c.discount_max_money',
  259. 'c.discount_ratio',
  260. 'c.use_goods_category_ids',
  261. ];
  262. $lists = CouponList::alias('cl')
  263. ->leftJoin('coupon c', 'c.id = cl.coupon_id')
  264. ->field($field)
  265. ->where($where)
  266. ->select()
  267. ->toArray();
  268. // 可用优惠券
  269. $canUse = [];
  270. // 不可用优惠券
  271. $notCanUse = [];
  272. foreach ($lists as &$item) {
  273. // 不可用原因
  274. $item['fail_use_tips'] = '';
  275. // 不可用原因详细信息
  276. $item['fail_use_detail'] = [];
  277. // 检查是否已到可使用时间
  278. $flagUserTime = self::checkUseTime($item);
  279. // 检查当前商品是否可用券
  280. $flagGoods = self::checkGoods($item, $params);
  281. // 检查是否达到使用门槛
  282. $flagCondition = self::checkCondition($item, $orderAmountResult);
  283. $item['money'] = clearZero($item['money']);
  284. if ($flagUserTime && $flagCondition && $flagGoods) {
  285. $canUse[] = $item;
  286. } else {
  287. $notCanUse[] = $item;
  288. }
  289. }
  290. return [
  291. 'can_use' => $canUse,
  292. 'can_use_count' => count($canUse),
  293. 'not_can_use' => $notCanUse,
  294. 'not_can_use_count' => count($notCanUse),
  295. ];
  296. }
  297. /**
  298. * @notes 获取购物车商品
  299. * @param $cartIds
  300. * @return array
  301. * @throws \think\db\exception\DataNotFoundException
  302. * @throws \think\db\exception\DbException
  303. * @throws \think\db\exception\ModelNotFoundException
  304. * @author Tab
  305. * @date 2021/9/15 19:04
  306. */
  307. public static function handleCart($cartIds)
  308. {
  309. $data = [];
  310. $cartData = Cart::where([
  311. ['id', 'in', $cartIds],
  312. ['selected', '=', YesNoEnum::YES]
  313. ])->select()->toArray();
  314. foreach ($cartData as $item) {
  315. $data[] = ['item_id' => $item['item_id'], 'num' => $item['goods_num']];
  316. }
  317. return $data;
  318. }
  319. /**
  320. * @notes 计算订单价格
  321. * @param $params
  322. * @return array
  323. * @author Tab
  324. * @date 2021/9/8 15:30
  325. */
  326. public static function calcOrderAmount($params)
  327. {
  328. $result['sum'] = 0;
  329. $result['goods'] = [];
  330. // 提取item_id
  331. $item_ids = array_column($params['goods'], 'item_id');
  332. // 获取规格价格
  333. $items = GoodsItem::where('id', 'in', $item_ids)->column('goods_id,id,sell_price', 'id');
  334. $goodsIds = array_column($items,'goods_id');
  335. //获取会员价
  336. $levelGoodsItem = DiscountLogic::getGoodsDiscount($params['user_id'], $goodsIds);
  337. // 计算订单总价
  338. foreach($params['goods'] as $item) {
  339. if (isset($items[$item['item_id']])) {
  340. $goodsItem = $items[$item['item_id']];
  341. $price = $levelGoodsItem[$goodsItem['goods_id']][$goodsItem['id']]['discount_price'] ?? $goodsItem['sell_price'];
  342. $result['sum'] = bcadd($item['num'] * $price, $result['sum'], 2);
  343. $result['goods'][$goodsItem['goods_id']] = bcadd($item['num'] * $price, $result['goods'][$goodsItem['goods_id']] ?? 0, 2);
  344. }
  345. }
  346. return $result;
  347. }
  348. /**
  349. * @notes 检查使用时间
  350. * @param $item
  351. * @return bool
  352. * @author Tab
  353. * @date 2021/9/9 18:40
  354. */
  355. public static function checkUseTime(&$item)
  356. {
  357. switch($item['use_time_type']) {
  358. // 固定时间
  359. case CouponEnum::USE_TIME_TYPE_FIXED:
  360. $item['use_time_text2'] = date('Y.m.d', $item['use_time_start']) . ' ~ ' . date('Y.m.d', $item['use_time_end']);
  361. $item['use_time_tips'] = date('Y.m.d H:i:s', $item['use_time_start']) . ' - ' . date('Y.m.d H:i:s', $item['use_time_end']);
  362. if(time() >= $item['use_time_start'] && time() <= $item['use_time_end']) {
  363. return true;
  364. }
  365. $item['fail_use_tips'] = '不在使用时间范围内';
  366. $item['fail_use_detail'] = ['不在使用时间范围内'];
  367. return false;
  368. // 当天起多少天内
  369. case CouponEnum::USE_TIME_TYPE_TODAY:
  370. $item['use_time_text2'] = '领取当日起' . $item['use_time'] . '天内可用';
  371. $effectiveTime = strtotime($item['create_time']) + 24 * 60 * 60 * $item['use_time'];
  372. $item['use_time_tips'] = '有效期至' . date('Y.m.d H:i:s', $effectiveTime);
  373. if (time() < $effectiveTime) {
  374. return true;
  375. }
  376. $item['fail_use_tips'] = '不在使用时间范围内';
  377. $item['fail_use_detail'] = ['不在使用时间范围内'];
  378. return false;
  379. // 次日起多少天内
  380. case CouponEnum::USE_TIME_TYPE_TOMORROW:
  381. $item['use_time_text2'] = '领取次日起' . $item['use_time'] . '天内可用';
  382. $today = date('Y-m-d', strtotime($item['create_time']));
  383. $today .= ' 00:00:00';
  384. $effectiveStartTime = strtotime($today) + 24 * 60 * 60;
  385. $effectiveEndTime = strtotime($today) + 24 * 60 * 60 * ($item['use_time'] + 1);
  386. $item['use_time_tips'] = '有效期至' . date('Y.m.d H:i:s', $effectiveEndTime);
  387. if (time() >= $effectiveStartTime && time() <= $effectiveEndTime) {
  388. return true;
  389. }
  390. $item['fail_use_tips'] = '不在使用时间范围内';
  391. $item['fail_use_detail'] = ['不在使用时间范围内'];
  392. return false;
  393. }
  394. $item['fail_use_tips'] = '不在使用时间范围内';
  395. $item['fail_use_detail'] = ['不在使用时间范围内'];
  396. return false;
  397. }
  398. /**
  399. * @notes 使用门槛校验
  400. * @param $item
  401. * @param $orderAmount
  402. * @return bool
  403. * @author Tab
  404. * @date 2021/9/9 18:51
  405. */
  406. public static function checkCondition(&$item, $orderAmountResult)
  407. {
  408. $orderAmount = 0;
  409. foreach ($orderAmountResult['goods'] as $goods_id => $goods_money) {
  410. if (in_array($goods_id, $item['coupon_use_goods'])) {
  411. $orderAmount = bcadd($goods_money, $orderAmount);
  412. }
  413. }
  414. // 无门槛
  415. if($item['condition_type'] == CouponEnum::CONDITION_TYPE_NOT) {
  416. $item['condition_tips'] = '无门槛';
  417. return true;
  418. }
  419. $item['condition_tips'] = '满' . $item['condition_money'] . '可用';
  420. // 订单满金额
  421. if($item['condition_type'] == CouponEnum::CONDITION_TYPE_FULL && $orderAmount >= $item['condition_money']) {
  422. return true;
  423. }
  424. // 折扣券
  425. if($item['condition_type'] == CouponEnum::CONDITION_TYPE_DISCOUNT && $orderAmount >= $item['condition_money']) {
  426. return true;
  427. }
  428. $item['fail_use_tips'] = '未满足规定的订单金额';
  429. $item['fail_use_detail'] = ['未满足规定的订单金额'];
  430. return false;
  431. }
  432. /**
  433. * @notes 校验当前商品是否可用优惠券
  434. * @param $item
  435. * @param $params
  436. * @return bool
  437. * @throws \think\db\exception\DataNotFoundException
  438. * @throws \think\db\exception\DbException
  439. * @throws \think\db\exception\ModelNotFoundException
  440. * @author Tab
  441. * @date 2021/9/9 19:03
  442. */
  443. public static function checkGoods(&$item, $params)
  444. {
  445. // 记录可使用次优惠券的商品id
  446. $item['coupon_use_goods'] = [];
  447. $itemIds = array_column($params['goods'], 'item_id');
  448. $goodsIds = GoodsItem::where('id', 'in', $itemIds)->select()->column('goods_id');
  449. // 全部商品可用
  450. if($item['use_goods_type'] == CouponEnum::USE_GOODS_TYPE_NOT) {
  451. $item['goods_tips'] = '全店通用';
  452. $item['coupon_use_goods'] = $goodsIds;
  453. return true;
  454. }
  455. // 指定商品可用
  456. if($item['use_goods_type'] == CouponEnum::USE_GOODS_TYPE_ALLOW) {
  457. $item['goods_tips'] = '指定商品可用';
  458. $allow = explode(',', $item['use_goods_ids']);
  459. $item['fail_use_detail'] = self::goodsData($allow, '可用商品:');
  460. foreach ($goodsIds as $id) {
  461. if (in_array($id, $allow)) {
  462. $item['coupon_use_goods'][] = $id;
  463. }
  464. }
  465. if ($item['coupon_use_goods']) {
  466. return true;
  467. }
  468. $item['fail_use_tips'] = '部分商品不适用';
  469. return false;
  470. }
  471. // 指定商品不可用
  472. if($item['use_goods_type'] == CouponEnum::USE_GOODS_TYPE_BAN) {
  473. $item['goods_tips'] = '指定商品不可用';
  474. $ban = explode(',', $item['use_goods_ids']);
  475. $item['fail_use_detail'] = self::goodsData($ban, '不可用商品:');
  476. foreach ($goodsIds as $id) {
  477. if (! in_array($id, $ban)) {
  478. $item['coupon_use_goods'][] = $id;
  479. }
  480. }
  481. if ($item['coupon_use_goods']) {
  482. return true;
  483. }
  484. $item['fail_use_tips'] = '部分商品不适用';
  485. return false;
  486. }
  487. // 指定分类可用
  488. if($item['use_goods_type'] == CouponEnum::USE_GOODS_TYPE_CATEGORY) {
  489. $item['goods_tips'] = '指定分类可用';
  490. $categoryList = GoodsCategory::where('id', 'in', $item['use_goods_category_ids'])->select()->toArray();
  491. $categoryListIds = array_column($categoryList, 'id');
  492. $item['fail_use_detail'] = '可用分类:' . implode(' ', array_column($categoryList, 'name'));
  493. foreach ($goodsIds as $id) {
  494. $categoryIndexIds = GoodsCategoryIndex::where('goods_id', $id)->column('category_id');
  495. if (array_intersect($categoryIndexIds, $categoryListIds)) {
  496. $item['coupon_use_goods'][] = $id;
  497. }
  498. }
  499. if ($item['coupon_use_goods']) {
  500. return true;
  501. }
  502. $item['fail_use_tips'] = '部分商品不适用';
  503. return false;
  504. }
  505. $item['fail_use_tips'] = '部分商品不适用';
  506. return false;
  507. }
  508. /**
  509. * @notes 商品名称
  510. * @param $goodsIds
  511. * @author Tab
  512. * @date 2021/9/10 16:36
  513. */
  514. public static function goodsData($goodsIds, $tips)
  515. {
  516. $data[] = $tips;
  517. $goods = Goods::field('name')->where('id', 'in', $goodsIds)->select()->toArray();
  518. foreach($goods as $item) {
  519. $data[] = $item['name'];
  520. }
  521. return $data;
  522. }
  523. }