ThirdGameOrderService.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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. if ($playerIds === []) {
  242. return [];
  243. }
  244. $sn = (string) config('third_game.sn');
  245. $placeholders = implode(',', array_fill(0, count($playerIds), '?'));
  246. $expression = "CONCAT('p', SUBSTRING(MD5(CONCAT(?, '_', `member_id`)), 1, 10))";
  247. $rows = DB::table('users')
  248. ->select(['id', 'member_id', 'username', 'first_name'])
  249. ->selectRaw($expression . ' AS third_game_player_id', [$sn])
  250. ->whereRaw($expression . " IN ({$placeholders})", array_merge([$sn], $playerIds))
  251. ->get();
  252. $result = [];
  253. foreach ($rows as $row) {
  254. $result[(string) $row->third_game_player_id] = $row;
  255. }
  256. return $result;
  257. }
  258. /**
  259. * @return array<string, ThirdGameOrderModel>
  260. */
  261. private function existingSnapshots(array $orders): array
  262. {
  263. $orderKeys = [];
  264. foreach ($orders as $order) {
  265. $gameOrderId = trim((string) ($order['game_order_id'] ?? ''));
  266. if ($gameOrderId === '') {
  267. continue;
  268. }
  269. $orderKeys[] = $this->identity(
  270. trim((string) ($order['platform'] ?? '')),
  271. trim((string) ($order['player_id'] ?? '')),
  272. $gameOrderId
  273. );
  274. }
  275. $orderKeys = array_values(array_unique($orderKeys));
  276. if ($orderKeys === []) {
  277. return [];
  278. }
  279. $rows = ThirdGameOrderModel::query()
  280. ->whereIn('order_key', $orderKeys)
  281. ->get(['order_key', 'user_id', 'member_id', 'username', 'first_name', 'created_at']);
  282. $result = [];
  283. foreach ($rows as $row) {
  284. $result[(string) $row->order_key] = $row;
  285. }
  286. return $result;
  287. }
  288. private function format(ThirdGameOrderModel $order): array
  289. {
  290. $userId = $order->current_user_id ?? $order->user_id;
  291. $memberId = $order->current_member_id ?? $order->member_id;
  292. $username = $order->current_username ?? $order->username;
  293. $firstName = $order->current_first_name ?? $order->first_name;
  294. $gameType = (int) $order->game_type;
  295. $status = (int) $order->status;
  296. return [
  297. 'id' => (int) $order->id,
  298. 'user_id' => $userId === null ? null : (int) $userId,
  299. 'member_id' => $memberId === null ? null : (string) $memberId,
  300. 'username' => (string) ($username ?? ''),
  301. 'first_name' => (string) ($firstName ?? ''),
  302. 'player_id' => (string) $order->player_id,
  303. 'platform' => (string) $order->platform,
  304. 'currency' => (string) $order->currency,
  305. 'game_type' => $gameType,
  306. 'game_type_text' => self::GAME_TYPE_NAMES[$gameType] ?? '未知',
  307. 'game_name' => (string) $order->game_name,
  308. 'round' => (string) $order->round_no,
  309. 'table' => (string) $order->table_no,
  310. 'seat' => (string) $order->seat,
  311. 'bet_amount' => $this->number($order->bet_amount),
  312. 'valid_amount' => $this->number($order->valid_amount),
  313. 'settled_amount' => $this->number($order->settled_amount),
  314. 'bet_content' => (string) ($order->bet_content ?? ''),
  315. 'status' => $status,
  316. 'status_text' => self::STATUS_NAMES[$status] ?? '未知',
  317. 'game_order_id' => (string) $order->game_order_id,
  318. 'bet_time' => $this->formatTime($order->bet_time),
  319. 'last_update_time' => $this->formatTime($order->last_update_time),
  320. ];
  321. }
  322. private function identity(string $platform, string $playerId, string $gameOrderId): string
  323. {
  324. return hash('sha256', $platform . "\0" . $playerId . "\0" . $gameOrderId);
  325. }
  326. private function decimal($value): ?string
  327. {
  328. if (!is_numeric($value)) {
  329. return null;
  330. }
  331. $value = trim((string) $value);
  332. if (preg_match('/^-?\d+(?:\.\d+)?$/D', $value)) {
  333. return bcadd($value, '0', 10);
  334. }
  335. return number_format((float) $value, 10, '.', '');
  336. }
  337. private function text($value): string
  338. {
  339. if (is_array($value) || is_object($value)) {
  340. return json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?: '';
  341. }
  342. return is_scalar($value) ? (string) $value : '';
  343. }
  344. private function dateTime($value): ?string
  345. {
  346. if ($value === null || $value === '') {
  347. return null;
  348. }
  349. try {
  350. return Carbon::parse($value, config('app.timezone', 'Asia/Shanghai'))->format('Y-m-d H:i:s');
  351. } catch (\Throwable $e) {
  352. return null;
  353. }
  354. }
  355. private function formatTime($value): ?string
  356. {
  357. return $value ? Carbon::parse($value)->format('Y-m-d H:i:s') : null;
  358. }
  359. private function number($value)
  360. {
  361. return $value === null || $value === '' ? null : (float) $value;
  362. }
  363. private function options(array $items): array
  364. {
  365. $options = [];
  366. foreach ($items as $value => $label) {
  367. $options[] = ['label' => $label, 'value' => $value];
  368. }
  369. return $options;
  370. }
  371. }