CouponController.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: zilongs
  5. * Date: 20-10-24
  6. * Time: 上午11:14
  7. */
  8. namespace App\Http\Controllers\Api\V1;
  9. use App\Models\Coupon;
  10. use App\Models\UserCoupon;
  11. class CouponController extends AuthController
  12. {
  13. public function couponList()
  14. {
  15. $data = Coupon::where('position_type', 1)->where('num', '>', 0)->orderBy('id', 'desc')->paginate();
  16. return out($data);
  17. }
  18. public function receiveCoupon()
  19. {
  20. $req = request()->post();
  21. $this->validate(request(), [
  22. 'coupon_id' => 'required|integer'
  23. ]);
  24. $user = $this->user;
  25. $coupon = Coupon::select(['num', 'position_type'])->where('id', $req['coupon_id'])->first();
  26. if ($coupon['num'] <= 0) {
  27. return out(null, 10001, '该优惠券数量不足');
  28. }
  29. if ($coupon['position_type'] == 2) {
  30. return out(null, 10002, '该优惠券不能领取');
  31. }
  32. if (UserCoupon::where('user_id', $user['id'])->where('coupon_id', $req['coupon_id'])->exists()) {
  33. return out(null, 10003, '您已经领取过该优惠券了');
  34. }
  35. $add = Coupon::select(['id as coupon_id', 'name', 'title', 'desc', 'rules', 'icon', 'type', 'usable_type', 'money', 'discount', 'min_consume_amount', 'max_reduce_amount', 'expire_type', 'effective_days', 'start_time', 'end_time'])->where('id', $req['coupon_id'])->first()->getOriginal();
  36. $add['user_id'] = $user['id'];
  37. $expire_time = $add['end_time'];
  38. if ($add['expire_type'] == 1) {
  39. $expire_time = time() + $add['effective_days']*24*3600;
  40. }
  41. $add['expire_time'] = $expire_time;
  42. UserCoupon::create($add);
  43. Coupon::where('id', $req['coupon_id'])->decrement('num');
  44. return out();
  45. }
  46. public function userCouponList()
  47. {
  48. $user = $this->user;
  49. UserCoupon::where('user_id', $user['id'])->where('status', 1)->where('expire_time', '<=', time())->update(['status' => 3]);
  50. $data = UserCoupon::with('couponType')->where('user_id', $user['id'])->orderBy('id', 'desc')->paginate();
  51. return out($data);
  52. }
  53. }