| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269 |
- <?php
- namespace App\Services;
- use App\Support\MaintenancePolicy as Policy;
- use Carbon\Carbon;
- use DateTimeImmutable;
- use DateTimeZone;
- use Illuminate\Database\QueryException;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Schema;
- use Illuminate\Support\Facades\Validator;
- use Illuminate\Validation\Rule;
- use Illuminate\Validation\ValidationException;
- class MaintenanceService
- {
- private ?array $nameCache = null;
- public function options(): array
- {
- $this->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, 'embeddable' => 1],
- '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'], 'embeddable' => ['sometimes', 'required', 'integer', 'in:0,1'],
- ])->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;
- // Whether the platform / lottery / sport opens embedded (iframe) on the member site; independent of maintenance.
- if (array_key_exists('embeddable', $params)) {
- if (Policy::parentScope($row['scope_code']) === null) $this->invalid('embeddable', '只有子类可以设置是否支持内嵌');
- $row['embeddable'] = (int) $params['embeddable'];
- }
- 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', 'embeddable']));
- $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'], 'embeddable' => $parent === null ? null : (int) ($row['embeddable'] ?? 1),
- '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);
- if (Policy::parentScope($row['scope_code']) === null) unset($row['embeddable']); else $row['embeddable'] = (int) ($row['embeddable'] ?? 1);
- $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]); }
- }
|