ShopService.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. <?php
  2. namespace App\Module\Shop\Services;
  3. use App\Module\Fund\Enums\LOG_TYPE;
  4. use App\Module\Fund\Logic\User as FundUser;
  5. use App\Module\GameItems\Services\ItemService;
  6. use App\Module\Shop\Events\ShopItemPurchased;
  7. use App\Module\Shop\Logics\ShopLogic;
  8. use App\Module\Shop\Models\ShopItem;
  9. use App\Module\Shop\Models\ShopPromotion;
  10. use App\Module\Shop\Models\ShopPromotionItem;
  11. use App\Module\Shop\Dtos\ShopItemDto;
  12. use App\Module\Shop\Dtos\ShopCategoryDto;
  13. use Exception;
  14. use Illuminate\Database\Eloquent\Collection;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Support\Facades\Log;
  17. use UCore\Exception\LogicException;
  18. /**
  19. * 商店服务类
  20. *
  21. * 提供商店相关的服务,包括获取商品列表、购买商品等功能。
  22. * 该类是商店模块对外提供服务的主要入口,封装了商店操作的复杂逻辑。
  23. *
  24. * 所有方法均为静态方法,可直接通过类名调用。
  25. */
  26. class ShopService
  27. {
  28. /**
  29. * 获取商店商品列表
  30. *
  31. * @param array $filters 过滤条件
  32. * @param int|null $userId 用户ID(可选,用于获取用户购买数量)
  33. * @return array ShopItemDto数组
  34. */
  35. public static function getShopItems(array $filters = [], ?int $userId = null): array
  36. {
  37. $shopLogic = new ShopLogic();
  38. $shopItems = $shopLogic->getShopItems($filters);
  39. // 批量获取用户购买数量,避免N+1查询
  40. $userBoughtCounts = [];
  41. if ($userId !== null && $shopItems->isNotEmpty()) {
  42. $shopItemIds = $shopItems->pluck('id')->toArray();
  43. $userBoughtCounts = \App\Module\Shop\Models\ShopPurchaseLog::where('user_id', $userId)
  44. ->whereIn('shop_item_id', $shopItemIds)
  45. ->groupBy('shop_item_id')
  46. ->selectRaw('shop_item_id, SUM(quantity) as total_quantity')
  47. ->pluck('total_quantity', 'shop_item_id')
  48. ->toArray();
  49. }
  50. // 将模型集合转换为DTO数组
  51. return $shopItems->map(function ($shopItem) use ($userId, $userBoughtCounts) {
  52. return ShopItemDto::fromModelOptimized($shopItem, $userId, $userBoughtCounts);
  53. })->values()->all();
  54. }
  55. /**
  56. * 获取商店分类列表
  57. *
  58. * @param bool $onlyActive 是否只获取激活的分类
  59. * @return array ShopCategoryDto数组
  60. */
  61. public static function getShopCategories(bool $onlyActive = true): array
  62. {
  63. $shopLogic = new ShopLogic();
  64. $categories = $shopLogic->getShopCategories($onlyActive);
  65. // 将模型集合转换为DTO数组
  66. return $categories->map(function ($category) {
  67. return ShopCategoryDto::fromModel($category);
  68. })->values()->all();
  69. }
  70. /**
  71. * 获取商店分类树
  72. *
  73. * @param bool $onlyActive 是否只获取激活的分类
  74. * @return array 分类树
  75. */
  76. public static function getShopCategoryTree(bool $onlyActive = true): array
  77. {
  78. $shopLogic = new ShopLogic();
  79. return $shopLogic->getShopCategoryTree($onlyActive);
  80. }
  81. /**
  82. * 购买商品
  83. * 注意:由于商品结构变更,此方法需要根据消耗组和奖励组重新实现
  84. *
  85. * @param int $userId 用户ID
  86. * @param int $shopItemId 商品ID
  87. * @param int $quantity 购买数量
  88. * @param array $options 选项
  89. * @return array|bool 购买结果或失败标志
  90. */
  91. public static function buyShopItem(int $userId, int $shopItemId, int $quantity = 1, array $options = [])
  92. {
  93. try {
  94. // 获取商品信息
  95. $shopItem = ShopItem::with(['consumeGroup', 'rewardGroup'])->findOrFail($shopItemId);
  96. // 检查购买限制
  97. $shopLogic = new ShopLogic();
  98. list($canBuy, $errorMessage) = $shopLogic->checkBuyLimit($userId, $shopItem, $quantity);
  99. if (!$canBuy) {
  100. throw new LogicException($errorMessage);
  101. }
  102. // 开始事务
  103. DB::beginTransaction();
  104. // TODO: 实现消耗组逻辑 - 扣除用户资源
  105. if ($shopItem->consumeGroup) {
  106. // 这里需要实现消耗组的扣除逻辑
  107. // $consumeResult = ConsumeService::consume($userId, $shopItem->consume_group_id, $quantity);
  108. // if (!$consumeResult) {
  109. // throw new LogicException("资源不足");
  110. // }
  111. }
  112. // TODO: 实现奖励组逻辑 - 给予用户奖励
  113. $rewardResults = [];
  114. if ($shopItem->rewardGroup) {
  115. // 这里需要实现奖励组的发放逻辑
  116. // $rewardResults = RewardService::giveReward($userId, $shopItem->reward_group_id, $quantity);
  117. }
  118. // 记录购买记录
  119. $purchaseLog = $shopLogic->recordPurchase($userId, $shopItem, $quantity, 0); // 总价暂时为0
  120. // 触发商品购买事件
  121. event(new ShopItemPurchased($userId, $shopItem, $quantity, 0, $purchaseLog->id));
  122. // 提交事务
  123. DB::commit();
  124. // 返回结果
  125. return [
  126. 'success' => true,
  127. 'shop_item' => [
  128. 'id' => $shopItem->id,
  129. 'name' => $shopItem->name,
  130. 'consume_group' => $shopItem->consumeGroup ? $shopItem->consumeGroup->name : null,
  131. 'reward_group' => $shopItem->rewardGroup ? $shopItem->rewardGroup->name : null
  132. ],
  133. 'rewards' => $rewardResults,
  134. 'purchase_log_id' => $purchaseLog->id
  135. ];
  136. } catch (Exception $e) {
  137. // 回滚事务
  138. if (DB::transactionLevel() > 0) {
  139. DB::rollBack();
  140. }
  141. Log::error('购买商品失败', [
  142. 'user_id' => $userId,
  143. 'shop_item_id' => $shopItemId,
  144. 'quantity' => $quantity,
  145. 'error' => $e->getMessage(),
  146. 'trace' => $e->getTraceAsString()
  147. ]);
  148. return false;
  149. }
  150. }
  151. /**
  152. * 获取用户购买记录
  153. *
  154. * @param int $userId 用户ID
  155. * @param array $filters 过滤条件
  156. * @return Collection 购买记录
  157. */
  158. public static function getUserPurchaseHistory(int $userId, array $filters = []): Collection
  159. {
  160. $shopLogic = new ShopLogic();
  161. return $shopLogic->getUserPurchaseHistory($userId, $filters);
  162. }
  163. /**
  164. * 获取商品详情
  165. *
  166. * @param int $shopItemId 商品ID
  167. * @param int|null $userId 用户ID(可选,用于获取用户购买数量)
  168. * @return ShopItemDto|null 商品详情DTO
  169. */
  170. public static function getShopItemDetail(int $shopItemId, ?int $userId = null): ?ShopItemDto
  171. {
  172. $shopItem = ShopItem::with(['category', 'consumeGroup', 'rewardGroup', 'promotions'])->find($shopItemId);
  173. if (!$shopItem) {
  174. return null;
  175. }
  176. return ShopItemDto::fromModel($shopItem, $userId);
  177. }
  178. /**
  179. * 获取促销活动列表
  180. *
  181. * @param array $filters 过滤条件
  182. * @return Collection 促销活动列表
  183. */
  184. public static function getPromotions(array $filters = []): Collection
  185. {
  186. $shopLogic = new ShopLogic();
  187. return $shopLogic->getPromotions($filters);
  188. }
  189. /**
  190. * 获取促销活动详情
  191. *
  192. * @param int $promotionId 促销活动ID
  193. * @return ShopPromotion|null 促销活动详情
  194. */
  195. public static function getPromotionDetail(int $promotionId): ?ShopPromotion
  196. {
  197. $shopLogic = new ShopLogic();
  198. return $shopLogic->getPromotionDetail($promotionId);
  199. }
  200. /**
  201. * 添加商品到促销活动
  202. *
  203. * @param int $promotionId 促销活动ID
  204. * @param int $shopItemId 商品ID
  205. * @param int|null $customDiscountValue 自定义折扣值
  206. * @return ShopPromotionItem 促销商品关联
  207. */
  208. public static function addItemToPromotion(int $promotionId, int $shopItemId, ?int $customDiscountValue = null): ShopPromotionItem
  209. {
  210. $shopLogic = new ShopLogic();
  211. return $shopLogic->addItemToPromotion($promotionId, $shopItemId, $customDiscountValue);
  212. }
  213. /**
  214. * 从促销活动中移除商品
  215. *
  216. * @param int $promotionId 促销活动ID
  217. * @param int $shopItemId 商品ID
  218. * @return bool 是否成功
  219. */
  220. public static function removeItemFromPromotion(int $promotionId, int $shopItemId): bool
  221. {
  222. $shopLogic = new ShopLogic();
  223. return $shopLogic->removeItemFromPromotion($promotionId, $shopItemId);
  224. }
  225. /**
  226. * 获取商品的价格信息
  227. * 注意:由于商品不再有固定价格,此方法需要根据消耗组重新实现
  228. *
  229. * @param int $shopItemId 商品ID
  230. * @return array 价格信息
  231. */
  232. public static function getItemPriceInfo(int $shopItemId): array
  233. {
  234. $shopItem = ShopItem::with(['consumeGroup', 'rewardGroup'])->findOrFail($shopItemId);
  235. $promotion = $shopItem->getActivePromotion();
  236. return [
  237. 'consume_group' => $shopItem->consumeGroup ? [
  238. 'id' => $shopItem->consumeGroup->id,
  239. 'name' => $shopItem->consumeGroup->name,
  240. 'description' => $shopItem->consumeGroup->description
  241. ] : null,
  242. 'reward_group' => $shopItem->rewardGroup ? [
  243. 'id' => $shopItem->rewardGroup->id,
  244. 'name' => $shopItem->rewardGroup->name,
  245. 'description' => $shopItem->rewardGroup->description
  246. ] : null,
  247. 'promotion' => $promotion ? [
  248. 'id' => $promotion->id,
  249. 'name' => $promotion->name,
  250. 'discount_type' => $promotion->discount_type,
  251. 'discount_value' => $promotion->discount_value,
  252. 'end_time' => $promotion->end_time ? $promotion->end_time->toDateTimeString() : null
  253. ] : null
  254. ];
  255. }
  256. }