MexMatchLogic.php 35 KB

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