| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157 |
- <?php
- namespace App\Services;
- use App\Support\MaintenancePolicy as Policy;
- use Carbon\Carbon;
- use DateTimeImmutable;
- use DateTimeZone;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Validator;
- use Illuminate\Validation\Rule;
- use Illuminate\Validation\ValidationException;
- class MaintenanceService
- {
- public function options(): array
- {
- $options = static fn ($map) => array_map(static fn ($value, $label) => compact('value', 'label'), array_keys($map), array_values($map));
- return ['scopes' => $options(Policy::scopes()), 'categories' => $options(Policy::CATEGORIES),
- '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', Rule::in(array_keys(Policy::scopes()))], '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();
- $texts = [];
- foreach (DB::table('maintenance_translations')->get() as $text) $texts[$text->maintenance_id][$text->language] = ['content' => $text->content];
- $rows = [];
- foreach (DB::table('maintenance_settings')->orderBy('id')->get() as $record) {
- $row = $this->dto((array) $record, $texts[$record->id] ?? []);
- if (!empty($params['scope_code']) && $row['scope_code'] !== $params['scope_code']) continue;
- if (!empty($params['platform']) && !in_array($params['platform'], $row['platforms'], true)) continue;
- if (isset($params['enabled']) && $row['enabled'] !== (int) $params['enabled']) continue;
- if (!empty($params['state']) && $row['state'] !== $params['state']) continue;
- if (!empty($params['language']) && !isset($texts[$record->id][$params['language']])) continue;
- $rows[] = $row;
- }
- 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); }
- 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']);
- return ['id' => (int) $row['id'], 'scope_code' => $row['scope_code'], 'scope_name' => Policy::scopes()[$row['scope_code']],
- '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);
- foreach ($row['translations'] as &$text) $text['title'] = Policy::scopes()[$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 now(): Carbon { return Carbon::now('UTC'); }
- private function invalid(string $field, string $message): void { throw ValidationException::withMessages([$field => $message]); }
- }
|