| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402 |
- <?php
- namespace App\Module\Mex\Logic;
- use App\Module\Mex\Models\MexOrder;
- use App\Module\Mex\Models\MexPriceConfig;
- use App\Module\Mex\Enums\OrderType;
- use App\Module\Mex\Enums\OrderStatus;
- use App\Module\Mex\Events\OrderCreatedEvent;
- use App\Module\Fund\Enums\FUND_CURRENCY_TYPE;
- use App\Module\Mex\Logic\FundLogic;
- use App\Module\GameItems\Services\ItemService;
- use App\Module\GameItems\Enums\FREEZE_REASON_TYPE;
- use Illuminate\Support\Facades\DB;
- use UCore\Helper\Logger;
- /**
- * 农贸市场订单逻辑
- *
- * 处理订单相关的核心业务逻辑
- */
- class MexOrderLogic
- {
- /**
- * 创建卖出订单
- *
- * @param int $userId 用户ID
- * @param int $itemId 商品ID
- * @param int $quantity 数量
- * @param float $price 价格(信任Fund模块的数据处理)
- * @param FUND_CURRENCY_TYPE|null $currencyType 币种类型,默认使用钻石
- * @return array 操作结果
- */
- public static function createSellOrder(int $userId, int $itemId, int $quantity, float $price, ?FUND_CURRENCY_TYPE $currencyType = null): array
- {
- // 检查事务状态,确保调用者已开启事务
- \UCore\Db\Helper::check_tr();
- // 获取币种类型,默认使用钻石
- $currencyType = $currencyType ?? FundLogic::getDefaultCurrency();
- // 验证价格配置是否存在(不验证价格范围,挂单阶段无价格验证)
- $priceConfig = MexPriceConfig::where('item_id', $itemId)->where('is_enabled', true)->first();
- if (!$priceConfig) {
- return [ 'success' => false, 'message' => '商品未配置价格信息' ];
- }
- // 直接计算总金额,信任Fund模块的精度处理
- $totalAmount = bcmul($price, $quantity, 9);
- try {
- // 1. 验证用户是否有足够的物品
- $checkResult = ItemService::checkItemQuantity($userId, $itemId, $quantity);
- if (!$checkResult->success) {
- return [ 'success' => false, 'message' => $checkResult->message ];
- }
- // 2. 创建订单记录
- $order = MexOrder::create([
- 'user_id' => $userId,
- 'item_id' => $itemId,
- 'currency_type' => $currencyType->value,
- 'order_type' => OrderType::SELL,
- 'quantity' => $quantity,
- 'price' => $price,
- 'total_amount' => $totalAmount,
- 'status' => OrderStatus::PENDING,
- ]);
- // 3. 冻结用户物品
- $freezeResult = ItemService::freezeItem(
- $userId,
- $itemId,
- null, // 统一属性物品,不需要实例ID
- $quantity,
- "农贸市场卖出订单冻结,订单ID:{$order->id}",
- [
- 'reason_type' => FREEZE_REASON_TYPE::TRADE_ORDER->value,
- 'source_id' => $order->id,
- 'source_type' => 'mex_sell_order',
- ]
- );
- if (!$freezeResult['success']) {
- throw new \Exception('冻结物品失败:' . $freezeResult['message']);
- }
- // 4. 触发订单创建事件
- event(new OrderCreatedEvent($order));
- return [
- 'success' => true,
- 'order_id' => $order->id,
- 'freeze_log_id' => $freezeResult['freeze_log_id'] ?? null,
- 'message' => '卖出订单创建成功,等待撮合'
- ];
- } catch (\Exception $e) {
- return [ 'success' => false, 'message' => '创建订单失败:' . $e->getMessage() ];
- }
- }
- /**
- * 创建买入订单
- *
- * @param int $userId 用户ID
- * @param int $itemId 商品ID
- * @param int $quantity 数量
- * @param float $price 价格(信任Fund模块的数据处理)
- * @param FUND_CURRENCY_TYPE|null $currencyType 币种类型,默认使用钻石
- * @return array 操作结果
- */
- public static function createBuyOrder(int $userId, int $itemId, int $quantity, float $price, ?FUND_CURRENCY_TYPE $currencyType = null): array
- {
- // 检查事务状态,确保调用者已开启事务
- \UCore\Db\Helper::check_tr();
- // 获取币种类型,默认使用钻石
- $currencyType = $currencyType ?? FundLogic::getDefaultCurrency();
- // 验证价格配置是否存在(不验证价格范围和保护阈值,挂单阶段无价格验证)
- $priceConfig = MexPriceConfig::where('item_id', $itemId)->where('is_enabled', true)->first();
- if (!$priceConfig) {
- return [ 'success' => false, 'message' => '商品未配置价格信息' ];
- }
- // 直接计算总金额,信任Fund模块的精度处理
- $totalAmount = bcmul($price, $quantity, 9);
- Logger::debug(" create ");
- try {
- // 1. 创建订单记录
- $order = MexOrder::create([
- 'user_id' => $userId,
- 'item_id' => $itemId,
- 'currency_type' => $currencyType->value,
- 'order_type' => OrderType::BUY,
- 'quantity' => $quantity,
- 'price' => $price,
- 'total_amount' => $totalAmount,
- 'status' => OrderStatus::PENDING,
- 'frozen_amount' => $totalAmount,
- ]);
- // 2. 冻结用户资金
- $freezeResult = self::freezeOrderFunds($order);
- if (!$freezeResult['success']) {
- return [ 'success' => false, 'message' => '冻结资金失败:' . $freezeResult['message'] ];
- }
- // 触发订单创建事件
- event(new OrderCreatedEvent($order));
- return [
- 'success' => true,
- 'order_id' => $order->id,
- 'message' => '买入订单创建成功,等待撮合'
- ];
- } catch (\Exception $e) {
- return [ 'success' => false, 'message' => '创建订单失败:' . $e->getMessage() ];
- }
- }
- /**
- * 取消订单
- *
- * @param int $userId 用户ID
- * @param int $orderId 订单ID
- * @return array 操作结果
- */
- public static function cancelOrder(int $userId, int $orderId): array
- {
- // 检查事务状态,确保调用者已开启事务
- \UCore\Db\Helper::check_tr();
- $order = MexOrder::where('id', $orderId)->where('user_id', $userId)->first();
- if (!$order) {
- return [ 'success' => false, 'message' => '订单不存在' ];
- }
- if ($order->status !== OrderStatus::PENDING) {
- return [ 'success' => false, 'message' => '只能取消等待中的订单' ];
- }
- // 1. 更新订单状态为取消
- $order->update([ 'status' => OrderStatus::CANCELLED ]);
- // 2. 处理解冻逻辑
- if ($order->order_type === OrderType::SELL) {
- // 卖出订单:解冻物品
- $unfreezeResult = self::unfreezeOrderItems($order);
- if (!$unfreezeResult['success']) {
- return [ 'success' => false, 'message' => '解冻物品失败:' . $unfreezeResult['message'] ];
- }
- } elseif ($order->order_type === OrderType::BUY) {
- // 买入订单:解冻资金
- $unfreezeResult = self::unfreezeOrderFunds($order);
- if (!$unfreezeResult['success']) {
- return [ 'success' => false, 'message' => '解冻资金失败:' . $unfreezeResult['message'] ];
- }
- }
- return [ 'success' => true, 'message' => '订单已取消' ];
- }
- /**
- * 获取用户订单列表
- *
- * @param int $userId 用户ID
- * @param int $page 页码
- * @param int $pageSize 每页数量
- * @return array 订单列表
- */
- public static function getUserOrders(int $userId, int $page = 1, int $pageSize = 20, $itemId = null): array
- {
- $where['user_id'] = $userId;
- if ($itemId) {
- $where['item_id'] = $itemId;
- }
- $orders = MexOrder::where($where)
- ->orderBy('created_at', 'desc')
- ->paginate($pageSize, [ '*' ], 'page', $page);
- return [
- 'orders' => $orders->items(),
- 'total' => $orders->total(),
- 'page' => $page,
- 'page_size' => $pageSize,
- ];
- }
- /**
- * 获取订单详情
- *
- * @param int $userId 用户ID
- * @param int $orderId 订单ID
- * @return array|null 订单详情
- */
- public static function getOrderDetail(int $userId, int $orderId): ?array
- {
- $order = MexOrder::where('id', $orderId)->where('user_id', $userId)->first();
- return $order ? $order->toArray() : null;
- }
- /**
- * 解冻订单相关的物品(卖出订单取消时使用)
- *
- * @param MexOrder $order 订单对象
- * @return array 解冻结果
- */
- private static function unfreezeOrderItems(MexOrder $order): array
- {
- // 查找该订单相关的冻结记录
- $freezeLogs = \App\Module\GameItems\Models\ItemFreezeLog::where('source_id', $order->id)
- ->where('source_type', 'mex_sell_order')
- ->where('action_type', \App\Module\GameItems\Enums\FREEZE_ACTION_TYPE::FREEZE)
- ->get();
- if ($freezeLogs->isEmpty()) {
- return [ 'success' => true, 'message' => '没有找到需要解冻的物品' ];
- }
- $unfrozenCount = 0;
- foreach ($freezeLogs as $freezeLog) {
- // 使用ItemService解冻物品
- \App\Module\GameItems\Services\ItemService::safeUnfreezeItem($freezeLog->id);
- $unfrozenCount++;
- }
- return [
- 'success' => true,
- 'message' => "成功解冻 {$unfrozenCount} 个冻结记录",
- 'unfrozen_count' => $unfrozenCount
- ];
- }
- /**
- * 冻结订单相关的资金(买入订单创建时使用)
- *
- * @param MexOrder $order 订单对象
- * @return array 冻结结果
- */
- private static function freezeOrderFunds(MexOrder $order): array
- {
- try {
- // 获取可用账户类型和冻结账户类型
- $availableAccountType = FundLogic::getAvailableAccountType($order->currency_type);
- $frozenAccountType = FundLogic::getFrozenAccountType($order->currency_type);
- if (!$availableAccountType || !$frozenAccountType) {
- return [ 'success' => false, 'message' => '不支持的币种类型' ];
- }
- // 创建Fund服务实例(可用账户)
- $fundService = new \App\Module\Fund\Services\FundService($order->user_id, $availableAccountType->value);
- // 验证用户可用余额是否充足
- if ($fundService->balance() < $order->frozen_amount) {
- return [ 'success' => false, 'message' => '可用余额不足' ];
- }
- // 使用circulation方法将资金从可用账户转移到冻结账户
- $circulationResult = $fundService->circulation(
- $frozenAccountType,
- (float)$order->frozen_amount,
- $order->id,
- 'mex_buy_order',
- "农贸市场买入订单冻结,订单ID:{$order->id}"
- );
- if (is_string($circulationResult)) {
- return [ 'success' => false, 'message' => '资金冻结失败:' . $circulationResult ];
- }
- return [
- 'success' => true,
- 'message' => '资金冻结成功',
- 'frozen_amount' => $order->frozen_amount,
- 'circulation_id' => $circulationResult->id ?? null
- ];
- } catch (\Exception $e) {
- return [ 'success' => false, 'message' => '冻结资金异常:' . $e->getMessage() ];
- }
- }
- /**
- * 解冻订单相关的资金(买入订单取消时使用)
- *
- * @param MexOrder $order 订单对象
- * @return array 解冻结果
- */
- private static function unfreezeOrderFunds(MexOrder $order): array
- {
- try {
- // 获取可用账户类型和冻结账户类型
- $availableAccountType = FundLogic::getAvailableAccountType($order->currency_type);
- $frozenAccountType = FundLogic::getFrozenAccountType($order->currency_type);
- if (!$availableAccountType || !$frozenAccountType) {
- return [ 'success' => false, 'message' => '不支持的币种类型' ];
- }
- // 创建Fund服务实例(冻结账户)
- $fundService = new \App\Module\Fund\Services\FundService($order->user_id, $frozenAccountType->value);
- // 验证冻结账户余额是否充足
- if ($fundService->balance() < $order->frozen_amount) {
- return [ 'success' => false, 'message' => '冻结账户余额不足,可能已被解冻' ];
- }
- // 使用circulation方法将资金从冻结账户转移回可用账户
- $circulationResult = $fundService->circulation(
- $availableAccountType,
- (float)$order->frozen_amount,
- $order->id,
- 'mex_buy_order_cancel',
- "农贸市场买入订单取消解冻,订单ID:{$order->id}"
- );
- if (is_string($circulationResult)) {
- return [ 'success' => false, 'message' => '资金解冻失败:' . $circulationResult ];
- }
- return [
- 'success' => true,
- 'message' => '资金解冻成功',
- 'unfrozen_amount' => $order->frozen_amount,
- 'circulation_id' => $circulationResult->id ?? null
- ];
- } catch (\Exception $e) {
- return [ 'success' => false, 'message' => '解冻资金异常:' . $e->getMessage() ];
- }
- }
- /**
- * 获取待撮合的买入订单
- * 根据文档要求:二级排序(价格DESC + 时间ASC),移除数量排序
- *
- * @param int $itemId 商品ID
- * @param int $limit 限制数量
- * @return array 订单列表
- */
- public static function getPendingBuyOrders(int $itemId, int $limit = 100): array
- {
- $orders = MexOrder::where('item_id', $itemId)
- ->where('order_type', OrderType::BUY)
- ->where('status', OrderStatus::PENDING)
- ->orderBy('price', 'desc') // 价格优先(高价优先)
- ->orderBy('created_at', 'asc') // 时间优先(早下单优先)
- ->limit($limit)
- ->get();
- return $orders->toArray();
- }
- }
|