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.

327 lines
12 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
  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. $res = Db::table('ims_system_coupon_user as u')
  157. ->leftjoin('ims_system_coupon_user_receive as r', 'u.id', '=', 'r.system_coupon_user_id')
  158. ->where([
  159. ['r.user_id', '=', $user_id],
  160. ['r.receive_type', '=', 4],
  161. ['u.active_type', '=', 2],
  162. ])
  163. ->select('r.id')
  164. ->first();
  165. return $res;
  166. }
  167. /*
  168. *获取活动信息
  169. */
  170. public function getActiveInfo()
  171. {
  172. $time = time();
  173. $res = Db::table('ims_system_coupon_user')
  174. ->where([
  175. ['status', '=', 1],
  176. ['active_type', '=', 2],
  177. ['start_time', '<=', $time],
  178. ['end_time', '>', $time],
  179. ])
  180. ->whereRaw('inventory > inventory_use')
  181. ->orderBy('addtime', 'desc')
  182. ->get();
  183. return $res;
  184. }
  185. /**
  186. * 将优惠券绑定活动
  187. * 领取优惠券 COUPON_REBATE_FORWARD 可多张
  188. * 返还优惠券 COUPON_REBATE_REPAY 只一张
  189. */
  190. public function tieCouponActive($couponActivity, $couponForward, $couponRepay)
  191. {
  192. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  193. $data = [
  194. 'activity', $couponActivity,
  195. 'forward' , $couponForward,
  196. 'repay' , $couponRepay
  197. ];
  198. $result = [
  199. 'result' => ($ssdb->exec('multi_hset', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY, $data) === false) ? false : true ,
  200. 'data' => $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY)
  201. ];
  202. return $result;
  203. }
  204. /*
  205. * 支付成功 返券
  206. */
  207. public function couponRebate($order_id)
  208. {
  209. /* 判断优惠券类型是否为转发活动优惠券 */
  210. $coupon = Db::table('ims_system_coupon_user_receive as r')
  211. ->leftjoin('ims_system_coupon_user_use as u', 'u.user_receive_id', '=', 'r.id')
  212. ->where([
  213. ['u.order_main_id', '=', $order_id],
  214. ['r.send_user_id', '>', 0],
  215. ['r.rebate_type', '=', 1],
  216. ['r.receive_type', '=', 4],
  217. ['u.status', '=', 1],
  218. ])
  219. ->select('r.id', 'r.send_user_id', 'u.system_coupon_id')
  220. ->first();
  221. /* 如果使用的优惠券为转发活动优惠券 则给赠送者返一张优惠券*/
  222. if (isset($coupon->send_user_id) && ($coupon->send_user_id) > 0) {
  223. //判断该优惠券是否有库存
  224. // $inventory = Db::table('system_coupon_user_receive as r');
  225. // if($inventory['inventory'] <= 0){
  226. // return '库存不足';
  227. // }
  228. //return $exist_coupon;
  229. //开启事务
  230. try {
  231. /*
  232. * 如果已有该优惠券 则领取数量 可用数量 自增1
  233. * 否则新增一条返券记录
  234. */
  235. $nowTime = time();
  236. $res = Db::table('ims_system_coupon_user_receive')->moreIncrementOrInsert(
  237. [
  238. 'system_coupon_user_id' => $coupon->system_coupon_id,
  239. 'user_id' => $coupon->send_user_id,
  240. 'receive_type' => 5,
  241. 'status' => 0,
  242. ],
  243. [
  244. 'order_main_id' => $order_id,
  245. 'receive_time' => $nowTime,
  246. 'update_time' => $nowTime,
  247. 'created_at' => $nowTime,
  248. 'updated_at' => $nowTime,
  249. ],
  250. [
  251. 'number' => 1,
  252. 'number_remain' => 1,
  253. ]
  254. );
  255. // if ($res) {
  256. // //首次返券更新rebate_type字段 防止重复返券
  257. // Db::table('system_coupon_user_receive')->where('id', $coupon->id)->update(['rebate_type' => 2]);
  258. // //更新库存操作
  259. // Db::table('system_coupon_user')
  260. // ->where('id', $coupon->id)
  261. // ->increment('inventory_use');
  262. // } else {
  263. // Db::rollBack();
  264. // return '事务失败';
  265. // }
  266. // 提交
  267. Db::commit();
  268. } catch (\Exception $e) {
  269. // 回滚
  270. Db::rollBack();
  271. return '返券失败';
  272. }
  273. } else {
  274. // $str1 = 'order_main_id:'.$this->order_id . ',未查询到用户领取优惠券信息['.$coupon.']';
  275. // $this->couponErrorLog($str1);
  276. }
  277. return '返券成功';
  278. }
  279. /**
  280. * 清优惠券领取记录(SSDB)
  281. */
  282. public function clearSsdbCouponReceiveByName($activity, $userId, $get = 0){
  283. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  284. if($get > 0){
  285. return [
  286. $ssdb->exec('hgetAll', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId ),
  287. $ssdb->exec('hgetAll', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $userId ),
  288. SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId
  289. ];
  290. }
  291. return ( $ssdb->exec('hclear', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $activity . $userId ) === false) ? false : true;
  292. }
  293. }