MexMatchLogic.php 35 KB

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