MexMatchLogic.php 42 KB

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