MexOrderLogic.php 15 KB

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