MexOrderLogic.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. <?php
  2. namespace App\Module\Mex\Logic;
  3. use App\Module\Mex\Models\MexOrder;
  4. use App\Module\Mex\Models\MexPriceConfig;
  5. use App\Module\Mex\Enums\OrderType;
  6. use App\Module\Mex\Enums\OrderStatus;
  7. use App\Module\Mex\Events\OrderCreatedEvent;
  8. use App\Module\Fund\Enums\FUND_CURRENCY_TYPE;
  9. use App\Module\Mex\Logic\FundLogic;
  10. use App\Module\GameItems\Services\ItemService;
  11. use App\Module\GameItems\Enums\FREEZE_REASON_TYPE;
  12. use Illuminate\Support\Facades\Log;
  13. use UCore\Helper\Logger;
  14. /**
  15. * 农贸市场订单逻辑
  16. *
  17. * 处理订单相关的核心业务逻辑
  18. */
  19. class MexOrderLogic
  20. {
  21. /**
  22. * 创建卖出订单
  23. *
  24. * @param int $userId 用户ID
  25. * @param int $itemId 商品ID
  26. * @param int $quantity 数量
  27. * @param float $price 价格(信任Fund模块的数据处理)
  28. * @param FUND_CURRENCY_TYPE|null $currencyType 币种类型,默认使用钻石
  29. * @return array 操作结果
  30. */
  31. public static function createSellOrder(int $userId, int $itemId, int $quantity, float $price, ?FUND_CURRENCY_TYPE $currencyType = null): array
  32. {
  33. // 检查事务状态,确保调用者已开启事务
  34. \UCore\Db\Helper::check_tr();
  35. // 获取币种类型,默认使用钻石
  36. $currencyType = $currencyType ?? FundLogic::getDefaultCurrency();
  37. // 验证价格配置是否存在(不验证价格范围,挂单阶段无价格验证)
  38. $priceConfig = MexPriceConfig::where('item_id', $itemId)->where('is_enabled', true)->first();
  39. if (!$priceConfig) {
  40. return [ 'success' => false, 'message' => '商品未配置价格信息' ];
  41. }
  42. // 直接计算总金额,信任Fund模块的精度处理
  43. $totalAmount = bcmul($price, $quantity, 9);
  44. try {
  45. // 1. 验证用户是否有足够的物品
  46. $checkResult = ItemService::checkItemQuantity($userId, $itemId, $quantity);
  47. if (!$checkResult->success) {
  48. return [ 'success' => false, 'message' => $checkResult->message ];
  49. }
  50. // 2. 创建订单记录
  51. $order = MexOrder::create([
  52. 'user_id' => $userId,
  53. 'item_id' => $itemId,
  54. 'currency_type' => $currencyType->value,
  55. 'order_type' => OrderType::SELL,
  56. 'quantity' => $quantity,
  57. 'price' => $price,
  58. 'total_amount' => $totalAmount,
  59. 'status' => OrderStatus::PENDING,
  60. ]);
  61. // 3. 冻结用户物品
  62. $freezeResult = ItemService::freezeItem(
  63. $userId,
  64. $itemId,
  65. null, // 统一属性物品,不需要实例ID
  66. $quantity,
  67. "农贸市场卖出订单冻结,订单ID:{$order->id}",
  68. [
  69. 'reason_type' => FREEZE_REASON_TYPE::TRADE_ORDER->value,
  70. 'source_id' => $order->id,
  71. 'source_type' => 'mex_sell_order',
  72. ]
  73. );
  74. if (!$freezeResult['success']) {
  75. throw new \Exception('冻结物品失败:' . $freezeResult['message']);
  76. }
  77. // 4. 触发订单创建事件
  78. event(new OrderCreatedEvent($order));
  79. return [
  80. 'success' => true,
  81. 'order_id' => $order->id,
  82. 'freeze_log_id' => $freezeResult['freeze_log_id'] ?? null,
  83. 'message' => '卖出订单创建成功,等待撮合'
  84. ];
  85. } catch (\Exception $e) {
  86. Log::error('创建卖出订单失败', [
  87. 'user_id' => $userId,
  88. 'item_id' => $itemId,
  89. 'error' => $e->getMessage()
  90. ]);
  91. throw $e; // 重新抛出异常,不隐藏错误
  92. }
  93. }
  94. /**
  95. * 创建买入订单
  96. *
  97. * @param int $userId 用户ID
  98. * @param int $itemId 商品ID
  99. * @param int $quantity 数量
  100. * @param float $price 价格(信任Fund模块的数据处理)
  101. * @param FUND_CURRENCY_TYPE|null $currencyType 币种类型,默认使用钻石
  102. * @return array 操作结果
  103. */
  104. public static function createBuyOrder(int $userId, int $itemId, int $quantity, float $price, ?FUND_CURRENCY_TYPE $currencyType = null): array
  105. {
  106. // 检查事务状态,确保调用者已开启事务
  107. \UCore\Db\Helper::check_tr();
  108. // 获取币种类型,默认使用钻石
  109. $currencyType = $currencyType ?? FundLogic::getDefaultCurrency();
  110. // 验证价格配置是否存在(不验证价格范围和保护阈值,挂单阶段无价格验证)
  111. $priceConfig = MexPriceConfig::where('item_id', $itemId)->where('is_enabled', true)->first();
  112. if (!$priceConfig) {
  113. return [ 'success' => false, 'message' => '商品未配置价格信息' ];
  114. }
  115. // 直接计算总金额,信任Fund模块的精度处理
  116. $totalAmount = bcmul($price, $quantity, 9);
  117. Logger::debug(" create ");
  118. try {
  119. // 1. 创建订单记录
  120. $order = MexOrder::create([
  121. 'user_id' => $userId,
  122. 'item_id' => $itemId,
  123. 'currency_type' => $currencyType->value,
  124. 'order_type' => OrderType::BUY,
  125. 'quantity' => $quantity,
  126. 'price' => $price,
  127. 'total_amount' => $totalAmount,
  128. 'status' => OrderStatus::PENDING,
  129. 'frozen_amount' => $totalAmount,
  130. ]);
  131. // 2. 冻结用户资金
  132. $freezeResult = self::freezeOrderFunds($order);
  133. if (!$freezeResult['success']) {
  134. return [ 'success' => false, 'message' => '冻结资金失败:' . $freezeResult['message'] ];
  135. }
  136. // 触发订单创建事件
  137. event(new OrderCreatedEvent($order));
  138. return [
  139. 'success' => true,
  140. 'order_id' => $order->id,
  141. 'message' => '买入订单创建成功,等待撮合'
  142. ];
  143. } catch (\Exception $e) {
  144. Log::error('创建买入订单失败', [
  145. 'user_id' => $userId,
  146. 'item_id' => $itemId,
  147. 'error' => $e->getMessage()
  148. ]);
  149. throw $e; // 重新抛出异常,不隐藏错误
  150. }
  151. }
  152. /**
  153. * 取消订单
  154. *
  155. * @param int $userId 用户ID
  156. * @param int $orderId 订单ID
  157. * @return array 操作结果
  158. */
  159. public static function cancelOrder(int $userId, int $orderId): array
  160. {
  161. // 检查事务状态,确保调用者已开启事务
  162. \UCore\Db\Helper::check_tr();
  163. $order = MexOrder::where('id', $orderId)->where('user_id', $userId)->first();
  164. if (!$order) {
  165. return [ 'success' => false, 'message' => '订单不存在' ];
  166. }
  167. if ($order->status !== OrderStatus::PENDING) {
  168. return [ 'success' => false, 'message' => '只能取消等待中的订单' ];
  169. }
  170. // 1. 更新订单状态为取消
  171. $order->update([ 'status' => OrderStatus::CANCELLED ]);
  172. // 2. 处理解冻逻辑
  173. if ($order->order_type === OrderType::SELL) {
  174. // 卖出订单:解冻物品
  175. $unfreezeResult = self::unfreezeOrderItems($order);
  176. if (!$unfreezeResult['success']) {
  177. return [ 'success' => false, 'message' => '解冻物品失败:' . $unfreezeResult['message'] ];
  178. }
  179. } elseif ($order->order_type === OrderType::BUY) {
  180. // 买入订单:解冻资金
  181. $unfreezeResult = self::unfreezeOrderFunds($order);
  182. if (!$unfreezeResult['success']) {
  183. return [ 'success' => false, 'message' => '解冻资金失败:' . $unfreezeResult['message'] ];
  184. }
  185. }
  186. return [ 'success' => true, 'message' => '订单已取消' ];
  187. }
  188. /**
  189. * 获取用户订单列表
  190. *
  191. * @param int $userId 用户ID
  192. * @param int $page 页码
  193. * @param int $pageSize 每页数量
  194. * @return array 订单列表
  195. */
  196. public static function getUserOrders(int $userId, int $page = 1, int $pageSize = 20, $itemId = null): array
  197. {
  198. $where['user_id'] = $userId;
  199. if ($itemId) {
  200. $where['item_id'] = $itemId;
  201. }
  202. $orders = MexOrder::where($where)
  203. ->orderBy('created_at', 'desc')
  204. ->paginate($pageSize, [ '*' ], 'page', $page);
  205. return [
  206. 'orders' => $orders->items(),
  207. 'total' => $orders->total(),
  208. 'page' => $page,
  209. 'page_size' => $pageSize,
  210. ];
  211. }
  212. /**
  213. * 获取订单详情
  214. *
  215. * @param int $userId 用户ID
  216. * @param int $orderId 订单ID
  217. * @return array|null 订单详情
  218. */
  219. public static function getOrderDetail(int $userId, int $orderId): ?array
  220. {
  221. $order = MexOrder::where('id', $orderId)->where('user_id', $userId)->first();
  222. return $order ? $order->toArray() : null;
  223. }
  224. /**
  225. * 解冻订单相关的物品(卖出订单取消时使用)
  226. *
  227. * @param MexOrder $order 订单对象
  228. * @return array 解冻结果
  229. */
  230. private static function unfreezeOrderItems(MexOrder $order): array
  231. {
  232. // 查找该订单相关的冻结记录
  233. $freezeLogs = \App\Module\GameItems\Models\ItemFreezeLog::where('source_id', $order->id)
  234. ->where('source_type', 'mex_sell_order')
  235. ->where('action_type', \App\Module\GameItems\Enums\FREEZE_ACTION_TYPE::FREEZE)
  236. ->get();
  237. if ($freezeLogs->isEmpty()) {
  238. return [ 'success' => true, 'message' => '没有找到需要解冻的物品' ];
  239. }
  240. $unfrozenCount = 0;
  241. foreach ($freezeLogs as $freezeLog) {
  242. // 使用ItemService解冻物品
  243. \App\Module\GameItems\Services\ItemService::safeUnfreezeItem($freezeLog->id);
  244. $unfrozenCount++;
  245. }
  246. return [
  247. 'success' => true,
  248. 'message' => "成功解冻 {$unfrozenCount} 个冻结记录",
  249. 'unfrozen_count' => $unfrozenCount
  250. ];
  251. }
  252. /**
  253. * 冻结订单相关的资金(买入订单创建时使用)
  254. *
  255. * @param MexOrder $order 订单对象
  256. * @return array 冻结结果
  257. */
  258. private static function freezeOrderFunds(MexOrder $order): array
  259. {
  260. try {
  261. // 获取可用账户类型和冻结账户类型
  262. $availableAccountType = FundLogic::getAvailableAccountType($order->currency_type);
  263. $frozenAccountType = FundLogic::getFrozenAccountType($order->currency_type);
  264. if (!$availableAccountType || !$frozenAccountType) {
  265. return [ 'success' => false, 'message' => '不支持的币种类型' ];
  266. }
  267. // 创建Fund服务实例(可用账户)
  268. $fundService = new \App\Module\Fund\Services\FundService($order->user_id, $availableAccountType->value);
  269. // 验证用户可用余额是否充足
  270. if ($fundService->balance() < $order->frozen_amount) {
  271. return [ 'success' => false, 'message' => '可用余额不足' ];
  272. }
  273. // 使用circulation方法将资金从可用账户转移到冻结账户
  274. $circulationResult = $fundService->circulation(
  275. $frozenAccountType,
  276. (float)$order->frozen_amount,
  277. $order->id,
  278. 'mex_buy_order',
  279. "农贸市场买入订单冻结,订单ID:{$order->id}"
  280. );
  281. if (is_string($circulationResult)) {
  282. return [ 'success' => false, 'message' => '资金冻结失败:' . $circulationResult ];
  283. }
  284. return [
  285. 'success' => true,
  286. 'message' => '资金冻结成功',
  287. 'frozen_amount' => $order->frozen_amount,
  288. 'circulation_id' => $circulationResult->id ?? null
  289. ];
  290. } catch (\Exception $e) {
  291. Log::error('冻结订单资金失败', [
  292. 'order_id' => $order->id,
  293. 'error' => $e->getMessage()
  294. ]);
  295. throw $e; // 重新抛出异常,不隐藏错误
  296. }
  297. }
  298. /**
  299. * 解冻订单相关的资金(买入订单取消时使用)
  300. *
  301. * @param MexOrder $order 订单对象
  302. * @return array 解冻结果
  303. */
  304. private static function unfreezeOrderFunds(MexOrder $order): array
  305. {
  306. try {
  307. // 获取可用账户类型和冻结账户类型
  308. $availableAccountType = FundLogic::getAvailableAccountType($order->currency_type);
  309. $frozenAccountType = FundLogic::getFrozenAccountType($order->currency_type);
  310. if (!$availableAccountType || !$frozenAccountType) {
  311. return [ 'success' => false, 'message' => '不支持的币种类型' ];
  312. }
  313. // 创建Fund服务实例(冻结账户)
  314. $fundService = new \App\Module\Fund\Services\FundService($order->user_id, $frozenAccountType->value);
  315. // 验证冻结账户余额是否充足
  316. if ($fundService->balance() < $order->frozen_amount) {
  317. return [ 'success' => false, 'message' => '冻结账户余额不足,可能已被解冻' ];
  318. }
  319. // 使用circulation方法将资金从冻结账户转移回可用账户
  320. $circulationResult = $fundService->circulation(
  321. $availableAccountType,
  322. (float)$order->frozen_amount,
  323. $order->id,
  324. 'mex_buy_order_cancel',
  325. "农贸市场买入订单取消解冻,订单ID:{$order->id}"
  326. );
  327. if (is_string($circulationResult)) {
  328. return [ 'success' => false, 'message' => '资金解冻失败:' . $circulationResult ];
  329. }
  330. return [
  331. 'success' => true,
  332. 'message' => '资金解冻成功',
  333. 'unfrozen_amount' => $order->frozen_amount,
  334. 'circulation_id' => $circulationResult->id ?? null
  335. ];
  336. } catch (\Exception $e) {
  337. Log::error('解冻订单资金失败', [
  338. 'order_id' => $order->id,
  339. 'error' => $e->getMessage()
  340. ]);
  341. throw $e; // 重新抛出异常,不隐藏错误
  342. }
  343. }
  344. /**
  345. * 获取待撮合的买入订单
  346. * 根据文档要求:二级排序(价格DESC + 时间ASC),移除数量排序
  347. *
  348. * @param int $itemId 商品ID
  349. * @param int $limit 限制数量
  350. * @return array 订单列表
  351. */
  352. public static function getPendingBuyOrders(int $itemId, int $limit = 100): array
  353. {
  354. $orders = MexOrder::where('item_id', $itemId)
  355. ->where('order_type', OrderType::BUY)
  356. ->where('status', OrderStatus::PENDING)
  357. ->orderBy('price', 'desc') // 价格优先(高价优先)
  358. ->orderBy('created_at', 'asc') // 时间优先(早下单优先)
  359. ->limit($limit)
  360. ->get();
  361. return $orders->toArray();
  362. }
  363. }