StoreCouponSendRepository.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace app\common\repositories\store\coupon;
  3. use app\common\dao\store\coupon\StoreCouponSendDao;
  4. use app\common\repositories\BaseRepository;
  5. use app\common\repositories\user\UserMerchantRepository;
  6. use ln\jobs\MerchantSendCouponJob;
  7. use think\exception\ValidateException;
  8. use think\facade\Cache;
  9. use think\facade\Db;
  10. use think\facade\Queue;
  11. /**
  12. * @mixin StoreCouponSendDao
  13. */
  14. class StoreCouponSendRepository extends BaseRepository
  15. {
  16. public function __construct(StoreCouponSendDao $dao)
  17. {
  18. $this->dao = $dao;
  19. }
  20. public function getList(array $where, $page, $limit)
  21. {
  22. $query = $this->dao->search($where);
  23. $count = $query->count();
  24. $list = $query->setOption('field', [])->field('B.*,A.coupon_num,A.create_time,A.status as send_status, A.mark,A.coupon_send_id')
  25. ->append(['useCount', 'used_num'])->page($page, $limit)->order('coupon_send_id DESC')->select();
  26. return compact('count', 'list');
  27. }
  28. public function create($data, $merId)
  29. {
  30. $userMerchantRepository = app()->make(UserMerchantRepository::class);
  31. $query = null;
  32. $coupon = app()->make(StoreCouponRepository::class)->getWhere(['mer_id' => $merId, 'coupon_id' => $data['coupon_id'], 'is_del' => 0]);
  33. if (!$coupon) {
  34. throw new ValidateException('优惠券不存在');
  35. }
  36. if ($data['is_all']) {
  37. $query = $userMerchantRepository->search(['mer_id' => $merId] + $data['search']);
  38. } else {
  39. $query = $userMerchantRepository->search(['uids' => $data['uid'], 'mer_id' => $merId]);
  40. }
  41. $uid = $query->column('A.uid');
  42. $uTotal = count($uid);
  43. if (!$uTotal) {
  44. throw new ValidateException('请选择用户');
  45. }
  46. if ($coupon['is_limited'] && $coupon->remain_count < $uTotal) {
  47. throw new ValidateException('该优惠券可领取数不足' . $uTotal);
  48. }
  49. return Db::transaction(function () use ($uid, $merId, $data, $coupon, $uTotal) {
  50. $search = $data['mark'];
  51. if($coupon['is_limited']){
  52. $coupon->remain_count -= $uTotal;
  53. }
  54. $send = $this->dao->create([
  55. 'mer_id' => $merId,
  56. 'coupon_id' => $coupon->coupon_id,
  57. 'coupon_num' => $uTotal,
  58. 'status' => 0,
  59. 'mark' => [
  60. 'type' => $data['is_all'],
  61. 'search' => count($search) ? $search : null
  62. ]
  63. ]);
  64. $coupon->save();
  65. Cache::store('file')->set('_send_coupon' . $send->coupon_send_id, $uid);
  66. Queue::push(MerchantSendCouponJob::class, $send->coupon_send_id);
  67. return $send;
  68. });
  69. }
  70. }