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.

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