ShopService.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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\Models\ShopPurchaseLog;
  12. use Exception;
  13. use Illuminate\Database\Eloquent\Collection;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Support\Facades\Log;
  16. use UCore\Exception\LogicException;
  17. /**
  18. * 商店服务类
  19. *
  20. * 提供商店相关的服务,包括获取商品列表、购买商品等功能。
  21. * 该类是商店模块对外提供服务的主要入口,封装了商店操作的复杂逻辑。
  22. *
  23. * 所有方法均为静态方法,可直接通过类名调用。
  24. */
  25. class ShopService
  26. {
  27. /**
  28. * 获取商店商品列表
  29. *
  30. * @param array $filters 过滤条件
  31. * @return Collection 商品列表
  32. */
  33. public static function getShopItems(array $filters = []): Collection
  34. {
  35. $shopLogic = new ShopLogic();
  36. return $shopLogic->getShopItems($filters);
  37. }
  38. /**
  39. * 获取商店分类列表
  40. *
  41. * @param bool $onlyActive 是否只获取激活的分类
  42. * @return Collection 分类列表
  43. */
  44. public static function getShopCategories(bool $onlyActive = true): Collection
  45. {
  46. $shopLogic = new ShopLogic();
  47. return $shopLogic->getShopCategories($onlyActive);
  48. }
  49. /**
  50. * 获取商店分类树
  51. *
  52. * @param bool $onlyActive 是否只获取激活的分类
  53. * @return array 分类树
  54. */
  55. public static function getShopCategoryTree(bool $onlyActive = true): array
  56. {
  57. $shopLogic = new ShopLogic();
  58. return $shopLogic->getShopCategoryTree($onlyActive);
  59. }
  60. /**
  61. * 购买商品
  62. *
  63. * @param int $userId 用户ID
  64. * @param int $shopItemId 商品ID
  65. * @param int $quantity 购买数量
  66. * @param array $options 选项
  67. * @return array|bool 购买结果或失败标志
  68. */
  69. public static function buyShopItem(int $userId, int $shopItemId, int $quantity = 1, array $options = [])
  70. {
  71. try {
  72. // 获取商品信息
  73. $shopItem = ShopItem::findOrFail($shopItemId);
  74. // 检查购买限制
  75. $shopLogic = new ShopLogic();
  76. list($canBuy, $errorMessage) = $shopLogic->checkBuyLimit($userId, $shopItem, $quantity);
  77. if (!$canBuy) {
  78. throw new LogicException($errorMessage);
  79. }
  80. // 计算总价
  81. $totalPrice = $shopItem->price * $quantity;
  82. // 开始事务
  83. DB::beginTransaction();
  84. // 扣除用户货币
  85. $fundResult = FundUser::handle(
  86. $userId,
  87. $shopItem->currency_id,
  88. -$totalPrice,
  89. LOG_TYPE::TRADE,
  90. $shopItemId,
  91. "购买商品:{$shopItem->name} x {$quantity}"
  92. );
  93. if (is_string($fundResult)) {
  94. throw new LogicException("购买失败:" . $fundResult);
  95. }
  96. // 添加物品到用户背包
  97. $itemResult = ItemService::addItem(
  98. $userId,
  99. $shopItem->item_id,
  100. $quantity * $shopItem->item_quantity,
  101. [
  102. 'source_type' => 'shop_buy',
  103. 'source_id' => $shopItemId,
  104. 'details' => [
  105. 'shop_item_id' => $shopItemId,
  106. 'shop_item_name' => $shopItem->name,
  107. 'price' => $shopItem->price,
  108. 'quantity' => $quantity
  109. ]
  110. ]
  111. );
  112. // 记录购买记录
  113. $purchaseLog = $shopLogic->recordPurchase($userId, $shopItem, $quantity, $totalPrice);
  114. // 触发商品购买事件
  115. event(new ShopItemPurchased($userId, $shopItem, $quantity, $totalPrice, $purchaseLog->id));
  116. // 提交事务
  117. DB::commit();
  118. // 返回结果
  119. return [
  120. 'success' => true,
  121. 'shop_item' => [
  122. 'id' => $shopItem->id,
  123. 'name' => $shopItem->name,
  124. 'price' => $shopItem->price,
  125. 'currency_id' => $shopItem->currency_id
  126. ],
  127. 'item' => [
  128. 'id' => $shopItem->item_id,
  129. 'name' => $shopItem->item->name,
  130. 'quantity' => $quantity * $shopItem->item_quantity
  131. ],
  132. 'total_price' => $totalPrice,
  133. 'purchase_log_id' => $purchaseLog->id
  134. ];
  135. } catch (Exception $e) {
  136. // 回滚事务
  137. if (DB::transactionLevel() > 0) {
  138. DB::rollBack();
  139. }
  140. Log::error('购买商品失败', [
  141. 'user_id' => $userId,
  142. 'shop_item_id' => $shopItemId,
  143. 'quantity' => $quantity,
  144. 'error' => $e->getMessage(),
  145. 'trace' => $e->getTraceAsString()
  146. ]);
  147. return false;
  148. }
  149. }
  150. /**
  151. * 获取用户购买记录
  152. *
  153. * @param int $userId 用户ID
  154. * @param array $filters 过滤条件
  155. * @return Collection 购买记录
  156. */
  157. public static function getUserPurchaseHistory(int $userId, array $filters = []): Collection
  158. {
  159. $shopLogic = new ShopLogic();
  160. return $shopLogic->getUserPurchaseHistory($userId, $filters);
  161. }
  162. /**
  163. * 获取商品详情
  164. *
  165. * @param int $shopItemId 商品ID
  166. * @return ShopItem|null 商品详情
  167. */
  168. public static function getShopItemDetail(int $shopItemId): ?ShopItem
  169. {
  170. return ShopItem::with(['item', 'category', 'promotions'])->find($shopItemId);
  171. }
  172. /**
  173. * 获取促销活动列表
  174. *
  175. * @param array $filters 过滤条件
  176. * @return Collection 促销活动列表
  177. */
  178. public static function getPromotions(array $filters = []): Collection
  179. {
  180. $shopLogic = new ShopLogic();
  181. return $shopLogic->getPromotions($filters);
  182. }
  183. /**
  184. * 获取促销活动详情
  185. *
  186. * @param int $promotionId 促销活动ID
  187. * @return ShopPromotion|null 促销活动详情
  188. */
  189. public static function getPromotionDetail(int $promotionId): ?ShopPromotion
  190. {
  191. $shopLogic = new ShopLogic();
  192. return $shopLogic->getPromotionDetail($promotionId);
  193. }
  194. /**
  195. * 添加商品到促销活动
  196. *
  197. * @param int $promotionId 促销活动ID
  198. * @param int $shopItemId 商品ID
  199. * @param int|null $customDiscountValue 自定义折扣值
  200. * @return ShopPromotionItem 促销商品关联
  201. */
  202. public static function addItemToPromotion(int $promotionId, int $shopItemId, ?int $customDiscountValue = null): ShopPromotionItem
  203. {
  204. $shopLogic = new ShopLogic();
  205. return $shopLogic->addItemToPromotion($promotionId, $shopItemId, $customDiscountValue);
  206. }
  207. /**
  208. * 从促销活动中移除商品
  209. *
  210. * @param int $promotionId 促销活动ID
  211. * @param int $shopItemId 商品ID
  212. * @return bool 是否成功
  213. */
  214. public static function removeItemFromPromotion(int $promotionId, int $shopItemId): bool
  215. {
  216. $shopLogic = new ShopLogic();
  217. return $shopLogic->removeItemFromPromotion($promotionId, $shopItemId);
  218. }
  219. /**
  220. * 获取商品的折扣价格
  221. *
  222. * @param int $shopItemId 商品ID
  223. * @return array 价格信息
  224. */
  225. public static function getItemPriceInfo(int $shopItemId): array
  226. {
  227. $shopItem = ShopItem::findOrFail($shopItemId);
  228. $originalPrice = $shopItem->price;
  229. $discountedPrice = $shopItem->getDiscountedPrice();
  230. $promotion = $shopItem->getActivePromotion();
  231. return [
  232. 'original_price' => $originalPrice,
  233. 'discounted_price' => $discountedPrice,
  234. 'has_discount' => $discountedPrice < $originalPrice,
  235. 'discount_percentage' => $originalPrice > 0 ? round((1 - $discountedPrice / $originalPrice) * 100) : 0,
  236. 'promotion' => $promotion ? [
  237. 'id' => $promotion->id,
  238. 'name' => $promotion->name,
  239. 'discount_type' => $promotion->discount_type,
  240. 'discount_value' => $promotion->discount_value,
  241. 'end_time' => $promotion->end_time ? $promotion->end_time->toDateTimeString() : null
  242. ] : null
  243. ];
  244. }
  245. }