ensure(); $options = static fn ($map) => array_map(static fn ($value, $label) => compact('value', 'label'), array_keys($map), array_values($map)); $names = $this->names(); $subcategories = []; foreach ($names as $value => $label) { $parent = Policy::parentScope($value); if ($parent !== null) $subcategories[] = ['value' => $value, 'label' => $label, 'parent' => $parent]; } return ['scopes' => $options(Policy::scopes()), 'categories' => $options(Policy::CATEGORIES), 'subcategories' => $subcategories, 'platforms' => $options(['PC' => 'PC', 'H5' => 'H5', 'APP' => 'APP']), 'languages' => $options(Policy::LANGUAGES), 'states' => $options(Policy::STATES), 'timezones' => DateTimeZone::listIdentifiers(), 'defaults' => ['enabled' => 0, 'platforms' => ['PC', 'H5', 'APP'], 'timezone' => 'Asia/Shanghai', 'ends_at' => null], 'business_codes' => ['site' => Policy::SITE_CODE, 'game' => Policy::GAME_CODE]]; } public function listing(array $input): array { $params = Validator::make($input, [ 'page' => ['nullable', 'integer', 'min:1', 'max:1000000'], 'limit' => ['nullable', 'integer', 'min:1', 'max:100'], 'scope_code' => ['nullable', 'string', 'max:64'], 'parent_scope' => ['nullable', Rule::in(array_keys(Policy::CATEGORIES))], 'platform' => ['nullable', Rule::in(['PC', 'H5', 'APP'])], 'enabled' => ['nullable', 'integer', 'in:0,1'], 'state' => ['nullable', Rule::in(array_keys(Policy::STATES))], 'language' => ['nullable', Rule::in(array_keys(Policy::LANGUAGES))], ])->validate(); if (!empty($params['scope_code']) && !isset(Policy::scopes()[$params['scope_code']]) && Policy::parentScope($params['scope_code']) === null) { $this->invalid('scope_code', '维护范围不存在'); } $this->ensure(); $texts = []; foreach (DB::table('maintenance_translations')->get() as $text) $texts[$text->maintenance_id][$text->language] = ['content' => $text->content]; // 平台、开关、状态、语言:作用在每一行(大类和子项各自判断) $hasFilter = !empty($params['platform']) || isset($params['enabled']) || !empty($params['state']) || !empty($params['language']); $matches = function (array $row) use ($params, $texts): bool { if (!empty($params['platform']) && !in_array($params['platform'], $row['platforms'], true)) return false; if (isset($params['enabled']) && $row['enabled'] !== (int) $params['enabled']) return false; if (!empty($params['state']) && $row['state'] !== $params['state']) return false; if (!empty($params['language']) && !isset($texts[$row['id']][$params['language']])) return false; return true; }; $top = []; $children = []; foreach (DB::table('maintenance_settings')->orderBy('id')->get() as $record) { $row = $this->dto((array) $record, $texts[$record->id] ?? []); if ($row['parent_scope'] === null) $top[$row['scope_code']] = $row; else $children[$row['parent_scope']][] = $row; } // 父级缺失的子项(正常不会出现)当作顶层显示,避免丢失 foreach ($children as $parent => $rows) { if (!isset($top[$parent])) { foreach ($rows as $row) $top[$row['scope_code']] = $row; unset($children[$parent]); } } $scope = $params['scope_code'] ?? ''; $scopeParent = $scope !== '' ? Policy::parentScope($scope) : null; $rows = []; foreach ($top as $code => $row) { if (!empty($params['parent_scope']) && $code !== $params['parent_scope']) continue; if ($scope !== '' && $code !== ($scopeParent ?? $scope)) continue; $kids = $children[$code] ?? []; if ($scopeParent !== null) $kids = array_values(array_filter($kids, fn ($kid) => $kid['scope_code'] === $scope)); $shown = $hasFilter ? array_values(array_filter($kids, $matches)) : $kids; // 只按子项查询时,大类只是容器,不算命中 $self = $scopeParent === null && (!$hasFilter || $matches($row)); if (!$self && $shown === []) continue; $rows[] = $row + ['matched' => $self, 'children_count' => count($children[$code] ?? []), 'children' => $shown]; } // 分页只按顶层(整站、大类);子游戏 / 平台在所属大类的 children 里 return ['total' => count($rows), 'data' => array_slice($rows, ((int) ($params['page'] ?? 1) - 1) * (int) ($params['limit'] ?? 20), (int) ($params['limit'] ?? 20))]; } public function detail(int $id): array { $row = DB::table('maintenance_settings')->where('id', $id)->first(); if (!$row) $this->invalid('id', '维护设置不存在'); return $this->dto((array) $row, $this->texts($id)); } public function save(array $input): array { $params = Validator::make($input, [ 'id' => ['required', 'integer', 'min:1'], 'scope_code' => ['prohibited'], 'platforms' => ['sometimes', 'required', 'array', 'min:1', 'max:3'], 'platforms.*' => ['required', 'distinct', Rule::in(['PC', 'H5', 'APP'])], 'enabled' => ['sometimes', 'required', 'integer', 'in:0,1'], 'start_now' => ['sometimes', 'boolean'], 'starts_at' => ['sometimes', 'required', 'date_format:Y-m-d H:i:s'], 'ends_at' => ['nullable', 'date_format:Y-m-d H:i:s'], 'timezone' => ['sometimes', 'required', 'string', Rule::in(DateTimeZone::listIdentifiers())], 'translations' => ['sometimes', 'array'], ])->validate(); return DB::transaction(function () use ($params) { $id = (int) $params['id']; $found = DB::table('maintenance_settings')->where('id', $id)->lockForUpdate()->first(); if (!$found) $this->invalid('id', '维护设置不存在'); $before = $this->snapshot($id); $row = (array) $found; foreach (['enabled', 'timezone', 'platforms'] as $field) if (array_key_exists($field, $params)) $row[$field] = $params[$field]; $row['platforms'] = array_values(array_intersect(['PC', 'H5', 'APP'], Policy::platforms($row))); if (!empty($params['start_now'])) $row['starts_at'] = $this->now()->format('Y-m-d H:i:s'); elseif (isset($params['starts_at'])) $row['starts_at'] = $this->utc($params['starts_at'], $row['timezone'], 'starts_at'); if (array_key_exists('ends_at', $params)) $row['ends_at'] = $params['ends_at'] === null ? null : $this->utc($params['ends_at'], $row['timezone'], 'ends_at'); if ($row['ends_at'] !== null && $row['ends_at'] <= $row['starts_at']) $this->invalid('ends_at', '结束时间必须晚于开始时间'); $texts = $before['translations']; foreach ($texts as &$text) unset($text['title']); unset($text); if (array_key_exists('translations', $params)) { if (array_diff(array_keys($params['translations']), array_keys(Policy::LANGUAGES))) $this->invalid('translations', '仅支持zh/en/vi'); $texts = []; foreach ($params['translations'] as $language => $text) { if (!is_array($text)) $this->invalid('translations', '语言内容必须为对象'); $value = Validator::make($text, ['content' => ['nullable', 'string', 'max:5000']])->validate(); if (trim((string) ($value['content'] ?? '')) !== '') $texts[$language] = ['content' => $value['content']]; } } $values = array_intersect_key($row, array_flip(['enabled', 'timezone', 'platforms', 'starts_at', 'ends_at'])); $values['enabled'] = (int) $values['enabled']; $values['platforms'] = json_encode($values['platforms'], JSON_THROW_ON_ERROR); $values['updated_at'] = $this->now()->format('Y-m-d H:i:s'); DB::table('maintenance_settings')->where('id', $id)->update($values); if (array_key_exists('translations', $params)) { DB::table('maintenance_translations')->where('maintenance_id', $id)->delete(); foreach ($texts as $language => $text) DB::table('maintenance_translations')->insert(['maintenance_id' => $id, 'language' => $language, 'content' => $text['content']]); } $after = $this->snapshot($id); if ($before !== $after) { OperationAuditService::record('maintenance', $id, 'update', $before, $after, $this->now()->setTimezone('Asia/Shanghai')->format('Y-m-d H:i:s')); $local = static fn ($at) => $at === null ? null : Carbon::parse($at, 'UTC')->setTimezone('Asia/Shanghai')->format('Y-m-d H:i:s'); SiteRealtimeService::changed('maintenance', $id, 'update', $after['enabled'] ? ['start' => $local($after['starts_at']), 'end' => $local($after['ends_at'])] : []); } return $this->detail($id); }); } public function status(int $id, int $enabled): array { return $this->save(compact('id', 'enabled')); } public function logs(array $input): array { return LocalizedAuditService::listing('maintenance', $input); } /** Telegram 28 bets: the chat game follows pc28_switch (1 = 极速28). Telegram has no PC/H5/APP, so any platform matches. */ public function telegramPc28Failure($language): ?array { $language = Policy::language($language) ?? 'zh'; $switch = DB::table('config')->where('field', 'pc28_switch')->value('val'); $subcategory = $switch == 1 ? 'self:lottery:jisu28' : 'self:lottery:pc28'; $now = $this->now()->getTimestamp(); $row = Policy::select($this->runtimeRows($language), null, 'self:lottery', $now, $subcategory); return $row === null ? null : Policy::failure($row, null, $language, $now); } public function runtimeRows(string $language): array { return DB::table('maintenance_settings as m')->leftJoin('maintenance_translations as t', function ($join) use ($language) { $join->on('t.maintenance_id', '=', 'm.id')->where('t.language', $language); })->where('m.enabled', 1)->select('m.*', 't.content')->get()->map(fn ($row) => (array) $row)->all(); } private function dto(array $row, array $texts): array { $public = Policy::publicRule($row, 'zh'); unset($public['language'], $public['content']); $parent = Policy::parentScope($row['scope_code']); return ['id' => (int) $row['id'], 'scope_code' => $row['scope_code'], 'scope_name' => $this->names()[$row['scope_code']] ?? $row['scope_code'], 'scope_level' => $row['scope_code'] === 'site' ? 'site' : ($parent === null ? 'category' : 'subcategory'), 'parent_scope' => $parent, 'enabled' => (int) $row['enabled'], 'state' => Policy::state($row, $this->now()->getTimestamp()), 'translations' => (object) $texts] + $public; } private function texts(int $id): array { $texts = []; foreach (DB::table('maintenance_translations')->where('maintenance_id', $id)->orderBy('language')->get() as $text) $texts[$text->language] = ['content' => $text->content]; return $texts; } private function snapshot(int $id): array { $row = (array) DB::table('maintenance_settings')->where('id', $id)->first(); unset($row['created_at'], $row['updated_at']); $row['enabled'] = (int) $row['enabled']; $row['platforms'] = Policy::platforms($row); $row['translations'] = $this->texts($id); $names = $this->names(); foreach ($row['translations'] as &$text) $text['title'] = $names[$row['scope_code']] ?? $row['scope_code']; return $row; } private function utc(string $value, string $timezone, string $field): string { $date = DateTimeImmutable::createFromFormat('!Y-m-d H:i:s', $value, new DateTimeZone($timezone)); if (!$date || $date->format('Y-m-d H:i:s') !== $value) $this->invalid($field, '该时区中不存在此时间'); // Repeated local wall times during DST transitions require a different, unambiguous time. $utc = $date->getTimestamp(); foreach ([-7200, -3600, -1800, 1800, 3600, 7200] as $offset) { if ($date->setTimestamp($utc + $offset)->format('Y-m-d H:i:s') === $value) $this->invalid($field, '该时区中此时间存在夏令时歧义,请选择其他时间'); } return $date->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d H:i:s'); } private function names(): array { if ($this->nameCache !== null) return $this->nameCache; $names = Policy::scopes(); if (Schema::hasTable('config')) { foreach (Policy::configList(DB::table('config')->where('field', 'game_list')->value('val')) as $item) { $code = Policy::lotterySubcategory($item); if ($code !== null) $names[$code] = Policy::CATEGORIES['self:lottery'] . ' / ' . $this->label($item['name'] ?? '', $code); } foreach (Policy::configList(DB::table('config')->where('field', 'sport_list')->value('val')) as $item) { $code = Policy::sportSubcategory((string) ($item['code'] ?? '')); if ($code !== null) $names[$code] = Policy::CATEGORIES['self:sport'] . ' / ' . $this->label($item['name'] ?? '', $code); } } if (!Schema::hasTable('egame_items')) return $this->nameCache = $names; $rows = DB::table('egame_items')->where('item_type', 'platform')->where('game_type', '>', 0) ->where('plat_type', '!=', '')->orderBy('id')->get(['plat_type', 'game_type', 'name', 'status']); foreach ($rows as $row) { $code = Policy::thirdSubcategory((int) $row->game_type, (string) $row->plat_type); if ($code === null) continue; $parent = Policy::parentScope($code); $plat = strtolower(trim((string) $row->plat_type)); $label = trim((string) $row->name); $names[$code] = Policy::CATEGORIES[$parent] . ' / ' . ($label === '' ? strtoupper($plat) : $label); } return $this->nameCache = $names; } private function label($name, string $code): string { $name = trim((string) $name); return $name === '' ? substr($code, strrpos($code, ':') + 1) : $name; } /** Missing subcategory rows stay disabled. Opening maintenance still requires an explicit save. */ private function ensure(): void { $existing = DB::table('maintenance_settings')->pluck('scope_code')->all(); $now = $this->now()->format('Y-m-d H:i:s'); foreach ($this->names() as $code => $_) { if (isset(Policy::scopes()[$code]) || in_array($code, $existing, true) || Policy::parentScope($code) === null) continue; try { DB::table('maintenance_settings')->insert(['scope_code' => $code, 'platforms' => '["PC","H5","APP"]', 'enabled' => false, 'starts_at' => $now, 'ends_at' => null, 'timezone' => 'Asia/Shanghai', 'created_at' => $now, 'updated_at' => $now]); $existing[] = $code; } catch (QueryException $e) { // Another admin request inserted the same scope first (integrity constraint violation). if ((string) $e->getCode() !== '23000') throw $e; } } } private function now(): Carbon { return Carbon::now('UTC'); } private function invalid(string $field, string $message): void { throw ValidationException::withMessages([$field => $message]); } }