ThirdGameOrderService.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. <?php
  2. namespace App\Services;
  3. use App\Models\ThirdGameOrder as ThirdGameOrderModel;
  4. use Carbon\Carbon;
  5. use Illuminate\Support\Facades\DB;
  6. class ThirdGameOrderService
  7. {
  8. private const GAME_TYPE_NAMES = [
  9. 1 => '视讯',
  10. 2 => '老虎机',
  11. 3 => '彩票',
  12. 4 => '体育',
  13. 5 => '电竞',
  14. 6 => '捕猎',
  15. 7 => '棋牌',
  16. ];
  17. private const STATUS_NAMES = [
  18. 0 => '未完成',
  19. 1 => '已完成',
  20. 2 => '已取消',
  21. 3 => '已撤单',
  22. ];
  23. private ThirdGameBalanceService $provider;
  24. public function __construct(ThirdGameBalanceService $provider)
  25. {
  26. $this->provider = $provider;
  27. }
  28. public function syncHistory(
  29. string $startTime,
  30. string $endTime,
  31. int $page = 1,
  32. int $limit = 2000
  33. ): array {
  34. return $this->persistProviderResult(
  35. $this->provider->historyOrders($startTime, $endTime, $page, $limit)
  36. );
  37. }
  38. public function syncRealtime(int $page = 1, int $limit = 2000): array
  39. {
  40. return $this->persistProviderResult($this->provider->realtimeOrders($page, $limit));
  41. }
  42. private function persistProviderResult(array $result): array
  43. {
  44. if (empty($result['ok'])) {
  45. return $result;
  46. }
  47. $orders = is_array($result['list'] ?? null) ? $result['list'] : [];
  48. $users = $this->usersByPlayerId(array_values(array_unique(array_filter(array_map(
  49. static fn(array $order): string => trim((string) ($order['player_id'] ?? '')),
  50. $orders
  51. )))));
  52. $existing = $this->existingSnapshots($orders);
  53. $now = Carbon::now(config('app.timezone', 'Asia/Shanghai'))->format('Y-m-d H:i:s');
  54. $rows = [];
  55. $matchedUserIds = [];
  56. foreach ($orders as $order) {
  57. $platform = trim((string) ($order['platform'] ?? ''));
  58. $gameOrderId = trim((string) ($order['game_order_id'] ?? ''));
  59. if ($gameOrderId === '') {
  60. continue;
  61. }
  62. $playerId = trim((string) ($order['player_id'] ?? ''));
  63. $identity = $this->identity($platform, $playerId, $gameOrderId);
  64. $user = $users[$playerId] ?? null;
  65. $previous = $existing[$identity] ?? null;
  66. $userId = $user->id ?? $previous->user_id ?? null;
  67. if ($userId !== null) {
  68. $matchedUserIds[(int) $userId] = true;
  69. }
  70. $rows[$identity] = [
  71. 'order_key' => $identity,
  72. 'user_id' => $userId,
  73. 'member_id' => $user->member_id ?? $previous->member_id ?? null,
  74. 'username' => (string) ($user->username ?? $previous->username ?? ''),
  75. 'first_name' => (string) ($user->first_name ?? $previous->first_name ?? ''),
  76. 'player_id' => $playerId,
  77. 'platform' => $platform,
  78. 'currency' => trim((string) ($order['currency'] ?? '')),
  79. 'game_type' => min(255, max(0, (int) ($order['game_type'] ?? 0))),
  80. 'game_name' => (string) ($order['game_name'] ?? ''),
  81. 'round_no' => (string) ($order['round'] ?? ''),
  82. 'table_no' => (string) ($order['table'] ?? ''),
  83. 'seat' => (string) ($order['seat'] ?? ''),
  84. 'bet_amount' => $this->decimal($order['bet_amount'] ?? null),
  85. 'valid_amount' => $this->decimal($order['valid_amount'] ?? null),
  86. 'settled_amount' => $this->decimal($order['settled_amount'] ?? null),
  87. 'bet_content' => $this->text($order['bet_content'] ?? ''),
  88. 'status' => min(255, max(0, (int) ($order['status'] ?? 0))),
  89. 'game_order_id' => $gameOrderId,
  90. 'bet_time' => $this->dateTime($order['bet_time'] ?? null),
  91. 'last_update_time' => $this->dateTime($order['last_update_time'] ?? null),
  92. 'created_at' => $previous->created_at ?? $now,
  93. 'updated_at' => $now,
  94. ];
  95. }
  96. if ($rows !== []) {
  97. ThirdGameOrderModel::query()->upsert(
  98. array_values($rows),
  99. ['order_key'],
  100. [
  101. 'user_id', 'member_id', 'username', 'first_name', 'player_id', 'currency',
  102. 'game_type', 'game_name', 'round_no', 'table_no', 'seat', 'bet_amount',
  103. 'valid_amount', 'settled_amount', 'bet_content', 'status', 'bet_time',
  104. 'last_update_time', 'updated_at',
  105. ]
  106. );
  107. }
  108. $pageNo = (int) ($result['page_no'] ?? $page);
  109. $pageSize = (int) ($result['page_size'] ?? $limit);
  110. $total = (int) ($result['total'] ?? count($orders));
  111. return [
  112. 'ok' => true,
  113. 'received' => count($orders),
  114. 'synced' => count($rows),
  115. 'matched_users' => count($matchedUserIds),
  116. 'unmatched_orders' => count(array_filter($rows, static fn(array $row): bool => $row['user_id'] === null)),
  117. 'total' => $total,
  118. 'page_no' => $pageNo,
  119. 'page_size' => $pageSize,
  120. 'has_more' => $pageSize > 0 && $pageNo * $pageSize < $total,
  121. ];
  122. }
  123. public function syncForList(array $params): array
  124. {
  125. if ((int) ($params['page'] ?? 1) > 1) {
  126. return ['attempted' => false, 'ok' => true, 'message' => ''];
  127. }
  128. $result = $this->syncRealtime(1, 2000);
  129. if (empty($result['ok'])) {
  130. return [
  131. 'attempted' => true,
  132. 'ok' => false,
  133. 'message' => (string) ($result['msg'] ?? '三方订单同步失败'),
  134. ];
  135. }
  136. unset($result['ok']);
  137. return array_merge([
  138. 'attempted' => true,
  139. 'ok' => true,
  140. 'message' => '',
  141. ], $result);
  142. }
  143. public function paginate(array $params): array
  144. {
  145. $page = max(1, (int) ($params['page'] ?? 1));
  146. $limit = min(200, max(1, (int) ($params['limit'] ?? 20)));
  147. $query = ThirdGameOrderModel::query()
  148. ->leftJoin('users', 'users.id', '=', 'third_game_orders.user_id');
  149. if (!empty($params['user_id'])) {
  150. $userId = (int) $params['user_id'];
  151. $query->where(function ($query) use ($userId) {
  152. $query->where('users.id', $userId)
  153. ->orWhere(function ($query) use ($userId) {
  154. $query->whereNull('users.id')
  155. ->where('third_game_orders.user_id', $userId);
  156. });
  157. });
  158. }
  159. if (!empty($params['member_id'])) {
  160. $memberId = (string) $params['member_id'];
  161. $query->where(function ($query) use ($memberId) {
  162. $query->where('users.member_id', $memberId)
  163. ->orWhere(function ($query) use ($memberId) {
  164. $query->whereNull('users.id')
  165. ->where('third_game_orders.member_id', $memberId);
  166. });
  167. });
  168. }
  169. if (!empty($params['username'])) {
  170. $username = '%' . $params['username'] . '%';
  171. $query->where(function ($query) use ($username) {
  172. $query->where('users.username', 'like', $username)
  173. ->orWhere(function ($query) use ($username) {
  174. $query->whereNull('users.id')
  175. ->where('third_game_orders.username', 'like', $username);
  176. });
  177. });
  178. }
  179. if (!empty($params['first_name'])) {
  180. $firstName = '%' . $params['first_name'] . '%';
  181. $query->where(function ($query) use ($firstName) {
  182. $query->where('users.first_name', 'like', $firstName)
  183. ->orWhere(function ($query) use ($firstName) {
  184. $query->whereNull('users.id')
  185. ->where('third_game_orders.first_name', 'like', $firstName);
  186. });
  187. });
  188. }
  189. if (!empty($params['player_id'])) {
  190. $query->where('third_game_orders.player_id', (string) $params['player_id']);
  191. }
  192. if (!empty($params['platform'])) {
  193. $query->where('third_game_orders.platform', (string) $params['platform']);
  194. }
  195. if (!empty($params['game_order_id'])) {
  196. $query->where('third_game_orders.game_order_id', (string) $params['game_order_id']);
  197. }
  198. if (isset($params['game_type']) && $params['game_type'] !== '') {
  199. $query->where('third_game_orders.game_type', (int) $params['game_type']);
  200. }
  201. if (isset($params['status']) && $params['status'] !== '') {
  202. $query->where('third_game_orders.status', (int) $params['status']);
  203. }
  204. if (!empty($params['start_time']) && !empty($params['end_time'])) {
  205. $query->whereBetween('third_game_orders.last_update_time', [
  206. $params['start_time'],
  207. $params['end_time'],
  208. ]);
  209. }
  210. $total = (clone $query)->count('third_game_orders.id');
  211. $list = $query
  212. ->select('third_game_orders.*')
  213. ->addSelect([
  214. 'users.id as current_user_id',
  215. 'users.member_id as current_member_id',
  216. 'users.username as current_username',
  217. 'users.first_name as current_first_name',
  218. ])
  219. ->orderByDesc('third_game_orders.last_update_time')
  220. ->orderByDesc('third_game_orders.id')
  221. ->forPage($page, $limit)
  222. ->get()
  223. ->map(fn(ThirdGameOrderModel $order): array => $this->format($order))
  224. ->all();
  225. return [
  226. 'total' => $total,
  227. 'page' => $page,
  228. 'limit' => $limit,
  229. 'list' => $list,
  230. 'options' => [
  231. 'game_types' => $this->options(self::GAME_TYPE_NAMES),
  232. 'statuses' => $this->options(self::STATUS_NAMES),
  233. ],
  234. ];
  235. }
  236. /**
  237. * @return array<string, object>
  238. */
  239. private function usersByPlayerId(array $playerIds): array
  240. {
  241. $requested = [];
  242. foreach ($playerIds as $playerId) {
  243. $playerId = trim((string) $playerId);
  244. if (!preg_match('/^u([1-9]\d*)$/D', $playerId, $matches)) {
  245. continue;
  246. }
  247. $userId = filter_var($matches[1], FILTER_VALIDATE_INT, [
  248. 'options' => ['min_range' => 1, 'max_range' => PHP_INT_MAX],
  249. ]);
  250. if ($userId !== false) {
  251. $requested[(int) $userId] = $playerId;
  252. }
  253. }
  254. if ($requested === []) {
  255. return [];
  256. }
  257. $rows = DB::table('users')
  258. ->select(['id', 'member_id', 'username', 'first_name'])
  259. ->whereIn('id', array_keys($requested))
  260. ->get();
  261. $result = [];
  262. foreach ($rows as $row) {
  263. $playerId = $requested[(int) $row->id] ?? null;
  264. if ($playerId !== null) {
  265. $result[$playerId] = $row;
  266. }
  267. }
  268. return $result;
  269. }
  270. /**
  271. * @return array<string, ThirdGameOrderModel>
  272. */
  273. private function existingSnapshots(array $orders): array
  274. {
  275. $orderKeys = [];
  276. foreach ($orders as $order) {
  277. $gameOrderId = trim((string) ($order['game_order_id'] ?? ''));
  278. if ($gameOrderId === '') {
  279. continue;
  280. }
  281. $orderKeys[] = $this->identity(
  282. trim((string) ($order['platform'] ?? '')),
  283. trim((string) ($order['player_id'] ?? '')),
  284. $gameOrderId
  285. );
  286. }
  287. $orderKeys = array_values(array_unique($orderKeys));
  288. if ($orderKeys === []) {
  289. return [];
  290. }
  291. $rows = ThirdGameOrderModel::query()
  292. ->whereIn('order_key', $orderKeys)
  293. ->get(['order_key', 'user_id', 'member_id', 'username', 'first_name', 'created_at']);
  294. $result = [];
  295. foreach ($rows as $row) {
  296. $result[(string) $row->order_key] = $row;
  297. }
  298. return $result;
  299. }
  300. private function format(ThirdGameOrderModel $order): array
  301. {
  302. $userId = $order->current_user_id ?? $order->user_id;
  303. $memberId = $order->current_member_id ?? $order->member_id;
  304. $username = $order->current_username ?? $order->username;
  305. $firstName = $order->current_first_name ?? $order->first_name;
  306. $gameType = (int) $order->game_type;
  307. $status = (int) $order->status;
  308. return [
  309. 'id' => (int) $order->id,
  310. 'user_id' => $userId === null ? null : (int) $userId,
  311. 'member_id' => $memberId === null ? null : (string) $memberId,
  312. 'username' => (string) ($username ?? ''),
  313. 'first_name' => (string) ($firstName ?? ''),
  314. 'player_id' => (string) $order->player_id,
  315. 'platform' => (string) $order->platform,
  316. 'currency' => (string) $order->currency,
  317. 'game_type' => $gameType,
  318. 'game_type_text' => self::GAME_TYPE_NAMES[$gameType] ?? '未知',
  319. 'game_name' => (string) $order->game_name,
  320. 'round' => (string) $order->round_no,
  321. 'table' => (string) $order->table_no,
  322. 'seat' => (string) $order->seat,
  323. 'bet_amount' => $this->number($order->bet_amount),
  324. 'valid_amount' => $this->number($order->valid_amount),
  325. 'settled_amount' => $this->number($order->settled_amount),
  326. 'bet_content' => (string) ($order->bet_content ?? ''),
  327. 'status' => $status,
  328. 'status_text' => self::STATUS_NAMES[$status] ?? '未知',
  329. 'game_order_id' => (string) $order->game_order_id,
  330. 'bet_time' => $this->formatTime($order->bet_time),
  331. 'last_update_time' => $this->formatTime($order->last_update_time),
  332. ];
  333. }
  334. private function identity(string $platform, string $playerId, string $gameOrderId): string
  335. {
  336. return hash('sha256', $platform . "\0" . $playerId . "\0" . $gameOrderId);
  337. }
  338. private function decimal($value): ?string
  339. {
  340. if (!is_numeric($value)) {
  341. return null;
  342. }
  343. $value = trim((string) $value);
  344. if (preg_match('/^-?\d+(?:\.\d+)?$/D', $value)) {
  345. return bcadd($value, '0', 10);
  346. }
  347. return number_format((float) $value, 10, '.', '');
  348. }
  349. private function text($value): string
  350. {
  351. if (is_array($value) || is_object($value)) {
  352. return json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?: '';
  353. }
  354. return is_scalar($value) ? (string) $value : '';
  355. }
  356. private function dateTime($value): ?string
  357. {
  358. if ($value === null || $value === '') {
  359. return null;
  360. }
  361. try {
  362. return Carbon::parse($value, config('app.timezone', 'Asia/Shanghai'))->format('Y-m-d H:i:s');
  363. } catch (\Throwable $e) {
  364. return null;
  365. }
  366. }
  367. private function formatTime($value): ?string
  368. {
  369. return $value ? Carbon::parse($value)->format('Y-m-d H:i:s') : null;
  370. }
  371. private function number($value)
  372. {
  373. return $value === null || $value === '' ? null : (float) $value;
  374. }
  375. private function options(array $items): array
  376. {
  377. $options = [];
  378. foreach ($items as $value => $label) {
  379. $options[] = ['label' => $label, 'value' => $value];
  380. }
  381. return $options;
  382. }
  383. }