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.

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