MexOrderLogic.php 15 KB

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