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.

401 lines
14 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. <?php
  2. namespace App\Service;
  3. use App\Model\OrderMain;
  4. use App\Model\ShopCar;
  5. use Hyperf\Di\Annotation\Inject;
  6. use Hyperf\DbConnection\Db;
  7. use App\Model\CouponUserRecType;
  8. use App\Model\Coupon;
  9. use App\Model\CouponRec;
  10. use App\Model\CouponUserUse;
  11. use Hyperf\Utils\ApplicationContext;
  12. use App\TaskWorker\SSDBTask;
  13. use App\Constants\SsdbKeysPrefix;
  14. use App\Constants\LogLabel;
  15. use App\Commons\Log;
  16. use Exception;
  17. use App\Service\CommonService;
  18. use Hyperf\Redis\Redis;
  19. class CouponService implements CouponServiceInterface
  20. {
  21. /**
  22. * @Inject
  23. * @var Log
  24. */
  25. protected $log;
  26. /**
  27. * @Inject
  28. * @var CommonService
  29. */
  30. protected $commonService;
  31. /**
  32. * 获取用户可领取优惠卷接口
  33. */
  34. public function getSystemCouponUserList($userId,$receiveType)
  35. {
  36. /* 优惠券活动标志 2 */
  37. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  38. $couponActivity = $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY);
  39. $activityType = $couponActivity === false ? 0 : $couponActivity['activity'];
  40. $result = [
  41. 'active_type' => 1,
  42. 'not_receive' => [],
  43. 'jump_data' => [
  44. 'src' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType,
  45. 'src2' => "/zh_cjdianc/pages/couponrebate/index?activity_type=".$activityType,
  46. 'share_bg' => env('OSS_IMG_HOST').'/static/img/coupon_share.png',
  47. 'receive_bg' => env('OSS_IMG_HOST').'/static/img/coupon_bg.png',
  48. 'coupons' => []
  49. ]
  50. ];
  51. $nowTime = time();
  52. $c_ids = [];
  53. $whereC = [
  54. ['end_time','>',$nowTime],
  55. ['start_time','<=',$nowTime],
  56. ['status','=',1]
  57. ];
  58. // 渠道开启,查询该渠道可以领取的优惠券ID
  59. // 渠道未开启,查询所有优惠券
  60. if (env('SUB_CHANNEL') == 1) {
  61. $c_ids = CouponUserRecType::where('receive_type', $receiveType)->where($whereC)->pluck('system_coupon_user_id');
  62. } else {
  63. $c_ids = Coupon::where($whereC)->pluck('id');
  64. }
  65. $couponReceive = CouponRec::where('user_id',$userId);
  66. // 渠道开启,查询该用户在此渠道领过的优惠券ID
  67. if (env('SUB_CHANNEL') == 1) {
  68. $couponReceive->where('receive_type', $receiveType);
  69. }
  70. $cr_ids = $couponReceive->pluck('system_coupon_user_id');
  71. // 可领取的券ID
  72. $c_ids = $c_ids->toArray();
  73. // 已经领取的券ID
  74. $cr_ids = $cr_ids->toArray();
  75. // 当前用户可领的优惠券ID
  76. $couponIds = array_diff($c_ids, $cr_ids);
  77. // 转发型优惠券
  78. $couponReceiveIds = ($couponActivity === false || $this->commonService->empty($couponActivity['forward']) )? [] : explode(',',$couponActivity['forward']);
  79. // 所有优惠券
  80. $couponIds = array_merge($couponIds,$couponReceiveIds);
  81. $whereC = [
  82. ['u.end_time','>',$nowTime],
  83. ['u.start_time','<=',$nowTime],
  84. ['u.status','=',1]
  85. ];
  86. // 查询领取型1 和 转发型2
  87. $whereActiveType = [1,2];
  88. if (env('SUB_CHANNEL') == 1) {
  89. array_push($whereC, ['type.receive_type','=', $receiveType]);
  90. }
  91. $coupons = Db::table('ims_system_coupon_user as u')
  92. ->join('ims_system_coupon_user_receivetype as type', 'u.id', '=', 'type.system_coupon_user_id')
  93. ->whereIn('u.id', $couponIds)
  94. ->whereIn('u.active_type', $whereActiveType)
  95. ->where($whereC)
  96. ->whereRaw('u.inventory_use < u.inventory and u.inventory-u.inventory_use >= type.one_receive_number')
  97. ->select('u.*','type.one_receive_number')
  98. ->orderBy('u.weigh','desc')
  99. ->get();
  100. foreach ($coupons as $k => &$v){
  101. if($v->active_type == 1 && count($result['not_receive']) < 4){
  102. $result['not_receive'][] = $v;
  103. }else if($v->active_type == 2 && in_array($v->id,$couponReceiveIds)){
  104. $result['jump_data']['coupons'][] = $v->id;
  105. }
  106. if($v->discount_type == 2){
  107. $v->discounts = floatval($v->discounts);
  108. }
  109. }
  110. $result['active_type'] = count($result['jump_data']['coupons']) > 0 ? 2 : $result['active_type'] ;
  111. return $result;
  112. }
  113. //统计用户
  114. public function userCouponAccount()
  115. {
  116. }
  117. /**
  118. * 用户领取优惠卷
  119. */
  120. public function userReceiveCoupon()
  121. {
  122. }
  123. /**
  124. * 获取用户已经领取的优惠卷列表
  125. */
  126. public function getUserReceiveCouponList()
  127. {
  128. }
  129. /**
  130. * 获取用户当前订单可用的优惠券列表
  131. * 按分类(1订单 等优惠)分组返回
  132. */
  133. public function getUserAvailableCoupons($orderAmount,$userId,$marketId,$type,$storetypeId,$carIds)
  134. {
  135. $available = [];
  136. $notAvailable = [];
  137. //如果存在特价商品 不给用券
  138. $carIdsArr = explode(',',$carIds);
  139. $shopCarExists = ShopCar::whereIn('id',$carIdsArr)
  140. ->where('money',0.01)
  141. ->exists();
  142. if($shopCarExists){
  143. return [
  144. 'available' => $available,
  145. 'not_available' => array_values($notAvailable)
  146. ];
  147. }
  148. $storetypeIds = explode(',', str_replace(',', ',', $storetypeId));
  149. if (empty($orderAmount) || empty($userId)) {
  150. return [
  151. 'available' => $available,
  152. 'not_available' => array_values($notAvailable)
  153. ];
  154. }
  155. // 获取用户优惠券
  156. $currentTime = time();
  157. $data = Db::table('ims_system_coupon_user_receive as receive')
  158. ->select([
  159. 'receive.id as receive_id',
  160. 'receive.user_id',
  161. 'receive.number_remain',
  162. 'coupon.id',
  163. 'coupon.title',
  164. 'coupon.full_amount',
  165. 'coupon.discounts',
  166. 'coupon.usable_start_time',
  167. 'coupon.usable_end_time',
  168. 'coupon.discount_type'
  169. ])
  170. ->join('ims_system_coupon_user as coupon', 'coupon.id', '=', 'receive.system_coupon_user_id')
  171. ->where(['receive.user_id' => $userId])
  172. ->whereIn('receive.status', [0,1])
  173. ->where('receive.number_remain', '>', 0)
  174. ->whereIn('coupon.type', [1,$type])
  175. ->where('coupon.full_amount', '<=', $orderAmount)
  176. ->where('coupon.usable_start_time', '<=', $currentTime)
  177. ->where('coupon.usable_end_time', '>=', $currentTime)
  178. ->where('coupon.usable_number', '<=', Db::raw('receive.number_remain'))
  179. ->where('coupon.market_id', 'in', [0, $marketId])
  180. ->whereIn('coupon.storetype_id', $storetypeIds)
  181. ->orderByRaw('coupon.discounts DESC, coupon.full_amount DESC')
  182. ->get();
  183. // 分离用户今天用过的优惠券种类
  184. $container = ApplicationContext::getContainer();
  185. $redis = $container->get(Redis::class);
  186. $couponIds = $redis->sMembers('coupon_'.date('Ymd').'_used_'.$userId);
  187. foreach ($data as $key => &$item) {
  188. if (in_array($item->id, $couponIds)) {
  189. $notAvailable[$item->id] = $item;
  190. } else {
  191. $available[] = $item;
  192. }
  193. }
  194. return [
  195. 'available' => $available,
  196. 'not_available' => array_values($notAvailable)
  197. ];
  198. }
  199. /**
  200. * @inheritDoc
  201. */
  202. public function getOrderCanUseCoupons($orderAmount, $marketId, $userId, $fields=[], $type = 1, $storeTypeIds = [0])
  203. {
  204. // 用户今日使用过的优惠券
  205. $redis = ApplicationContext::getContainer()->get(Redis::class);
  206. $couponTodayUsedIds = $redis->sMembers('coupon_'.date('Ymd').'_used_'.$userId);
  207. $currentTime = time();
  208. $builder = Db::table('ims_system_coupon_user_receive as receive')
  209. ->join('ims_system_coupon_user as coupon', 'coupon.id', '=', 'receive.system_coupon_user_id', 'inner');
  210. if (is_array($fields)&&!empty($fields)) {
  211. $builder->select($fields);
  212. }
  213. if (is_array($couponTodayUsedIds)&&!empty($couponTodayUsedIds)) {
  214. $builder->whereNotIn('coupon.id', $couponTodayUsedIds);
  215. }
  216. return $builder->where(['receive.user_id' => $userId])
  217. ->whereIn('receive.status', [0,1])
  218. ->where('receive.number_remain', '>', 0)
  219. ->whereIn('coupon.type', [1,$type])
  220. ->where('coupon.full_amount', '<=', $orderAmount)
  221. ->where('coupon.usable_start_time', '<=', $currentTime)
  222. ->where('coupon.usable_end_time', '>=', $currentTime)
  223. ->where('coupon.usable_number', '<=', Db::raw('receive.number_remain'))
  224. ->where('coupon.market_id', 'in', [0, $marketId])
  225. ->whereIn('coupon.storetype_id', $storeTypeIds)
  226. ->orderByRaw('coupon.discounts DESC, coupon.full_amount DESC')
  227. ->get()
  228. ->toArray();
  229. }
  230. /**
  231. * 缓存优惠券今日使用情况
  232. * @param $userId
  233. * @param $couponId
  234. * @param $couponRecId
  235. * @return bool
  236. */
  237. function cacheTodayCouponUsed($userId, $couponId, $couponRecId)
  238. {
  239. $redis = ApplicationContext::getContainer()->get(Redis::class);
  240. $setRes = $redis->sAdd(
  241. 'coupon_'.date('Ymd').'_used_'.$userId,
  242. $couponId
  243. );
  244. $expireRes = $redis->expire(
  245. 'coupon_'.date('Ymd').'_used_'.$userId,
  246. strtotime(date('Y-m-d').' 23:59:59')-time()
  247. );
  248. return $setRes&&$expireRes;
  249. }
  250. /**
  251. * 取消订单返券
  252. * @param $order_id
  253. * @return bool
  254. */
  255. public function refundOrderCoupons($global_order_id){
  256. $order_main = OrderMain::where('global_order_id',$global_order_id)
  257. ->select('id','user_id')
  258. ->first();
  259. $order_id = $order_main->id;
  260. $coupon = CouponUserUse::where([
  261. ['order_main_id','=',$order_id],
  262. ['status','=',CouponUserUse::COUPON_USE_STATE_USED],
  263. ])
  264. ->select('id','user_receive_id','number')
  265. ->first();
  266. if (empty($coupon)) {
  267. return '';
  268. }
  269. // 返回用户优惠券数量并更新状态
  270. $res = Db::update("UPDATE ims_system_coupon_user_receive SET number_remain=number_remain+{$coupon->number}, status=IF(number=number_remain,0,1), update_time=".time().""
  271. ." WHERE id={$coupon->user_receive_id} AND number>=(number_remain+{$coupon->number})");
  272. // 更新使用记录状态为已退回
  273. CouponUserUse::where([
  274. ['id','=',$coupon->id],
  275. ['status','=',CouponUserUse::COUPON_USE_STATE_USED],
  276. ])
  277. ->update([
  278. 'status' => CouponUserUse::COUPON_USE_STATE_CANCEL,
  279. 'return_time' => time(),
  280. 'update_time' => time(),
  281. ]);
  282. //删除当日 redis 使用记录缓存
  283. $redis = ApplicationContext::getContainer()->get(Redis::class);
  284. $remRes = $redis->sRem(
  285. 'coupon_'.date('Ymd').'_used_'.$order_main->user_id,
  286. $coupon->system_coupon_id
  287. );
  288. return $res;
  289. }
  290. /* 删除-优惠券今日使用的缓存
  291. * @param $userId
  292. * @param $couponId
  293. * @return bool
  294. */
  295. public function clearTodayCouponUsed($userId, $couponId)
  296. {
  297. $redis = ApplicationContext::getContainer()->get(Redis::class);
  298. $res = $redis->sRem(
  299. 'coupon_'.date('Ymd').'_used_'.$userId,
  300. $couponId
  301. );
  302. return $res;
  303. }
  304. /**
  305. * 退款返还优惠券
  306. * 先查询是否正常使用优惠券
  307. * 修改状态,退还领取记录库存,删除ssdb缓存
  308. */
  309. public function orderRefundCoupon($global_order_id)
  310. {
  311. $time = time();
  312. Db::beginTransaction();
  313. try {
  314. $couponUses = CouponUserUse::query()
  315. ->select('id','system_coupon_id','user_id','number','user_receive_id')
  316. ->where('global_order_id',$global_order_id)
  317. ->where('status',CouponUserUse::COUPON_USE_STATE_USED)
  318. ->select();
  319. if(!empty($couponUse)){
  320. foreach($couponUses as $use){
  321. $use->status = CouponUserUse::COUPON_USE_STATE_USED;
  322. $use->return_time = $time;
  323. $use->update_time = $time;
  324. $res = $use->save();
  325. $couponReceive = CouponRec::query()
  326. ->where('id',$use->user_receive_id)
  327. ->whereRaw('number >= number_remain+'.$use->number)
  328. ->update([
  329. 'number_remain' => Db::raw('number_remain+'.$use->number),
  330. 'status' => Db::raw('IF(number=number_remain,' . CouponRec::STATE_UNUSED . ',' . CouponRec::STATE_SOME . ')'),
  331. 'update_time' => $time
  332. ]);
  333. $clearUseRedis = $this->clearTodayCouponUsed($use->user_id,$use->system_coupon_id);
  334. }
  335. }
  336. Db::commit();
  337. return true;
  338. } catch (Exception $e) {
  339. $this->log->event(LogLabel::ORDER_LOG, ['msg'=> '订单退款','exception' => $e->getMessage()]);
  340. Db::rollBack();
  341. return false;
  342. }
  343. return true;
  344. }
  345. }