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.

447 lines
18 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
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
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. $idsData = 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. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  50. $receiveSsdb = [];
  51. // 判断是否已全部领取
  52. $couponActivity = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY,0);
  53. $userReceiveCouponIds = $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $couponActivity . $userId);
  54. if($userReceiveCouponIds !== false){
  55. $ids = array_diff($idsData, $userReceiveCouponIds);
  56. $receiveSsdb = $userReceiveCouponIds;
  57. }else{
  58. $ids = $idsData;
  59. }
  60. if(count($ids) > 0){
  61. try{
  62. Db::transaction( function() use ($ids,$receiveType,$userId,$sendUserId,$phone,$now,&$result,&$errorData,&$receiveSsdb) {
  63. $success = [];
  64. $fail = [];
  65. //读写锁,完全控制,性能低
  66. $coupons = Coupon::whereIn('id', $ids)->lockForUpdate()
  67. ->select('id','title','status','inventory','inventory_use','start_time','end_time','full_amount','discounts','active_type')
  68. ->get();
  69. foreach($coupons as $coupon){
  70. $errorData['coupon_id'] = $coupon->id;
  71. //如果优惠卷库存小于等于已领取的数量 或者 未在活动时间内可领取, 否则返回领取失败的优惠券
  72. if (
  73. $coupon->status == 1
  74. &&
  75. $coupon->inventory > $coupon->inventory_use
  76. &&
  77. $coupon->start_time <= $now
  78. &&
  79. $coupon->end_time >= $now
  80. &&
  81. $coupon->active_type == 2
  82. )
  83. {
  84. // 查询一次能领取的数量
  85. $couponReceiveType = CouponUserRecType::where('system_coupon_user_id',$coupon->id)->select('one_receive_number');
  86. if (env('SUB_CHANNEL') == 1) {
  87. $couponReceiveType->where('receive_type',$receiveType);
  88. }
  89. $couponReceiveType = $couponReceiveType->first();
  90. // 优惠券可领取数量 >= 本次领取数量
  91. if($coupon->inventory - $coupon->inventory_use >= $couponReceiveType->one_receive_number){
  92. // 判断是否领取过 存在记录则领取过
  93. $isReceive = CouponRec::select('id')
  94. ->where('system_coupon_user_id',$coupon->id)
  95. ->where('user_id',$userId)
  96. ->exists();
  97. if(!$isReceive){
  98. //记录已领取的数量
  99. $coupon->inventory_use += $couponReceiveType->number;
  100. $couponReceive = new CouponRec;
  101. $couponReceive->user_id = $userId;
  102. $couponReceive->system_coupon_user_id = $coupon->id;
  103. $couponReceive->order_main_id = 0;
  104. $couponReceive->receive_time = $now;
  105. $couponReceive->number = $couponReceiveType->one_receive_number;
  106. $couponReceive->number_remain = $couponReceiveType->one_receive_number;
  107. $couponReceive->status = 0;
  108. $couponReceive->update_time = $now;
  109. $couponReceive->receive_type = $receiveType;
  110. $couponReceive->send_user_id = $sendUserId;
  111. $couponReceive->phone = $phone;
  112. if ( $couponReceive->save() && $coupon->save() ) {
  113. $success[] = $coupon;
  114. $receiveSsdb[] = $coupon->id;
  115. }
  116. }else{
  117. $fail[] = $coupon;
  118. $receiveSsdb[] = $coupon->id;
  119. $result['status'] = 3;
  120. $result['coupon_text'] = '您已领取!赶快去下单吧~';
  121. $errorData['msg'] = '用户已经领取了优惠券';
  122. $this->log->event(
  123. LogLabel::COUPON_LOG,
  124. $errorData
  125. );
  126. }
  127. }else{
  128. $fail[] = $coupon;
  129. $errorData['remain_receive_number'] = $coupon->inventory - $coupon->inventory_use;
  130. $errorData['one_receive_number'] = $couponReceiveType->one_receive_number;
  131. $errorData['msg'] = '优惠券剩余数量不足';
  132. $this->log->event(
  133. LogLabel::COUPON_LOG,
  134. $errorData
  135. );
  136. }
  137. }else{
  138. $fail[] = $coupon;
  139. $errorData['msg'] = '优惠券已经过期或者被禁用或者已领完';
  140. $this->log->event(
  141. LogLabel::COUPON_LOG,
  142. $errorData
  143. );
  144. }
  145. }
  146. $result['data'] = [
  147. 'success' => $success,
  148. 'fail' => $fail
  149. ];
  150. if(count($success) > 0){
  151. $result['status'] = 0;
  152. $result['coupon_text'] = '恭喜您领取成功!';
  153. }
  154. });
  155. } catch (Exception $e){
  156. $errorData['msg'] = $e->getMessage();
  157. $this->log->event(
  158. LogLabel::COUPON_LOG,
  159. $errorData
  160. );
  161. }
  162. if(count($receiveSsdb) > 0){
  163. $saveSsdb = [];
  164. foreach($receiveSsdb as $kssdb => $vssdb){
  165. $saveSsdb[] = $kssdb;
  166. $saveSsdb[] = $vssdb;
  167. }
  168. // 记录到ssdb
  169. if(false === $ssdb->exec('multi_hset',SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $couponActivity . $userId, $saveSsdb)){
  170. $errorData['msg'] = '记录领取优惠券到ssdb失败';
  171. $this->log->event(
  172. LogLabel::COUPON_LOG,
  173. $errorData
  174. );
  175. };
  176. }
  177. }else{
  178. $result['status'] = 2;
  179. $result['coupon_text'] = '您已领取!赶快去下单吧~';
  180. }
  181. return $result;
  182. }
  183. /*
  184. * 判断用户是否已领取过优惠券
  185. * */
  186. public function isCouponRebate($user_id)
  187. {
  188. //获取SSDB上的活动信息
  189. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  190. $active = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY);
  191. $coupon_ids = explode(',',$active['forward']);
  192. $res = Db::table('ims_system_coupon_user as u')
  193. ->leftjoin('ims_system_coupon_user_receive as r', 'u.id', '=', 'r.system_coupon_user_id')
  194. ->whereIn('r.system_coupon_user_id',$coupon_ids)
  195. ->where([
  196. ['r.user_id', '=', $user_id],
  197. ['r.receive_type', '=', 4],
  198. ['u.active_type', '=', 2],
  199. ])
  200. ->select('r.id')
  201. ->first();
  202. return $res;
  203. }
  204. /*
  205. *获取活动信息
  206. */
  207. public function getActiveInfo()
  208. {
  209. //获取SSDB上的活动信息
  210. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  211. $active = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY);
  212. $coupon_ids = explode(',',$active['forward']);
  213. $time = time();
  214. $res = Db::table('ims_system_coupon_user')
  215. ->whereIn('id',$coupon_ids)
  216. ->where([
  217. ['status', '=', 1],
  218. ['active_type', '=', 2],
  219. ['start_time', '<=', $time],
  220. ['end_time', '>', $time],
  221. ])
  222. ->whereRaw('inventory > inventory_use')
  223. ->orderBy('weigh', 'desc')
  224. ->orderBy('addtime', 'desc')
  225. ->get();
  226. return $res;
  227. }
  228. /**
  229. * 将优惠券绑定活动
  230. * 领取优惠券 COUPON_REBATE_FORWARD 可多张
  231. * 返还优惠券 COUPON_REBATE_REPAY 只一张
  232. */
  233. public function tieCouponActive($couponActivity, $couponForward, $couponRepay)
  234. {
  235. $result = [
  236. 'forward' => true,
  237. 'repay' => true,
  238. 'activity' => true,
  239. ];
  240. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  241. // $rrss1 = $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_FORWARD . $couponActivity);
  242. // $rrss2 = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_REPAY . $couponActivity,0);
  243. // $rrss3 = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY,0);
  244. // return [$rrss1,$rrss2,$rrss3];
  245. // 记录活动本次 activity_type 活动标志值
  246. if (false === $ssdb->exec('hset', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY, [0,$couponActivity])) {
  247. $this->log->event(
  248. LogLabel::COUPON_LOG,
  249. [
  250. 'coupon_activity' => $couponActivity,
  251. 'msg' => '记录活动标志值(activity_type)到ssdb失败'
  252. ]
  253. );
  254. $result['activity'] = false;
  255. };
  256. // 记录领取类型优惠券
  257. $forwardData = [];
  258. foreach ($couponForward as $kForward => $vForward) {
  259. $forwardData[] = $kForward;
  260. $forwardData[] = $vForward;
  261. }
  262. if (false === $ssdb->exec('multi_hset', SsdbKeysPrefix::COUPON_REBATE_FORWARD . $couponActivity, $forwardData)) {
  263. $this->log->event(
  264. LogLabel::COUPON_LOG,
  265. [
  266. 'coupon_activity' => $couponActivity,
  267. 'coupon_forward' => $forwardData,
  268. 'msg' => '绑定-领取-优惠券到ssdb失败'
  269. ]
  270. );
  271. $result['forward'] = false;
  272. };
  273. // 记录返还类型优惠券
  274. if (false === $ssdb->exec('hset', SsdbKeysPrefix::COUPON_REBATE_REPAY . $couponActivity, [0,$couponRepay])) {
  275. $this->log->event(
  276. LogLabel::COUPON_LOG,
  277. [
  278. 'coupon_activity' => $couponActivity,
  279. 'coupon_Repay' => $couponRepay,
  280. 'msg' => '绑定-返还-优惠券到ssdb失败'
  281. ]
  282. );
  283. $result['repay'] = false;
  284. };
  285. return $result;
  286. }
  287. /*
  288. * 支付成功 返券
  289. */
  290. public function couponRebate($order_id)
  291. {
  292. //获取SSDB上的活动信息
  293. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  294. $active = $ssdb->execWithoutTask('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY);
  295. //判断返券优惠券是否有库存
  296. $inventory = Db::table('ims_system_coupon_user')
  297. ->where('id',$active['repay'])
  298. ->whereRaw('inventory > inventory_use')
  299. ->exists();
  300. if(!$inventory){
  301. return '库存不足';
  302. }
  303. //获取活动发放优惠券id
  304. $coupon_ids = explode(',',$active['forward']);
  305. /* 判断被使用的优惠券类型是否为转发活动优惠券 */
  306. $coupon = Db::table('ims_system_coupon_user_receive as r')
  307. ->leftjoin('ims_system_coupon_user_use as u', 'u.user_receive_id', '=', 'r.id')
  308. ->where([
  309. ['u.order_main_id', '=', $order_id],
  310. ['r.send_user_id', '>', 0],
  311. ['r.rebate_type', '=', 1],
  312. ['r.receive_type', '=', 4],
  313. ])
  314. ->whereIn('r.system_coupon_user_id',$coupon_ids)
  315. ->select('r.user_id', 'r.send_user_id')
  316. ->first();
  317. /* 如果使用的优惠券为转发活动优惠券 则给赠送者返一张优惠券*/
  318. if (isset($coupon->send_user_id) && ($coupon->send_user_id) > 0) {
  319. //是否已返过券
  320. $exists_coupon_rebate = Db::table('ims_system_coupon_user_receive')
  321. ->where([
  322. ['system_coupon_user_id' ,'=', $active['repay']],
  323. ['user_id' ,'=', $coupon->send_user_id],
  324. ['receive_type' ,'=', 5],
  325. ])
  326. ->select('id','status')
  327. ->first();
  328. //开启事务
  329. Db::beginTransaction();
  330. try {
  331. //返券
  332. if($exists_coupon_rebate->id){
  333. //如果已有该优惠券 则领取数量 和 可用数量 自增1
  334. Db::table('ims_system_coupon_user_receive')
  335. ->where([
  336. ['id' ,'=', $exists_coupon_rebate->id],
  337. ])
  338. ->increment('number');
  339. Db::table('ims_system_coupon_user_receive')
  340. ->where([
  341. ['id' ,'=', $exists_coupon_rebate->id],
  342. ])
  343. ->increment('number_remain');
  344. //如果该用户在领取表中 status为已用完状态 2 则改为已用部分 1
  345. if($exists_coupon_rebate->status == 2){
  346. Db::table('ims_system_coupon_user_receive')
  347. ->where([
  348. ['id' ,'=', $exists_coupon_rebate->id],
  349. ])
  350. ->update(['status' => 1]);;
  351. }
  352. }else {
  353. //否则新增一条返券记录
  354. $nowTime = time();
  355. Db::table('ims_system_coupon_user_receive')->insert([
  356. [
  357. 'user_id' => $coupon->send_user_id,
  358. 'system_coupon_user_id' => $active['repay'],
  359. 'receive_type' => 5,
  360. 'status' => 0,
  361. 'number' => 1,
  362. 'number_remain' => 1,
  363. 'order_main_id' => $order_id,
  364. 'receive_time' => $nowTime,
  365. 'update_time' => $nowTime,
  366. 'created_at' => $nowTime,
  367. 'updated_at' => $nowTime,
  368. ]
  369. ]);
  370. }
  371. //首次返券更新rebate_type字段 防止重复返券
  372. Db::table('ims_system_coupon_user_receive')
  373. ->where([
  374. ['user_id','=',$coupon->user_id],
  375. ['receive_type','=',4],
  376. ])
  377. ->whereIn('system_coupon_user_id',$coupon_ids)
  378. ->update(['rebate_type' => 2]);
  379. //更新库存操作
  380. Db::table('ims_system_coupon_user')
  381. ->where('id', $active['repay']['repay'])
  382. ->increment('inventory_use');
  383. // 提交
  384. Db::commit();
  385. } catch (\Exception $e) {
  386. // 回滚
  387. Db::rollBack();
  388. $log_Data = array();
  389. $log_Data['name'] = '返券';
  390. $log_Data['order_main_id'] = $order_id;
  391. $log_Data['msg'] = '返券失败';
  392. $this->log->event(
  393. LogLabel::COUPON_LOG,
  394. $log_Data
  395. );
  396. }
  397. }
  398. $log_Data = array();
  399. $log_Data['name'] = '返券';
  400. $log_Data['user_id'] = $order_id;
  401. $log_Data['send_user_id'] = $coupon->send_user_id;
  402. $log_Data['order_main_id'] = $order_id;
  403. $log_Data['msg'] = '返券成功';
  404. $this->log->event(
  405. LogLabel::COUPON_LOG,
  406. $log_Data
  407. );
  408. return '返券成功';
  409. }
  410. }