| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061 |
- <?php
- namespace App\Module\Mex\Logic;
- use App\Module\Game\Enums\REWARD_SOURCE_TYPE;
- use App\Module\Mex\Models\MexOrder;
- use App\Module\Mex\Models\MexWarehouse;
- use App\Module\Mex\Models\MexTransaction;
- use App\Module\Mex\Models\MexPriceConfig;
- use App\Module\Mex\Enums\OrderType;
- use App\Module\Mex\Enums\OrderStatus;
- use App\Module\Mex\Enums\TransactionType;
- use App\Module\Fund\Services\FundService;
- use App\Module\Fund\Enums\FUND_TYPE;
- use App\Module\Fund\Enums\FUND_CURRENCY_TYPE;
- use App\Module\GameItems\Services\ItemService;
- use App\Module\Mex\Logic\FundLogic;
- use App\Module\Mex\Logic\MexMatchLogLogic;
- use App\Module\Mex\Enums\MatchType;
- use App\Module\GameItems\Enums\FREEZE_REASON_TYPE;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- /**
- * 农贸市场撮合逻辑
- *
- * 处理撮合相关的核心业务逻辑
- * 根据文档要求分离用户买入物品和用户卖出物品的撮合逻辑
- */
- class MexMatchLogic
- {
- /**
- * 仓库账户ID
- */
- private const WAREHOUSE_USER_ID = 15;
- /**
- * 调控账户ID
- */
- private const CONTROL_USER_ID = 16;
- /**
- * 执行用户买入物品撮合任务
- *
- * @param int|null $itemId 指定商品ID,null表示处理所有商品
- * @param int $batchSize 批处理大小
- * @return array 撮合结果
- */
- public static function executeUserBuyItemMatch(?int $itemId = null, int $batchSize = 100): array
- {
- $startTime = microtime(true);
- $totalMatched = 0;
- $totalAmount = '0.00000';
- $processedItems = [];
- $errors = [];
- try {
- if ($itemId) {
- // 处理指定商品
- $result = self::executeUserBuyItemMatchForItem($itemId, $batchSize);
- $processedItems[] = $itemId;
- $totalMatched += $result['matched_orders'];
- $totalAmount = bcadd($totalAmount, $result['total_amount'], 5);
- if (!$result['success']) {
- $errors[] = "商品 {$itemId}: " . $result['message'];
- }
- } else {
- // 处理所有有待撮合的用户买入物品订单的商品
- $itemIds = MexOrder::where('order_type', OrderType::BUY)
- ->where('status', OrderStatus::PENDING)
- ->distinct()
- ->pluck('item_id')
- ->toArray();
- // 如果没有待撮合的订单,记录一条总体日志表示没有可处理的商品
- if (empty($itemIds)) {
- $endTime = microtime(true);
- $executionTimeMs = round(($endTime - $startTime) * 1000);
- // 记录没有待撮合订单的日志(使用商品ID 0 表示全局撮合任务)
- MexMatchLogLogic::logMatch(
- MatchType::USER_BUY,
- 0, // 使用0表示全局撮合任务
- $batchSize,
- [
- 'success' => true,
- 'message' => '没有待撮合的用户买入物品订单',
- 'matched_orders' => 0,
- 'total_amount' => '0.00000',
- ],
- $executionTimeMs
- );
- }
- foreach ($itemIds as $currentItemId) {
- $result = self::executeUserBuyItemMatchForItem($currentItemId, $batchSize);
- $processedItems[] = $currentItemId;
- $totalMatched += $result['matched_orders'];
- $totalAmount = bcadd($totalAmount, $result['total_amount'], 5);
- if (!$result['success']) {
- $errors[] = "商品 {$currentItemId}: " . $result['message'];
- }
- }
- }
- $endTime = microtime(true);
- $executionTime = round(($endTime - $startTime) * 1000, 2); // 毫秒
- Log::info('Mex用户买入物品撮合任务执行完成', [
- 'processed_items' => $processedItems,
- 'total_matched' => $totalMatched,
- 'total_amount' => $totalAmount,
- 'execution_time_ms' => $executionTime,
- 'errors' => $errors,
- ]);
- return [
- 'success' => true,
- 'message' => '用户买入物品撮合任务执行完成',
- 'processed_items' => $processedItems,
- 'total_matched' => $totalMatched,
- 'total_amount' => $totalAmount,
- 'execution_time_ms' => $executionTime,
- 'errors' => $errors,
- ];
- } catch (\Exception $e) {
- Log::error('Mex用户买入物品撮合任务执行失败', [
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString(),
- ]);
- return [
- 'success' => false,
- 'message' => '用户买入物品撮合任务执行失败:' . $e->getMessage(),
- 'processed_items' => $processedItems,
- 'total_matched' => $totalMatched,
- 'total_amount' => $totalAmount,
- ];
- }
- }
- /**
- * 执行用户卖出物品撮合任务
- *
- * @param int|null $itemId 指定商品ID,null表示处理所有商品
- * @param int $batchSize 批处理大小
- * @return array 撮合结果
- */
- public static function executeUserSellItemMatch(?int $itemId = null, int $batchSize = 100): array
- {
- $startTime = microtime(true);
- $totalMatched = 0;
- $totalAmount = '0.00000';
- $processedItems = [];
- $errors = [];
- try {
- if ($itemId) {
- // 处理指定商品
- $result = self::executeUserSellItemMatchForItem($itemId, $batchSize);
- $processedItems[] = $itemId;
- $totalMatched += $result['matched_orders'];
- $totalAmount = bcadd($totalAmount, $result['total_amount'], 5);
- if (!$result['success']) {
- $errors[] = "商品 {$itemId}: " . $result['message'];
- }
- } else {
- // 处理所有有待撮合的用户卖出物品订单的商品
- $itemIds = MexOrder::where('order_type', OrderType::SELL)
- ->where('status', OrderStatus::PENDING)
- ->distinct()
- ->pluck('item_id')
- ->toArray();
- // 如果没有待撮合的订单,记录一条总体日志表示没有可处理的商品
- if (empty($itemIds)) {
- $endTime = microtime(true);
- $executionTimeMs = round(($endTime - $startTime) * 1000);
- // 记录没有待撮合订单的日志(使用商品ID 0 表示全局撮合任务)
- MexMatchLogLogic::logMatch(
- MatchType::USER_SELL,
- 0, // 使用0表示全局撮合任务
- $batchSize,
- [
- 'success' => true,
- 'message' => '没有待撮合的用户卖出物品订单',
- 'matched_orders' => 0,
- 'total_amount' => '0.00000',
- ],
- $executionTimeMs
- );
- }
- foreach ($itemIds as $currentItemId) {
- $result = self::executeUserSellItemMatchForItem($currentItemId, $batchSize);
- $processedItems[] = $currentItemId;
- $totalMatched += $result['matched_orders'];
- $totalAmount = bcadd($totalAmount, $result['total_amount'], 5);
- if (!$result['success']) {
- $errors[] = "商品 {$currentItemId}: " . $result['message'];
- }
- }
- }
- $endTime = microtime(true);
- $executionTime = round(($endTime - $startTime) * 1000, 2); // 毫秒
- Log::info('Mex用户卖出物品撮合任务执行完成', [
- 'processed_items' => $processedItems,
- 'total_matched' => $totalMatched,
- 'total_amount' => $totalAmount,
- 'execution_time_ms' => $executionTime,
- 'errors' => $errors,
- ]);
- return [
- 'success' => true,
- 'message' => '用户卖出物品撮合任务执行完成',
- 'processed_items' => $processedItems,
- 'total_matched' => $totalMatched,
- 'total_amount' => $totalAmount,
- 'execution_time_ms' => $executionTime,
- 'errors' => $errors,
- ];
- } catch (\Exception $e) {
- Log::error('Mex用户卖出物品撮合任务执行失败', [
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString(),
- ]);
- return [
- 'success' => false,
- 'message' => '用户卖出物品撮合任务执行失败:' . $e->getMessage(),
- 'processed_items' => $processedItems,
- 'total_matched' => $totalMatched,
- 'total_amount' => $totalAmount,
- ];
- }
- }
- /**
- * 执行单个商品的用户买入物品撮合
- *
- * @param int $itemId 商品ID
- * @param int $batchSize 批处理大小
- * @return array 撮合结果
- */
- public static function executeUserBuyItemMatchForItem(int $itemId, int $batchSize = 100): array
- {
- $startTime = microtime(true);
- try {
- // 注意:根据文档要求,Logic层不应该开启事务,事务应该在Service层处理
- // 检查用户买入物品撮合条件
- $conditionCheck = self::checkUserBuyItemMatchConditions($itemId);
- if (!$conditionCheck['can_match']) {
- $result = [
- 'success' => false,
- 'message' => $conditionCheck['message'],
- 'matched_orders' => 0,
- 'total_amount' => '0.00000',
- ];
- // 记录撮合日志
- $endTime = microtime(true);
- $executionTimeMs = round(($endTime - $startTime) * 1000);
- MexMatchLogLogic::logMatch(MatchType::USER_BUY, $itemId, $batchSize, $result, $executionTimeMs);
- return $result;
- }
- $warehouse = $conditionCheck['warehouse'];
- $priceConfig = $conditionCheck['price_config'];
- // 获取待撮合的用户买入物品订单(MySQL查询时完成筛选和二级排序)
- $buyOrders = MexOrder::where('item_id', $itemId)
- ->where('order_type', OrderType::BUY)
- ->where('status', OrderStatus::PENDING)
- ->where('price', '>=', $priceConfig->max_price) // 价格验证:价格≥最高价
- ->where('quantity', '<=', $priceConfig->protection_threshold) // 数量保护:数量≤保护阈值
- ->orderBy('price', 'desc') // 价格优先(高价优先)
- ->orderBy('created_at', 'asc') // 时间优先(早下单优先)
- ->limit($batchSize)
- ->get();
- // 为价格不符合条件的买入订单记录无法成交原因
- MexOrder::where('item_id', $itemId)
- ->where('order_type', OrderType::BUY)
- ->where('status', OrderStatus::PENDING)
- ->where('price', '<', $priceConfig->max_price) // 价格低于最高价
- ->update([
- 'last_match_failure_reason' => "价格验证失败:买入价格低于最高价格 {$priceConfig->max_price}"
- ]);
- // 为数量超过保护阈值的买入订单记录无法成交原因
- MexOrder::where('item_id', $itemId)
- ->where('order_type', OrderType::BUY)
- ->where('status', OrderStatus::PENDING)
- ->where('price', '>=', $priceConfig->max_price) // 价格符合条件
- ->where('quantity', '>', $priceConfig->protection_threshold) // 数量超过保护阈值
- ->update([
- 'last_match_failure_reason' => "数量保护:订单数量超过保护阈值 {$priceConfig->protection_threshold}"
- ]);
- if ($buyOrders->isEmpty()) {
- $result = [
- 'success' => true,
- 'message' => '没有符合条件的用户买入物品订单',
- 'matched_orders' => 0,
- 'total_amount' => '0.00000',
- ];
- // 记录撮合日志
- $endTime = microtime(true);
- $executionTimeMs = round(($endTime - $startTime) * 1000);
- MexMatchLogLogic::logMatch(MatchType::USER_BUY, $itemId, $batchSize, $result, $executionTimeMs);
- return $result;
- }
- $matchedOrders = 0;
- $totalAmount = '0.00000';
- $currentStock = $warehouse->quantity;
- foreach ($buyOrders as $order) {
- // 检查库存是否充足(整单匹配原则)
- if ($currentStock < $order->quantity) {
- // 记录库存不足的无法成交原因
- $order->update([
- 'last_match_failure_reason' => "库存不足:当前库存 {$currentStock},需要 {$order->quantity}"
- ]);
- // 库存不足时结束本次撮合处理,避免无效循环
- break;
- }
- // 执行用户买入物品订单撮合(带事务处理)
- $matchResult = \App\Module\Mex\Services\MexMatchService::executeUserBuyItemOrderMatchWithTransaction($order, $warehouse);
- if ($matchResult['success']) {
- $matchedOrders++;
- $totalAmount = bcadd($totalAmount, $matchResult['total_amount'], 5);
- $currentStock -= $order->quantity;
- // 更新仓库对象的库存(用于后续订单判断)
- $warehouse->quantity = $currentStock;
- // 清除之前的无法成交原因(如果有的话)
- if ($order->last_match_failure_reason) {
- $order->update(['last_match_failure_reason' => null]);
- }
- } else {
- // 记录撮合失败的原因
- $order->update([
- 'last_match_failure_reason' => $matchResult['message']
- ]);
- }
- }
- $result = [
- 'success' => true,
- 'message' => "成功撮合 {$matchedOrders} 个用户买入物品订单",
- 'matched_orders' => $matchedOrders,
- 'total_amount' => $totalAmount,
- ];
- // 记录撮合日志
- $endTime = microtime(true);
- $executionTimeMs = round(($endTime - $startTime) * 1000);
- MexMatchLogLogic::logMatch(MatchType::USER_BUY, $itemId, $batchSize, $result, $executionTimeMs);
- return $result;
- } catch (\Exception $e) {
- $result = [
- 'success' => false,
- 'message' => '用户买入物品撮合执行失败:' . $e->getMessage(),
- 'matched_orders' => 0,
- 'total_amount' => '0.00000',
- ];
- // 记录撮合日志(包含错误信息)
- $endTime = microtime(true);
- $executionTimeMs = round(($endTime - $startTime) * 1000);
- MexMatchLogLogic::logMatch(MatchType::USER_BUY, $itemId, $batchSize, $result, $executionTimeMs, $e->getMessage());
- return $result;
- }
- }
- /**
- * 执行单个商品的用户卖出物品撮合
- *
- * @param int $itemId 商品ID
- * @param int $batchSize 批处理大小
- * @return array 撮合结果
- */
- public static function executeUserSellItemMatchForItem(int $itemId, int $batchSize = 100): array
- {
- $startTime = microtime(true);
- try {
- // 注意:根据文档要求,Logic层不应该开启事务,事务应该在Service层处理
- // 检查用户卖出物品撮合条件
- $conditionCheck = self::checkUserSellItemMatchConditions($itemId);
- if (!$conditionCheck['can_match']) {
- $result = [
- 'success' => false,
- 'message' => $conditionCheck['message'],
- 'matched_orders' => 0,
- 'total_amount' => '0.00000',
- ];
- // 记录撮合日志
- $endTime = microtime(true);
- $executionTimeMs = round(($endTime - $startTime) * 1000);
- MexMatchLogLogic::logMatch(MatchType::USER_SELL, $itemId, $batchSize, $result, $executionTimeMs);
- return $result;
- }
- $priceConfig = $conditionCheck['price_config'];
- // 获取待撮合的用户卖出物品订单
- $sellOrders = MexOrder::where('item_id', $itemId)
- ->where('order_type', OrderType::SELL)
- ->where('status', OrderStatus::PENDING)
- ->where('price', '<',$priceConfig->min_price)
- ->orderBy('price', 'asc')
- ->orderBy('id', 'asc')
- ->limit($batchSize)
- ->get();
- if ($sellOrders->isEmpty()) {
- $result = [
- 'success' => true,
- 'message' => '没有待撮合的用户卖出物品订单',
- 'matched_orders' => 0,
- 'total_amount' => '0.00000',
- ];
- // 记录撮合日志
- $endTime = microtime(true);
- $executionTimeMs = round(($endTime - $startTime) * 1000);
- MexMatchLogLogic::logMatch(MatchType::USER_SELL, $itemId, $batchSize, $result, $executionTimeMs);
- return $result;
- }
- $matchedOrders = 0;
- $totalAmount = '0.00000';
- foreach ($sellOrders as $order) {
- // 价格验证:用户卖出物品价格≤最低价
- if (bccomp($order->price, $priceConfig->min_price, 5) > 0) {
- Log::info('卖出订单价格验证失败', [
- 'order_id' => $order->id,
- 'order_price' => $order->price,
- 'min_price' => $priceConfig->min_price,
- 'price_compare' => bccomp($order->price, $priceConfig->min_price, 5)
- ]);
- // 记录价格验证失败的无法成交原因
- $order->update([
- 'last_match_failure_reason' => "价格验证失败:卖出价格 {$order->price} 高于最低价格 {$priceConfig->min_price}"
- ]);
- continue; // 价格不符合条件,跳过此订单
- }
- // 执行用户卖出物品订单撮合(带事务处理)
- $matchResult = \App\Module\Mex\Services\MexMatchService::executeUserSellItemOrderMatchWithTransaction($order);
- if ($matchResult['success']) {
- $matchedOrders++;
- $totalAmount = bcadd($totalAmount, $matchResult['total_amount'], 5);
- Log::info('卖出订单撮合成功', [
- 'order_id' => $order->id,
- 'total_amount' => $matchResult['total_amount']
- ]);
- // 清除之前的无法成交原因(如果有的话)
- if ($order->last_match_failure_reason) {
- $order->update(['last_match_failure_reason' => null]);
- }
- } else {
- Log::error('卖出订单撮合失败', [
- 'order_id' => $order->id,
- 'error_message' => $matchResult['message']
- ]);
- // 记录撮合失败的原因
- $order->update([
- 'last_match_failure_reason' => $matchResult['message']
- ]);
- }
- }
- $result = [
- 'success' => true,
- 'message' => "成功撮合 {$matchedOrders} 个用户卖出物品订单",
- 'matched_orders' => $matchedOrders,
- 'total_amount' => $totalAmount,
- ];
- // 记录撮合日志
- $endTime = microtime(true);
- $executionTimeMs = round(($endTime - $startTime) * 1000);
- MexMatchLogLogic::logMatch(MatchType::USER_SELL, $itemId, $batchSize, $result, $executionTimeMs);
- return $result;
- } catch (\Exception $e) {
- $result = [
- 'success' => false,
- 'message' => '用户卖出物品撮合执行失败:' . $e->getMessage(),
- 'matched_orders' => 0,
- 'total_amount' => '0.00000',
- ];
- // 记录撮合日志(包含错误信息)
- $endTime = microtime(true);
- $executionTimeMs = round(($endTime - $startTime) * 1000);
- MexMatchLogLogic::logMatch(MatchType::USER_SELL, $itemId, $batchSize, $result, $executionTimeMs, $e->getMessage());
- return $result;
- }
- }
- /**
- * 执行单个用户买入物品订单的撮合
- *
- * @param MexOrder $order 用户买入物品订单
- * @param MexWarehouse $warehouse 仓库信息
- * @return array 撮合结果
- */
- public static function executeUserBuyItemOrderMatch(MexOrder $order, MexWarehouse $warehouse): array
- {
- try {
- // 计算成交金额
- $totalAmount = bcmul($order->price, $order->quantity, 9);
- // 先执行账户流转逻辑,确保资金和物品流转成功后再更新订单状态和创建成交记录
- // 1. 用户冻结资金转入仓库账户
- $fundResult = self::transferFrozenFundsToWarehouse($order->user_id, $totalAmount, $order->id, $order->currency_type);
- if (!$fundResult['success']) {
- throw new \Exception('资金流转失败:' . $fundResult['message']);
- }
- // 2. 仓库账户物品转出到用户账户
- $itemResult = self::transferItemsFromWarehouseToUser($order->user_id, $order->item_id, $order->quantity, $order->id);
- if (!$itemResult['success']) {
- throw new \Exception('物品流转失败:' . $itemResult['message']);
- }
- // 资金和物品流转成功后,更新订单状态
- $order->update([
- 'status' => OrderStatus::COMPLETED,
- 'completed_quantity' => $order->quantity,
- 'completed_amount' => $totalAmount,
- 'completed_at' => now(),
- ]);
- // 更新仓库库存
- $warehouse->quantity -= $order->quantity;
- $warehouse->total_sell_quantity += $order->quantity;
- $warehouse->total_sell_amount = bcadd($warehouse->total_sell_amount, $totalAmount, 5);
- $warehouse->last_transaction_at = now();
- $warehouse->save();
- // 创建成交记录
- $transaction = MexTransaction::create([
- 'buy_order_id' => $order->id,
- 'sell_order_id' => null,
- 'buyer_id' => $order->user_id,
- 'seller_id' => self::WAREHOUSE_USER_ID, // 仓库账户作为卖方
- 'item_id' => $order->item_id,
- 'currency_type' => $order->currency_type->value,
- 'quantity' => $order->quantity,
- 'price' => $order->price,
- 'total_amount' => $totalAmount,
- 'transaction_type' => TransactionType::USER_BUY,
- 'is_admin_operation' => false,
- ]);
- // 验证成交记录是否创建成功
- if (!$transaction || !$transaction->id) {
- throw new \Exception('成交记录创建失败');
- }
- return [
- 'success' => true,
- 'message' => '订单撮合成功',
- 'order_id' => $order->id,
- 'transaction_id' => $transaction->id,
- 'total_amount' => $totalAmount,
- ];
- } catch (\Exception $e) {
- return [
- 'success' => false,
- 'message' => '订单撮合失败:' . $e->getMessage(),
- 'order_id' => $order->id,
- 'total_amount' => '0.00000',
- ];
- }
- }
- /**
- * 执行单个用户卖出物品订单的撮合
- *
- * @param MexOrder $order 用户卖出物品订单
- * @return array 撮合结果
- */
- public static function executeUserSellItemOrderMatch(MexOrder $order): array
- {
- try {
- // 计算成交金额
- $totalAmount = bcmul($order->price, $order->quantity, 5);
- // 先执行账户流转逻辑,确保资金和物品流转成功后再更新订单状态和创建成交记录
- // 1. 用户冻结物品转入仓库账户
- $itemResult = self::transferFrozenItemsToWarehouse($order->user_id, $order->item_id, $order->quantity, $order->id);
- if (!$itemResult['success']) {
- throw new \Exception('物品流转失败:' . $itemResult['message']);
- }
- // 2. 仓库账户资金转出到用户账户
- $fundResult = self::transferFundsFromWarehouseToUser($order->user_id, $totalAmount, $order->id, $order->currency_type);
- if (!$fundResult['success']) {
- throw new \Exception('资金流转失败:' . $fundResult['message']);
- }
- // 资金和物品流转成功后,更新订单状态
- $order->update([
- 'status' => OrderStatus::COMPLETED,
- 'completed_quantity' => $order->quantity,
- 'completed_amount' => $totalAmount,
- 'completed_at' => now(),
- ]);
- // 更新仓库库存
- $warehouse = MexWarehouse::where('item_id', $order->item_id)->first();
- if (!$warehouse) {
- // 如果仓库记录不存在,创建新记录
- $warehouse = MexWarehouse::create([
- 'item_id' => $order->item_id,
- 'quantity' => $order->quantity,
- 'total_buy_amount' => $totalAmount,
- 'total_buy_quantity' => $order->quantity,
- 'last_transaction_at' => now(),
- ]);
- } else {
- // 更新现有仓库记录
- $warehouse->quantity += $order->quantity;
- $warehouse->total_buy_quantity += $order->quantity;
- $warehouse->total_buy_amount = bcadd($warehouse->total_buy_amount, $totalAmount, 5);
- $warehouse->last_transaction_at = now();
- $warehouse->save();
- }
- // 创建成交记录
- $transaction = MexTransaction::create([
- 'buy_order_id' => null,
- 'sell_order_id' => $order->id,
- 'buyer_id' => self::WAREHOUSE_USER_ID, // 仓库账户作为买方
- 'seller_id' => $order->user_id,
- 'item_id' => $order->item_id,
- 'currency_type' => $order->currency_type->value,
- 'quantity' => $order->quantity,
- 'price' => $order->price,
- 'total_amount' => $totalAmount,
- 'transaction_type' => TransactionType::USER_SELL,
- 'is_admin_operation' => false,
- ]);
- // 验证成交记录是否创建成功
- if (!$transaction || !$transaction->id) {
- throw new \Exception('成交记录创建失败');
- }
- return [
- 'success' => true,
- 'message' => '用户卖出物品订单撮合成功',
- 'order_id' => $order->id,
- 'transaction_id' => $transaction->id,
- 'total_amount' => $totalAmount,
- ];
- } catch (\Exception $e) {
- return [
- 'success' => false,
- 'message' => '用户卖出物品订单撮合失败:' . $e->getMessage(),
- 'order_id' => $order->id,
- 'total_amount' => '0.00000',
- ];
- }
- }
- /**
- * 检查用户买入物品撮合条件
- *
- * @param int $itemId 商品ID
- * @return array 检查结果
- */
- public static function checkUserBuyItemMatchConditions(int $itemId): array
- {
- // 检查价格配置
- $priceConfig = MexPriceConfig::where('item_id', $itemId)->where('is_enabled', true)->first();
- if (!$priceConfig) {
- return [
- 'can_match' => false,
- 'message' => '商品未配置价格信息或已禁用',
- ];
- }
- // 检查仓库库存
- $warehouse = MexWarehouse::where('item_id', $itemId)->first();
- if (!$warehouse || $warehouse->quantity <= 0) {
- return [
- 'can_match' => false,
- 'message' => '仓库库存不足',
- ];
- }
- // 检查是否有符合条件的待撮合用户买入物品订单
- $pendingBuyOrders = MexOrder::where('item_id', $itemId)
- ->where('order_type', OrderType::BUY)
- ->where('status', OrderStatus::PENDING)
- ->where('price', '>=', $priceConfig->max_price) // 价格≥最高价
- ->where('quantity', '<=', $priceConfig->protection_threshold) // 数量≤保护阈值
- ->count();
- if ($pendingBuyOrders === 0) {
- return [
- 'can_match' => false,
- 'message' => '没有符合条件的待撮合用户买入物品订单',
- ];
- }
- return [
- 'can_match' => true,
- 'message' => '用户买入物品撮合条件满足',
- 'warehouse' => $warehouse,
- 'price_config' => $priceConfig,
- 'pending_orders' => $pendingBuyOrders,
- ];
- }
- /**
- * 检查用户卖出物品撮合条件
- *
- * @param int $itemId 商品ID
- * @return array 检查结果
- */
- public static function checkUserSellItemMatchConditions(int $itemId): array
- {
- // 检查价格配置
- $priceConfig = MexPriceConfig::where('item_id', $itemId)->where('is_enabled', true)->first();
- if (!$priceConfig) {
- return [
- 'can_match' => false,
- 'message' => '商品未配置价格信息或已禁用',
- ];
- }
- // 检查是否有待撮合的用户卖出物品订单
- $pendingSellOrders = MexOrder::where('item_id', $itemId)
- ->where('order_type', OrderType::SELL)
- ->where('status', OrderStatus::PENDING)
- ->count();
- if ($pendingSellOrders === 0) {
- return [
- 'can_match' => false,
- 'message' => '没有待撮合的用户卖出物品订单',
- ];
- }
- return [
- 'can_match' => true,
- 'message' => '用户卖出物品撮合条件满足',
- 'price_config' => $priceConfig,
- 'pending_orders' => $pendingSellOrders,
- ];
- }
- /**
- * 获取用户买入物品撮合统计信息
- *
- * @return array 统计信息
- */
- public static function getUserBuyItemMatchStats(): array
- {
- // 获取待撮合用户买入物品订单统计
- $pendingStats = MexOrder::where('order_type', OrderType::BUY)
- ->where('status', OrderStatus::PENDING)
- ->selectRaw('
- COUNT(*) as total_pending,
- COUNT(DISTINCT item_id) as pending_items,
- SUM(quantity) as total_quantity,
- SUM(total_amount) as total_amount
- ')
- ->first();
- // 获取今日用户买入物品撮合统计
- $todayStats = MexTransaction::where('transaction_type', TransactionType::USER_BUY)
- ->whereDate('created_at', today())
- ->selectRaw('
- COUNT(*) as today_matched,
- SUM(quantity) as today_quantity,
- SUM(total_amount) as today_amount
- ')
- ->first();
- // 获取有库存的商品数量
- $availableItems = MexWarehouse::where('quantity', '>', 0)->count();
- return [
- 'pending_orders' => $pendingStats->total_pending ?? 0,
- 'pending_items' => $pendingStats->pending_items ?? 0,
- 'pending_quantity' => $pendingStats->total_quantity ?? 0,
- 'pending_amount' => $pendingStats->total_amount ?? '0.00000',
- 'today_matched' => $todayStats->today_matched ?? 0,
- 'today_quantity' => $todayStats->today_quantity ?? 0,
- 'today_amount' => $todayStats->today_amount ?? '0.00000',
- 'available_items' => $availableItems,
- 'stats_time' => now(),
- ];
- }
- /**
- * 获取用户卖出物品撮合统计信息
- *
- * @return array 统计信息
- */
- public static function getUserSellItemMatchStats(): array
- {
- // 获取待撮合用户卖出物品订单统计
- $pendingStats = MexOrder::where('order_type', OrderType::SELL)
- ->where('status', OrderStatus::PENDING)
- ->selectRaw('
- COUNT(*) as total_pending,
- COUNT(DISTINCT item_id) as pending_items,
- SUM(quantity) as total_quantity,
- SUM(total_amount) as total_amount
- ')
- ->first();
- // 获取今日用户卖出物品撮合统计
- $todayStats = MexTransaction::where('transaction_type', TransactionType::USER_SELL)
- ->whereDate('created_at', today())
- ->selectRaw('
- COUNT(*) as today_matched,
- SUM(quantity) as today_quantity,
- SUM(total_amount) as today_amount
- ')
- ->first();
- return [
- 'pending_orders' => $pendingStats->total_pending ?? 0,
- 'pending_items' => $pendingStats->pending_items ?? 0,
- 'pending_quantity' => $pendingStats->total_quantity ?? 0,
- 'pending_amount' => $pendingStats->total_amount ?? '0.00000',
- 'today_matched' => $todayStats->today_matched ?? 0,
- 'today_quantity' => $todayStats->today_quantity ?? 0,
- 'today_amount' => $todayStats->today_amount ?? '0.00000',
- 'stats_time' => now(),
- ];
- }
- /**
- * 将用户冻结资金转入仓库账户
- *
- * @param int $userId 用户ID
- * @param string $amount 金额
- * @param int $orderId 订单ID
- * @param FUND_CURRENCY_TYPE|null $currencyType 币种类型,默认使用钻石
- * @return array 转移结果
- */
- private static function transferFrozenFundsToWarehouse(int $userId, string $amount, int $orderId, ?FUND_CURRENCY_TYPE $currencyType = null): array
- {
- try {
- // 获取币种类型,默认使用钻石
- $currencyType = $currencyType ?? FundLogic::getDefaultCurrency();
- // 获取对应的冻结账户类型
- $frozenAccountType = FundLogic::getFrozenAccountType($currencyType);
- if (!$frozenAccountType) {
- return [
- 'success' => false,
- 'message' => '不支持的币种类型',
- ];
- }
- // 从用户冻结账户转移到仓库账户
- $fundService = new FundService($userId, $frozenAccountType->value);
- // 多少钱,就是多少钱,资金模块能够正确处理,不需要外部处理
- $result = $fundService->trade(
- self::WAREHOUSE_USER_ID,
- $amount,
- 'MEX_ORDER',
- $orderId,
- '用户买入物品撮合-资金转移'
- );
- if (is_string($result)) {
- return [
- 'success' => false,
- 'message' => $result,
- ];
- }
- return [
- 'success' => true,
- 'message' => '资金转移成功',
- 'data' => $result,
- ];
- } catch (\Exception $e) {
- return [
- 'success' => false,
- 'message' => '资金转移异常:' . $e->getMessage(),
- ];
- }
- }
- /**
- * 将仓库账户物品转出到用户账户
- *
- * @param int $userId 用户ID
- * @param int $itemId 物品ID
- * @param int $quantity 数量
- * @param int $orderId 订单ID
- * @return array 转移结果
- */
- private static function transferItemsFromWarehouseToUser(int $userId, int $itemId, int $quantity, int $orderId): array
- {
- try {
- // 添加物品到用户账户
- $result = ItemService::addItem($userId, $itemId, $quantity, [
- 'source' => 'mex_order',
- 'source_type' => REWARD_SOURCE_TYPE::MEX_BUY,
- 'source_id' => $orderId,
- 'remark' => '用户买入物品撮合-物品转移',
- ]);
- if (!$result || !isset($result['success']) || !$result['success']) {
- return [
- 'success' => false,
- 'message' => '物品添加失败:' . ($result['message'] ?? '未知错误'),
- ];
- }
- return [
- 'success' => true,
- 'message' => '物品转移成功',
- 'data' => $result,
- ];
- } catch (\Exception $e) {
- return [
- 'success' => false,
- 'message' => '物品转移异常:' . $e->getMessage(),
- ];
- }
- }
- /**
- * 将用户冻结物品转入仓库账户
- *
- * @param int $userId 用户ID
- * @param int $itemId 物品ID
- * @param int $quantity 数量
- * @param int $orderId 订单ID
- * @return array 转移结果
- */
- private static function transferFrozenItemsToWarehouse(int $userId, int $itemId, int $quantity, int $orderId): array
- {
- try {
- // 消耗用户物品(包括冻结的物品)
- $result = ItemService::consumeItem($userId, $itemId, null, $quantity, [
- 'source' => 'mex_order',
- 'source_id' => $orderId,
- 'remark' => '用户卖出物品撮合-物品转移',
- 'include_frozen' => true, // 包括冻结的物品
- ]);
- if (!$result || !isset($result['success']) || !$result['success']) {
- return [
- 'success' => false,
- 'message' => '物品消耗失败:' . ($result['message'] ?? '未知错误'),
- ];
- }
- return [
- 'success' => true,
- 'message' => '物品转移成功',
- 'data' => $result,
- ];
- } catch (\Exception $e) {
- return [
- 'success' => false,
- 'message' => '物品转移异常:' . $e->getMessage(),
- ];
- }
- }
- /**
- * 将仓库账户资金转出到用户账户
- *
- * @param int $userId 用户ID
- * @param string $amount 金额
- * @param int $orderId 订单ID
- * @param FUND_CURRENCY_TYPE|null $currencyType 币种类型,默认使用钻石
- * @return array 转移结果
- */
- private static function transferFundsFromWarehouseToUser(int $userId, string $amount, int $orderId, ?FUND_CURRENCY_TYPE $currencyType = null): array
- {
- try {
- // 获取币种类型,默认使用钻石
- $currencyType = $currencyType ?? FundLogic::getDefaultCurrency();
- // 获取对应的可用账户类型
- $availableAccountType = FundLogic::getAvailableAccountType($currencyType);
- if (!$availableAccountType) {
- return [
- 'success' => false,
- 'message' => '不支持的币种类型',
- ];
- }
- // 从仓库账户转移到用户账户
- $fundService = new FundService(self::WAREHOUSE_USER_ID, $availableAccountType->value);
- // 资金系统,能够正确处理金额,不需要外部处理
- $result = $fundService->trade(
- $userId,
- $amount,
- 'MEX_ORDER',
- $orderId,
- '用户卖出物品撮合-资金转移'
- );
- if (is_string($result)) {
- return [
- 'success' => false,
- 'message' => $result,
- ];
- }
- return [
- 'success' => true,
- 'message' => '资金转移成功',
- 'data' => $result,
- ];
- } catch (\Exception $e) {
- return [
- 'success' => false,
- 'message' => '资金转移异常:' . $e->getMessage(),
- ];
- }
- }
- }
|