DiscountService.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. <?php
  2. namespace app\common\Service;
  3. use think\Db;
  4. use think\Model;
  5. use app\common\Enum\StatusEnum;
  6. use app\common\Enum\ActivityEnum;
  7. use app\common\Enum\GoodsEnum;
  8. /**
  9. * 折扣活动服务类
  10. *
  11. * 外层折扣字段说明:
  12. * - has_discount: 是否有折扣活动
  13. * - discount_price: 折扣价格(单规格商品直接使用,多规格商品显示最低价)
  14. * - discount: 折扣率(单规格商品直接使用,多规格商品显示最低折扣)
  15. * - discount_amount: 折扣金额(原价-折扣价,仅单规格商品)
  16. * - min_discount_price: 最低折扣价格
  17. * - max_discount_price: 最高折扣价格
  18. * - min_discount: 最低折扣率
  19. * - max_discount: 最高折扣率
  20. * - price_range: 价格区间文本(如:¥99 或 ¥99-199)
  21. */
  22. class DiscountService
  23. {
  24. /**
  25. * 查询当前时间段内的商品折扣信息
  26. * @param array $goodsIds 商品ID数组,为空则查询所有参与折扣的商品
  27. * @param int $limit 限制数量
  28. * @return array
  29. */
  30. public static function getCurrentDiscountGoods($goodsIds = [], $limit = 0)
  31. {
  32. // 第一步:查询当前时间有效的活动ID
  33. $activeActivityIds = self::getActiveActivityIds();
  34. if (empty($activeActivityIds)) {
  35. return [];
  36. }
  37. // 第二步:查询这些活动的SKU数据
  38. $query = Db::table('shop_activity_sku')
  39. ->alias('sku')
  40. ->join('shop_goods goods', 'sku.goods_id = goods.id')
  41. ->join('shop_goods_sku spec', 'sku.sku_id = spec.id', 'left')
  42. ->join(['shop_activity'=> 'activity'], 'sku.activity_id = activity.id')
  43. ->where('sku.activity_id', 'in', $activeActivityIds)
  44. ->where('goods.status', GoodsEnum::STATUS_ON_SALE) // 已上架的商品
  45. ->where('sku.stocks', '>', 0) // 有折扣库存的商品
  46. ->field([
  47. 'goods.id as goods_id',
  48. 'goods.title',
  49. 'goods.sub_title',
  50. 'goods.image',
  51. 'goods.price as original_price',
  52. 'goods.market_price',
  53. 'goods.stocks as goods_stocks',
  54. 'goods.sales',
  55. 'goods.spec_type',
  56. 'sku.id as activity_sku_id',
  57. 'sku.sku_id',
  58. 'sku.discount',
  59. 'sku.discount_price',
  60. 'sku.stocks as discount_stocks',
  61. 'sku.sale_quantity',
  62. 'activity.id as activity_id',
  63. 'activity.name as activity_name',
  64. 'activity.start_time',
  65. 'activity.end_time',
  66. 'spec.price as sku_price',
  67. 'spec.image as sku_image',
  68. // 'spec.specs as sku_specs'
  69. ]);
  70. // 如果指定了商品ID,则添加条件
  71. if (!empty($goodsIds)) {
  72. $query->where('sku.goods_id', 'in', $goodsIds);
  73. }
  74. // 如果设置了限制数量
  75. if ($limit > 0) {
  76. $query->limit($limit);
  77. }
  78. // 按折扣力度排序,折扣越大越靠前
  79. $query->order('sku.discount', 'asc');
  80. $result = $query->select();
  81. // 处理返回数据
  82. $processedData = [];
  83. foreach ($result as $item) {
  84. $goodsId = $item['goods_id'];
  85. $skuId = $item['sku_id'];
  86. // 如果商品还没有在结果中,初始化
  87. if (!isset($processedData[$goodsId])) {
  88. $processedData[$goodsId] = self::initGoodsDiscountStructure($item);
  89. }
  90. // 添加折扣信息
  91. $discountInfo = [
  92. 'activity_sku_id' => $item['activity_sku_id'],
  93. 'sku_id' => $skuId,
  94. 'discount' => $item['discount'],
  95. 'discount_price' => $item['discount_price'],
  96. 'discount_stocks' => $item['discount_stocks'],
  97. 'sale_quantity' => $item['sale_quantity']
  98. ];
  99. // 如果是多规格商品,添加规格信息
  100. if ($skuId > 0) {
  101. $discountInfo['sku_price'] = $item['sku_price'];
  102. $discountInfo['sku_image'] = $item['sku_image'];
  103. // $discountInfo['sku_specs'] = $item['sku_specs'];
  104. }
  105. $processedData[$goodsId]['discount_info'][] = $discountInfo;
  106. }
  107. // 处理外层折扣价格字段
  108. $processedData = self::processGoodsDiscountData($processedData);
  109. return array_values($processedData);
  110. }
  111. /**
  112. * 限时查询一个当前活动的信息和商品信息 活动信息直接加一个商品数组字段
  113. * @param mixed $activityId
  114. * @return array|bool|Model|string|\PDOStatement|null
  115. */
  116. public static function getCurrentActivity()
  117. {
  118. $currentTime = time();
  119. // 查询活动信息
  120. $activity = Db::table('shop_activity')
  121. // ->where('id', $activityId)
  122. ->where('start_time', '<=', $currentTime)
  123. ->where('end_time', '>=', $currentTime)
  124. ->where('activity_status', ActivityEnum::ACTIVITY_STATUS_ONGOING)
  125. ->where('status', StatusEnum::ENABLED)
  126. ->find();
  127. if (!$activity) {
  128. return null;
  129. }
  130. // 查询该活动下的商品信息
  131. $goods = Db::table('shop_activity_sku')
  132. ->alias('sku')
  133. ->join('shop_goods goods', 'sku.goods_id = goods.id')
  134. ->join('shop_goods_sku spec', 'sku.sku_id = spec.id', 'left')
  135. ->where('sku.activity_id', $activity['id'])
  136. ->where('goods.status', GoodsEnum::STATUS_ON_SALE)
  137. ->where('sku.stocks', '>', 0)
  138. ->field([
  139. 'goods.id as goods_id',
  140. 'goods.title',
  141. 'goods.sub_title',
  142. 'goods.image',
  143. 'goods.price as original_price',
  144. 'goods.market_price',
  145. 'goods.stocks as goods_stocks',
  146. 'goods.sales',
  147. 'goods.spec_type',
  148. 'sku.id as activity_sku_id',
  149. 'sku.sku_id',
  150. 'sku.discount',
  151. 'sku.discount_price',
  152. 'sku.stocks as discount_stocks',
  153. 'sku.sale_quantity',
  154. 'spec.price as sku_price',
  155. 'spec.image as sku_image'
  156. ])
  157. ->order('sku.discount', 'asc')
  158. ->select();
  159. // 处理商品数据
  160. $processedGoods = [];
  161. foreach ($goods as $item) {
  162. $goodsId = $item['goods_id'];
  163. if (!isset($processedGoods[$goodsId])) {
  164. $processedGoods[$goodsId] = self::initGoodsDiscountStructure($item);
  165. }
  166. $discountInfo = [
  167. 'activity_sku_id' => $item['activity_sku_id'],
  168. 'sku_id' => $item['sku_id'],
  169. 'discount' => $item['discount'],
  170. 'discount_price' => $item['discount_price'],
  171. 'discount_stocks' => $item['discount_stocks'],
  172. 'sale_quantity' => $item['sale_quantity']
  173. ];
  174. if ($item['sku_id'] > 0) {
  175. $discountInfo['sku_price'] = $item['sku_price'];
  176. $discountInfo['sku_image'] = $item['sku_image'];
  177. }
  178. $processedGoods[$goodsId]['discount_info'][] = $discountInfo;
  179. }
  180. // 处理外层折扣价格字段
  181. foreach ($processedGoods as &$goodsItem) {
  182. $discountPrices = [];
  183. $discounts = [];
  184. // 收集所有折扣价格和折扣率
  185. foreach ($goodsItem['discount_info'] as $discount) {
  186. $discountPrices[] = $discount['discount_price'];
  187. $discounts[] = $discount['discount'];
  188. }
  189. if (!empty($discountPrices)) {
  190. // 计算最低和最高折扣价格
  191. $goodsItem['min_discount_price'] = min($discountPrices);
  192. $goodsItem['max_discount_price'] = max($discountPrices);
  193. $goodsItem['min_discount'] = min($discounts);
  194. $goodsItem['max_discount'] = max($discounts);
  195. // 单规格商品处理
  196. if ($goodsItem['spec_type'] == 0) {
  197. $goodsItem['discount_price'] = $goodsItem['min_discount_price'];
  198. $goodsItem['discount'] = $goodsItem['min_discount'];
  199. $goodsItem['discount_amount'] = round($goodsItem['original_price'] - $goodsItem['discount_price'], 2);
  200. $goodsItem['price_range'] = '¥' . $goodsItem['discount_price'];
  201. }
  202. // 多规格商品处理
  203. else {
  204. // 设置价格区间
  205. if ($goodsItem['min_discount_price'] == $goodsItem['max_discount_price']) {
  206. $goodsItem['price_range'] = '¥' . $goodsItem['min_discount_price'];
  207. } else {
  208. $goodsItem['price_range'] = '¥' . $goodsItem['min_discount_price'] . '-' . $goodsItem['max_discount_price'];
  209. }
  210. // 对于多规格,使用最低价格作为主要显示价格
  211. $goodsItem['discount_price'] = $goodsItem['min_discount_price'];
  212. $goodsItem['discount'] = $goodsItem['min_discount'];
  213. }
  214. }
  215. }
  216. // 在活动信息中添加商品数组字段
  217. $activity['goods'] = array_values($processedGoods);
  218. return $activity;
  219. }
  220. // 限时zhe'kou一个当前活动的信息和商品信息 活动信息直接加一个商品数组字段
  221. public static function getCurrentActivityInfoAndPrize($activityId)
  222. {
  223. $activity = Db::table('shop_activity')->where('id', $activityId)->find();
  224. $prize = Db::table('shop_activity_sku_prize')->where('activity_id', $activityId)->find();
  225. return ['activity' => $activity, 'prize' => $prize];
  226. }
  227. /**
  228. * 根据商品ID和SKU ID获取折扣信息
  229. * @param int $goodsId 商品ID
  230. * @param int $skuId SKU ID,单规格商品传0
  231. * @return array|null
  232. */
  233. public static function getGoodsDiscountInfo($goodsId, $skuId = 0)
  234. {
  235. $currentTime = time();
  236. // 第一步:查询当前时间有效的活动ID
  237. $activeActivityIds = Db::table('shop_activity')
  238. ->where('start_time', '<=', $currentTime)
  239. ->where('end_time', '>=', $currentTime)
  240. ->where('activity_status', ActivityEnum::ACTIVITY_STATUS_ONGOING)
  241. ->where('status', 'normal')
  242. ->column('id');
  243. if (empty($activeActivityIds)) {
  244. return null;
  245. }
  246. // 第二步:查询指定商品的折扣信息
  247. $discountInfo = Db::table('shop_activity_sku_prize')
  248. ->alias('sku')
  249. ->join('shop_activity activity', 'sku.activity_id = activity.id')
  250. ->where('sku.goods_id', $goodsId)
  251. ->where('sku.sku_id', $skuId)
  252. ->where('sku.activity_id', 'in', $activeActivityIds)
  253. ->where('sku.status', 1)
  254. ->where('sku.stocks', '>', 0)
  255. ->field([
  256. 'sku.id as activity_sku_id',
  257. 'sku.discount',
  258. 'sku.discount_price',
  259. 'sku.stocks as discount_stocks',
  260. 'sku.sale_quantity',
  261. 'activity.id as activity_id',
  262. 'activity.name as activity_name',
  263. 'activity.start_time',
  264. 'activity.end_time'
  265. ])
  266. ->find();
  267. return $discountInfo ?: null;
  268. }
  269. /**
  270. * 批量获取商品的折扣信息
  271. * @param array $goodsIds 商品ID数组
  272. * @return array 键为商品ID,值为折扣信息数组
  273. */
  274. public static function getBatchGoodsDiscountInfo($goodsIds)
  275. {
  276. if (empty($goodsIds)) {
  277. return [];
  278. }
  279. $currentTime = time();
  280. // 第一步:查询当前时间有效的活动ID
  281. $activeActivityIds = Db::table('shop_activity')
  282. ->where('start_time', '<=', $currentTime)
  283. ->where('end_time', '>=', $currentTime)
  284. ->where('activity_status', ActivityEnum::ACTIVITY_STATUS_ONGOING)
  285. ->where('status', 'normal')
  286. ->column('id');
  287. if (empty($activeActivityIds)) {
  288. return [];
  289. }
  290. // 第二步:查询指定商品的折扣信息
  291. $result = Db::table('shop_activity_sku_prize')
  292. ->alias('sku')
  293. ->join('shop_activity activity', 'sku.activity_id = activity.id')
  294. ->where('sku.goods_id', 'in', $goodsIds)
  295. ->where('sku.activity_id', 'in', $activeActivityIds)
  296. ->where('sku.status', 1)
  297. ->where('sku.stocks', '>', 0)
  298. ->field([
  299. 'sku.goods_id',
  300. 'sku.sku_id',
  301. 'sku.id as activity_sku_id',
  302. 'sku.discount',
  303. 'sku.discount_price',
  304. 'sku.stocks as discount_stocks',
  305. 'sku.sale_quantity',
  306. 'activity.id as activity_id',
  307. 'activity.name as activity_name'
  308. ])
  309. ->order('sku.discount', 'asc')
  310. ->select();
  311. // 按商品ID分组
  312. $discountData = [];
  313. foreach ($result as $item) {
  314. $goodsId = $item['goods_id'];
  315. if (!isset($discountData[$goodsId])) {
  316. $discountData[$goodsId] = [];
  317. }
  318. $discountData[$goodsId][] = $item;
  319. }
  320. return $discountData;
  321. }
  322. /**
  323. * 检查商品是否参与当前折扣活动
  324. * @param int $goodsId 商品ID
  325. * @param int $skuId SKU ID
  326. * @return bool
  327. */
  328. public static function hasActiveDiscount($goodsId, $skuId = 0)
  329. {
  330. $discountInfo = self::getGoodsDiscountInfo($goodsId, $skuId);
  331. return !empty($discountInfo);
  332. }
  333. /**
  334. * 计算折扣后的价格
  335. * @param float $originalPrice 原价
  336. * @param float $discount 折扣(如9.0表示9折)
  337. * @return float
  338. */
  339. public static function calculateDiscountPrice($originalPrice, $discount)
  340. {
  341. return round($originalPrice * $discount / 10, 2);
  342. }
  343. /**
  344. * 获取活动剩余时间(秒)
  345. * @param int $endTime 活动结束时间戳
  346. * @return int
  347. */
  348. public static function getActivityRemainingTime($endTime)
  349. {
  350. return max(0, $endTime - time());
  351. }
  352. /**
  353. * 格式化活动剩余时间
  354. * @param int $endTime 活动结束时间戳
  355. * @return array
  356. */
  357. public static function formatRemainingTime($endTime)
  358. {
  359. $remaining = self::getActivityRemainingTime($endTime);
  360. if ($remaining <= 0) {
  361. return ['days' => 0, 'hours' => 0, 'minutes' => 0, 'seconds' => 0];
  362. }
  363. $days = floor($remaining / 86400);
  364. $hours = floor(($remaining % 86400) / 3600);
  365. $minutes = floor(($remaining % 3600) / 60);
  366. $seconds = $remaining % 60;
  367. return [
  368. 'days' => $days,
  369. 'hours' => $hours,
  370. 'minutes' => $minutes,
  371. 'seconds' => $seconds
  372. ];
  373. }
  374. /**
  375. * 处理商品的折扣价格信息(公共方法)
  376. * @param array $goodsData 商品数据数组
  377. * @return array 处理后的商品数据
  378. */
  379. private static function processGoodsDiscountData($goodsData)
  380. {
  381. foreach ($goodsData as &$goods) {
  382. $discountPrices = [];
  383. $discounts = [];
  384. // 收集所有折扣价格和折扣率
  385. foreach ($goods['discount_info'] as $discount) {
  386. $discountPrices[] = $discount['discount_price'];
  387. $discounts[] = $discount['discount'];
  388. }
  389. if (!empty($discountPrices)) {
  390. // 计算最低和最高折扣价格
  391. $goods['min_discount_price'] = min($discountPrices);
  392. $goods['max_discount_price'] = max($discountPrices);
  393. $goods['min_discount'] = min($discounts);
  394. $goods['max_discount'] = max($discounts);
  395. // 单规格商品处理
  396. if ($goods['spec_type'] == 0) {
  397. $goods['discount_price'] = $goods['min_discount_price'];
  398. $goods['discount'] = $goods['min_discount'];
  399. $goods['discount_amount'] = round($goods['original_price'] - $goods['discount_price'], 2);
  400. $goods['price_range'] = '¥' . $goods['discount_price'];
  401. }
  402. // 多规格商品处理
  403. else {
  404. // 设置价格区间
  405. if ($goods['min_discount_price'] == $goods['max_discount_price']) {
  406. $goods['price_range'] = '¥' . $goods['min_discount_price'];
  407. } else {
  408. $goods['price_range'] = '¥' . $goods['min_discount_price'] . '-' . $goods['max_discount_price'];
  409. }
  410. // 对于多规格,使用最低价格作为主要显示价格
  411. $goods['discount_price'] = $goods['min_discount_price'];
  412. $goods['discount'] = $goods['min_discount'];
  413. }
  414. }
  415. }
  416. return $goodsData;
  417. }
  418. /**
  419. * 获取当前有效的活动ID列表
  420. * @return array
  421. */
  422. private static function getActiveActivityIds()
  423. {
  424. $currentTime = time();
  425. return Db::table('shop_activity')
  426. ->where('start_time', '<=', $currentTime)
  427. ->where('end_time', '>=', $currentTime)
  428. ->where('activity_status', ActivityEnum::ACTIVITY_STATUS_ONGOING)
  429. ->where('status', StatusEnum::ENABLED)
  430. ->column('id');
  431. }
  432. /**
  433. * 初始化商品折扣数据结构
  434. * @param array $item 商品数据
  435. * @return array
  436. */
  437. private static function initGoodsDiscountStructure($item)
  438. {
  439. return [
  440. 'goods_id' => $item['goods_id'],
  441. 'title' => $item['title'],
  442. 'sub_title' => $item['sub_title'],
  443. 'image' => $item['image'],
  444. 'original_price' => $item['original_price'],
  445. 'market_price' => $item['market_price'],
  446. 'goods_stocks' => $item['goods_stocks'],
  447. 'sales' => $item['sales'],
  448. 'spec_type' => $item['spec_type'],
  449. 'activity_id' => $item['activity_id'] ?? null,
  450. 'activity_name' => $item['activity_name'] ?? null,
  451. 'start_time' => $item['start_time'] ?? null,
  452. 'end_time' => $item['end_time'] ?? null,
  453. 'has_discount' => true,
  454. 'discount_info' => [],
  455. // 初始化折扣价格相关字段
  456. 'min_discount_price' => null,
  457. 'max_discount_price' => null,
  458. 'min_discount' => null,
  459. 'max_discount' => null,
  460. 'discount_price' => null,
  461. 'discount' => null,
  462. 'discount_amount' => null,
  463. 'price_range' => ''
  464. ];
  465. }
  466. }