ThirdGameOrderService.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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 sync(
  29. string $startTime,
  30. string $endTime,
  31. int $page = 1,
  32. int $limit = 2000
  33. ): array {
  34. $result = $this->provider->historyOrders($startTime, $endTime, $page, $limit);
  35. if (empty($result['ok'])) {
  36. return $result;
  37. }
  38. $orders = is_array($result['list'] ?? null) ? $result['list'] : [];
  39. $users = $this->usersByPlayerId(array_values(array_unique(array_filter(array_map(
  40. static fn(array $order): string => trim((string) ($order['player_id'] ?? '')),
  41. $orders
  42. )))));
  43. $existing = $this->existingSnapshots($orders);
  44. $now = Carbon::now(config('app.timezone', 'Asia/Shanghai'))->format('Y-m-d H:i:s');
  45. $rows = [];
  46. $matchedUserIds = [];
  47. foreach ($orders as $order) {
  48. $platform = trim((string) ($order['platform'] ?? ''));
  49. $gameOrderId = trim((string) ($order['game_order_id'] ?? ''));
  50. if ($gameOrderId === '') {
  51. continue;
  52. }
  53. $playerId = trim((string) ($order['player_id'] ?? ''));
  54. $identity = $this->identity($platform, $playerId, $gameOrderId);
  55. $user = $users[$playerId] ?? null;
  56. $previous = $existing[$identity] ?? null;
  57. $userId = $user->id ?? $previous->user_id ?? null;
  58. if ($userId !== null) {
  59. $matchedUserIds[(int) $userId] = true;
  60. }
  61. $rows[$identity] = [
  62. 'order_key' => $identity,
  63. 'user_id' => $userId,
  64. 'member_id' => $user->member_id ?? $previous->member_id ?? null,
  65. 'username' => (string) ($user->username ?? $previous->username ?? ''),
  66. 'first_name' => (string) ($user->first_name ?? $previous->first_name ?? ''),
  67. 'player_id' => $playerId,
  68. 'platform' => $platform,
  69. 'currency' => trim((string) ($order['currency'] ?? '')),
  70. 'game_type' => min(255, max(0, (int) ($order['game_type'] ?? 0))),
  71. 'game_name' => (string) ($order['game_name'] ?? ''),
  72. 'round_no' => (string) ($order['round'] ?? ''),
  73. 'table_no' => (string) ($order['table'] ?? ''),
  74. 'seat' => (string) ($order['seat'] ?? ''),
  75. 'bet_amount' => $this->decimal($order['bet_amount'] ?? null),
  76. 'valid_amount' => $this->decimal($order['valid_amount'] ?? null),
  77. 'settled_amount' => $this->decimal($order['settled_amount'] ?? null),
  78. 'bet_content' => $this->text($order['bet_content'] ?? ''),
  79. 'status' => min(255, max(0, (int) ($order['status'] ?? 0))),
  80. 'game_order_id' => $gameOrderId,
  81. 'bet_time' => $this->dateTime($order['bet_time'] ?? null),
  82. 'last_update_time' => $this->dateTime($order['last_update_time'] ?? null),
  83. 'created_at' => $previous->created_at ?? $now,
  84. 'updated_at' => $now,
  85. ];
  86. }
  87. if ($rows !== []) {
  88. ThirdGameOrderModel::query()->upsert(
  89. array_values($rows),
  90. ['order_key'],
  91. [
  92. 'user_id', 'member_id', 'username', 'first_name', 'player_id', 'currency',
  93. 'game_type', 'game_name', 'round_no', 'table_no', 'seat', 'bet_amount',
  94. 'valid_amount', 'settled_amount', 'bet_content', 'status', 'bet_time',
  95. 'last_update_time', 'updated_at',
  96. ]
  97. );
  98. }
  99. $pageNo = (int) ($result['page_no'] ?? $page);
  100. $pageSize = (int) ($result['page_size'] ?? $limit);
  101. $total = (int) ($result['total'] ?? count($orders));
  102. return [
  103. 'ok' => true,
  104. 'received' => count($orders),
  105. 'synced' => count($rows),
  106. 'matched_users' => count($matchedUserIds),
  107. 'unmatched_orders' => count(array_filter($rows, static fn(array $row): bool => $row['user_id'] === null)),
  108. 'total' => $total,
  109. 'page_no' => $pageNo,
  110. 'page_size' => $pageSize,
  111. 'has_more' => $pageSize > 0 && $pageNo * $pageSize < $total,
  112. ];
  113. }
  114. public function paginate(array $params): array
  115. {
  116. $page = max(1, (int) ($params['page'] ?? 1));
  117. $limit = min(200, max(1, (int) ($params['limit'] ?? 20)));
  118. $query = ThirdGameOrderModel::query()
  119. ->leftJoin('users', 'users.id', '=', 'third_game_orders.user_id');
  120. if (!empty($params['user_id'])) {
  121. $userId = (int) $params['user_id'];
  122. $query->where(function ($query) use ($userId) {
  123. $query->where('users.id', $userId)
  124. ->orWhere(function ($query) use ($userId) {
  125. $query->whereNull('users.id')
  126. ->where('third_game_orders.user_id', $userId);
  127. });
  128. });
  129. }
  130. if (!empty($params['member_id'])) {
  131. $memberId = (string) $params['member_id'];
  132. $query->where(function ($query) use ($memberId) {
  133. $query->where('users.member_id', $memberId)
  134. ->orWhere(function ($query) use ($memberId) {
  135. $query->whereNull('users.id')
  136. ->where('third_game_orders.member_id', $memberId);
  137. });
  138. });
  139. }
  140. if (!empty($params['username'])) {
  141. $username = '%' . $params['username'] . '%';
  142. $query->where(function ($query) use ($username) {
  143. $query->where('users.username', 'like', $username)
  144. ->orWhere(function ($query) use ($username) {
  145. $query->whereNull('users.id')
  146. ->where('third_game_orders.username', 'like', $username);
  147. });
  148. });
  149. }
  150. if (!empty($params['first_name'])) {
  151. $firstName = '%' . $params['first_name'] . '%';
  152. $query->where(function ($query) use ($firstName) {
  153. $query->where('users.first_name', 'like', $firstName)
  154. ->orWhere(function ($query) use ($firstName) {
  155. $query->whereNull('users.id')
  156. ->where('third_game_orders.first_name', 'like', $firstName);
  157. });
  158. });
  159. }
  160. if (!empty($params['player_id'])) {
  161. $query->where('third_game_orders.player_id', (string) $params['player_id']);
  162. }
  163. if (!empty($params['platform'])) {
  164. $query->where('third_game_orders.platform', (string) $params['platform']);
  165. }
  166. if (!empty($params['game_order_id'])) {
  167. $query->where('third_game_orders.game_order_id', (string) $params['game_order_id']);
  168. }
  169. if (isset($params['game_type']) && $params['game_type'] !== '') {
  170. $query->where('third_game_orders.game_type', (int) $params['game_type']);
  171. }
  172. if (isset($params['status']) && $params['status'] !== '') {
  173. $query->where('third_game_orders.status', (int) $params['status']);
  174. }
  175. if (!empty($params['start_time']) && !empty($params['end_time'])) {
  176. $query->whereBetween('third_game_orders.last_update_time', [
  177. $params['start_time'],
  178. $params['end_time'],
  179. ]);
  180. }
  181. $total = (clone $query)->count('third_game_orders.id');
  182. $list = $query
  183. ->select('third_game_orders.*')
  184. ->addSelect([
  185. 'users.id as current_user_id',
  186. 'users.member_id as current_member_id',
  187. 'users.username as current_username',
  188. 'users.first_name as current_first_name',
  189. ])
  190. ->orderByDesc('third_game_orders.last_update_time')
  191. ->orderByDesc('third_game_orders.id')
  192. ->forPage($page, $limit)
  193. ->get()
  194. ->map(fn(ThirdGameOrderModel $order): array => $this->format($order))
  195. ->all();
  196. return [
  197. 'total' => $total,
  198. 'page' => $page,
  199. 'limit' => $limit,
  200. 'list' => $list,
  201. 'options' => [
  202. 'game_types' => $this->options(self::GAME_TYPE_NAMES),
  203. 'statuses' => $this->options(self::STATUS_NAMES),
  204. ],
  205. ];
  206. }
  207. /**
  208. * @return array<string, object>
  209. */
  210. private function usersByPlayerId(array $playerIds): array
  211. {
  212. if ($playerIds === []) {
  213. return [];
  214. }
  215. $sn = (string) config('third_game.sn');
  216. $placeholders = implode(',', array_fill(0, count($playerIds), '?'));
  217. $expression = "CONCAT('p', SUBSTRING(MD5(CONCAT(?, '_', `member_id`)), 1, 10))";
  218. $rows = DB::table('users')
  219. ->select(['id', 'member_id', 'username', 'first_name'])
  220. ->selectRaw($expression . ' AS third_game_player_id', [$sn])
  221. ->whereRaw($expression . " IN ({$placeholders})", array_merge([$sn], $playerIds))
  222. ->get();
  223. $result = [];
  224. foreach ($rows as $row) {
  225. $result[(string) $row->third_game_player_id] = $row;
  226. }
  227. return $result;
  228. }
  229. /**
  230. * @return array<string, ThirdGameOrderModel>
  231. */
  232. private function existingSnapshots(array $orders): array
  233. {
  234. $orderKeys = [];
  235. foreach ($orders as $order) {
  236. $gameOrderId = trim((string) ($order['game_order_id'] ?? ''));
  237. if ($gameOrderId === '') {
  238. continue;
  239. }
  240. $orderKeys[] = $this->identity(
  241. trim((string) ($order['platform'] ?? '')),
  242. trim((string) ($order['player_id'] ?? '')),
  243. $gameOrderId
  244. );
  245. }
  246. $orderKeys = array_values(array_unique($orderKeys));
  247. if ($orderKeys === []) {
  248. return [];
  249. }
  250. $rows = ThirdGameOrderModel::query()
  251. ->whereIn('order_key', $orderKeys)
  252. ->get(['order_key', 'user_id', 'member_id', 'username', 'first_name', 'created_at']);
  253. $result = [];
  254. foreach ($rows as $row) {
  255. $result[(string) $row->order_key] = $row;
  256. }
  257. return $result;
  258. }
  259. private function format(ThirdGameOrderModel $order): array
  260. {
  261. $userId = $order->current_user_id ?? $order->user_id;
  262. $memberId = $order->current_member_id ?? $order->member_id;
  263. $username = $order->current_username ?? $order->username;
  264. $firstName = $order->current_first_name ?? $order->first_name;
  265. $gameType = (int) $order->game_type;
  266. $status = (int) $order->status;
  267. return [
  268. 'id' => (int) $order->id,
  269. 'user_id' => $userId === null ? null : (int) $userId,
  270. 'member_id' => $memberId === null ? null : (string) $memberId,
  271. 'username' => (string) ($username ?? ''),
  272. 'first_name' => (string) ($firstName ?? ''),
  273. 'player_id' => (string) $order->player_id,
  274. 'platform' => (string) $order->platform,
  275. 'currency' => (string) $order->currency,
  276. 'game_type' => $gameType,
  277. 'game_type_text' => self::GAME_TYPE_NAMES[$gameType] ?? '未知',
  278. 'game_name' => (string) $order->game_name,
  279. 'round' => (string) $order->round_no,
  280. 'table' => (string) $order->table_no,
  281. 'seat' => (string) $order->seat,
  282. 'bet_amount' => $this->number($order->bet_amount),
  283. 'valid_amount' => $this->number($order->valid_amount),
  284. 'settled_amount' => $this->number($order->settled_amount),
  285. 'bet_content' => (string) ($order->bet_content ?? ''),
  286. 'status' => $status,
  287. 'status_text' => self::STATUS_NAMES[$status] ?? '未知',
  288. 'game_order_id' => (string) $order->game_order_id,
  289. 'bet_time' => $this->formatTime($order->bet_time),
  290. 'last_update_time' => $this->formatTime($order->last_update_time),
  291. ];
  292. }
  293. private function identity(string $platform, string $playerId, string $gameOrderId): string
  294. {
  295. return hash('sha256', $platform . "\0" . $playerId . "\0" . $gameOrderId);
  296. }
  297. private function decimal($value): ?string
  298. {
  299. if (!is_numeric($value)) {
  300. return null;
  301. }
  302. $value = trim((string) $value);
  303. if (preg_match('/^-?\d+(?:\.\d+)?$/D', $value)) {
  304. return bcadd($value, '0', 10);
  305. }
  306. return number_format((float) $value, 10, '.', '');
  307. }
  308. private function text($value): string
  309. {
  310. if (is_array($value) || is_object($value)) {
  311. return json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?: '';
  312. }
  313. return is_scalar($value) ? (string) $value : '';
  314. }
  315. private function dateTime($value): ?string
  316. {
  317. if ($value === null || $value === '') {
  318. return null;
  319. }
  320. try {
  321. return Carbon::parse($value, config('app.timezone', 'Asia/Shanghai'))->format('Y-m-d H:i:s');
  322. } catch (\Throwable $e) {
  323. return null;
  324. }
  325. }
  326. private function formatTime($value): ?string
  327. {
  328. return $value ? Carbon::parse($value)->format('Y-m-d H:i:s') : null;
  329. }
  330. private function number($value)
  331. {
  332. return $value === null || $value === '' ? null : (float) $value;
  333. }
  334. private function options(array $items): array
  335. {
  336. $options = [];
  337. foreach ($items as $value => $label) {
  338. $options[] = ['label' => $label, 'value' => $value];
  339. }
  340. return $options;
  341. }
  342. }