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.

213 lines
8.6 KiB

6 years ago
  1. <?php
  2. namespace App\Service;
  3. use Hyperf\Di\Annotation\Inject;
  4. use Hyperf\DbConnection\Db;
  5. use App\Model\Coupon;
  6. use App\Model\CouponUserRecType;
  7. use App\Model\CouponRec;
  8. use App\Constants\LogLabel;
  9. use App\Commons\Log;
  10. use Hyperf\Utils\ApplicationContext;
  11. use App\TaskWorker\SSDBTask;
  12. use App\Constants\SsdbKeysPrefix;
  13. use Exception;
  14. class CouponRebateService implements CouponRebateServiceInterface
  15. {
  16. /**
  17. * @Inject
  18. * @var Log
  19. */
  20. protected $log;
  21. /**
  22. * 领取优惠券
  23. * 返券活动领取
  24. * 一次可领取多张优惠券
  25. * 一个用户不可重复领取
  26. */
  27. public function userReceiveCoupon($params)
  28. {
  29. $userId = $params["user_id"];
  30. $receiveType = $params["receive_type"];
  31. $ids = $params["ids"];
  32. $sendUserId = $params["send_user_id"];
  33. $phone = $params["phone"];
  34. $now = time();
  35. $ids = is_array($ids) ? implode(',',$ids) : $ids;
  36. // status: 0领取成功 >0领取失败
  37. $result = [
  38. 'status' => 1,
  39. 'coupon_text' => '继续努力~'
  40. ];
  41. // 错误日志记录
  42. $errorData = [
  43. 'coupon_ids' =>$ids,
  44. 'user_id' =>$userId,
  45. 'receiveType' =>$receiveType,
  46. 'sendUserId' =>$sendUserId,
  47. 'phone' =>$phone
  48. ];
  49. $receiveSsdb = [];
  50. try{
  51. Db::transaction( function() use ($ids,$receiveType,$userId,$sendUserId,$phone,$now,&$result,&$errorData,&$receiveSsdb) {
  52. $success = [];
  53. $fail = [];
  54. //读写锁,完全控制,性能低
  55. $coupons = Coupon::whereIn('id', $ids)->lockForUpdate()
  56. ->select('id','title','status','inventory','inventory_use','start_time','end_time','full_amount','discounts','active_type')
  57. ->get();
  58. foreach($coupons as $coupon){
  59. $errorData['coupon_id'] = $coupon->id;
  60. //如果优惠卷库存小于等于已领取的数量 或者 未在活动时间内可领取, 否则返回领取失败的优惠券
  61. if (
  62. $coupon->status == 1
  63. &&
  64. $coupon->inventory > $coupon->inventory_use
  65. &&
  66. $coupon->start_time <= $now
  67. &&
  68. $coupon->end_time >= $now
  69. &&
  70. $coupon->active_type == 2
  71. )
  72. {
  73. // 查询一次能领取的数量
  74. $couponReceiveType = CouponUserRecType::where('system_coupon_user_id',$coupon->id)->select('one_receive_number');
  75. if (env('SUB_CHANNEL') == 1) {
  76. $couponReceiveType->where('receive_type',$receiveType);
  77. }
  78. $couponReceiveType = $couponReceiveType->first();
  79. // 优惠券可领取数量 >= 本次领取数量
  80. if($coupon->inventory - $coupon->inventory_use >= $couponReceiveType->one_receive_number){
  81. // 判断是否领取过 存在记录则领取过
  82. $isReceive = CouponRec::select('id')
  83. ->where('system_coupon_user_id',$ids)
  84. ->where('user_id',$userId)
  85. ->exists();
  86. if(!$isReceive){
  87. //记录已领取的数量
  88. $coupon->inventory_use += $couponReceiveType->number;
  89. $couponReceive = new CouponRec;
  90. $couponReceive->user_id = $userId;
  91. $couponReceive->system_coupon_user_id = $coupon->id;
  92. $couponReceive->order_main_id = 0;
  93. $couponReceive->receive_time = $now;
  94. $couponReceive->number = $couponReceiveType->one_receive_number;
  95. $couponReceive->number_remain = $couponReceiveType->one_receive_number;
  96. $couponReceive->status = 0;
  97. $couponReceive->update_time = $now;
  98. $couponReceive->receive_type = $receiveType;
  99. $couponReceive->send_user_id = $sendUserId;
  100. $couponReceive->phone = $phone;
  101. if ( $couponReceive->save() && $coupon->save() ) {
  102. $success[] = $coupon;
  103. $receiveSsdb[] = $coupon->id;;
  104. }
  105. }else{
  106. $fail[] = $coupon;
  107. $receiveSsdb[] = $coupon->id;
  108. $result['status'] = 2;
  109. $result['coupon_text'] = '您已领取!赶快去下单吧~';
  110. $errorData['msg'] = '用户已经领取了优惠券';
  111. $this->log->event(
  112. LogLabel::COUPON_LOG,
  113. $errorData
  114. );
  115. }
  116. }else{
  117. $fail[] = $coupon;
  118. $errorData['remain_receive_number'] = $coupon->inventory - $coupon->inventory_use;
  119. $errorData['one_receive_number'] = $couponReceiveType->one_receive_number;
  120. $errorData['msg'] = '优惠券剩余数量不足';
  121. $this->log->event(
  122. LogLabel::COUPON_LOG,
  123. $errorData
  124. );
  125. }
  126. }else{
  127. $fail[] = $coupon;
  128. $errorData['msg'] = '优惠券已经过期或者被禁用或者已领完';
  129. $this->log->event(
  130. LogLabel::COUPON_LOG,
  131. $errorData
  132. );
  133. }
  134. }
  135. $result['data'] = [
  136. 'success' => $success,
  137. 'fail' => $fail
  138. ];
  139. if(count($success) > 0){
  140. $result['status'] = 0;
  141. $result['coupon_text'] = '恭喜您领取成功!';
  142. }
  143. });
  144. } catch (Exception $e){
  145. $errorData['msg'] = $e->getMessage();
  146. $this->log->event(
  147. LogLabel::COUPON_LOG,
  148. $errorData
  149. );
  150. }
  151. if(count($receiveSsdb) > 0){
  152. // 记录到ssdb
  153. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  154. if(false === $ssdb->exec('hset',SsdbKeysPrefix::COUPON_REBATE_RECEIVE.$userId,$receiveSsdb)){
  155. $errorData['msg'] = '记录领取优惠券到ssdb失败';
  156. $this->log->event(
  157. LogLabel::COUPON_LOG,
  158. $errorData
  159. );
  160. };
  161. }
  162. return $result;
  163. }
  164. public function isCouponRebate($user_id)
  165. {
  166. $res = Db::table('ims_system_coupon_user as u')
  167. ->leftjoin('ims_system_coupon_user_receive as r','u.id','=','r.system_coupon_user_id')
  168. ->where([
  169. ['r.user_id','=',$user_id],
  170. ['r.receive_type','=',4],
  171. ['u.active_type','=',2],
  172. ])
  173. ->select('r.id')
  174. ->first();
  175. return $res;
  176. }
  177. public function getActiveInfo()
  178. {
  179. $time = time();
  180. $res = Db::table('ims_system_coupon_user')
  181. ->where([
  182. ['status','=',1],
  183. ['active_type','=',2],
  184. ['start_time','<=',$time],
  185. ['end_time','>',$time],
  186. ])
  187. ->whereRaw('inventory > inventory_use')
  188. ->orderBy('addtime','desc')
  189. ->get();
  190. return $res;
  191. }
  192. }