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.

530 lines
21 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. use App\Service\CommonService;
  15. use function AlibabaCloud\Client\json;
  16. class CouponRebateService implements CouponRebateServiceInterface
  17. {
  18. /**
  19. * @Inject
  20. * @var Log
  21. */
  22. protected $log;
  23. /**
  24. * @Inject
  25. * @var CommonService
  26. */
  27. protected $commonService;
  28. /**
  29. * 领取优惠券
  30. * 返券活动领取
  31. * 一次可领取多张优惠券
  32. * 一个用户不可重复领取
  33. */
  34. public function userReceiveCoupon($params)
  35. {
  36. $userId = $params["user_id"];
  37. $receiveType = $params["receive_type"];
  38. $sendUserId = $params["send_user_id"];
  39. $phone = $params["phone"];
  40. // status: 0领取成功 >0领取失败
  41. $result = [
  42. 'status' => 1,
  43. 'coupon_text' => '活动已过期~'
  44. ];
  45. /* 如果请求的优惠券ids为空,则返回过期提示 */
  46. if($this->commonService->empty($params["ids"])){
  47. return $result;
  48. }
  49. $ids = $params["ids"];
  50. $idsData = is_array($ids) ? $ids : explode(',',$ids);
  51. // 错误日志记录
  52. $errorData = [
  53. 'coupon_ids' =>$ids,
  54. 'user_id' =>$userId,
  55. 'receiveType' =>$receiveType,
  56. 'sendUserId' =>$sendUserId,
  57. 'phone' =>$phone
  58. ];
  59. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  60. $activity = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY ,'activity');
  61. // ssdb 键值
  62. $ssdbKey = 'activity_'.$activity.'_user_'.$userId;
  63. $receiveSsdb = [];
  64. // 判断是否已全部领取过
  65. $userReceive = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_RECEIVE,$ssdbKey);
  66. if($userReceive === false){
  67. $ids = $idsData;
  68. }else{
  69. $userReceiveCouponIds = empty($userReceive) ? [] : explode(',',$userReceive) ;
  70. $ids = array_diff($idsData, $userReceiveCouponIds);
  71. $receiveSsdb = $userReceiveCouponIds;
  72. }
  73. if(count($ids) > 0){
  74. try{
  75. Db::transaction( function() use ($ids,$receiveType,$userId,$sendUserId,$phone,&$result,&$errorData,&$receiveSsdb) {
  76. $now = time();
  77. $success = [];
  78. //获取优惠券信息 (读写锁,完全控制,性能低)
  79. $coupons = Coupon::whereIn('id', $ids)->lockForUpdate()
  80. ->where('active_type',2)
  81. ->where('status',1)
  82. ->where('start_time', '<=', $now)
  83. ->where('end_time', '>=', $now)
  84. ->whereRaw('inventory > inventory_use')
  85. ->select('id','title','inventory','inventory_use','full_amount','discounts','active_type')
  86. ->get();
  87. foreach($coupons as $coupon){
  88. $errorData['coupon_id'] = $coupon->id;
  89. // 查询一次能领取的数量
  90. $couponReceiveType = CouponUserRecType::where('system_coupon_user_id',$coupon->id)->select('one_receive_number');
  91. if (env('SUB_CHANNEL') == 1) {
  92. $couponReceiveType->where('receive_type',$receiveType);
  93. }
  94. $couponReceiveType = $couponReceiveType->first();
  95. // 优惠券可领取数量 >= 本次领取数量
  96. if($coupon->inventory - $coupon->inventory_use >= $couponReceiveType->one_receive_number){
  97. // 判断是否领取过 存在记录则领取过
  98. $isReceive = CouponRec::select('id')
  99. ->where('system_coupon_user_id',$coupon->id)
  100. ->where('user_id',$userId)
  101. ->exists();
  102. if(!$isReceive){
  103. //记录已领取的数量
  104. $coupon->inventory_use += $couponReceiveType->one_receive_number;
  105. $couponReceive = new CouponRec;
  106. $couponReceive->user_id = $userId;
  107. $couponReceive->system_coupon_user_id = $coupon->id;
  108. $couponReceive->order_main_id = 0;
  109. $couponReceive->receive_time = $now;
  110. $couponReceive->number = $couponReceiveType->one_receive_number;
  111. $couponReceive->number_remain = $couponReceiveType->one_receive_number;
  112. $couponReceive->status = 0;
  113. $couponReceive->update_time = $now;
  114. $couponReceive->receive_type = $receiveType;
  115. $couponReceive->send_user_id = $sendUserId;
  116. $couponReceive->phone = $phone;
  117. if ( $couponReceive->save() && $coupon->save() ) {
  118. $success[] = $coupon;
  119. $receiveSsdb[] = $coupon->id;
  120. }else{
  121. $errorData['msg'] = '添加优惠券到用户领取表或者记录已领取数量失败';
  122. $this->log->event(
  123. LogLabel::COUPON_LOG,
  124. $errorData
  125. );
  126. }
  127. }
  128. }
  129. }
  130. if(count($success) > 0){
  131. $result['status'] = 0;
  132. $result['coupon_text'] = '恭喜您领取成功!';
  133. }
  134. });
  135. } catch (Exception $e){
  136. $errorData['msg'] = $e->getMessage();
  137. $this->log->event(
  138. LogLabel::COUPON_LOG,
  139. $errorData
  140. );
  141. }
  142. if(count($receiveSsdb) > 0){
  143. $saveSsdb = [
  144. $ssdbKey,
  145. implode(',',$receiveSsdb)
  146. ];
  147. if(false === $ssdb->exec('hset',SsdbKeysPrefix::COUPON_REBATE_RECEIVE, $saveSsdb)){
  148. $errorData['msg'] = '记录领取优惠券到ssdb失败';
  149. $this->log->event(
  150. LogLabel::COUPON_LOG,
  151. $errorData
  152. );
  153. };
  154. }
  155. }else{
  156. $result['status'] = 2;
  157. $result['coupon_text'] = '您已领取!赶快去下单吧~';
  158. }
  159. return $result;
  160. }
  161. /*
  162. * 判断用户是否已领取过优惠券
  163. * */
  164. public function isCouponRebate($user_id)
  165. {
  166. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  167. $activity = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY ,'activity');
  168. // ssdb 键值
  169. $ssdbKey = 'activity_'.$activity.'_user_'.$user_id;
  170. // 判断是否已全部领取过
  171. $userReceive = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_RECEIVE,$ssdbKey);
  172. if($userReceive === false || is_null($userReceive)){
  173. return false;
  174. }else{
  175. return $userReceive;
  176. }
  177. }
  178. /*
  179. *获取活动信息
  180. */
  181. public function getActiveInfo()
  182. {
  183. //获取SSDB上的活动信息
  184. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  185. $active = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY);
  186. $coupon_ids = explode(',',$active['forward']);
  187. $time = time();
  188. $res = Db::table('ims_system_coupon_user')
  189. ->whereIn('id',$coupon_ids)
  190. ->where([
  191. ['status', '=', 1],
  192. ['active_type', '=', 2],
  193. ['start_time', '<=', $time],
  194. ['end_time', '>', $time],
  195. ])
  196. ->whereRaw('inventory > inventory_use')
  197. ->orderBy('weigh', 'desc')
  198. ->orderBy('addtime', 'desc')
  199. ->get();
  200. return $res;
  201. }
  202. /**
  203. * 将优惠券绑定活动
  204. * 领取优惠券 COUPON_REBATE_FORWARD 可多张
  205. * 返还优惠券 COUPON_REBATE_REPAY 只一张
  206. */
  207. public function tieCouponActive($couponActivity, $couponForward, $couponRepay)
  208. {
  209. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  210. $data = [
  211. 'activity', $couponActivity,
  212. 'forward' , $couponForward,
  213. 'repay' , $couponRepay
  214. ];
  215. $result = [
  216. 'result' => ($ssdb->exec('multi_hset', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY, $data) === false) ? false : true ,
  217. 'data' => $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY)
  218. ];
  219. return $result;
  220. }
  221. /*
  222. * 支付成功 返券
  223. */
  224. public function couponRebate($order_id)
  225. {
  226. //获取SSDB上的活动信息
  227. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  228. $active = $ssdb->execWithoutTask('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY);
  229. //判断返券优惠券是否有库存
  230. $inventory = Db::table('ims_system_coupon_user')
  231. ->where('id',$active['repay'])
  232. ->whereRaw('inventory > inventory_use')
  233. ->exists();
  234. if(!$inventory){
  235. //库存不足
  236. return false;
  237. }
  238. //获取活动发放优惠券id
  239. $coupon_ids = explode(',',$active['forward']);
  240. /* 判断被使用的优惠券类型是否为转发活动优惠券 */
  241. $coupon = Db::table('ims_system_coupon_user_receive as r')
  242. ->leftjoin('ims_system_coupon_user_use as u', 'u.user_receive_id', '=', 'r.id')
  243. ->where([
  244. ['u.order_main_id', '=', $order_id],
  245. ['r.send_user_id', '>', 0],
  246. ['r.rebate_type', '=', 1],
  247. ['r.receive_type', '=', 4],
  248. ])
  249. ->whereIn('r.system_coupon_user_id',$coupon_ids)
  250. ->select('r.user_id', 'r.send_user_id')
  251. ->first();
  252. /* 如果使用的优惠券为转发活动优惠券
  253. **则给赠送者返一张优惠券
  254. * **自己给自己转发的券不给返券
  255. */
  256. if ($coupon && ($coupon->user_id != $coupon->send_user_id)) {
  257. //是否已返过券
  258. $exists_coupon_rebate = Db::table('ims_system_coupon_user_receive')
  259. ->where([
  260. ['system_coupon_user_id' ,'=', $active['repay']],
  261. ['user_id' ,'=', $coupon->send_user_id],
  262. ['receive_type' ,'=', 5],
  263. ])
  264. ->select('id','status')
  265. ->first();
  266. //开启事务
  267. Db::beginTransaction();
  268. try {
  269. //返券
  270. if($exists_coupon_rebate){
  271. //如果已有该优惠券 则领取数量 和 可用数量 自增1
  272. Db::table('ims_system_coupon_user_receive')
  273. ->where([
  274. ['id' ,'=', $exists_coupon_rebate->id],
  275. ])
  276. ->increment('number');
  277. Db::table('ims_system_coupon_user_receive')
  278. ->where([
  279. ['id' ,'=', $exists_coupon_rebate->id],
  280. ])
  281. ->increment('number_remain');
  282. //如果该用户在领取表中 status为已用完状态 2 则改为已用部分 1
  283. if($exists_coupon_rebate->status == 2){
  284. Db::table('ims_system_coupon_user_receive')
  285. ->where([
  286. ['id' ,'=', $exists_coupon_rebate->id],
  287. ])
  288. ->update(['status' => 1]);;
  289. }
  290. }else {
  291. //否则新增一条返券记录
  292. $nowTime = time();
  293. Db::table('ims_system_coupon_user_receive')->insert([
  294. [
  295. 'user_id' => $coupon->send_user_id,
  296. 'system_coupon_user_id' => $active['repay'],
  297. 'receive_type' => 5,
  298. 'status' => 0,
  299. 'number' => 1,
  300. 'number_remain' => 1,
  301. 'order_main_id' => $order_id,
  302. 'receive_time' => $nowTime,
  303. 'update_time' => $nowTime,
  304. 'created_at' => $nowTime,
  305. 'updated_at' => $nowTime,
  306. ]
  307. ]);
  308. }
  309. //首次返券更新rebate_type字段 防止重复返券
  310. Db::table('ims_system_coupon_user_receive')
  311. ->where([
  312. ['user_id','=',$coupon->user_id],
  313. ['receive_type','=',4],
  314. ])
  315. ->whereIn('system_coupon_user_id',$coupon_ids)
  316. ->update(['rebate_type' => 2]);
  317. //更新库存操作
  318. Db::table('ims_system_coupon_user')
  319. ->where('id', $active['repay'])
  320. ->increment('inventory_use');
  321. //添加领取记录到ssdb
  322. $data = [
  323. $order_id,$coupon->user_id,
  324. ];
  325. $ssdb->execWithoutTask('multi_hset', SsdbKeysPrefix::COUPON_REBATE_LIST.$coupon->send_user_id, $data);
  326. // 提交
  327. Db::commit();
  328. } catch (\Exception $e) {
  329. //写入日志文件
  330. $log_Data = array();
  331. $log_Data['name'] = '返券';
  332. $log_Data['order_id'] = $order_id;
  333. $log_Data['msg'] = '返券失败';
  334. $this->log->event(
  335. LogLabel::COUPON_LOG,
  336. $log_Data
  337. );
  338. // 回滚
  339. Db::rollBack();
  340. }
  341. }
  342. return true;
  343. }
  344. /*
  345. * 支付成功 返券
  346. */
  347. public function couponRebateInTask($order_id)
  348. {
  349. //获取SSDB上的活动信息
  350. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  351. $active = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY);
  352. //判断返券优惠券是否有库存
  353. $inventory = Db::table('ims_system_coupon_user')
  354. ->where('id',$active['repay'])
  355. ->whereRaw('inventory > inventory_use')
  356. ->exists();
  357. if(!$inventory){
  358. //库存不足
  359. return false;
  360. }
  361. //获取活动发放优惠券id
  362. $coupon_ids = explode(',',$active['forward']);
  363. /* 判断被使用的优惠券类型是否为转发活动优惠券 */
  364. $coupon = Db::table('ims_system_coupon_user_receive as r')
  365. ->leftjoin('ims_system_coupon_user_use as u', 'u.user_receive_id', '=', 'r.id')
  366. ->where([
  367. ['u.order_main_id', '=', $order_id],
  368. ['r.send_user_id', '>', 0],
  369. ['r.rebate_type', '=', 1],
  370. ['r.receive_type', '=', 4],
  371. ])
  372. ->whereIn('r.system_coupon_user_id',$coupon_ids)
  373. ->select('r.user_id', 'r.send_user_id')
  374. ->first();
  375. /* 如果使用的优惠券为转发活动优惠券
  376. **则给赠送者返一张优惠券
  377. * **自己给自己转发的券不给返券
  378. */
  379. if ($coupon && ($coupon->user_id != $coupon->send_user_id)) {
  380. //是否已返过券
  381. $exists_coupon_rebate = Db::table('ims_system_coupon_user_receive')
  382. ->where([
  383. ['system_coupon_user_id' ,'=', $active['repay']],
  384. ['user_id' ,'=', $coupon->send_user_id],
  385. ['receive_type' ,'=', 5],
  386. ])
  387. ->select('id','status')
  388. ->first();
  389. //开启事务
  390. Db::beginTransaction();
  391. try {
  392. //返券
  393. if($exists_coupon_rebate){
  394. //如果已有该优惠券 则领取数量 和 可用数量 自增1
  395. Db::table('ims_system_coupon_user_receive')
  396. ->where([
  397. ['id' ,'=', $exists_coupon_rebate->id],
  398. ])
  399. ->increment('number');
  400. Db::table('ims_system_coupon_user_receive')
  401. ->where([
  402. ['id' ,'=', $exists_coupon_rebate->id],
  403. ])
  404. ->increment('number_remain');
  405. //如果该用户在领取表中 status为已用完状态 2 则改为已用部分 1
  406. if($exists_coupon_rebate->status == 2){
  407. Db::table('ims_system_coupon_user_receive')
  408. ->where([
  409. ['id' ,'=', $exists_coupon_rebate->id],
  410. ])
  411. ->update(['status' => 1]);;
  412. }
  413. }else {
  414. //否则新增一条返券记录
  415. $nowTime = time();
  416. Db::table('ims_system_coupon_user_receive')->insert([
  417. [
  418. 'user_id' => $coupon->send_user_id,
  419. 'system_coupon_user_id' => $active['repay'],
  420. 'receive_type' => 5,
  421. 'status' => 0,
  422. 'number' => 1,
  423. 'number_remain' => 1,
  424. 'order_main_id' => $order_id,
  425. 'receive_time' => $nowTime,
  426. 'update_time' => $nowTime,
  427. 'created_at' => $nowTime,
  428. 'updated_at' => $nowTime,
  429. ]
  430. ]);
  431. }
  432. //首次返券更新rebate_type字段 防止重复返券
  433. Db::table('ims_system_coupon_user_receive')
  434. ->where([
  435. ['user_id','=',$coupon->user_id],
  436. ['receive_type','=',4],
  437. ])
  438. ->whereIn('system_coupon_user_id',$coupon_ids)
  439. ->update(['rebate_type' => 2]);
  440. //更新库存操作
  441. Db::table('ims_system_coupon_user')
  442. ->where('id', $active['repay'])
  443. ->increment('inventory_use');
  444. //添加领取记录到ssdb
  445. $data = [
  446. $order_id,$coupon->user_id,
  447. ];
  448. $ssdb->exec('multi_hset', SsdbKeysPrefix::COUPON_REBATE_LIST.$coupon->send_user_id, $data);
  449. // 提交
  450. Db::commit();
  451. } catch (\Exception $e) {
  452. //写入日志文件
  453. $log_Data = array();
  454. $log_Data['name'] = '返券';
  455. $log_Data['order_id'] = $order_id;
  456. $log_Data['msg'] = '返券失败';
  457. $this->log->event(
  458. LogLabel::COUPON_LOG,
  459. $log_Data
  460. );
  461. // 回滚
  462. Db::rollBack();
  463. }
  464. }
  465. return true;
  466. }
  467. /**
  468. * 清优惠券领取记录(SSDB)
  469. */
  470. public function clearSsdbCouponReceiveByName($activity, $userId, $get = 0, $isAll = 0){
  471. $key = 'activity_'.$activity.'_user_'.$userId;
  472. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  473. if($isAll > 0){
  474. if($get > 0){
  475. return $ssdb->exec('hgetAll', SsdbKeysPrefix::COUPON_REBATE_RECEIVE);
  476. }else{
  477. return ( $ssdb->exec('hclear', SsdbKeysPrefix::COUPON_REBATE_RECEIVE) === false) ? false : true ;
  478. }
  479. }else {
  480. if($get > 0){
  481. return $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_RECEIVE, $key);
  482. }else{
  483. return ( $ssdb->exec('hdel', SsdbKeysPrefix::COUPON_REBATE_RECEIVE, $key) === false) ? false : true ;
  484. }
  485. }
  486. }
  487. }