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.

395 lines
16 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
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 function AlibabaCloud\Client\json;
  15. class CouponRebateService implements CouponRebateServiceInterface
  16. {
  17. /**
  18. * @Inject
  19. * @var Log
  20. */
  21. protected $log;
  22. /**
  23. * 领取优惠券
  24. * 返券活动领取
  25. * 一次可领取多张优惠券
  26. * 一个用户不可重复领取
  27. */
  28. public function userReceiveCoupon($params)
  29. {
  30. $userId = $params["user_id"];
  31. $receiveType = $params["receive_type"];
  32. $ids = $params["ids"];
  33. $sendUserId = $params["send_user_id"];
  34. $phone = $params["phone"];
  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. $activity = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY ,'activity');
  51. // ssdb 键值
  52. $ssdbKey = 'activity_'.$activity.'_user_'.$userId;
  53. $receiveSsdb = [];
  54. // 判断是否已全部领取过
  55. $userReceive = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_RECEIVE,$ssdbKey);
  56. if($userReceive === false){
  57. $ids = $idsData;
  58. }else{
  59. $userReceiveCouponIds = empty($userReceive) ? [] : explode(',',$userReceive) ;
  60. $ids = array_diff($idsData, $userReceiveCouponIds);
  61. $receiveSsdb = $userReceiveCouponIds;
  62. }
  63. if(count($ids) > 0){
  64. try{
  65. Db::transaction( function() use ($ids,$receiveType,$userId,$sendUserId,$phone,&$result,&$errorData,&$receiveSsdb) {
  66. $now = time();
  67. $success = [];
  68. //获取优惠券信息 (读写锁,完全控制,性能低)
  69. $coupons = Coupon::whereIn('id', $ids)->lockForUpdate()
  70. ->where('active_type',2)
  71. ->where('status',1)
  72. ->where('start_time', '<=', $now)
  73. ->where('end_time', '>=', $now)
  74. ->whereRaw('inventory > inventory_use')
  75. ->select('id','title','inventory','inventory_use','full_amount','discounts','active_type')
  76. ->get();
  77. foreach($coupons as $coupon){
  78. $errorData['coupon_id'] = $coupon->id;
  79. // 查询一次能领取的数量
  80. $couponReceiveType = CouponUserRecType::where('system_coupon_user_id',$coupon->id)->select('one_receive_number');
  81. if (env('SUB_CHANNEL') == 1) {
  82. $couponReceiveType->where('receive_type',$receiveType);
  83. }
  84. $couponReceiveType = $couponReceiveType->first();
  85. // 优惠券可领取数量 >= 本次领取数量
  86. if($coupon->inventory - $coupon->inventory_use >= $couponReceiveType->one_receive_number){
  87. // 判断是否领取过 存在记录则领取过
  88. $isReceive = CouponRec::select('id')
  89. ->where('system_coupon_user_id',$coupon->id)
  90. ->where('user_id',$userId)
  91. ->exists();
  92. if(!$isReceive){
  93. //记录已领取的数量
  94. $coupon->inventory_use += $couponReceiveType->one_receive_number;
  95. $couponReceive = new CouponRec;
  96. $couponReceive->user_id = $userId;
  97. $couponReceive->system_coupon_user_id = $coupon->id;
  98. $couponReceive->order_main_id = 0;
  99. $couponReceive->receive_time = $now;
  100. $couponReceive->number = $couponReceiveType->one_receive_number;
  101. $couponReceive->number_remain = $couponReceiveType->one_receive_number;
  102. $couponReceive->status = 0;
  103. $couponReceive->update_time = $now;
  104. $couponReceive->receive_type = $receiveType;
  105. $couponReceive->send_user_id = $sendUserId;
  106. $couponReceive->phone = $phone;
  107. if ( $couponReceive->save() && $coupon->save() ) {
  108. $success[] = $coupon;
  109. $receiveSsdb[] = $coupon->id;
  110. }else{
  111. $errorData['msg'] = '添加优惠券到用户领取表或者记录已领取数量失败';
  112. $this->log->event(
  113. LogLabel::COUPON_LOG,
  114. $errorData
  115. );
  116. }
  117. }
  118. }
  119. }
  120. if(count($success) > 0){
  121. $result['status'] = 0;
  122. $result['coupon_text'] = '恭喜您领取成功!';
  123. }
  124. });
  125. } catch (Exception $e){
  126. $errorData['msg'] = $e->getMessage();
  127. $this->log->event(
  128. LogLabel::COUPON_LOG,
  129. $errorData
  130. );
  131. }
  132. if(count($receiveSsdb) > 0){
  133. ;
  134. $saveSsdb = [
  135. $ssdbKey,
  136. implode(',',$receiveSsdb)
  137. ];
  138. if(false === $ssdb->exec('hset',SsdbKeysPrefix::COUPON_REBATE_RECEIVE, $saveSsdb)){
  139. $errorData['msg'] = '记录领取优惠券到ssdb失败';
  140. $this->log->event(
  141. LogLabel::COUPON_LOG,
  142. $errorData
  143. );
  144. };
  145. }
  146. }else{
  147. $result['status'] = 2;
  148. $result['coupon_text'] = '您已领取!赶快去下单吧~';
  149. }
  150. return $result;
  151. }
  152. /*
  153. * 判断用户是否已领取过优惠券
  154. * */
  155. public function isCouponRebate($user_id)
  156. {
  157. //获取SSDB上的活动信息
  158. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  159. $active = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY);
  160. $coupon_ids = explode(',',$active['forward']);
  161. $res = Db::table('ims_system_coupon_user as u')
  162. ->leftjoin('ims_system_coupon_user_receive as r', 'u.id', '=', 'r.system_coupon_user_id')
  163. ->whereIn('r.system_coupon_user_id',$coupon_ids)
  164. ->where([
  165. ['r.user_id', '=', $user_id],
  166. ['r.receive_type', '=', 4],
  167. ['u.active_type', '=', 2],
  168. ])
  169. ->select('r.id')
  170. ->first();
  171. return $res;
  172. }
  173. /*
  174. *获取活动信息
  175. */
  176. public function getActiveInfo()
  177. {
  178. //获取SSDB上的活动信息
  179. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  180. $active = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY);
  181. $coupon_ids = explode(',',$active['forward']);
  182. $time = time();
  183. $res = Db::table('ims_system_coupon_user')
  184. ->whereIn('id',$coupon_ids)
  185. ->where([
  186. ['status', '=', 1],
  187. ['active_type', '=', 2],
  188. ['start_time', '<=', $time],
  189. ['end_time', '>', $time],
  190. ])
  191. ->whereRaw('inventory > inventory_use')
  192. ->orderBy('weigh', 'desc')
  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. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  205. $data = [
  206. 'activity', $couponActivity,
  207. 'forward' , $couponForward,
  208. 'repay' , $couponRepay
  209. ];
  210. $result = [
  211. 'result' => ($ssdb->exec('multi_hset', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY, $data) === false) ? false : true ,
  212. 'data' => $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY)
  213. ];
  214. return $result;
  215. }
  216. /*
  217. * 支付成功 返券
  218. */
  219. public function couponRebate($order_id)
  220. {
  221. //获取SSDB上的活动信息
  222. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  223. $active = $ssdb->execWithoutTask('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY);
  224. //判断返券优惠券是否有库存
  225. $inventory = Db::table('ims_system_coupon_user')
  226. ->where('id',$active['repay'])
  227. ->whereRaw('inventory > inventory_use')
  228. ->exists();
  229. if(!$inventory){
  230. //库存不足
  231. return false;
  232. }
  233. //获取活动发放优惠券id
  234. $coupon_ids = explode(',',$active['forward']);
  235. /* 判断被使用的优惠券类型是否为转发活动优惠券 */
  236. $coupon = Db::table('ims_system_coupon_user_receive as r')
  237. ->leftjoin('ims_system_coupon_user_use as u', 'u.user_receive_id', '=', 'r.id')
  238. ->where([
  239. ['u.order_main_id', '=', $order_id],
  240. ['r.send_user_id', '>', 0],
  241. ['r.rebate_type', '=', 1],
  242. ['r.receive_type', '=', 4],
  243. ])
  244. ->whereIn('r.system_coupon_user_id',$coupon_ids)
  245. ->select('r.user_id', 'r.send_user_id')
  246. ->first();
  247. /* 如果使用的优惠券为转发活动优惠券 则给赠送者返一张优惠券*/
  248. if (isset($coupon->send_user_id) && ($coupon->send_user_id) > 0) {
  249. //是否已返过券
  250. $exists_coupon_rebate = Db::table('ims_system_coupon_user_receive')
  251. ->where([
  252. ['system_coupon_user_id' ,'=', $active['repay']],
  253. ['user_id' ,'=', $coupon->send_user_id],
  254. ['receive_type' ,'=', 5],
  255. ])
  256. ->select('id','status')
  257. ->first();
  258. //开启事务
  259. Db::beginTransaction();
  260. try {
  261. //返券
  262. if($exists_coupon_rebate->id){
  263. //如果已有该优惠券 则领取数量 和 可用数量 自增1
  264. Db::table('ims_system_coupon_user_receive')
  265. ->where([
  266. ['id' ,'=', $exists_coupon_rebate->id],
  267. ])
  268. ->increment('number');
  269. Db::table('ims_system_coupon_user_receive')
  270. ->where([
  271. ['id' ,'=', $exists_coupon_rebate->id],
  272. ])
  273. ->increment('number_remain');
  274. //如果该用户在领取表中 status为已用完状态 2 则改为已用部分 1
  275. if($exists_coupon_rebate->status == 2){
  276. Db::table('ims_system_coupon_user_receive')
  277. ->where([
  278. ['id' ,'=', $exists_coupon_rebate->id],
  279. ])
  280. ->update(['status' => 1]);;
  281. }
  282. }else {
  283. //否则新增一条返券记录
  284. $nowTime = time();
  285. Db::table('ims_system_coupon_user_receive')->insert([
  286. [
  287. 'user_id' => $coupon->send_user_id,
  288. 'system_coupon_user_id' => $active['repay'],
  289. 'receive_type' => 5,
  290. 'status' => 0,
  291. 'number' => 1,
  292. 'number_remain' => 1,
  293. 'order_main_id' => $order_id,
  294. 'receive_time' => $nowTime,
  295. 'update_time' => $nowTime,
  296. 'created_at' => $nowTime,
  297. 'updated_at' => $nowTime,
  298. ]
  299. ]);
  300. }
  301. //首次返券更新rebate_type字段 防止重复返券
  302. Db::table('ims_system_coupon_user_receive')
  303. ->where([
  304. ['user_id','=',$coupon->user_id],
  305. ['receive_type','=',4],
  306. ])
  307. ->whereIn('system_coupon_user_id',$coupon_ids)
  308. ->update(['rebate_type' => 2]);
  309. //更新库存操作
  310. Db::table('ims_system_coupon_user')
  311. ->where('id', $active['repay']['repay'])
  312. ->increment('inventory_use');
  313. // 提交
  314. Db::commit();
  315. } catch (\Exception $e) {
  316. // 回滚
  317. Db::rollBack();
  318. $log_Data = array();
  319. $log_Data['name'] = '返券';
  320. $log_Data['order_main_id'] = $order_id;
  321. $log_Data['msg'] = '返券失败';
  322. $this->log->event(
  323. LogLabel::COUPON_LOG,
  324. $log_Data
  325. );
  326. }
  327. }
  328. $log_Data = array();
  329. $log_Data['name'] = '返券';
  330. $log_Data['user_id'] = $order_id;
  331. $log_Data['send_user_id'] = $coupon->send_user_id;
  332. $log_Data['order_main_id'] = $order_id;
  333. $log_Data['msg'] = '返券成功';
  334. $this->log->event(
  335. LogLabel::COUPON_LOG,
  336. $log_Data
  337. );
  338. return true;
  339. }
  340. /**
  341. * 清优惠券领取记录(SSDB)
  342. */
  343. public function clearSsdbCouponReceiveByName($activity, $userId, $get = 0, $isAll = 0){
  344. $key = 'activity_'.$activity.'_user_'.$userId;
  345. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  346. if($isAll > 0){
  347. if($get > 0){
  348. return $ssdb->exec('hgetAll', SsdbKeysPrefix::COUPON_REBATE_RECEIVE);
  349. }else{
  350. return ( $ssdb->exec('hclear', SsdbKeysPrefix::COUPON_REBATE_RECEIVE) === false) ? false : true ;
  351. }
  352. }else {
  353. $ssdb->exec('hclear', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId );
  354. if($get > 0){
  355. return $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_RECEIVE, $key);
  356. }else{
  357. return ( $ssdb->exec('hdel', SsdbKeysPrefix::COUPON_REBATE_RECEIVE, $key) === false) ? false : true ;
  358. }
  359. }
  360. }
  361. }