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.

219 lines
8.8 KiB

5 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) ? $ids : explode(',',$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. $isr = [];
  55. //读写锁,完全控制,性能低
  56. $coupons = Coupon::whereIn('id', $ids)->lockForUpdate()
  57. ->select('id','title','status','inventory','inventory_use','start_time','end_time','full_amount','discounts','active_type')
  58. ->get();
  59. foreach($coupons as $coupon){
  60. $errorData['coupon_id'] = $coupon->id;
  61. //如果优惠卷库存小于等于已领取的数量 或者 未在活动时间内可领取, 否则返回领取失败的优惠券
  62. if (
  63. $coupon->status == 1
  64. &&
  65. $coupon->inventory > $coupon->inventory_use
  66. &&
  67. $coupon->start_time <= $now
  68. &&
  69. $coupon->end_time >= $now
  70. &&
  71. $coupon->active_type == 2
  72. )
  73. {
  74. // 查询一次能领取的数量
  75. $couponReceiveType = CouponUserRecType::where('system_coupon_user_id',$coupon->id)->select('one_receive_number');
  76. if (env('SUB_CHANNEL') == 1) {
  77. $couponReceiveType->where('receive_type',$receiveType);
  78. }
  79. $couponReceiveType = $couponReceiveType->first();
  80. // 优惠券可领取数量 >= 本次领取数量
  81. if($coupon->inventory - $coupon->inventory_use >= $couponReceiveType->one_receive_number){
  82. // 判断是否领取过 存在记录则领取过
  83. $isReceive = CouponRec::select('id')
  84. ->where('system_coupon_user_id',$coupon->id)
  85. ->where('user_id',$userId)
  86. ->exists();
  87. if(!$isReceive){
  88. //记录已领取的数量
  89. $coupon->inventory_use += $couponReceiveType->number;
  90. $couponReceive = new CouponRec;
  91. $couponReceive->user_id = $userId;
  92. $couponReceive->system_coupon_user_id = $coupon->id;
  93. $couponReceive->order_main_id = 0;
  94. $couponReceive->receive_time = $now;
  95. $couponReceive->number = $couponReceiveType->one_receive_number;
  96. $couponReceive->number_remain = $couponReceiveType->one_receive_number;
  97. $couponReceive->status = 0;
  98. $couponReceive->update_time = $now;
  99. $couponReceive->receive_type = $receiveType;
  100. $couponReceive->send_user_id = $sendUserId;
  101. $couponReceive->phone = $phone;
  102. // if ( $couponReceive->save() && $coupon->save() ) {
  103. // $success[] = $coupon;
  104. // $receiveSsdb[] = $coupon->id;;
  105. // }
  106. }else{
  107. $fail[] = $coupon;
  108. $receiveSsdb[] = $coupon->id;
  109. $result['status'] = 2;
  110. $result['coupon_text'] = '您已领取!赶快去下单吧~';
  111. $errorData['msg'] = '用户已经领取了优惠券';
  112. $this->log->event(
  113. LogLabel::COUPON_LOG,
  114. $errorData
  115. );
  116. }
  117. }else{
  118. $fail[] = $coupon;
  119. $errorData['remain_receive_number'] = $coupon->inventory - $coupon->inventory_use;
  120. $errorData['one_receive_number'] = $couponReceiveType->one_receive_number;
  121. $errorData['msg'] = '优惠券剩余数量不足';
  122. $this->log->event(
  123. LogLabel::COUPON_LOG,
  124. $errorData
  125. );
  126. }
  127. }else{
  128. $fail[] = $coupon;
  129. $errorData['msg'] = '优惠券已经过期或者被禁用或者已领完';
  130. $this->log->event(
  131. LogLabel::COUPON_LOG,
  132. $errorData
  133. );
  134. }
  135. }
  136. $result['data'] = [
  137. 'success' => $success,
  138. 'fail' => $fail
  139. ];
  140. if(count($success) > 0){
  141. $result['status'] = 0;
  142. $result['coupon_text'] = '恭喜您领取成功!';
  143. }
  144. });
  145. } catch (Exception $e){
  146. $errorData['msg'] = $e->getMessage();
  147. $this->log->event(
  148. LogLabel::COUPON_LOG,
  149. $errorData
  150. );
  151. }
  152. if(count($receiveSsdb) > 0){
  153. $saveSsdb = [];
  154. foreach($receiveSsdb as $kssdb => $vssdb){
  155. $saveSsdb[] = $kssdb;
  156. $saveSsdb[] = $vssdb;
  157. }
  158. // 记录到ssdb
  159. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  160. if(false === $ssdb->exec('hset',SsdbKeysPrefix::COUPON_REBATE_RECEIVE.$userId,$saveSsdb)){
  161. $errorData['msg'] = '记录领取优惠券到ssdb失败';
  162. $this->log->event(
  163. LogLabel::COUPON_LOG,
  164. $errorData
  165. );
  166. };
  167. }
  168. return $result;
  169. }
  170. public function isCouponRebate($user_id)
  171. {
  172. $res = Db::table('ims_system_coupon_user as u')
  173. ->leftjoin('ims_system_coupon_user_receive as r','u.id','=','r.system_coupon_user_id')
  174. ->where([
  175. ['r.user_id','=',$user_id],
  176. ['r.receive_type','=',4],
  177. ['u.active_type','=',2],
  178. ])
  179. ->select('r.id')
  180. ->first();
  181. return $res;
  182. }
  183. public function getActiveInfo()
  184. {
  185. $time = time();
  186. $res = Db::table('ims_system_coupon_user')
  187. ->where([
  188. ['status','=',1],
  189. ['active_type','=',2],
  190. ['start_time','<=',$time],
  191. ['end_time','>',$time],
  192. ])
  193. ->whereRaw('inventory > inventory_use')
  194. ->orderBy('addtime','desc')
  195. ->get();
  196. return $res;
  197. }
  198. }