You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

305 lines
10 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://doc.hyperf.io
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace App\Controller;
  12. use App\Model\CouponUserRecType;
  13. use App\Model\Coupon;
  14. use App\Model\CouponRec;
  15. use Hyperf\DbConnection\Db;
  16. use Hyperf\Redis\Redis;
  17. use Hyperf\Utils\ApplicationContext;
  18. class CouponController extends BaseController
  19. {
  20. /**
  21. * 获取用户可领取优惠卷接口
  22. */
  23. public function getSystemCouponUserList()
  24. {
  25. $user_id = $this->request->input('user_id', 0);
  26. $receive_type = $this->request->input('receive_type', 0);
  27. if ($this->empty($user_id) || $this->empty($receive_type)) {
  28. return $this->success(['not_reveive' => []]);
  29. }
  30. $c_ids = [];
  31. // 渠道开启,查询该渠道可以领取的优惠券ID
  32. // 渠道未开启,查询所有优惠券
  33. if (env('SUB_CHANNEL') == 1) {
  34. $c_ids = CouponUserRecType::where('receive_type', $receive_type)->pluck('system_coupon_user_id');
  35. } else {
  36. $c_ids = Coupon::pluck('id');
  37. }
  38. $nowTime = time();
  39. $where = [
  40. ['user_id',"=",$user_id]
  41. ];
  42. // 渠道开启,查询该用户在此渠道领过的优惠券ID
  43. if (env('SUB_CHANNEL') == 1) {
  44. array_push($where, ['receive_type', "=", $receive_type]);
  45. }
  46. $cr_ids = CouponRec::where($where)->pluck('system_coupon_user_id');
  47. //领过券的ID
  48. $c_ids = $c_ids->toArray();
  49. $cr_ids = $cr_ids->toArray();
  50. // 当前用户可领的优惠券ID
  51. $couponIds = array_diff($c_ids, $cr_ids);
  52. $whereC = [
  53. ['u.end_time','>',$nowTime],
  54. ['u.start_time','<=',$nowTime],
  55. ['u.status','=',1],
  56. ['u.active_type','=',1],
  57. ];
  58. if (env('SUB_CHANNEL') == 1) {
  59. array_push($whereC, ['type.receive_type','=',$receive_type]);
  60. }
  61. $c = Db::table('ims_system_coupon_user as u')
  62. ->where($whereC)
  63. ->join('ims_system_coupon_user_receivetype as type', 'u.id', '=', 'type.system_coupon_user_id')
  64. ->whereRaw('u.inventory_use <= u.inventory and u.inventory-u.inventory_use > type.one_receive_number')
  65. // ->whereIn('u.id',$c_ids)
  66. // ->whereNotIn('u.id',$cr_ids)
  67. ->whereIn('u.id', $couponIds)
  68. ->select('u.*','type.one_receive_number')
  69. ->orderBy('u.weigh','desc')
  70. // ->orderByRaw('FIELD(u.id, '.implode(", " , $ids).')')
  71. ->limit(4)
  72. ->get();
  73. foreach ($c as $k => &$v){
  74. if($v->discount_type == 2){
  75. $v->discounts = floatval($v->discounts);
  76. }
  77. }
  78. return $this->success(['not_reveive'=>$c]);
  79. }
  80. //统计用户
  81. public function userCouponAccount()
  82. {
  83. $userId = $this->request->input("user_id", 0);
  84. $nowTime = time();
  85. $num = Db::table('ims_system_coupon_user_receive as receive')
  86. ->join('ims_system_coupon_user as u', 'u.id', '=', 'receive.system_coupon_user_id')
  87. ->where([
  88. ['receive.user_id','=',$userId],
  89. ['receive.number_remain','>',0],
  90. ['u.usable_end_time','>',$nowTime],
  91. ])
  92. ->whereIn('receive.status',[0,1])
  93. ->sum('receive.number_remain');
  94. return $this->success(['total' => $num]);
  95. }
  96. /**
  97. * 用户领取优惠卷
  98. */
  99. public function userReceiveCoupon()
  100. {
  101. $userId = $this->request->input("user_id", 0);
  102. $receiveType = $this->request->input("receive_type", 0);
  103. $ids = $this->request->input("ids", '');
  104. $ids = explode(',', $ids);
  105. $now = time();
  106. $success = [];
  107. $fail = [];
  108. if ($this->empty($userId) || $this->empty($receiveType) || $this->empty($ids)) {
  109. return $this->success([
  110. 'success' => $success,
  111. 'fail' => $fail,
  112. ]);
  113. }
  114. Db::transaction(function () use ($ids,$receiveType,$userId,&$success,&$fail,$now) {
  115. //读写锁,完全控制,性能底
  116. $cps = Coupon::whereIn('id', $ids)->lockForUpdate()->get();
  117. //写锁,可能在高并发下,读取到脏数据,写入可能有超发情况
  118. //$cps = Coupon::whereIn('id', $ids)->sharedLock()->get();
  119. foreach ($cps as $key => $cp) {
  120. $where = [
  121. 'system_coupon_user_id' => $cp->id,
  122. ];
  123. if (env('SUB_CHANNEL') == 1) {
  124. $where['receive_type'] = $receiveType;
  125. }
  126. $crt = CouponUserRecType::where($where)->first();
  127. $cr = new CouponRec;
  128. $cr->user_id = $userId;
  129. $cr->system_coupon_user_id = $cp->id;
  130. $cr->order_main_id = 0;
  131. $cr->receive_time = $now;
  132. $cr->number = $crt->one_receive_number;
  133. $cr->number_remain = $crt->one_receive_number;
  134. $cr->status = 0;
  135. $cr->update_time = $now;
  136. $cr->receive_type = $receiveType;
  137. //如果优惠卷库存小于等于已领取的数量, 则返回领取失败的优惠券
  138. if ($cp->inventory<=$cp->inventory_use||$cp->inventory<($cp->inventory_use+$cr->number)){
  139. $fail[] = $cp;
  140. }else{
  141. $cp->inventory_use += $cr->number;//记录已领取的数量
  142. if ($cr->save()&&$cp->save()) {
  143. $success[] = $cp;
  144. } else {
  145. $fail[] = $cp;
  146. }
  147. }
  148. }
  149. });
  150. return $this->success([
  151. 'success' => $success,
  152. 'fail' => $fail,
  153. ]);
  154. }
  155. /**
  156. * 获取用户已经领取的优惠卷列表
  157. */
  158. public function getUserReceiveCouponList()
  159. {
  160. $userId = $this->request->input("user_id");
  161. $not_expired = [];
  162. $expired = [];
  163. if ($this->empty($userId)) {
  164. return $this->success(['not_expired' => $not_expired, 'expired' => $expired]);
  165. }
  166. $nowTime = time();
  167. $coupons = Db::table('ims_system_coupon_user_receive as receive')
  168. ->join('ims_system_coupon_user as u', 'u.id', '=', 'receive.system_coupon_user_id')
  169. ->where([
  170. ['receive.user_id','=',$userId],
  171. ])
  172. ->whereIn('receive.status',[0,1])
  173. ->select('u.*','receive.number_remain')
  174. ->orderBy('u.weigh','desc')
  175. ->get();
  176. foreach ($coupons as $key => $coupon) {
  177. if ($coupon->usable_end_time < $nowTime || $coupon->number_remain <= 0) {
  178. $expired[] = $coupon;
  179. } else {
  180. $not_expired[] = $coupon;
  181. }
  182. }
  183. $ret = ['not_expired' => $not_expired, 'expired' => $expired];
  184. return $this->success($ret);
  185. }
  186. /**
  187. * 获取用户当前订单可用的优惠券列表
  188. * 按分类(1订单 等优惠)分组返回
  189. */
  190. public function getUserAvailableCoupons()
  191. {
  192. // 获取参数
  193. # 订单金额
  194. $orderAmount = $this->request->input('order_amount', 0);
  195. # 用户id
  196. $userId = $this->request->input('user_id', 0);
  197. # 市场id
  198. $marketId = $this->request->input('market_id', 0);
  199. # 类型,1全平台 2线上 3线下,20200718默认全平台
  200. $type = $this->request->input('type', 1);
  201. # 店铺类型id
  202. $storetypeId = $this->request->input('storetype_id', 0);
  203. $storetypeIds = explode(',', str_replace(',', ',', $storetypeId));
  204. $available = [];
  205. $notAvailable = [];
  206. if ($this->empty($orderAmount) || $this->empty($userId)) {
  207. return $this->success([
  208. 'available' => $available,
  209. 'not_available' => array_values($notAvailable)
  210. ]);
  211. }
  212. // 获取用户优惠券
  213. $currentTime = time();
  214. $data = Db::table('ims_system_coupon_user_receive as receive')
  215. ->select([
  216. 'receive.id as receive_id',
  217. 'receive.user_id',
  218. 'receive.number_remain',
  219. 'coupon.id',
  220. 'coupon.title',
  221. 'coupon.full_amount',
  222. 'coupon.discounts',
  223. 'coupon.usable_start_time',
  224. 'coupon.usable_end_time',
  225. 'coupon.discount_type'
  226. ])
  227. ->join('ims_system_coupon_user as coupon', 'coupon.id', '=', 'receive.system_coupon_user_id')
  228. ->where(['receive.user_id' => $userId])
  229. ->whereIn('receive.status', [0,1])
  230. ->where('receive.number_remain', '>', 0)
  231. ->whereIn('coupon.type', [1,$type])
  232. ->where('coupon.full_amount', '<=', $orderAmount)
  233. ->where('coupon.usable_start_time', '<=', $currentTime)
  234. ->where('coupon.usable_end_time', '>=', $currentTime)
  235. ->where('coupon.usable_number', '<=', Db::raw('receive.number_remain'))
  236. ->where('coupon.market_id', 'in', [0, $marketId])
  237. ->whereIn('coupon.storetype_id', $storetypeIds)
  238. ->orderByRaw('coupon.discounts DESC, coupon.full_amount DESC')
  239. ->get();
  240. // 分离用户今天用过的优惠券种类
  241. $container = ApplicationContext::getContainer();
  242. $redis = $container->get(Redis::class);
  243. $couponIds = $redis->sMembers('coupon_'.date('Ymd').'_used_'.$userId);
  244. foreach ($data as $key => &$item) {
  245. if (in_array($item->id, $couponIds)) {
  246. $notAvailable[$item->id] = $item;
  247. } else {
  248. $available[] = $item;
  249. }
  250. }
  251. return $this->success([
  252. 'available' => $available,
  253. 'not_available' => array_values($notAvailable)
  254. ]);
  255. }
  256. }