MexMatchLogic.php 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. <?php
  2. namespace App\Module\Mex\Logic;
  3. use App\Module\Game\Enums\REWARD_SOURCE_TYPE;
  4. use App\Module\Mex\Models\MexOrder;
  5. use App\Module\Mex\Models\MexWarehouse;
  6. use App\Module\Mex\Models\MexTransaction;
  7. use App\Module\Mex\Models\MexPriceConfig;
  8. use App\Module\Mex\Enums\OrderType;
  9. use App\Module\Mex\Enums\OrderStatus;
  10. use App\Module\Mex\Enums\TransactionType;
  11. use App\Module\Fund\Services\FundService;
  12. use App\Module\Fund\Enums\FUND_TYPE;
  13. use App\Module\Fund\Enums\FUND_CURRENCY_TYPE;
  14. use App\Module\GameItems\Services\ItemService;
  15. use App\Module\Mex\Logic\FundLogic;
  16. use App\Module\Mex\Logic\MexMatchLogLogic;
  17. use App\Module\Mex\Enums\MatchType;
  18. use App\Module\GameItems\Enums\FREEZE_REASON_TYPE;
  19. use Illuminate\Support\Facades\DB;
  20. use Illuminate\Support\Facades\Log;
  21. /**
  22. * 农贸市场撮合逻辑
  23. *
  24. * 处理撮合相关的核心业务逻辑
  25. * 根据文档要求分离用户买入物品和用户卖出物品的撮合逻辑
  26. */
  27. class MexMatchLogic
  28. {
  29. /**
  30. * 仓库账户ID
  31. */
  32. private const WAREHOUSE_USER_ID = 15;
  33. /**
  34. * 调控账户ID
  35. */
  36. private const CONTROL_USER_ID = 16;
  37. /**
  38. * 执行用户买入物品撮合任务
  39. *
  40. * @param int|null $itemId 指定商品ID,null表示处理所有商品
  41. * @param int $batchSize 批处理大小
  42. * @return array 撮合结果
  43. */
  44. public static function executeUserBuyItemMatch(?int $itemId = null, int $batchSize = 100): array
  45. {
  46. $startTime = microtime(true);
  47. $totalMatched = 0;
  48. $totalAmount = '0.00000';
  49. $processedItems = [];
  50. $errors = [];
  51. try {
  52. if ($itemId) {
  53. // 处理指定商品
  54. $result = self::executeUserBuyItemMatchForItem($itemId, $batchSize);
  55. $processedItems[] = $itemId;
  56. $totalMatched += $result['matched_orders'];
  57. $totalAmount = bcadd($totalAmount, $result['total_amount'], 5);
  58. if (!$result['success']) {
  59. $errors[] = "商品 {$itemId}: " . $result['message'];
  60. }
  61. } else {
  62. // 处理所有有待撮合的用户买入物品订单的商品
  63. $itemIds = MexOrder::where('order_type', OrderType::BUY)
  64. ->where('status', OrderStatus::PENDING)
  65. ->distinct()
  66. ->pluck('item_id')
  67. ->toArray();
  68. foreach ($itemIds as $currentItemId) {
  69. $result = self::executeUserBuyItemMatchForItem($currentItemId, $batchSize);
  70. $processedItems[] = $currentItemId;
  71. $totalMatched += $result['matched_orders'];
  72. $totalAmount = bcadd($totalAmount, $result['total_amount'], 5);
  73. if (!$result['success']) {
  74. $errors[] = "商品 {$currentItemId}: " . $result['message'];
  75. }
  76. }
  77. }
  78. $endTime = microtime(true);
  79. $executionTime = round(($endTime - $startTime) * 1000, 2); // 毫秒
  80. Log::info('Mex用户买入物品撮合任务执行完成', [
  81. 'processed_items' => $processedItems,
  82. 'total_matched' => $totalMatched,
  83. 'total_amount' => $totalAmount,
  84. 'execution_time_ms' => $executionTime,
  85. 'errors' => $errors,
  86. ]);
  87. return [
  88. 'success' => true,
  89. 'message' => '用户买入物品撮合任务执行完成',
  90. 'processed_items' => $processedItems,
  91. 'total_matched' => $totalMatched,
  92. 'total_amount' => $totalAmount,
  93. 'execution_time_ms' => $executionTime,
  94. 'errors' => $errors,
  95. ];
  96. } catch (\Exception $e) {
  97. Log::error('Mex用户买入物品撮合任务执行失败', [
  98. 'error' => $e->getMessage(),
  99. 'trace' => $e->getTraceAsString(),
  100. ]);
  101. return [
  102. 'success' => false,
  103. 'message' => '用户买入物品撮合任务执行失败:' . $e->getMessage(),
  104. 'processed_items' => $processedItems,
  105. 'total_matched' => $totalMatched,
  106. 'total_amount' => $totalAmount,
  107. ];
  108. }
  109. }
  110. /**
  111. * 执行用户卖出物品撮合任务
  112. *
  113. * @param int|null $itemId 指定商品ID,null表示处理所有商品
  114. * @param int $batchSize 批处理大小
  115. * @return array 撮合结果
  116. */
  117. public static function executeUserSellItemMatch(?int $itemId = null, int $batchSize = 100): array
  118. {
  119. $startTime = microtime(true);
  120. $totalMatched = 0;
  121. $totalAmount = '0.00000';
  122. $processedItems = [];
  123. $errors = [];
  124. try {
  125. if ($itemId) {
  126. // 处理指定商品
  127. $result = self::executeUserSellItemMatchForItem($itemId, $batchSize);
  128. $processedItems[] = $itemId;
  129. $totalMatched += $result['matched_orders'];
  130. $totalAmount = bcadd($totalAmount, $result['total_amount'], 5);
  131. if (!$result['success']) {
  132. $errors[] = "商品 {$itemId}: " . $result['message'];
  133. }
  134. } else {
  135. // 处理所有有待撮合的用户卖出物品订单的商品
  136. $itemIds = MexOrder::where('order_type', OrderType::SELL)
  137. ->where('status', OrderStatus::PENDING)
  138. ->distinct()
  139. ->pluck('item_id')
  140. ->toArray();
  141. foreach ($itemIds as $currentItemId) {
  142. $result = self::executeUserSellItemMatchForItem($currentItemId, $batchSize);
  143. $processedItems[] = $currentItemId;
  144. $totalMatched += $result['matched_orders'];
  145. $totalAmount = bcadd($totalAmount, $result['total_amount'], 5);
  146. if (!$result['success']) {
  147. $errors[] = "商品 {$currentItemId}: " . $result['message'];
  148. }
  149. }
  150. }
  151. $endTime = microtime(true);
  152. $executionTime = round(($endTime - $startTime) * 1000, 2); // 毫秒
  153. Log::info('Mex用户卖出物品撮合任务执行完成', [
  154. 'processed_items' => $processedItems,
  155. 'total_matched' => $totalMatched,
  156. 'total_amount' => $totalAmount,
  157. 'execution_time_ms' => $executionTime,
  158. 'errors' => $errors,
  159. ]);
  160. return [
  161. 'success' => true,
  162. 'message' => '用户卖出物品撮合任务执行完成',
  163. 'processed_items' => $processedItems,
  164. 'total_matched' => $totalMatched,
  165. 'total_amount' => $totalAmount,
  166. 'execution_time_ms' => $executionTime,
  167. 'errors' => $errors,
  168. ];
  169. } catch (\Exception $e) {
  170. Log::error('Mex用户卖出物品撮合任务执行失败', [
  171. 'error' => $e->getMessage(),
  172. 'trace' => $e->getTraceAsString(),
  173. ]);
  174. return [
  175. 'success' => false,
  176. 'message' => '用户卖出物品撮合任务执行失败:' . $e->getMessage(),
  177. 'processed_items' => $processedItems,
  178. 'total_matched' => $totalMatched,
  179. 'total_amount' => $totalAmount,
  180. ];
  181. }
  182. }
  183. /**
  184. * 执行单个商品的用户买入物品撮合
  185. *
  186. * @param int $itemId 商品ID
  187. * @param int $batchSize 批处理大小
  188. * @return array 撮合结果
  189. */
  190. public static function executeUserBuyItemMatchForItem(int $itemId, int $batchSize = 100): array
  191. {
  192. $startTime = microtime(true);
  193. try {
  194. // 注意:根据文档要求,Logic层不应该开启事务,事务应该在Service层处理
  195. // 检查用户买入物品撮合条件
  196. $conditionCheck = self::checkUserBuyItemMatchConditions($itemId);
  197. if (!$conditionCheck['can_match']) {
  198. $result = [
  199. 'success' => false,
  200. 'message' => $conditionCheck['message'],
  201. 'matched_orders' => 0,
  202. 'total_amount' => '0.00000',
  203. ];
  204. // 记录撮合日志
  205. $endTime = microtime(true);
  206. $executionTimeMs = round(($endTime - $startTime) * 1000);
  207. MexMatchLogLogic::logMatch(MatchType::USER_BUY, $itemId, $batchSize, $result, $executionTimeMs);
  208. return $result;
  209. }
  210. $warehouse = $conditionCheck['warehouse'];
  211. $priceConfig = $conditionCheck['price_config'];
  212. // 获取待撮合的用户买入物品订单(MySQL查询时完成筛选和二级排序)
  213. $buyOrders = MexOrder::where('item_id', $itemId)
  214. ->where('order_type', OrderType::BUY)
  215. ->where('status', OrderStatus::PENDING)
  216. ->where('price', '>=', $priceConfig->max_price) // 价格验证:价格≥最高价
  217. ->where('quantity', '<=', $priceConfig->protection_threshold) // 数量保护:数量≤保护阈值
  218. ->orderBy('price', 'desc') // 价格优先(高价优先)
  219. ->orderBy('created_at', 'asc') // 时间优先(早下单优先)
  220. ->limit($batchSize)
  221. ->get();
  222. if ($buyOrders->isEmpty()) {
  223. $result = [
  224. 'success' => true,
  225. 'message' => '没有符合条件的用户买入物品订单',
  226. 'matched_orders' => 0,
  227. 'total_amount' => '0.00000',
  228. ];
  229. // 记录撮合日志
  230. $endTime = microtime(true);
  231. $executionTimeMs = round(($endTime - $startTime) * 1000);
  232. MexMatchLogLogic::logMatch(MatchType::USER_BUY, $itemId, $batchSize, $result, $executionTimeMs);
  233. return $result;
  234. }
  235. $matchedOrders = 0;
  236. $totalAmount = '0.00000';
  237. $currentStock = $warehouse->quantity;
  238. foreach ($buyOrders as $order) {
  239. // 检查库存是否充足(整单匹配原则)
  240. if ($currentStock < $order->quantity) {
  241. // 库存不足时结束本次撮合处理,避免无效循环
  242. break;
  243. }
  244. // 执行用户买入物品订单撮合
  245. $matchResult = self::executeUserBuyItemOrderMatch($order, $warehouse);
  246. if ($matchResult['success']) {
  247. $matchedOrders++;
  248. $totalAmount = bcadd($totalAmount, $matchResult['total_amount'], 5);
  249. $currentStock -= $order->quantity;
  250. // 更新仓库对象的库存(用于后续订单判断)
  251. $warehouse->quantity = $currentStock;
  252. }
  253. }
  254. $result = [
  255. 'success' => true,
  256. 'message' => "成功撮合 {$matchedOrders} 个用户买入物品订单",
  257. 'matched_orders' => $matchedOrders,
  258. 'total_amount' => $totalAmount,
  259. ];
  260. // 记录撮合日志
  261. $endTime = microtime(true);
  262. $executionTimeMs = round(($endTime - $startTime) * 1000);
  263. MexMatchLogLogic::logMatch(MatchType::USER_BUY, $itemId, $batchSize, $result, $executionTimeMs);
  264. return $result;
  265. } catch (\Exception $e) {
  266. $result = [
  267. 'success' => false,
  268. 'message' => '用户买入物品撮合执行失败:' . $e->getMessage(),
  269. 'matched_orders' => 0,
  270. 'total_amount' => '0.00000',
  271. ];
  272. // 记录撮合日志(包含错误信息)
  273. $endTime = microtime(true);
  274. $executionTimeMs = round(($endTime - $startTime) * 1000);
  275. MexMatchLogLogic::logMatch(MatchType::USER_BUY, $itemId, $batchSize, $result, $executionTimeMs, $e->getMessage());
  276. return $result;
  277. }
  278. }
  279. /**
  280. * 执行单个商品的用户卖出物品撮合
  281. *
  282. * @param int $itemId 商品ID
  283. * @param int $batchSize 批处理大小
  284. * @return array 撮合结果
  285. */
  286. public static function executeUserSellItemMatchForItem(int $itemId, int $batchSize = 100): array
  287. {
  288. $startTime = microtime(true);
  289. try {
  290. // 注意:根据文档要求,Logic层不应该开启事务,事务应该在Service层处理
  291. // 检查用户卖出物品撮合条件
  292. $conditionCheck = self::checkUserSellItemMatchConditions($itemId);
  293. if (!$conditionCheck['can_match']) {
  294. $result = [
  295. 'success' => false,
  296. 'message' => $conditionCheck['message'],
  297. 'matched_orders' => 0,
  298. 'total_amount' => '0.00000',
  299. ];
  300. // 记录撮合日志
  301. $endTime = microtime(true);
  302. $executionTimeMs = round(($endTime - $startTime) * 1000);
  303. MexMatchLogLogic::logMatch(MatchType::USER_SELL, $itemId, $batchSize, $result, $executionTimeMs);
  304. return $result;
  305. }
  306. $priceConfig = $conditionCheck['price_config'];
  307. // 获取待撮合的用户卖出物品订单
  308. $sellOrders = MexOrder::where('item_id', $itemId)
  309. ->where('order_type', OrderType::SELL)
  310. ->where('status', OrderStatus::PENDING)
  311. ->limit($batchSize)
  312. ->get();
  313. if ($sellOrders->isEmpty()) {
  314. $result = [
  315. 'success' => true,
  316. 'message' => '没有待撮合的用户卖出物品订单',
  317. 'matched_orders' => 0,
  318. 'total_amount' => '0.00000',
  319. ];
  320. // 记录撮合日志
  321. $endTime = microtime(true);
  322. $executionTimeMs = round(($endTime - $startTime) * 1000);
  323. MexMatchLogLogic::logMatch(MatchType::USER_SELL, $itemId, $batchSize, $result, $executionTimeMs);
  324. return $result;
  325. }
  326. $matchedOrders = 0;
  327. $totalAmount = '0.00000';
  328. foreach ($sellOrders as $order) {
  329. // 价格验证:用户卖出物品价格≤最低价
  330. if (bccomp($order->price, $priceConfig->min_price, 5) > 0) {
  331. continue; // 价格不符合条件,跳过此订单
  332. }
  333. // 执行用户卖出物品订单撮合
  334. $matchResult = self::executeUserSellItemOrderMatch($order);
  335. if ($matchResult['success']) {
  336. $matchedOrders++;
  337. $totalAmount = bcadd($totalAmount, $matchResult['total_amount'], 5);
  338. }
  339. }
  340. $result = [
  341. 'success' => true,
  342. 'message' => "成功撮合 {$matchedOrders} 个用户卖出物品订单",
  343. 'matched_orders' => $matchedOrders,
  344. 'total_amount' => $totalAmount,
  345. ];
  346. // 记录撮合日志
  347. $endTime = microtime(true);
  348. $executionTimeMs = round(($endTime - $startTime) * 1000);
  349. MexMatchLogLogic::logMatch(MatchType::USER_SELL, $itemId, $batchSize, $result, $executionTimeMs);
  350. return $result;
  351. } catch (\Exception $e) {
  352. $result = [
  353. 'success' => false,
  354. 'message' => '用户卖出物品撮合执行失败:' . $e->getMessage(),
  355. 'matched_orders' => 0,
  356. 'total_amount' => '0.00000',
  357. ];
  358. // 记录撮合日志(包含错误信息)
  359. $endTime = microtime(true);
  360. $executionTimeMs = round(($endTime - $startTime) * 1000);
  361. MexMatchLogLogic::logMatch(MatchType::USER_SELL, $itemId, $batchSize, $result, $executionTimeMs, $e->getMessage());
  362. return $result;
  363. }
  364. }
  365. /**
  366. * 执行单个用户买入物品订单的撮合
  367. *
  368. * @param MexOrder $order 用户买入物品订单
  369. * @param MexWarehouse $warehouse 仓库信息
  370. * @return array 撮合结果
  371. */
  372. private static function executeUserBuyItemOrderMatch(MexOrder $order, MexWarehouse $warehouse): array
  373. {
  374. try {
  375. // 计算成交金额
  376. $totalAmount = bcmul($order->price, $order->quantity, 5);
  377. // 先执行账户流转逻辑,确保资金和物品流转成功后再更新订单状态和创建成交记录
  378. // 1. 用户冻结资金转入仓库账户
  379. $fundResult = self::transferFrozenFundsToWarehouse($order->user_id, $totalAmount, $order->id, $order->currency_type);
  380. if (!$fundResult['success']) {
  381. throw new \Exception('资金流转失败:' . $fundResult['message']);
  382. }
  383. // 2. 仓库账户物品转出到用户账户
  384. $itemResult = self::transferItemsFromWarehouseToUser($order->user_id, $order->item_id, $order->quantity, $order->id);
  385. if (!$itemResult['success']) {
  386. throw new \Exception('物品流转失败:' . $itemResult['message']);
  387. }
  388. // 资金和物品流转成功后,更新订单状态
  389. $order->update([
  390. 'status' => OrderStatus::COMPLETED,
  391. 'completed_quantity' => $order->quantity,
  392. 'completed_amount' => $totalAmount,
  393. 'completed_at' => now(),
  394. ]);
  395. // 更新仓库库存
  396. $warehouse->quantity -= $order->quantity;
  397. $warehouse->total_sell_quantity += $order->quantity;
  398. $warehouse->total_sell_amount = bcadd($warehouse->total_sell_amount, $totalAmount, 5);
  399. $warehouse->last_transaction_at = now();
  400. $warehouse->save();
  401. // 创建成交记录
  402. $transaction = MexTransaction::create([
  403. 'buy_order_id' => $order->id,
  404. 'sell_order_id' => null,
  405. 'buyer_id' => $order->user_id,
  406. 'seller_id' => self::WAREHOUSE_USER_ID, // 仓库账户作为卖方
  407. 'item_id' => $order->item_id,
  408. 'currency_type' => $order->currency_type->value,
  409. 'quantity' => $order->quantity,
  410. 'price' => $order->price,
  411. 'total_amount' => $totalAmount,
  412. 'transaction_type' => TransactionType::USER_BUY,
  413. 'is_admin_operation' => false,
  414. ]);
  415. // 验证成交记录是否创建成功
  416. if (!$transaction || !$transaction->id) {
  417. throw new \Exception('成交记录创建失败');
  418. }
  419. return [
  420. 'success' => true,
  421. 'message' => '订单撮合成功',
  422. 'order_id' => $order->id,
  423. 'transaction_id' => $transaction->id,
  424. 'total_amount' => $totalAmount,
  425. ];
  426. } catch (\Exception $e) {
  427. return [
  428. 'success' => false,
  429. 'message' => '订单撮合失败:' . $e->getMessage(),
  430. 'order_id' => $order->id,
  431. 'total_amount' => '0.00000',
  432. ];
  433. }
  434. }
  435. /**
  436. * 执行单个用户卖出物品订单的撮合
  437. *
  438. * @param MexOrder $order 用户卖出物品订单
  439. * @return array 撮合结果
  440. */
  441. private static function executeUserSellItemOrderMatch(MexOrder $order): array
  442. {
  443. try {
  444. // 计算成交金额
  445. $totalAmount = bcmul($order->price, $order->quantity, 5);
  446. // 先执行账户流转逻辑,确保资金和物品流转成功后再更新订单状态和创建成交记录
  447. // 1. 用户冻结物品转入仓库账户
  448. $itemResult = self::transferFrozenItemsToWarehouse($order->user_id, $order->item_id, $order->quantity, $order->id);
  449. if (!$itemResult['success']) {
  450. throw new \Exception('物品流转失败:' . $itemResult['message']);
  451. }
  452. // 2. 仓库账户资金转出到用户账户
  453. $fundResult = self::transferFundsFromWarehouseToUser($order->user_id, $totalAmount, $order->id, $order->currency_type);
  454. if (!$fundResult['success']) {
  455. throw new \Exception('资金流转失败:' . $fundResult['message']);
  456. }
  457. // 资金和物品流转成功后,更新订单状态
  458. $order->update([
  459. 'status' => OrderStatus::COMPLETED,
  460. 'completed_quantity' => $order->quantity,
  461. 'completed_amount' => $totalAmount,
  462. 'completed_at' => now(),
  463. ]);
  464. // 更新仓库库存
  465. $warehouse = MexWarehouse::where('item_id', $order->item_id)->first();
  466. if (!$warehouse) {
  467. // 如果仓库记录不存在,创建新记录
  468. $warehouse = MexWarehouse::create([
  469. 'item_id' => $order->item_id,
  470. 'quantity' => $order->quantity,
  471. 'total_buy_amount' => $totalAmount,
  472. 'total_buy_quantity' => $order->quantity,
  473. 'last_transaction_at' => now(),
  474. ]);
  475. } else {
  476. // 更新现有仓库记录
  477. $warehouse->quantity += $order->quantity;
  478. $warehouse->total_buy_quantity += $order->quantity;
  479. $warehouse->total_buy_amount = bcadd($warehouse->total_buy_amount, $totalAmount, 5);
  480. $warehouse->last_transaction_at = now();
  481. $warehouse->save();
  482. }
  483. // 创建成交记录
  484. $transaction = MexTransaction::create([
  485. 'buy_order_id' => null,
  486. 'sell_order_id' => $order->id,
  487. 'buyer_id' => self::WAREHOUSE_USER_ID, // 仓库账户作为买方
  488. 'seller_id' => $order->user_id,
  489. 'item_id' => $order->item_id,
  490. 'currency_type' => $order->currency_type->value,
  491. 'quantity' => $order->quantity,
  492. 'price' => $order->price,
  493. 'total_amount' => $totalAmount,
  494. 'transaction_type' => TransactionType::USER_SELL,
  495. 'is_admin_operation' => false,
  496. ]);
  497. // 验证成交记录是否创建成功
  498. if (!$transaction || !$transaction->id) {
  499. throw new \Exception('成交记录创建失败');
  500. }
  501. return [
  502. 'success' => true,
  503. 'message' => '用户卖出物品订单撮合成功',
  504. 'order_id' => $order->id,
  505. 'transaction_id' => $transaction->id,
  506. 'total_amount' => $totalAmount,
  507. ];
  508. } catch (\Exception $e) {
  509. return [
  510. 'success' => false,
  511. 'message' => '用户卖出物品订单撮合失败:' . $e->getMessage(),
  512. 'order_id' => $order->id,
  513. 'total_amount' => '0.00000',
  514. ];
  515. }
  516. }
  517. /**
  518. * 检查用户买入物品撮合条件
  519. *
  520. * @param int $itemId 商品ID
  521. * @return array 检查结果
  522. */
  523. public static function checkUserBuyItemMatchConditions(int $itemId): array
  524. {
  525. // 检查价格配置
  526. $priceConfig = MexPriceConfig::where('item_id', $itemId)->where('is_enabled', true)->first();
  527. if (!$priceConfig) {
  528. return [
  529. 'can_match' => false,
  530. 'message' => '商品未配置价格信息或已禁用',
  531. ];
  532. }
  533. // 检查仓库库存
  534. $warehouse = MexWarehouse::where('item_id', $itemId)->first();
  535. if (!$warehouse || $warehouse->quantity <= 0) {
  536. return [
  537. 'can_match' => false,
  538. 'message' => '仓库库存不足',
  539. ];
  540. }
  541. // 检查是否有符合条件的待撮合用户买入物品订单
  542. $pendingBuyOrders = MexOrder::where('item_id', $itemId)
  543. ->where('order_type', OrderType::BUY)
  544. ->where('status', OrderStatus::PENDING)
  545. ->where('price', '>=', $priceConfig->max_price) // 价格≥最高价
  546. ->where('quantity', '<=', $priceConfig->protection_threshold) // 数量≤保护阈值
  547. ->count();
  548. if ($pendingBuyOrders === 0) {
  549. return [
  550. 'can_match' => false,
  551. 'message' => '没有符合条件的待撮合用户买入物品订单',
  552. ];
  553. }
  554. return [
  555. 'can_match' => true,
  556. 'message' => '用户买入物品撮合条件满足',
  557. 'warehouse' => $warehouse,
  558. 'price_config' => $priceConfig,
  559. 'pending_orders' => $pendingBuyOrders,
  560. ];
  561. }
  562. /**
  563. * 检查用户卖出物品撮合条件
  564. *
  565. * @param int $itemId 商品ID
  566. * @return array 检查结果
  567. */
  568. public static function checkUserSellItemMatchConditions(int $itemId): array
  569. {
  570. // 检查价格配置
  571. $priceConfig = MexPriceConfig::where('item_id', $itemId)->where('is_enabled', true)->first();
  572. if (!$priceConfig) {
  573. return [
  574. 'can_match' => false,
  575. 'message' => '商品未配置价格信息或已禁用',
  576. ];
  577. }
  578. // 检查是否有待撮合的用户卖出物品订单
  579. $pendingSellOrders = MexOrder::where('item_id', $itemId)
  580. ->where('order_type', OrderType::SELL)
  581. ->where('status', OrderStatus::PENDING)
  582. ->count();
  583. if ($pendingSellOrders === 0) {
  584. return [
  585. 'can_match' => false,
  586. 'message' => '没有待撮合的用户卖出物品订单',
  587. ];
  588. }
  589. return [
  590. 'can_match' => true,
  591. 'message' => '用户卖出物品撮合条件满足',
  592. 'price_config' => $priceConfig,
  593. 'pending_orders' => $pendingSellOrders,
  594. ];
  595. }
  596. /**
  597. * 获取用户买入物品撮合统计信息
  598. *
  599. * @return array 统计信息
  600. */
  601. public static function getUserBuyItemMatchStats(): array
  602. {
  603. // 获取待撮合用户买入物品订单统计
  604. $pendingStats = MexOrder::where('order_type', OrderType::BUY)
  605. ->where('status', OrderStatus::PENDING)
  606. ->selectRaw('
  607. COUNT(*) as total_pending,
  608. COUNT(DISTINCT item_id) as pending_items,
  609. SUM(quantity) as total_quantity,
  610. SUM(total_amount) as total_amount
  611. ')
  612. ->first();
  613. // 获取今日用户买入物品撮合统计
  614. $todayStats = MexTransaction::where('transaction_type', TransactionType::USER_BUY)
  615. ->whereDate('created_at', today())
  616. ->selectRaw('
  617. COUNT(*) as today_matched,
  618. SUM(quantity) as today_quantity,
  619. SUM(total_amount) as today_amount
  620. ')
  621. ->first();
  622. // 获取有库存的商品数量
  623. $availableItems = MexWarehouse::where('quantity', '>', 0)->count();
  624. return [
  625. 'pending_orders' => $pendingStats->total_pending ?? 0,
  626. 'pending_items' => $pendingStats->pending_items ?? 0,
  627. 'pending_quantity' => $pendingStats->total_quantity ?? 0,
  628. 'pending_amount' => $pendingStats->total_amount ?? '0.00000',
  629. 'today_matched' => $todayStats->today_matched ?? 0,
  630. 'today_quantity' => $todayStats->today_quantity ?? 0,
  631. 'today_amount' => $todayStats->today_amount ?? '0.00000',
  632. 'available_items' => $availableItems,
  633. 'stats_time' => now(),
  634. ];
  635. }
  636. /**
  637. * 获取用户卖出物品撮合统计信息
  638. *
  639. * @return array 统计信息
  640. */
  641. public static function getUserSellItemMatchStats(): array
  642. {
  643. // 获取待撮合用户卖出物品订单统计
  644. $pendingStats = MexOrder::where('order_type', OrderType::SELL)
  645. ->where('status', OrderStatus::PENDING)
  646. ->selectRaw('
  647. COUNT(*) as total_pending,
  648. COUNT(DISTINCT item_id) as pending_items,
  649. SUM(quantity) as total_quantity,
  650. SUM(total_amount) as total_amount
  651. ')
  652. ->first();
  653. // 获取今日用户卖出物品撮合统计
  654. $todayStats = MexTransaction::where('transaction_type', TransactionType::USER_SELL)
  655. ->whereDate('created_at', today())
  656. ->selectRaw('
  657. COUNT(*) as today_matched,
  658. SUM(quantity) as today_quantity,
  659. SUM(total_amount) as today_amount
  660. ')
  661. ->first();
  662. return [
  663. 'pending_orders' => $pendingStats->total_pending ?? 0,
  664. 'pending_items' => $pendingStats->pending_items ?? 0,
  665. 'pending_quantity' => $pendingStats->total_quantity ?? 0,
  666. 'pending_amount' => $pendingStats->total_amount ?? '0.00000',
  667. 'today_matched' => $todayStats->today_matched ?? 0,
  668. 'today_quantity' => $todayStats->today_quantity ?? 0,
  669. 'today_amount' => $todayStats->today_amount ?? '0.00000',
  670. 'stats_time' => now(),
  671. ];
  672. }
  673. // 保留旧方法以兼容现有代码
  674. /**
  675. * 获取撮合统计信息(已废弃,请使用getUserBuyItemMatchStats)
  676. *
  677. * @deprecated 请使用getUserBuyItemMatchStats或getUserSellItemMatchStats
  678. * @return array 统计信息
  679. */
  680. public static function getMatchStats(): array
  681. {
  682. return self::getUserBuyItemMatchStats();
  683. }
  684. /**
  685. * 检查撮合条件(已废弃,请使用checkUserBuyItemMatchConditions)
  686. *
  687. * @deprecated 请使用checkUserBuyItemMatchConditions或checkUserSellItemMatchConditions
  688. * @param int $itemId 商品ID
  689. * @return array 检查结果
  690. */
  691. public static function checkMatchConditions(int $itemId): array
  692. {
  693. return self::checkUserBuyItemMatchConditions($itemId);
  694. }
  695. /**
  696. * 执行撮合任务(已废弃,请使用executeUserBuyItemMatch)
  697. *
  698. * @deprecated 请使用executeUserBuyItemMatch或executeUserSellItemMatch
  699. * @param int|null $itemId 指定商品ID,null表示处理所有商品
  700. * @param int $batchSize 批处理大小
  701. * @return array 撮合结果
  702. */
  703. public static function executeMatch(?int $itemId = null, int $batchSize = 100): array
  704. {
  705. return self::executeUserBuyItemMatch($itemId, $batchSize);
  706. }
  707. /**
  708. * 执行单个商品的撮合(已废弃,请使用executeUserBuyItemMatchForItem)
  709. *
  710. * @deprecated 请使用executeUserBuyItemMatchForItem或executeUserSellItemMatchForItem
  711. * @param int $itemId 商品ID
  712. * @param int $batchSize 批处理大小
  713. * @return array 撮合结果
  714. */
  715. public static function executeItemMatch(int $itemId, int $batchSize = 100): array
  716. {
  717. return self::executeUserBuyItemMatchForItem($itemId, $batchSize);
  718. }
  719. /**
  720. * 将用户冻结资金转入仓库账户
  721. *
  722. * @param int $userId 用户ID
  723. * @param string $amount 金额
  724. * @param int $orderId 订单ID
  725. * @param FUND_CURRENCY_TYPE|null $currencyType 币种类型,默认使用钻石
  726. * @return array 转移结果
  727. */
  728. private static function transferFrozenFundsToWarehouse(int $userId, string $amount, int $orderId, ?FUND_CURRENCY_TYPE $currencyType = null): array
  729. {
  730. try {
  731. // 获取币种类型,默认使用钻石
  732. $currencyType = $currencyType ?? FundLogic::getDefaultCurrency();
  733. // 获取对应的冻结账户类型
  734. $frozenAccountType = FundLogic::getFrozenAccountType($currencyType);
  735. if (!$frozenAccountType) {
  736. return [
  737. 'success' => false,
  738. 'message' => '不支持的币种类型',
  739. ];
  740. }
  741. // 从用户冻结账户转移到仓库账户
  742. $fundService = new FundService($userId, $frozenAccountType->value);
  743. $precision = $currencyType->getPrecision();
  744. $fundAmount = (int)bcmul($amount, bcpow('10', $precision), 0); // 根据币种精度转换
  745. $result = $fundService->trade(
  746. self::WAREHOUSE_USER_ID,
  747. $fundAmount,
  748. 'MEX_ORDER',
  749. $orderId,
  750. '用户买入物品撮合-资金转移'
  751. );
  752. if (is_string($result)) {
  753. return [
  754. 'success' => false,
  755. 'message' => $result,
  756. ];
  757. }
  758. return [
  759. 'success' => true,
  760. 'message' => '资金转移成功',
  761. 'data' => $result,
  762. ];
  763. } catch (\Exception $e) {
  764. return [
  765. 'success' => false,
  766. 'message' => '资金转移异常:' . $e->getMessage(),
  767. ];
  768. }
  769. }
  770. /**
  771. * 将仓库账户物品转出到用户账户
  772. *
  773. * @param int $userId 用户ID
  774. * @param int $itemId 物品ID
  775. * @param int $quantity 数量
  776. * @param int $orderId 订单ID
  777. * @return array 转移结果
  778. */
  779. private static function transferItemsFromWarehouseToUser(int $userId, int $itemId, int $quantity, int $orderId): array
  780. {
  781. try {
  782. // 添加物品到用户账户
  783. $result = ItemService::addItem($userId, $itemId, $quantity, [
  784. 'source' => 'mex_order',
  785. 'source_type' => REWARD_SOURCE_TYPE::MEX_BUY,
  786. 'source_id' => $orderId,
  787. 'remark' => '用户买入物品撮合-物品转移',
  788. ]);
  789. if (!$result || !isset($result['success']) || !$result['success']) {
  790. return [
  791. 'success' => false,
  792. 'message' => '物品添加失败:' . ($result['message'] ?? '未知错误'),
  793. ];
  794. }
  795. return [
  796. 'success' => true,
  797. 'message' => '物品转移成功',
  798. 'data' => $result,
  799. ];
  800. } catch (\Exception $e) {
  801. return [
  802. 'success' => false,
  803. 'message' => '物品转移异常:' . $e->getMessage(),
  804. ];
  805. }
  806. }
  807. /**
  808. * 将用户冻结物品转入仓库账户
  809. *
  810. * @param int $userId 用户ID
  811. * @param int $itemId 物品ID
  812. * @param int $quantity 数量
  813. * @param int $orderId 订单ID
  814. * @return array 转移结果
  815. */
  816. private static function transferFrozenItemsToWarehouse(int $userId, int $itemId, int $quantity, int $orderId): array
  817. {
  818. try {
  819. // TODO: 这里需要实现从用户冻结物品转移到仓库的逻辑
  820. // 由于物品冻结功能比较复杂,这里先返回成功,后续完善
  821. // 消耗用户物品(包括冻结的物品)
  822. $result = ItemService::consumeItem($userId, $itemId, null, $quantity, [
  823. 'source' => 'mex_order',
  824. 'source_id' => $orderId,
  825. 'remark' => '用户卖出物品撮合-物品转移',
  826. 'include_frozen' => true, // 包括冻结的物品
  827. ]);
  828. if (!$result || !isset($result['success']) || !$result['success']) {
  829. return [
  830. 'success' => false,
  831. 'message' => '物品消耗失败:' . ($result['message'] ?? '未知错误'),
  832. ];
  833. }
  834. return [
  835. 'success' => true,
  836. 'message' => '物品转移成功',
  837. 'data' => $result,
  838. ];
  839. } catch (\Exception $e) {
  840. return [
  841. 'success' => false,
  842. 'message' => '物品转移异常:' . $e->getMessage(),
  843. ];
  844. }
  845. }
  846. /**
  847. * 将仓库账户资金转出到用户账户
  848. *
  849. * @param int $userId 用户ID
  850. * @param string $amount 金额
  851. * @param int $orderId 订单ID
  852. * @param FUND_CURRENCY_TYPE|null $currencyType 币种类型,默认使用钻石
  853. * @return array 转移结果
  854. */
  855. private static function transferFundsFromWarehouseToUser(int $userId, string $amount, int $orderId, ?FUND_CURRENCY_TYPE $currencyType = null): array
  856. {
  857. try {
  858. // 获取币种类型,默认使用钻石
  859. $currencyType = $currencyType ?? FundLogic::getDefaultCurrency();
  860. // 获取对应的可用账户类型
  861. $availableAccountType = FundLogic::getAvailableAccountType($currencyType);
  862. if (!$availableAccountType) {
  863. return [
  864. 'success' => false,
  865. 'message' => '不支持的币种类型',
  866. ];
  867. }
  868. // 从仓库账户转移到用户账户
  869. $fundService = new FundService(self::WAREHOUSE_USER_ID, $availableAccountType->value);
  870. $precision = $currencyType->getPrecision();
  871. $fundAmount = (int)bcmul($amount, bcpow('10', $precision), 0); // 根据币种精度转换
  872. $result = $fundService->trade(
  873. $userId,
  874. $fundAmount,
  875. 'MEX_ORDER',
  876. $orderId,
  877. '用户卖出物品撮合-资金转移'
  878. );
  879. if (is_string($result)) {
  880. return [
  881. 'success' => false,
  882. 'message' => $result,
  883. ];
  884. }
  885. return [
  886. 'success' => true,
  887. 'message' => '资金转移成功',
  888. 'data' => $result,
  889. ];
  890. } catch (\Exception $e) {
  891. return [
  892. 'success' => false,
  893. 'message' => '资金转移异常:' . $e->getMessage(),
  894. ];
  895. }
  896. }
  897. }