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.

378 lines
15 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 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. $receiveSsdb = [];
  52. // 判断是否已全部领取过
  53. $userReceive = $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId);
  54. if($userReceive === false){
  55. $ids = $idsData;
  56. }else{
  57. $userReceiveCouponIds = empty($userReceive) ? [] : $userReceive ;
  58. $ids = array_diff($idsData, $userReceiveCouponIds);
  59. $receiveSsdb = $userReceiveCouponIds;
  60. }
  61. if(count($ids) > 0){
  62. try{
  63. Db::transaction( function() use ($ids,$receiveType,$userId,$sendUserId,$phone,&$result,&$errorData,&$receiveSsdb) {
  64. $now = time();
  65. $success = [];
  66. //获取优惠券信息 (读写锁,完全控制,性能低)
  67. $coupons = Coupon::whereIn('id', $ids)->lockForUpdate()
  68. ->where('active_type',2)
  69. ->where('status',1)
  70. ->where('start_time', '<=', $now)
  71. ->where('end_time', '>=', $now)
  72. ->whereRaw('inventory > inventory_use')
  73. ->select('id','title','inventory','inventory_use','full_amount','discounts','active_type')
  74. ->get();
  75. foreach($coupons as $coupon){
  76. $errorData['coupon_id'] = $coupon->id;
  77. // 查询一次能领取的数量
  78. $couponReceiveType = CouponUserRecType::where('system_coupon_user_id',$coupon->id)->select('one_receive_number');
  79. if (env('SUB_CHANNEL') == 1) {
  80. $couponReceiveType->where('receive_type',$receiveType);
  81. }
  82. $couponReceiveType = $couponReceiveType->first();
  83. // 优惠券可领取数量 >= 本次领取数量
  84. if($coupon->inventory - $coupon->inventory_use >= $couponReceiveType->one_receive_number){
  85. // 判断是否领取过 存在记录则领取过
  86. $isReceive = CouponRec::select('id')
  87. ->where('system_coupon_user_id',$coupon->id)
  88. ->where('user_id',$userId)
  89. ->exists();
  90. if(!$isReceive){
  91. //记录已领取的数量
  92. $coupon->inventory_use += $couponReceiveType->number;
  93. $couponReceive = new CouponRec;
  94. $couponReceive->user_id = $userId;
  95. $couponReceive->system_coupon_user_id = $coupon->id;
  96. $couponReceive->order_main_id = 0;
  97. $couponReceive->receive_time = $now;
  98. $couponReceive->number = $couponReceiveType->one_receive_number;
  99. $couponReceive->number_remain = $couponReceiveType->one_receive_number;
  100. $couponReceive->status = 0;
  101. $couponReceive->update_time = $now;
  102. $couponReceive->receive_type = $receiveType;
  103. $couponReceive->send_user_id = $sendUserId;
  104. $couponReceive->phone = $phone;
  105. if ( $couponReceive->save() && $coupon->save() ) {
  106. $success[] = $coupon;
  107. $receiveSsdb[] = $coupon->id;
  108. }else{
  109. $errorData['msg'] = '添加优惠券到用户领取表或者记录已领取数量失败';
  110. $this->log->event(
  111. LogLabel::COUPON_LOG,
  112. $errorData
  113. );
  114. }
  115. }
  116. }
  117. }
  118. if(count($success) > 0){
  119. $result['status'] = 0;
  120. $result['coupon_text'] = '恭喜您领取成功!';
  121. }
  122. });
  123. } catch (Exception $e){
  124. $errorData['msg'] = $e->getMessage();
  125. $this->log->event(
  126. LogLabel::COUPON_LOG,
  127. $errorData
  128. );
  129. }
  130. if(count($receiveSsdb) > 0){
  131. $saveSsdb = [];
  132. foreach($receiveSsdb as $kssdb => $vssdb){
  133. $saveSsdb[] = $kssdb;
  134. $saveSsdb[] = $vssdb;
  135. }
  136. // 记录到ssdb
  137. if(false === $ssdb->exec('multi_hset',SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId, $saveSsdb)){
  138. $errorData['msg'] = '记录领取优惠券到ssdb失败';
  139. $this->log->event(
  140. LogLabel::COUPON_LOG,
  141. $errorData
  142. );
  143. };
  144. }
  145. }else{
  146. $result['status'] = 2;
  147. $result['coupon_text'] = '您已领取!赶快去下单吧~';
  148. }
  149. return $result;
  150. }
  151. /*
  152. * 判断用户是否已领取过优惠券
  153. * */
  154. public function isCouponRebate($user_id)
  155. {
  156. //获取SSDB上的活动信息
  157. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  158. $active = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY);
  159. $coupon_ids = explode(',',$active['forward']);
  160. $res = Db::table('ims_system_coupon_user as u')
  161. ->leftjoin('ims_system_coupon_user_receive as r', 'u.id', '=', 'r.system_coupon_user_id')
  162. ->whereIn('r.system_coupon_user_id',$coupon_ids)
  163. ->where([
  164. ['r.user_id', '=', $user_id],
  165. ['r.receive_type', '=', 4],
  166. ['u.active_type', '=', 2],
  167. ])
  168. ->select('r.id')
  169. ->first();
  170. return $res;
  171. }
  172. /*
  173. *获取活动信息
  174. */
  175. public function getActiveInfo()
  176. {
  177. //获取SSDB上的活动信息
  178. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  179. $active = $ssdb->exec('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY);
  180. $coupon_ids = explode(',',$active['forward']);
  181. $time = time();
  182. $res = Db::table('ims_system_coupon_user')
  183. ->whereIn('id',$coupon_ids)
  184. ->where([
  185. ['status', '=', 1],
  186. ['active_type', '=', 2],
  187. ['start_time', '<=', $time],
  188. ['end_time', '>', $time],
  189. ])
  190. ->whereRaw('inventory > inventory_use')
  191. ->orderBy('weigh', 'desc')
  192. ->orderBy('addtime', 'desc')
  193. ->get();
  194. return $res;
  195. }
  196. /**
  197. * 将优惠券绑定活动
  198. * 领取优惠券 COUPON_REBATE_FORWARD 可多张
  199. * 返还优惠券 COUPON_REBATE_REPAY 只一张
  200. */
  201. public function tieCouponActive($couponActivity, $couponForward, $couponRepay)
  202. {
  203. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  204. $data = [
  205. 'activity', $couponActivity,
  206. 'forward' , $couponForward,
  207. 'repay' , $couponRepay
  208. ];
  209. $result = [
  210. 'result' => ($ssdb->exec('multi_hset', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY, $data) === false) ? false : true ,
  211. 'data' => $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY)
  212. ];
  213. return $result;
  214. }
  215. /*
  216. * 支付成功 返券
  217. */
  218. public function couponRebate($order_id)
  219. {
  220. //获取SSDB上的活动信息
  221. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  222. $active = $ssdb->execWithoutTask('hgetall',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY);
  223. //判断返券优惠券是否有库存
  224. $inventory = Db::table('ims_system_coupon_user')
  225. ->where('id',$active['repay'])
  226. ->whereRaw('inventory > inventory_use')
  227. ->exists();
  228. if(!$inventory){
  229. //库存不足
  230. return false;
  231. }
  232. //获取活动发放优惠券id
  233. $coupon_ids = explode(',',$active['forward']);
  234. /* 判断被使用的优惠券类型是否为转发活动优惠券 */
  235. $coupon = Db::table('ims_system_coupon_user_receive as r')
  236. ->leftjoin('ims_system_coupon_user_use as u', 'u.user_receive_id', '=', 'r.id')
  237. ->where([
  238. ['u.order_main_id', '=', $order_id],
  239. ['r.send_user_id', '>', 0],
  240. ['r.rebate_type', '=', 1],
  241. ['r.receive_type', '=', 4],
  242. ])
  243. ->whereIn('r.system_coupon_user_id',$coupon_ids)
  244. ->select('r.user_id', 'r.send_user_id')
  245. ->first();
  246. /* 如果使用的优惠券为转发活动优惠券 则给赠送者返一张优惠券*/
  247. if ($coupon) {
  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']['repay'])
  311. ->increment('inventory_use');
  312. // 提交
  313. Db::commit();
  314. } catch (\Exception $e) {
  315. // 回滚
  316. Db::rollBack();
  317. $log_Data = array();
  318. $log_Data['name'] = '返券';
  319. $log_Data['order_main_id'] = $order_id;
  320. $log_Data['msg'] = '返券失败';
  321. $this->log->event(
  322. LogLabel::COUPON_LOG,
  323. $log_Data
  324. );
  325. }
  326. }
  327. return true;
  328. }
  329. /**
  330. * 清优惠券领取记录(SSDB)
  331. */
  332. public function clearSsdbCouponReceiveByName($activity, $userId, $get = 0){
  333. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  334. if($get > 0){
  335. return [
  336. $ssdb->exec('hgetAll', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId ),
  337. $ssdb->exec('hgetAll', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $userId ),
  338. SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId
  339. ];
  340. }
  341. return ( $ssdb->exec('hclear', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId ) === false) ? false : true;
  342. }
  343. }