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.

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