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.

285 lines
11 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
  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. ])
  102. ->whereIn('lanzu_coupon_receive.status',[0,1]);
  103. break;
  104. case 'used':
  105. $builder = $builder->whereIn('lanzu_coupon_receive.status',[1,2]);
  106. break;
  107. case 'expired':
  108. $builder = $builder->where(function ($query) {
  109. $query->where('lanzu_coupon.usable_end_time', '<', time())
  110. ->orWhere('lanzu_coupon.status', '<>', 1);
  111. });
  112. break;
  113. }
  114. $builder = $builder->select(
  115. 'lanzu_coupon.title',
  116. 'lanzu_coupon.discounts',
  117. 'lanzu_coupon.full_amount',
  118. 'lanzu_coupon.discount_type',
  119. 'lanzu_coupon.introduce',
  120. 'lanzu_coupon.usable_start_time',
  121. 'lanzu_coupon.usable_end_time',
  122. 'lanzu_coupon_receive.number',
  123. 'lanzu_coupon_receive.number_remain'
  124. )
  125. ->orderBy('lanzu_coupon.weigh','desc');
  126. $paginate = $builder->paginate($pagesize);
  127. $couponList = $paginate->toArray();
  128. foreach ($couponList['data'] as $key => &$coupon) {
  129. //拼接满减文字提示
  130. $coupon['full_amount_text'] = '满' . $coupon['full_amount'] . "可用";
  131. //判断是折扣优惠券还是满减优惠券
  132. if($coupon['discount_type'] == 1){
  133. $coupon['discounts_text'] = '¥'.$coupon['discounts'];
  134. }elseif($coupon['discount_type'] == 2){
  135. $coupon['discounts_text'] = floatval($coupon['discounts'])."";
  136. }
  137. //拼接时间文字提示
  138. $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']);
  139. }
  140. return ['has_more_pages' => $paginate->hasMorePages(), 'coupon_list' => $couponList['data']];
  141. }
  142. /**
  143. * 获取用户当前线上订单可以使用的优惠券
  144. * 1、所有未过期额优惠券,并且满足订单的金额要求
  145. * 2、筛选出其中当日使用过的优惠券
  146. * 3、筛选出其中活动商品不可用的优惠券(订单中有活动商品且活动商品不可使用优惠券)
  147. * 4、筛选出其中活动商品可用但商品的活动类型不符合优惠券活动使用类型的要求(订单中有活动商品可以用优惠券,但是活动类型type和优惠券中的available活动类型不可用)
  148. * @param $userId
  149. * @param $marketId
  150. */
  151. public function allForOnlineOrderAvailable($userId, $marketId)
  152. {
  153. // 获取购物车数据
  154. $carts = $this->shopCartService->allForUser($userId, $marketId);
  155. $totalAmount = $carts['total'];
  156. // 获取购物车中商品和店铺的类别
  157. $storeCategoryIds = []; // 商户类型
  158. $goodsCategoryIds = []; // 商品类型
  159. $hasActivityGoodsCannotUse = false; // 购物车中是否有不可使用优惠券的活动商品
  160. $goodsActivityTypes = []; // 活动商品的类型集合
  161. foreach ($carts['store_lists'] as $key => &$cart) {
  162. // 商户类型
  163. if (isset($cart['store']['category_id']) && $cart['store']['category_id']) {
  164. array_push($storeCategoryIds, $cart['store']['category_id']);
  165. }
  166. if (isset($cart['shopping_cart']) && is_array($cart['shopping_cart'])) {
  167. foreach ($cart['shopping_cart'] as $key2 => &$goods) {
  168. // 商品类型
  169. if (isset($goods['goods']['category_id']) && $goods['goods']['category_id']) {
  170. array_push($goodsCategoryIds, $goods['goods']['category_id']);
  171. }
  172. // 活动商品不可使用优惠券的情况
  173. if ($goods['activity_type'] == 2 && $goods['goods']['can_use_coupon'] != 1) {
  174. $hasActivityGoodsCannotUse = true;
  175. }
  176. // 活动商品类型集合
  177. if ($goods['activity_type'] == 2) {
  178. array_merge($goodsActivityTypes, [$goods['goods']['type']]);
  179. }
  180. }
  181. }
  182. }
  183. $categoryIds = array_merge($storeCategoryIds, $goodsCategoryIds);
  184. $coupon = ApplicationContext::getContainer()->get(Coupon::class);
  185. $couponRec = ApplicationContext::getContainer()->get(CouponRec::class);
  186. $couponTable = $coupon->getTable();
  187. $receiveTable = $couponRec->getTable();
  188. $currentTime = time();
  189. // 获取用户已领取的优惠券,同时是在使用期内的优惠券
  190. $builder = $couponRec->with('coupon')
  191. ->select("{$receiveTable}.*")
  192. ->join($couponTable, "{$couponTable}.id", "=", "{$receiveTable}.coupon_id")
  193. ->where("{$receiveTable}.user_id", $userId)
  194. ->where("{$receiveTable}.number_remain", ">", 0)
  195. ->whereIn("{$receiveTable}.status", [0,1])
  196. ->where("{$couponTable}.usable_start_time", "<=", $currentTime)
  197. ->where("{$couponTable}.usable_end_time", ">=", $currentTime);
  198. if (!empty($marketId)) { # 市场限制
  199. $builder->where(function ($query) use ($marketId, $couponTable) {
  200. return $query->whereJsonContains("{$couponTable}.market_ids", [(string)$marketId])
  201. ->orWhereJsonLength("{$couponTable}.market_ids", '=', 0);
  202. });
  203. }
  204. if (!empty($categoryIds)) { # 分类限制
  205. $builder->where(function ($query) use ($categoryIds, $couponTable) {
  206. return $query->whereJsonContains("{$couponTable}.category_ids", $categoryIds)
  207. ->orWhereJsonLength("{$couponTable}.category_ids", '=', 0);
  208. });
  209. }
  210. $couponReceives = $builder->orderByRaw("{$couponTable}.usable_end_time ASC")->get();
  211. $available = [];
  212. $notAvailable = [];
  213. // 有活动商品不可用优惠券,全部都不可用了
  214. if ($hasActivityGoodsCannotUse) {
  215. $notAvailable = $couponReceives;
  216. foreach ($notAvailable as $key => &$item) {
  217. $item['not_available_reason'] = '活动不可用';
  218. }
  219. $couponReceives = [];
  220. }
  221. // 循环摘出失效不可用的优惠券
  222. foreach ($couponReceives as $key => &$item) {
  223. // 不满订单金额
  224. if ($item['coupon']['full_amount'] > $totalAmount) {
  225. $item['not_available_reason'] = '差'.bcsub($item['coupon']['full_amount'], $totalAmount, 2).'元';
  226. array_push($notAvailable, $item);
  227. continue;
  228. }
  229. // 今日已使用
  230. $todayUsedCouponIds = $this->couponService->allTodayCouponUsed($userId);
  231. if (in_array($item['coupon']['id'], $todayUsedCouponIds)) {
  232. $item['not_available_reason'] = '今日已使用';
  233. array_push($notAvailable, $item);
  234. continue;
  235. }
  236. // 活动商品可用,校验对应的优惠券可使用活动类型
  237. $intersects = array_intersect($goodsActivityTypes, $item['activity_available']); # 所有活动商品的活动类型和优惠券的可用活动类型求交集
  238. $canUseByTypes = array_diff($goodsActivityTypes, $intersects); # 所有活动商品的活动类型和上述交集求差集,如果为空则是可以用的,否则说明前者中有后者不能用的活动类型
  239. if (!empty($canUseByTypes)) {
  240. $item['not_available_reason'] = '活动不可用';
  241. array_push($notAvailable, $item);
  242. continue;
  243. }
  244. $item['not_available_reason'] = '';
  245. array_push($available, $item);
  246. }
  247. return ['available' => $available, 'not_available' => $notAvailable];
  248. }
  249. }