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.

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