Coupon.php 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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\model\Coupon as CouponModel;
  15. use cores\exception\BaseException;
  16. /**
  17. * 优惠券模型
  18. * Class Coupon
  19. * @package app\api\model
  20. */
  21. class Coupon extends CouponModel
  22. {
  23. /**
  24. * 隐藏字段
  25. * @var array
  26. */
  27. protected $hidden = [
  28. 'receive_num',
  29. 'is_delete',
  30. 'create_time',
  31. 'update_time',
  32. ];
  33. /**
  34. * 获取优惠券列表
  35. * @param int|null $limit 获取的数量
  36. * @param bool $onlyReceive 只显示可领取
  37. * @return mixed
  38. * @throws BaseException
  39. * @throws \think\db\exception\DataNotFoundException
  40. * @throws \think\db\exception\DbException
  41. * @throws \think\db\exception\ModelNotFoundException
  42. */
  43. public function getList(int $limit = null, bool $onlyReceive = false)
  44. {
  45. // 查询构造器
  46. $query = $this->getNewQuery();
  47. // 只显示可领取(未过期,未发完)的优惠券
  48. if ($onlyReceive) {
  49. $query->where('IF ( `total_num` > - 1, `receive_num` < `total_num`, 1 = 1 )')
  50. ->where('IF ( `expire_type` = 20, (`end_time` + 86400) >= ' . time() . ', 1 = 1 )');
  51. }
  52. // 查询数量
  53. $limit > 0 && $query->limit($limit);
  54. // 优惠券列表
  55. $couponList = $query->where('status', '=', 1)
  56. ->where('is_delete', '=', 0)
  57. ->order(['sort', 'create_time' => 'desc'])
  58. ->select();
  59. // 获取用户已领取的优惠券
  60. return $this->setIsReceive($couponList);
  61. }
  62. /**
  63. * 获取用户已领取的优惠券
  64. * @param mixed $couponList
  65. * @return mixed
  66. * @throws BaseException
  67. */
  68. private function setIsReceive($couponList)
  69. {
  70. // 获取用户已领取的优惠券
  71. $userInfo = UserService::getCurrentLoginUser();
  72. if ($userInfo !== false) {
  73. $UserCouponModel = new UserCoupon;
  74. $userCouponIds = $UserCouponModel->getUserCouponIds($userInfo['user_id']);
  75. foreach ($couponList as $key => $item) {
  76. $couponList[$key]['is_receive'] = in_array($item['coupon_id'], $userCouponIds);
  77. }
  78. }
  79. return $couponList;
  80. }
  81. }