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.

393 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. return $active;
  178. $coupon_ids = explode(',',$active['forward']);
  179. $time = time();
  180. $res = Db::table('ims_system_coupon_user')
  181. ->whereIn('id',$coupon_ids)
  182. ->where([
  183. ['status', '=', 1],
  184. ['active_type', '=', 2],
  185. ['start_time', '<=', $time],
  186. ['end_time', '>', $time],
  187. ])
  188. ->whereRaw('inventory > inventory_use')
  189. ->orderBy('weigh', 'desc')
  190. ->orderBy('addtime', 'desc')
  191. ->get();
  192. return $res;
  193. }
  194. /**
  195. * 将优惠券绑定活动
  196. * 领取优惠券 COUPON_REBATE_FORWARD 可多张
  197. * 返还优惠券 COUPON_REBATE_REPAY 只一张
  198. */
  199. public function tieCouponActive($couponActivity, $couponForward, $couponRepay)
  200. {
  201. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  202. $data = [
  203. 'activity', $couponActivity,
  204. 'forward' , $couponForward,
  205. 'repay' , $couponRepay
  206. ];
  207. $result = [
  208. 'result' => ($ssdb->exec('multi_hset', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY, $data) === false) ? false : true ,
  209. 'data' => $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY)
  210. ];
  211. return $result;
  212. }
  213. /*
  214. * 支付成功 返券
  215. */
  216. public function couponRebate($order_id)
  217. {
  218. //获取SSDB上的活动信息
  219. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  220. $active = $ssdb->execWithoutTask('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY);
  221. //判断返券优惠券是否有库存
  222. $inventory = Db::table('ims_system_coupon_user')
  223. ->where('id',$active['repay'])
  224. ->whereRaw('inventory > inventory_use')
  225. ->exists();
  226. if(!$inventory){
  227. //库存不足
  228. return false;
  229. }
  230. //获取活动发放优惠券id
  231. $coupon_ids = explode(',',$active['forward']);
  232. /* 判断被使用的优惠券类型是否为转发活动优惠券 */
  233. $coupon = Db::table('ims_system_coupon_user_receive as r')
  234. ->leftjoin('ims_system_coupon_user_use as u', 'u.user_receive_id', '=', 'r.id')
  235. ->where([
  236. ['u.order_main_id', '=', $order_id],
  237. ['r.send_user_id', '>', 0],
  238. ['r.rebate_type', '=', 1],
  239. ['r.receive_type', '=', 4],
  240. ])
  241. ->whereIn('r.system_coupon_user_id',$coupon_ids)
  242. ->select('r.user_id', 'r.send_user_id')
  243. ->first();
  244. /* 如果使用的优惠券为转发活动优惠券
  245. **则给赠送者返一张优惠券
  246. * **自己给自己转发的券不给返券
  247. */
  248. if ($coupon && ($coupon->user_id != $coupon->send_user_id)) {
  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){
  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'])
  312. ->increment('inventory_use');
  313. //添加领取记录到ssdb
  314. $data = [
  315. $order_id,$coupon->user_id,
  316. ];
  317. $ssdb->execWithoutTask('multi_hset', SsdbKeysPrefix::COUPON_REBATE_LIST.$coupon->send_user_id, $data);
  318. // 提交
  319. Db::commit();
  320. } catch (\Exception $e) {
  321. //写入日志文件
  322. $log_Data = array();
  323. $log_Data['name'] = '返券';
  324. $log_Data['order_id'] = $order_id;
  325. $log_Data['msg'] = '返券失败';
  326. $this->log->event(
  327. LogLabel::COUPON_LOG,
  328. $log_Data
  329. );
  330. // 回滚
  331. Db::rollBack();
  332. }
  333. }
  334. return true;
  335. }
  336. /**
  337. * 清优惠券领取记录(SSDB)
  338. */
  339. public function clearSsdbCouponReceiveByName($activity, $userId, $get = 0, $isAll = 0){
  340. $key = 'activity_'.$activity.'_user_'.$userId;
  341. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  342. if($isAll > 0){
  343. if($get > 0){
  344. return $ssdb->exec('hgetAll', SsdbKeysPrefix::COUPON_REBATE_RECEIVE);
  345. }else{
  346. return ( $ssdb->exec('hclear', SsdbKeysPrefix::COUPON_REBATE_RECEIVE) === false) ? false : true ;
  347. }
  348. }else {
  349. $ssdb->exec('hclear', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId );
  350. if($get > 0){
  351. return $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_RECEIVE, $key);
  352. }else{
  353. return ( $ssdb->exec('hdel', SsdbKeysPrefix::COUPON_REBATE_RECEIVE, $key) === false) ? false : true ;
  354. }
  355. }
  356. }
  357. }