MexOrderLogic.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. // 1. 更新订单状态为取消
  161. $order->update([ 'status' => OrderStatus::CANCELLED ]);
  162. // 2. 处理解冻逻辑
  163. if ($order->order_type === OrderType::SELL) {
  164. // 卖出订单:解冻物品
  165. $unfreezeResult = self::unfreezeOrderItems($order);
  166. if (!$unfreezeResult['success']) {
  167. return [ 'success' => false, 'message' => '解冻物品失败:' . $unfreezeResult['message'] ];
  168. }
  169. } elseif ($order->order_type === OrderType::BUY) {
  170. // 买入订单:解冻资金
  171. $unfreezeResult = self::unfreezeOrderFunds($order);
  172. if (!$unfreezeResult['success']) {
  173. return [ 'success' => false, 'message' => '解冻资金失败:' . $unfreezeResult['message'] ];
  174. }
  175. }
  176. return [ 'success' => true, 'message' => '订单已取消' ];
  177. }
  178. /**
  179. * 获取用户订单列表
  180. *
  181. * @param int $userId 用户ID
  182. * @param int $page 页码
  183. * @param int $pageSize 每页数量
  184. * @return array 订单列表
  185. */
  186. public static function getUserOrders(int $userId, int $page = 1, int $pageSize = 20, $itemId = null): array
  187. {
  188. $where['user_id'] = $userId;
  189. if ($itemId) {
  190. $where['item_id'] = $itemId;
  191. }
  192. $orders = MexOrder::where($where)
  193. ->orderBy('created_at', 'desc')
  194. ->paginate($pageSize, [ '*' ], 'page', $page);
  195. return [
  196. 'orders' => $orders->items(),
  197. 'total' => $orders->total(),
  198. 'page' => $page,
  199. 'page_size' => $pageSize,
  200. ];
  201. }
  202. /**
  203. * 获取订单详情
  204. *
  205. * @param int $userId 用户ID
  206. * @param int $orderId 订单ID
  207. * @return array|null 订单详情
  208. */
  209. public static function getOrderDetail(int $userId, int $orderId): ?array
  210. {
  211. $order = MexOrder::where('id', $orderId)->where('user_id', $userId)->first();
  212. return $order ? $order->toArray() : null;
  213. }
  214. /**
  215. * 解冻订单相关的物品(卖出订单取消时使用)
  216. *
  217. * @param MexOrder $order 订单对象
  218. * @return array 解冻结果
  219. */
  220. private static function unfreezeOrderItems(MexOrder $order): array
  221. {
  222. // 查找该订单相关的冻结记录
  223. $freezeLogs = \App\Module\GameItems\Models\ItemFreezeLog::where('source_id', $order->id)
  224. ->where('source_type', 'mex_sell_order')
  225. ->where('action_type', \App\Module\GameItems\Enums\FREEZE_ACTION_TYPE::FREEZE)
  226. ->get();
  227. if ($freezeLogs->isEmpty()) {
  228. return [ 'success' => true, 'message' => '没有找到需要解冻的物品' ];
  229. }
  230. $unfrozenCount = 0;
  231. foreach ($freezeLogs as $freezeLog) {
  232. // 使用ItemService解冻物品
  233. \App\Module\GameItems\Services\ItemService::safeUnfreezeItem($freezeLog->id);
  234. $unfrozenCount++;
  235. }
  236. return [
  237. 'success' => true,
  238. 'message' => "成功解冻 {$unfrozenCount} 个冻结记录",
  239. 'unfrozen_count' => $unfrozenCount
  240. ];
  241. }
  242. /**
  243. * 冻结订单相关的资金(买入订单创建时使用)
  244. *
  245. * @param MexOrder $order 订单对象
  246. * @return array 冻结结果
  247. */
  248. private static function freezeOrderFunds(MexOrder $order): array
  249. {
  250. try {
  251. // 获取可用账户类型和冻结账户类型
  252. $availableAccountType = FundLogic::getAvailableAccountType($order->currency_type);
  253. $frozenAccountType = FundLogic::getFrozenAccountType($order->currency_type);
  254. if (!$availableAccountType || !$frozenAccountType) {
  255. return [ 'success' => false, 'message' => '不支持的币种类型' ];
  256. }
  257. // 创建Fund服务实例(可用账户)
  258. $fundService = new \App\Module\Fund\Services\FundService($order->user_id, $availableAccountType->value);
  259. // 验证用户可用余额是否充足
  260. if ($fundService->balance() < $order->frozen_amount) {
  261. return [ 'success' => false, 'message' => '可用余额不足' ];
  262. }
  263. // 使用circulation方法将资金从可用账户转移到冻结账户
  264. $circulationResult = $fundService->circulation(
  265. $frozenAccountType,
  266. (float)$order->frozen_amount,
  267. $order->id,
  268. 'mex_buy_order',
  269. "农贸市场买入订单冻结,订单ID:{$order->id}"
  270. );
  271. if (is_string($circulationResult)) {
  272. return [ 'success' => false, 'message' => '资金冻结失败:' . $circulationResult ];
  273. }
  274. return [
  275. 'success' => true,
  276. 'message' => '资金冻结成功',
  277. 'frozen_amount' => $order->frozen_amount,
  278. 'circulation_id' => $circulationResult->id ?? null
  279. ];
  280. } catch (\Exception $e) {
  281. return [ 'success' => false, 'message' => '冻结资金异常:' . $e->getMessage() ];
  282. }
  283. }
  284. /**
  285. * 解冻订单相关的资金(买入订单取消时使用)
  286. *
  287. * @param MexOrder $order 订单对象
  288. * @return array 解冻结果
  289. */
  290. private static function unfreezeOrderFunds(MexOrder $order): array
  291. {
  292. try {
  293. // 获取可用账户类型和冻结账户类型
  294. $availableAccountType = FundLogic::getAvailableAccountType($order->currency_type);
  295. $frozenAccountType = FundLogic::getFrozenAccountType($order->currency_type);
  296. if (!$availableAccountType || !$frozenAccountType) {
  297. return [ 'success' => false, 'message' => '不支持的币种类型' ];
  298. }
  299. // 创建Fund服务实例(冻结账户)
  300. $fundService = new \App\Module\Fund\Services\FundService($order->user_id, $frozenAccountType->value);
  301. // 验证冻结账户余额是否充足
  302. if ($fundService->balance() < $order->frozen_amount) {
  303. return [ 'success' => false, 'message' => '冻结账户余额不足,可能已被解冻' ];
  304. }
  305. // 使用circulation方法将资金从冻结账户转移回可用账户
  306. $circulationResult = $fundService->circulation(
  307. $availableAccountType,
  308. (float)$order->frozen_amount,
  309. $order->id,
  310. 'mex_buy_order_cancel',
  311. "农贸市场买入订单取消解冻,订单ID:{$order->id}"
  312. );
  313. if (is_string($circulationResult)) {
  314. return [ 'success' => false, 'message' => '资金解冻失败:' . $circulationResult ];
  315. }
  316. return [
  317. 'success' => true,
  318. 'message' => '资金解冻成功',
  319. 'unfrozen_amount' => $order->frozen_amount,
  320. 'circulation_id' => $circulationResult->id ?? null
  321. ];
  322. } catch (\Exception $e) {
  323. return [ 'success' => false, 'message' => '解冻资金异常:' . $e->getMessage() ];
  324. }
  325. }
  326. /**
  327. * 获取待撮合的买入订单
  328. * 根据文档要求:二级排序(价格DESC + 时间ASC),移除数量排序
  329. *
  330. * @param int $itemId 商品ID
  331. * @param int $limit 限制数量
  332. * @return array 订单列表
  333. */
  334. public static function getPendingBuyOrders(int $itemId, int $limit = 100): array
  335. {
  336. $orders = MexOrder::where('item_id', $itemId)
  337. ->where('order_type', OrderType::BUY)
  338. ->where('status', OrderStatus::PENDING)
  339. ->orderBy('price', 'desc') // 价格优先(高价优先)
  340. ->orderBy('created_at', 'asc') // 时间优先(早下单优先)
  341. ->limit($limit)
  342. ->get();
  343. return $orders->toArray();
  344. }
  345. }