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.

406 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 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上的活动信息
  167. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  168. $active = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY);
  169. $coupon_ids = explode(',',$active['forward']);
  170. $res = Db::table('ims_system_coupon_user as u')
  171. ->leftjoin('ims_system_coupon_user_receive as r', 'u.id', '=', 'r.system_coupon_user_id')
  172. ->whereIn('r.system_coupon_user_id',$coupon_ids)
  173. ->where([
  174. ['r.user_id', '=', $user_id],
  175. ['r.receive_type', '=', 4],
  176. ['u.active_type', '=', 2],
  177. ])
  178. ->select('r.id')
  179. ->first();
  180. return $res;
  181. }
  182. /*
  183. *获取活动信息
  184. */
  185. public function getActiveInfo()
  186. {
  187. //获取SSDB上的活动信息
  188. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  189. $active = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY);
  190. $coupon_ids = explode(',',$active['forward']);
  191. $time = time();
  192. $res = Db::table('ims_system_coupon_user')
  193. ->whereIn('id',$coupon_ids)
  194. ->where([
  195. ['status', '=', 1],
  196. ['active_type', '=', 2],
  197. ['start_time', '<=', $time],
  198. ['end_time', '>', $time],
  199. ])
  200. ->whereRaw('inventory > inventory_use')
  201. ->orderBy('weigh', 'desc')
  202. ->orderBy('addtime', 'desc')
  203. ->get();
  204. return $res;
  205. }
  206. /**
  207. * 将优惠券绑定活动
  208. * 领取优惠券 COUPON_REBATE_FORWARD 可多张
  209. * 返还优惠券 COUPON_REBATE_REPAY 只一张
  210. */
  211. public function tieCouponActive($couponActivity, $couponForward, $couponRepay)
  212. {
  213. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  214. $data = [
  215. 'activity', $couponActivity,
  216. 'forward' , $couponForward,
  217. 'repay' , $couponRepay
  218. ];
  219. $result = [
  220. 'result' => ($ssdb->exec('multi_hset', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY, $data) === false) ? false : true ,
  221. 'data' => $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY)
  222. ];
  223. return $result;
  224. }
  225. /*
  226. * 支付成功 返券
  227. */
  228. public function couponRebate($order_id)
  229. {
  230. //获取SSDB上的活动信息
  231. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  232. $active = $ssdb->execWithoutTask('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY);
  233. //判断返券优惠券是否有库存
  234. $inventory = Db::table('ims_system_coupon_user')
  235. ->where('id',$active['repay'])
  236. ->whereRaw('inventory > inventory_use')
  237. ->exists();
  238. if(!$inventory){
  239. //库存不足
  240. return false;
  241. }
  242. //获取活动发放优惠券id
  243. $coupon_ids = explode(',',$active['forward']);
  244. /* 判断被使用的优惠券类型是否为转发活动优惠券 */
  245. $coupon = Db::table('ims_system_coupon_user_receive as r')
  246. ->leftjoin('ims_system_coupon_user_use as u', 'u.user_receive_id', '=', 'r.id')
  247. ->where([
  248. ['u.order_main_id', '=', $order_id],
  249. ['r.send_user_id', '>', 0],
  250. ['r.rebate_type', '=', 1],
  251. ['r.receive_type', '=', 4],
  252. ])
  253. ->whereIn('r.system_coupon_user_id',$coupon_ids)
  254. ->select('r.user_id', 'r.send_user_id')
  255. ->first();
  256. /* 如果使用的优惠券为转发活动优惠券 则给赠送者返一张优惠券*/
  257. if (isset($coupon->send_user_id) && ($coupon->send_user_id) > 0) {
  258. //是否已返过券
  259. $exists_coupon_rebate = Db::table('ims_system_coupon_user_receive')
  260. ->where([
  261. ['system_coupon_user_id' ,'=', $active['repay']],
  262. ['user_id' ,'=', $coupon->send_user_id],
  263. ['receive_type' ,'=', 5],
  264. ])
  265. ->select('id','status')
  266. ->first();
  267. //开启事务
  268. Db::beginTransaction();
  269. try {
  270. //返券
  271. if($exists_coupon_rebate->id){
  272. //如果已有该优惠券 则领取数量 和 可用数量 自增1
  273. Db::table('ims_system_coupon_user_receive')
  274. ->where([
  275. ['id' ,'=', $exists_coupon_rebate->id],
  276. ])
  277. ->increment('number');
  278. Db::table('ims_system_coupon_user_receive')
  279. ->where([
  280. ['id' ,'=', $exists_coupon_rebate->id],
  281. ])
  282. ->increment('number_remain');
  283. //如果该用户在领取表中 status为已用完状态 2 则改为已用部分 1
  284. if($exists_coupon_rebate->status == 2){
  285. Db::table('ims_system_coupon_user_receive')
  286. ->where([
  287. ['id' ,'=', $exists_coupon_rebate->id],
  288. ])
  289. ->update(['status' => 1]);;
  290. }
  291. }else {
  292. //否则新增一条返券记录
  293. $nowTime = time();
  294. Db::table('ims_system_coupon_user_receive')->insert([
  295. [
  296. 'user_id' => $coupon->send_user_id,
  297. 'system_coupon_user_id' => $active['repay'],
  298. 'receive_type' => 5,
  299. 'status' => 0,
  300. 'number' => 1,
  301. 'number_remain' => 1,
  302. 'order_main_id' => $order_id,
  303. 'receive_time' => $nowTime,
  304. 'update_time' => $nowTime,
  305. 'created_at' => $nowTime,
  306. 'updated_at' => $nowTime,
  307. ]
  308. ]);
  309. }
  310. //首次返券更新rebate_type字段 防止重复返券
  311. Db::table('ims_system_coupon_user_receive')
  312. ->where([
  313. ['user_id','=',$coupon->user_id],
  314. ['receive_type','=',4],
  315. ])
  316. ->whereIn('system_coupon_user_id',$coupon_ids)
  317. ->update(['rebate_type' => 2]);
  318. //更新库存操作
  319. Db::table('ims_system_coupon_user')
  320. ->where('id', $active['repay']['repay'])
  321. ->increment('inventory_use');
  322. // 提交
  323. Db::commit();
  324. } catch (\Exception $e) {
  325. // 回滚
  326. Db::rollBack();
  327. $log_Data = array();
  328. $log_Data['name'] = '返券';
  329. $log_Data['order_main_id'] = $order_id;
  330. $log_Data['msg'] = '返券失败';
  331. $this->log->event(
  332. LogLabel::COUPON_LOG,
  333. $log_Data
  334. );
  335. }
  336. }
  337. $log_Data = array();
  338. $log_Data['name'] = '返券';
  339. $log_Data['user_id'] = $order_id;
  340. $log_Data['send_user_id'] = $coupon->send_user_id;
  341. $log_Data['order_main_id'] = $order_id;
  342. $log_Data['msg'] = '返券成功';
  343. $this->log->event(
  344. LogLabel::COUPON_LOG,
  345. $log_Data
  346. );
  347. return true;
  348. }
  349. /**
  350. * 清优惠券领取记录(SSDB)
  351. */
  352. public function clearSsdbCouponReceiveByName($activity, $userId, $get = 0, $isAll = 0){
  353. $key = 'activity_'.$activity.'_user_'.$userId;
  354. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  355. if($isAll > 0){
  356. if($get > 0){
  357. return $ssdb->exec('hgetAll', SsdbKeysPrefix::COUPON_REBATE_RECEIVE);
  358. }else{
  359. return ( $ssdb->exec('hclear', SsdbKeysPrefix::COUPON_REBATE_RECEIVE) === false) ? false : true ;
  360. }
  361. }else {
  362. if($get > 0){
  363. return $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_RECEIVE, $key);
  364. }else{
  365. return ( $ssdb->exec('hdel', SsdbKeysPrefix::COUPON_REBATE_RECEIVE, $key) === false) ? false : true ;
  366. }
  367. }
  368. }
  369. }