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.

84 lines
2.7 KiB

  1. <?php
  2. namespace App\Service;
  3. use Hyperf\DbConnection\Db;
  4. use Hyperf\Redis\Redis;
  5. use Hyperf\Utils\ApplicationContext;
  6. class CouponService implements CoupnoServiceInterface
  7. {
  8. /**
  9. * @inheritDoc
  10. */
  11. public function getOrderCanUseCoupons($orderAmount, $marketId, $userId, $fields=[], $type = 1, $storeTypeIds = [0])
  12. {
  13. // 用户今日使用过的优惠券
  14. $redis = ApplicationContext::getContainer()->get(Redis::class);
  15. $couponTodayUsedIds = $redis->sMembers('coupon_'.date('Ymd').'_used_'.$userId);
  16. $currentTime = time();
  17. $builder = Db::table('ims_system_coupon_user_receive as receive')
  18. ->join('ims_system_coupon_user as coupon', 'coupon.id', '=', 'receive.system_coupon_user_id', 'inner');
  19. if (is_array($fields)&&!empty($fields)) {
  20. $builder->select([
  21. 'receive.id as receive_id',
  22. 'receive.user_id',
  23. 'receive.number_remain',
  24. 'coupon.id',
  25. 'coupon.title',
  26. 'coupon.full_amount',
  27. 'coupon.discounts',
  28. 'coupon.usable_start_time',
  29. 'coupon.usable_end_time',
  30. 'coupon.discount_type'
  31. ]);
  32. }
  33. if (is_array($couponTodayUsedIds)&&!empty($couponTodayUsedIds)) {
  34. $builder->whereNotIn('coupon.id', $couponTodayUsedIds);
  35. }
  36. return $builder->where(['receive.user_id' => $userId])
  37. ->whereIn('receive.status', [0,1])
  38. ->where('receive.number_remain', '>', 0)
  39. ->whereIn('coupon.type', [1,$type])
  40. ->where('coupon.full_amount', '<=', $orderAmount)
  41. ->where('coupon.usable_start_time', '<=', $currentTime)
  42. ->where('coupon.usable_end_time', '>=', $currentTime)
  43. ->where('coupon.usable_number', '<=', Db::raw('receive.number_remain'))
  44. ->where('coupon.market_id', 'in', [0, $marketId])
  45. ->whereIn('coupon.storetype_id', $storeTypeIds)
  46. ->orderByRaw('coupon.discounts DESC, coupon.full_amount DESC')
  47. ->get()
  48. ->toArray();
  49. }
  50. /**
  51. * 缓存优惠券今日使用情况
  52. * @param $userId
  53. * @param $couponId
  54. * @param $couponRecId
  55. * @return bool
  56. */
  57. function cacheTodayCouponUsed($userId, $couponId, $couponRecId)
  58. {
  59. $redis = ApplicationContext::getContainer()->get(Redis::class);
  60. $setRes = $redis->sAdd(
  61. 'coupon_'.date('Ymd').'_used_'.$userId,
  62. $couponId
  63. );
  64. $expireRes = $redis->expire(
  65. 'coupon_'.date('Ymd').'_used_'.$userId,
  66. strtotime(date('Y-m-d').' 23:59:59')-time()
  67. );
  68. return $setRes&&$expireRes;
  69. }
  70. }