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.

313 lines
12 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. <?php
  2. namespace App\Service\v3\Implementations;
  3. use App\Model\v3\Coupon;
  4. use App\Model\v3\CouponRec;
  5. use App\Model\v3\GoodsActivity;
  6. use App\Service\v3\Interfaces\CouponRecServiceInterface;
  7. use App\Service\v3\Interfaces\CouponServiceInterface;
  8. use App\Service\v3\Interfaces\ShopCartServiceInterface;
  9. use Hyperf\DbConnection\Db;
  10. use Hyperf\Redis\Redis;
  11. use Hyperf\Utils\ApplicationContext;
  12. use Hyperf\Di\Annotation\Inject;
  13. class CouponRecService implements CouponRecServiceInterface
  14. {
  15. /**
  16. * @Inject
  17. * @var ShopCartServiceInterface
  18. */
  19. protected $shopCartService;
  20. /**
  21. * @Inject
  22. * @var CouponServiceInterface
  23. */
  24. protected $couponService;
  25. public function do()
  26. {
  27. // TODO: Implement do() method.
  28. }
  29. public function check()
  30. {
  31. // TODO: Implement check() method.
  32. }
  33. public function undo()
  34. {
  35. // TODO: Implement undo() method.
  36. }
  37. /**
  38. * 获取当前订单可使用的优惠券
  39. * @param $totalAmount
  40. * @param $userId
  41. * @param $marketId
  42. * @param $type
  43. * @param $storeTypeIds
  44. * @return array
  45. */
  46. public function allForOrderOlAvailable($totalAmount, $userId, $marketId, $type, $storeTypeIds = [])
  47. {
  48. // 用户今日使用过的优惠券
  49. $redis = ApplicationContext::getContainer()->get(Redis::class);
  50. $couponTodayUsedIds = $redis->sMembers('coupon_'.date('Ymd').'_used_'.$userId);
  51. $currentTime = time();
  52. $builder = Db::table('lanzu_coupon_receive as receive')
  53. ->join('lanzu_coupon as coupon', 'coupon.id', '=', 'receive.coupon_id', 'inner');
  54. if (is_array($couponTodayUsedIds)&&!empty($couponTodayUsedIds)) {
  55. $builder->whereNotIn('coupon.id', $couponTodayUsedIds);
  56. }
  57. foreach ($storeTypeIds as $key => &$item) {
  58. $item = (string)$item;
  59. }
  60. if (!empty($storeTypeIds)) {
  61. $builder->whereJsonContains('coupon.category_ids', $storeTypeIds);
  62. }
  63. $builder->where(['receive.user_id' => $userId])
  64. ->whereIn('receive.status', [0,1])
  65. ->where('receive.number_remain', '>', 0)
  66. ->whereIn('coupon.type', [1,$type])
  67. ->where('coupon.full_amount', '<=', $totalAmount)
  68. ->where('coupon.usable_start_time', '<=', $currentTime)
  69. ->where('coupon.usable_end_time', '>=', $currentTime)
  70. ->where('coupon.usable_number', '<=', Db::raw('receive.number_remain'));
  71. if ($marketId) {
  72. $builder->whereJsonContains('coupon.market_ids', [(string)$marketId]);
  73. }
  74. return $builder->orderByRaw('coupon.discounts DESC, coupon.full_amount DESC')
  75. ->get()
  76. ->toArray();
  77. }
  78. /**
  79. * 用户优惠券列表
  80. * @param $userId
  81. * @param $type
  82. * @param int $page
  83. * @param int $pagesize
  84. * @return array
  85. */
  86. public function getListByUser($userId,$type,$page = 1,$pagesize = 5)
  87. {
  88. //查询优惠券
  89. $builder = CouponRec::query()->join('lanzu_coupon', 'lanzu_coupon.id', '=', 'lanzu_coupon_receive.coupon_id')
  90. ->where([
  91. ['lanzu_coupon_receive.user_id' ,'=', $userId],
  92. ]);
  93. /**
  94. * $type unused 未使用 used 已使用 expired 已失效
  95. */
  96. switch ($type){
  97. case 'unused':
  98. $builder = $builder->where([
  99. ['lanzu_coupon.usable_end_time' ,'>', time()],
  100. ['lanzu_coupon_receive.number_remain' ,'>', 0],
  101. ['lanzu_coupon.status','=',1]
  102. ])
  103. ->whereIn('lanzu_coupon_receive.status',[0,1]);
  104. break;
  105. case 'used':
  106. $builder = $builder->whereIn('lanzu_coupon_receive.status',[1,2]);
  107. break;
  108. case 'expired':
  109. $builder = $builder->where(function ($query) {
  110. $query->where('lanzu_coupon.usable_end_time', '<', time())
  111. ->orWhere('lanzu_coupon.status', '<>', 1);
  112. });
  113. break;
  114. }
  115. $builder = $builder->select(
  116. 'lanzu_coupon.title',
  117. 'lanzu_coupon.discounts',
  118. 'lanzu_coupon.full_amount',
  119. 'lanzu_coupon.discount_type',
  120. 'lanzu_coupon.introduce',
  121. 'lanzu_coupon.tags',
  122. 'lanzu_coupon.usable_start_time',
  123. 'lanzu_coupon.usable_end_time',
  124. 'lanzu_coupon_receive.number',
  125. 'lanzu_coupon_receive.number_remain'
  126. )
  127. ->orderBy('lanzu_coupon.weigh','desc');
  128. $paginate = $builder->paginate($pagesize);
  129. $couponList = $paginate->toArray();
  130. foreach ($couponList['data'] as $key => &$coupon) {
  131. //拼接满减文字提示
  132. $coupon['full_amount_text'] = '满' . $coupon['full_amount'] . "可用";
  133. //判断是折扣优惠券还是满减优惠券
  134. if($coupon['discount_type'] == 1){
  135. $coupon['discounts_text'] = '¥'.$coupon['discounts'];
  136. }elseif($coupon['discount_type'] == 2){
  137. $coupon['discounts_text'] = floatval($coupon['discounts'])."";
  138. }
  139. //拼接时间文字提示
  140. $coupon['time_text'] = date("Y-m-d H:i:s",$coupon['usable_start_time']). ' - ' .date("Y-m-d H:i:s",$coupon['usable_end_time']);
  141. }
  142. return ['has_more_pages' => $paginate->hasMorePages(), 'list' => $couponList['data']];
  143. }
  144. /**
  145. * 获取用户当前线上订单可以使用的优惠券
  146. * 1、所有未过期额优惠券,并且满足订单的金额要求
  147. * 2、筛选出其中当日使用过的优惠券
  148. * 3、筛选出其中活动商品不可用的优惠券(订单中有活动商品且活动商品不可使用优惠券)
  149. * 4、筛选出其中活动商品可用但商品的活动类型不符合优惠券活动使用类型的要求(订单中有活动商品可以用优惠券,但是活动类型type和优惠券中的available活动类型不可用)
  150. * @param $userId
  151. * @param $marketId
  152. */
  153. public function allForOnlineOrderAvailable($userId, $marketId)
  154. {
  155. // 获取购物车数据
  156. $carts = $this->shopCartService->allForUser($userId, $marketId);
  157. $totalAmount = $carts['total'];
  158. // 获取购物车中商品和店铺的类别
  159. $storeCategoryIds = []; // 商户类型
  160. $goodsCategoryIds = []; // 商品类型
  161. $hasActivityGoodsCannotUse = false; // 购物车中是否有不可使用优惠券的活动商品
  162. $goodsActivityTypes = []; // 活动商品的类型集合
  163. foreach ($carts['store_lists'] as $key => &$cart) {
  164. // 商户类型
  165. if (isset($cart['store']['category_id']) && $cart['store']['category_id']) {
  166. array_push($storeCategoryIds, $cart['store']['category_id']);
  167. }
  168. if (isset($cart['shopping_cart']) && is_array($cart['shopping_cart'])) {
  169. foreach ($cart['shopping_cart'] as $key2 => &$goods) {
  170. // 商品类型
  171. if (isset($goods['goods']['category_id']) && $goods['goods']['category_id']) {
  172. array_push($goodsCategoryIds, $goods['goods']['category_id']);
  173. }
  174. // 活动商品不可使用优惠券的情况
  175. if ($goods['activity_type'] == 2 && $goods['goods']['can_use_coupon'] != 1) {
  176. $hasActivityGoodsCannotUse = true;
  177. }
  178. // 活动商品类型集合
  179. if ($goods['activity_type'] == 2) {
  180. array_merge($goodsActivityTypes, [$goods['goods']['type']]);
  181. }
  182. }
  183. }
  184. }
  185. $categoryIds = array_merge($storeCategoryIds, $goodsCategoryIds);
  186. $coupon = ApplicationContext::getContainer()->get(Coupon::class);
  187. $couponRec = ApplicationContext::getContainer()->get(CouponRec::class);
  188. $couponTable = $coupon->getTable();
  189. $receiveTable = $couponRec->getTable();
  190. $currentTime = time();
  191. // 获取用户已领取的优惠券,同时是在使用期内的优惠券
  192. $builder = $couponRec->with('coupon')
  193. ->select("{$receiveTable}.*")
  194. ->join($couponTable, "{$couponTable}.id", "=", "{$receiveTable}.coupon_id")
  195. ->where("{$receiveTable}.user_id", $userId)
  196. ->where("{$receiveTable}.number_remain", ">", 0)
  197. ->whereIn("{$receiveTable}.status", [0,1])
  198. ->where("{$couponTable}.usable_start_time", "<=", $currentTime)
  199. ->where("{$couponTable}.usable_end_time", ">=", $currentTime);
  200. if (!empty($marketId)) { # 市场限制
  201. $builder->where(function ($query) use ($marketId, $couponTable) {
  202. return $query->whereJsonContains("{$couponTable}.market_ids", [(string)$marketId])
  203. ->orWhereJsonLength("{$couponTable}.market_ids", '=', 0);
  204. });
  205. }
  206. if (!empty($categoryIds)) { # 分类限制
  207. $builder->where(function ($query) use ($categoryIds, $couponTable) {
  208. return $query->whereJsonContains("{$couponTable}.category_ids", $categoryIds)
  209. ->orWhereJsonLength("{$couponTable}.category_ids", '=', 0);
  210. });
  211. }
  212. $couponReceives = $builder->orderByRaw("{$couponTable}.usable_end_time ASC")->get();
  213. $available = [];
  214. $notAvailable = [];
  215. // 有活动商品不可用优惠券,全部都不可用了
  216. if ($hasActivityGoodsCannotUse) {
  217. $notAvailable = $couponReceives;
  218. foreach ($notAvailable as $key => &$item) {
  219. $item['not_available_reason'] = '活动不可用';
  220. }
  221. $couponReceives = [];
  222. }
  223. // 循环摘出失效不可用的优惠券
  224. foreach ($couponReceives as $key => &$item) {
  225. // 不满订单金额
  226. if ($item['coupon']['full_amount'] > $totalAmount) {
  227. $item['not_available_reason'] = '差'.bcsub($item['coupon']['full_amount'], $totalAmount, 2).'元';
  228. array_push($notAvailable, $item);
  229. continue;
  230. }
  231. // 今日已使用
  232. $todayUsedCouponIds = $this->couponService->allTodayCouponUsed($userId);
  233. if (in_array($item['coupon']['id'], $todayUsedCouponIds)) {
  234. $item['not_available_reason'] = '今日已使用';
  235. array_push($notAvailable, $item);
  236. continue;
  237. }
  238. // 活动商品可用,校验对应的优惠券可使用活动类型
  239. $intersects = array_intersect($goodsActivityTypes, (array)$item['activity_available']); # 所有活动商品的活动类型和优惠券的可用活动类型求交集
  240. $canUseByTypes = array_diff($goodsActivityTypes, $intersects); # 所有活动商品的活动类型和上述交集求差集,如果为空则是可以用的,否则说明前者中有后者不能用的活动类型
  241. if (!empty($canUseByTypes)) {
  242. $item['not_available_reason'] = '活动不可用';
  243. array_push($notAvailable, $item);
  244. continue;
  245. }
  246. $item['not_available_reason'] = '';
  247. array_push($available, $item);
  248. }
  249. return ['available' => $available, 'not_available' => $notAvailable];
  250. }
  251. /**
  252. * @param $userId
  253. * @return mixed
  254. */
  255. public function statistics($userId)
  256. {
  257. //未使用
  258. $res['unused'] = 0;
  259. //已使用
  260. $res['used'] = 0;
  261. //已过期
  262. $res['expired'] = 0;
  263. $coupons = CouponRec::query()
  264. ->with('coupon')
  265. ->where('user_id',$userId)
  266. ->get();
  267. foreach ($coupons as $coupon){
  268. if($coupon->coupon->usable_end_time < time() || $coupon->coupon->status != 1){
  269. $res['expired'] += $coupon->number_remain;
  270. }else{
  271. $res['unused'] += $coupon->number_remain;
  272. }
  273. $res['used'] += $coupon->used_num;
  274. }
  275. return $res;
  276. }
  277. }