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.

346 lines
14 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
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) ? $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. if(count($receiveSsdb) > 0){
  146. $saveSsdb = [];
  147. foreach($receiveSsdb as $kssdb => $vssdb){
  148. $saveSsdb[] = $kssdb;
  149. $saveSsdb[] = $vssdb;
  150. }
  151. // 记录到ssdb
  152. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  153. if(false === $ssdb->exec('multi_hset',SsdbKeysPrefix::COUPON_REBATE_RECEIVE.$userId,$saveSsdb)){
  154. $errorData['msg'] = '记录领取优惠券到ssdb失败';
  155. $this->log->event(
  156. LogLabel::COUPON_LOG,
  157. $errorData
  158. );
  159. };
  160. }
  161. return $result;
  162. }
  163. /*
  164. * 判断用户是否已领取过优惠券
  165. * */
  166. public function isCouponRebate($user_id)
  167. {
  168. $res = Db::table('ims_system_coupon_user as u')
  169. ->leftjoin('ims_system_coupon_user_receive as r','u.id','=','r.system_coupon_user_id')
  170. ->where([
  171. ['r.user_id' ,'=', $user_id],
  172. ['r.receive_type','=', 4],
  173. ['u.active_type' ,'=', 2],
  174. ])
  175. ->select('r.id')
  176. ->first();
  177. return $res;
  178. }
  179. /*
  180. *获取活动信息
  181. */
  182. public function getActiveInfo()
  183. {
  184. $time = time();
  185. $res = Db::table('ims_system_coupon_user')
  186. ->where([
  187. ['status' ,'=', 1],
  188. ['active_type' ,'=', 2],
  189. ['start_time' ,'<=', $time],
  190. ['end_time' ,'>', $time],
  191. ])
  192. ->whereRaw('inventory > inventory_use')
  193. ->orderBy('addtime','desc')
  194. ->get();
  195. return $res;
  196. }
  197. /**
  198. * 将优惠券绑定活动
  199. * 领取优惠券 COUPON_REBATE_FORWARD 可多张
  200. * 返还优惠券 COUPON_REBATE_REPAY 只一张
  201. */
  202. public function tieCouponActive($couponActivity,$couponForward,$couponRepay)
  203. {
  204. $result = [
  205. 'forward' => true,
  206. 'repay' => true,
  207. ];
  208. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  209. $rrss1 = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_FORWARD.$couponActivity);
  210. $rrss2 = $ssdb->exec('get',SsdbKeysPrefix::COUPON_REBATE_REPAY.$couponActivity);
  211. return [$rrss1,$rrss2];
  212. // 记录领取类型优惠券
  213. $forwardData = [];
  214. foreach($couponForward as $kForward => $vForward){
  215. $forwardData[] = $kForward;
  216. $forwardData[] = $vForward;
  217. }
  218. if(false === $ssdb->exec('multi_hset',SsdbKeysPrefix::COUPON_REBATE_FORWARD.$couponActivity,$forwardData)){
  219. $this->log->event(
  220. LogLabel::COUPON_LOG,
  221. [
  222. 'coupon_activity' => $couponActivity,
  223. 'coupon_forward' => $forwardData,
  224. 'msg' => '绑定-领取-优惠券到ssdb失败'
  225. ]
  226. );
  227. $result['forward'] = false;
  228. };
  229. // 记录返还类型优惠券
  230. if(false === $ssdb->exec('set',SsdbKeysPrefix::COUPON_REBATE_REPAY.$couponActivity,$couponRepay)){
  231. $this->log->event(
  232. LogLabel::COUPON_LOG,
  233. [
  234. 'coupon_activity' => $couponActivity,
  235. 'coupon_Repay' => $couponRepay,
  236. 'msg' => '绑定-返还-优惠券到ssdb失败'
  237. ]
  238. );
  239. $result['repay'] = false;
  240. };
  241. return $result;
  242. }
  243. /*
  244. * 支付成功 返券
  245. */
  246. public function couponRebate($order_id)
  247. {
  248. /* 判断优惠券类型是否为转发活动优惠券 */
  249. $coupon = Db::table('ims_system_coupon_user_receive as r')
  250. ->leftjoin('ims_system_coupon_user_use as u', 'u.user_receive_id', '=', 'r.id')
  251. ->where([
  252. ['u.order_main_id', '=', $order_id],
  253. ['r.send_user_id', '>', 0],
  254. ['r.rebate_type', '=', 1],
  255. ['r.receive_type', '=', 4],
  256. ['u.status', '=', 1],
  257. ])
  258. ->select('r.id', 'r.send_user_id', 'u.system_coupon_id')
  259. ->first();
  260. /* 如果使用的优惠券为转发活动优惠券 则给赠送者返一张优惠券*/
  261. if (isset($coupon->send_user_id) && ($coupon->send_user_id) > 0) {
  262. //判断该优惠券是否有库存
  263. // $inventory = Db::table('system_coupon_user_receive as r');
  264. // if($inventory['inventory'] <= 0){
  265. // return '库存不足';
  266. // }
  267. //return $exist_coupon;
  268. //开启事务
  269. try {
  270. /*
  271. * 如果已有该优惠券 则领取数量 可用数量 自增1
  272. * 否则新增一条返券记录
  273. */
  274. $nowTime = time();
  275. $res = Db::table('ims_system_coupon_user_receive')->moreIncrementOrInsert(
  276. [
  277. 'system_coupon_user_id' => $coupon->system_coupon_id,
  278. 'user_id' => $coupon->send_user_id,
  279. 'receive_type' => 5,
  280. 'status' => 0,
  281. ],
  282. [
  283. 'order_main_id' => $order_id,
  284. 'receive_time' => $nowTime,
  285. 'update_time' => $nowTime,
  286. 'created_at' => $nowTime,
  287. 'updated_at' => $nowTime,
  288. ],
  289. [
  290. 'number' => 1,
  291. 'number_remain' => 1,
  292. ]
  293. );
  294. // if ($res) {
  295. // //首次返券更新rebate_type字段 防止重复返券
  296. // Db::table('system_coupon_user_receive')->where('id', $coupon->id)->update(['rebate_type' => 2]);
  297. // //更新库存操作
  298. // Db::table('system_coupon_user')
  299. // ->where('id', $coupon->id)
  300. // ->increment('inventory_use');
  301. // } else {
  302. // Db::rollBack();
  303. // return '事务失败';
  304. // }
  305. // 提交
  306. Db::commit();
  307. } catch (\Exception $e) {
  308. // 回滚
  309. Db::rollBack();
  310. return '返券失败';
  311. }
  312. } else {
  313. // $str1 = 'order_main_id:'.$this->order_id . ',未查询到用户领取优惠券信息['.$coupon.']';
  314. // $this->couponErrorLog($str1);
  315. }
  316. return '返券成功';
  317. }}