MaintenanceTest.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. <?php
  2. namespace Tests\Integration;
  3. use App\Http\Controllers\admin\Maintenance as MaintenanceController;
  4. use App\Http\Middleware\MemberMaintenance;
  5. use App\Http\Middleware\OperationsAdminMiddleware;
  6. use App\Services\MaintenanceService;
  7. use App\Services\Sharing\ShareDefaults;
  8. use App\Support\MaintenancePolicy as Policy;
  9. use Carbon\Carbon;
  10. use Illuminate\Config\Repository;
  11. use Illuminate\Database\Capsule\Manager;
  12. use Illuminate\Database\Schema\Blueprint;
  13. use Illuminate\Events\Dispatcher;
  14. use Illuminate\Foundation\Application;
  15. use Illuminate\Http\JsonResponse;
  16. use Illuminate\Http\Request;
  17. use Illuminate\Routing\Router;
  18. use Illuminate\Support\Facades\DB;
  19. use Illuminate\Support\Facades\Facade;
  20. use Illuminate\Support\Facades\Schema;
  21. use Illuminate\Translation\ArrayLoader;
  22. use Illuminate\Translation\Translator;
  23. use Illuminate\Validation\Factory;
  24. use Illuminate\Validation\ValidationException;
  25. use PHPUnit\Framework\TestCase;
  26. class MaintenanceTest extends TestCase
  27. {
  28. private Application $app;
  29. private MaintenanceService $service;
  30. protected function setUp(): void
  31. {
  32. Carbon::setTestNow(Carbon::parse('2026-10-26 10:00:00', 'Asia/Shanghai'));
  33. Facade::clearResolvedInstances();
  34. $this->app = new Application(dirname(__DIR__, 2));
  35. $this->app->instance('config', new Repository(['app' => ['locale' => 'zh', 'timezone' => 'Asia/Shanghai'], 'operations' => ['admin_ids' => [1]]]));
  36. Facade::setFacadeApplication($this->app);
  37. $db = new Manager($this->app); $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'bot_']);
  38. $db->setAsGlobal(); $db->bootEloquent(); $this->app->instance('db', $db->getDatabaseManager());
  39. $this->app->bind('db.schema', fn () => $db->schema());
  40. $translator = new Translator(new ArrayLoader(), 'zh'); $this->app->instance('translator', $translator);
  41. $this->app->instance('validator', new Factory($translator, $this->app)); $this->app->instance('log', new \Psr\Log\NullLogger());
  42. $this->app->instance(\Illuminate\Contracts\Routing\ResponseFactory::class, new class {
  43. public function json($data, $status = 200, $headers = [], $options = 0) { return new JsonResponse($data, $status, $headers, $options); }
  44. });
  45. Request::macro('validate', function (array $rules) { return app('validator')->make($this->all(), $rules)->validate(); });
  46. Schema::create('operation_audits', function (Blueprint $t) {
  47. $t->id(); $t->string('resource_type'); $t->integer('resource_id'); $t->string('action'); $t->json('changes');
  48. $t->integer('operator_id'); $t->string('operator_name'); $t->timestamp('created_at')->useCurrent();
  49. });
  50. Schema::create('users', function (Blueprint $t) { $t->id(); $t->string('user_id'); $t->string('language'); $t->bigInteger('delete_time')->nullable(); $t->integer('is_banned')->default(0); });
  51. Schema::create('user_session', function (Blueprint $t) { $t->id(); $t->string('user_id'); $t->string('token'); $t->bigInteger('expire_time'); $t->bigInteger('create_time'); $t->bigInteger('update_time'); });
  52. $this->migration()->up(); (require dirname(__DIR__, 2) . '/database/migrations/2026_10_27_150000_create_site_realtime_events.php')->up(); $this->service = new MaintenanceService(); $this->request();
  53. }
  54. protected function tearDown(): void { Carbon::setTestNow(); DB::disconnect(); Facade::clearResolvedInstances(); parent::tearDown(); }
  55. private function migration() { return require dirname(__DIR__, 2) . '/database/migrations/2026_10_26_120000_create_maintenance_settings.php'; }
  56. private function request(array $params = []): Request
  57. {
  58. $request = Request::create('/admin/maintenance/submit', 'POST', $params); $request->user = (object) ['id' => 1, 'username' => 'admin'];
  59. $this->app->instance('request', $request); return $request;
  60. }
  61. private function id(string $scope = 'site'): int { return (int) DB::table('maintenance_settings')->where('scope_code', $scope)->value('id'); }
  62. private function save(array $values = [], string $scope = 'site'): array
  63. {
  64. return $this->service->save($values + ['id' => $this->id($scope), 'enabled' => 1, 'starts_at' => '2026-10-26 09:00:00']);
  65. }
  66. private function decide(?string $platform = 'PC', ?string $category = null): ?array
  67. {
  68. return Policy::select($this->service->runtimeRows('zh'), $platform, $category, now()->getTimestamp());
  69. }
  70. public function test_websocket_events_use_local_delivery_times_for_utc_maintenance_and_cancel_disabled_boundaries(): void
  71. {
  72. $row = $this->save(['starts_at' => '2026-10-26 11:00:00', 'ends_at' => '2026-10-26 12:00:00']);
  73. $this->assertSame(['update', 'start', 'end'], DB::table('site_realtime_events')->orderBy('id')->pluck('action')->all());
  74. $this->assertSame(['2026-10-26 10:00:00', '2026-10-26 11:00:00', '2026-10-26 12:00:00'], DB::table('site_realtime_events')->orderBy('id')->pluck('available_at')->all());
  75. $this->service->status($row['id'], 0); $this->service->status($row['id'], 0);
  76. $this->assertSame(['update', 'update'], DB::table('site_realtime_events')->orderBy('id')->pluck('action')->all());
  77. DB::beginTransaction(); $this->save(); DB::rollBack();
  78. $this->assertSame(2, DB::table('site_realtime_events')->count());
  79. }
  80. public function test_migration_defaults_and_catalog_match_commission_types(): void
  81. {
  82. $this->assertSame(10, DB::table('maintenance_settings')->count());
  83. $this->assertSame(0, DB::table('maintenance_settings')->where('enabled', 1)->count());
  84. $this->assertSame(ShareDefaults::categories(), Policy::CATEGORIES);
  85. $this->assertSame(10, $this->service->listing([])['total']); $this->assertNull($this->decide());
  86. $this->assertContains('UTC', $this->service->options()['timezones']);
  87. $this->assertSame(['zh', 'en', 'vi'], array_column($this->service->options()['languages'], 'value'));
  88. $this->migration()->down(); $this->assertFalse(Schema::hasTable('maintenance_settings')); $this->assertTrue(Schema::hasTable('users'));
  89. }
  90. public function test_utc_conversion_and_exact_start_end_without_scheduler(): void
  91. {
  92. $row = $this->save(['starts_at' => '2026-10-26 10:00:00', 'ends_at' => '2026-10-26 11:00:00']);
  93. $this->assertSame('active', $row['state']); $this->assertSame('2026-10-26T02:00:00Z', $row['starts_at_utc']);
  94. $this->assertSame('2026-10-26 02:00:00', DB::table('maintenance_settings')->where('id', $row['id'])->value('starts_at'));
  95. Carbon::setTestNow(Carbon::parse('2026-10-26 09:59:59', 'Asia/Shanghai')); $this->assertNull($this->decide());
  96. Carbon::setTestNow(Carbon::parse('2026-10-26 10:00:00', 'Asia/Shanghai')); $this->assertSame('site', $this->decide()['scope_code']);
  97. Carbon::setTestNow(Carbon::parse('2026-10-26 11:00:00', 'Asia/Shanghai')); $this->assertNull($this->decide());
  98. $this->assertSame('expired', $this->service->detail($row['id'])['state']);
  99. $this->assertSame(1, DB::table('maintenance_settings')->where('id', $row['id'])->value('enabled'));
  100. $this->assertSame('expired', $this->service->status($row['id'], 1)['state']);
  101. $this->assertSame('active', $this->service->save(['id' => $row['id'], 'start_now' => true, 'ends_at' => null])['state']);
  102. }
  103. public function test_site_precedence_applies_only_to_effective_platform_and_time(): void
  104. {
  105. $this->save(['platforms' => ['H5']]); $this->save(['platforms' => ['PC', 'H5']], 'third:4');
  106. $this->assertSame('site', $this->decide('H5', 'third:4')['scope_code']);
  107. $this->assertSame('third:4', $this->decide('PC', 'third:4')['scope_code']);
  108. $this->assertNull($this->decide('APP', 'third:4')); $this->assertNull($this->decide('PC', 'self:sport'));
  109. $this->assertSame('site', $this->decide(null, 'third:4')['scope_code']);
  110. $this->save(['starts_at' => '2026-10-27 00:00:00']);
  111. $this->assertSame('third:4', $this->decide('H5', 'third:4')['scope_code']);
  112. $this->save(['ends_at' => '2026-10-26 10:00:00']);
  113. $this->assertSame('third:4', $this->decide('H5', 'third:4')['scope_code']);
  114. $this->assertSame('third:4', $this->decide(null, 'third:4')['scope_code']);
  115. }
  116. public function test_translations_blank_fallback_partial_update_and_audit_history(): void
  117. {
  118. $this->save(['translations' => ['zh' => ['content' => '<b>维护</b>'], 'en' => ['content' => 'Maintenance'], 'vi' => ['content' => ' ']]]);
  119. $this->assertSame(2, DB::table('maintenance_translations')->count());
  120. $this->assertSame('<b>维护</b>', $this->decide()['content']);
  121. $this->assertSame('Maintenance', Policy::failure($this->service->runtimeRows('en')[0], 'PC', 'en', now()->getTimestamp())['msg']);
  122. $fallback = Policy::failure($this->service->runtimeRows('vi')[0], 'PC', 'vi', now()->getTimestamp());
  123. $this->assertSame(11001, $fallback['code']); $this->assertStringContainsString('bảo trì', $fallback['msg']);
  124. $this->service->save(['id' => $this->id(), 'platforms' => ['PC']]); $this->assertSame(2, DB::table('maintenance_translations')->count());
  125. $before = DB::table('operation_audits')->count(); $this->service->status($this->id(), 1); $this->assertSame($before, DB::table('operation_audits')->count());
  126. $this->service->save(['id' => $this->id(), 'translations' => ['zh' => ['content' => '中文']]]);
  127. $logs = $this->service->logs(['language' => 'en', 'operator_name' => 'adm', 'resource_id' => $this->id()]);
  128. $this->assertSame(3, $logs['total']);
  129. $this->assertSame('整站', ((array) $logs['data'][0]['old_values'])['translations']['en']['title']);
  130. $audit = json_decode(DB::table('operation_audits')->orderBy('id')->value('changes'), true);
  131. $this->assertSame('site', $audit['after']['scope_code']);
  132. $this->assertSame(0, $this->service->listing(['language' => 'en'])['total']);
  133. }
  134. public function test_filters_are_applied_before_pagination_and_timezone_edit_preserves_instants(): void
  135. {
  136. $row = $this->save(['platforms' => ['APP'], 'translations' => ['en' => ['content' => 'Text']]]);
  137. $this->save(['platforms' => ['APP'], 'translations' => ['en' => ['content' => 'Game']]], 'third:2');
  138. $list = $this->service->listing(['enabled' => 1, 'state' => 'active', 'platform' => 'APP', 'language' => 'en', 'limit' => 1, 'page' => 2]);
  139. $this->assertSame(2, $list['total']); $this->assertSame('third:2', $list['data'][0]['scope_code']);
  140. $edited = $this->service->save(['id' => $row['id'], 'timezone' => 'America/New_York']);
  141. $this->assertSame($row['starts_at_utc'], $edited['starts_at_utc']); $this->assertSame('2026-10-25 21:00:00', $edited['starts_at']);
  142. $this->assertSame(1, $this->service->listing(['scope_code' => 'third:2'])['total']);
  143. }
  144. /** @dataProvider invalidInputs */
  145. public function test_invalid_schedules_scopes_and_payloads_leave_no_changes(array $input): void
  146. {
  147. $before = (array) DB::table('maintenance_settings')->where('id', $this->id())->first();
  148. try { $this->save($input); $this->fail('Expected validation failure'); }
  149. catch (ValidationException $e) { $this->assertNotEmpty($e->errors()); }
  150. $this->assertSame($before, (array) DB::table('maintenance_settings')->where('id', $this->id())->first());
  151. $this->assertSame(0, DB::table('operation_audits')->count());
  152. }
  153. public static function invalidInputs(): array
  154. {
  155. return array_map(fn ($input) => [$input], [
  156. ['id' => 999], ['scope_code' => 'third:4'], ['platforms' => []], ['platforms' => ['IOS']], ['platforms' => ['PC', 'PC']],
  157. ['enabled' => 2], ['timezone' => '+08:00'], ['timezone' => 'Not/AZone'], ['starts_at' => '2026-02-30 00:00:00'],
  158. ['ends_at' => '2026-10-26 08:00:00'], ['translations' => ['th' => ['content' => 'bad']]], ['translations' => ['zh' => 'bad']],
  159. ['translations' => ['en' => ['content' => str_repeat('x', 5001)]]],
  160. ['timezone' => 'America/New_York', 'starts_at' => '2026-03-08 02:30:00'],
  161. ['timezone' => 'America/New_York', 'starts_at' => '2026-11-01 01:30:00'],
  162. ]);
  163. }
  164. public function test_audit_failure_rolls_back_rule_and_translations(): void
  165. {
  166. DB::statement("CREATE TRIGGER reject_maintenance_audit BEFORE INSERT ON bot_operation_audits BEGIN SELECT RAISE(ABORT, 'audit failed'); END");
  167. try { $this->save(['translations' => ['zh' => ['content' => '维护']]]); $this->fail('Expected audit failure'); }
  168. catch (\Illuminate\Database\QueryException $e) { $this->assertStringContainsString('audit failed', $e->getMessage()); }
  169. $this->assertSame(0, DB::table('maintenance_settings')->where('enabled', 1)->count());
  170. $this->assertSame(0, DB::table('maintenance_translations')->count());
  171. }
  172. public function test_legacy_middleware_blocks_before_business_and_uses_saved_language_without_renewal(): void
  173. {
  174. $this->save(['translations' => ['en' => ['content' => 'Saved English']]]);
  175. DB::table('users')->insert(['user_id' => '101', 'language' => 'en']);
  176. DB::table('user_session')->insert(['user_id' => '101', 'token' => 'valid', 'create_time' => now()->getTimestamp() - 3600,
  177. 'update_time' => now()->getTimestamp() - 3600, 'expire_time' => now()->getTimestamp() + 3600]);
  178. $before = (array) DB::table('user_session')->first(); $called = false;
  179. $request = Request::create('/api/wallet/createPay', 'POST'); $request->headers->add(['Authorization' => 'valid', 'Lang' => 'vi', 'Platform' => 'PC']);
  180. $response = (new MemberMaintenance())->handle($request, function () use (&$called) { $called = true; return new JsonResponse(['code' => 0]); });
  181. $this->assertFalse($called); $this->assertSame(200, $response->getStatusCode());
  182. $this->assertSame(11001, $response->getData(true)['code']); $this->assertSame('Saved English', $response->getData(true)['msg']);
  183. $this->assertSame($before, (array) DB::table('user_session')->first());
  184. $this->assertStringContainsString('no-store', $response->headers->get('Cache-Control'));
  185. $this->service->status($this->id(), 0);
  186. $this->assertSame(0, (new MemberMaintenance())->handle($request, fn () => new JsonResponse(['code' => 0]))->getData(true)['code']);
  187. }
  188. public function test_routes_permissions_and_callbacks_settlement_and_admin_remain_outside_gate(): void
  189. {
  190. $router = new Router(new Dispatcher($this->app), $this->app); $this->app->instance('router', $router);
  191. if (!class_exists('Route')) class_alias(\Illuminate\Support\Facades\Route::class, 'Route');
  192. $router->group(['prefix' => 'admin'], function () { require dirname(__DIR__, 2) . '/routes/admin.php'; });
  193. $router->group(['prefix' => 'api'], function () { require dirname(__DIR__, 2) . '/routes/api.php'; require dirname(__DIR__, 2) . '/routes/api_private.php'; });
  194. foreach (['' => 'GET', '/options' => 'GET', '/detail' => 'GET', '/logs' => 'GET', '/submit' => 'POST', '/status' => 'POST'] as $suffix => $method) {
  195. $route = $router->getRoutes()->match(Request::create('/admin/maintenance' . $suffix, $method));
  196. foreach (['admin.jwt', 'check.button.uri', 'operations.admin'] as $middleware) $this->assertContains($middleware, $route->middleware());
  197. $this->assertNotContains(MemberMaintenance::class, $route->middleware());
  198. }
  199. $this->assertSame('admin/maintenance/submit', $route->defaults['permission_uri']);
  200. foreach (['/api/wallet/createPay' => 'POST', '/api/ActivityReward' => 'GET', '/api/newPc' => 'GET', '/api/issue' => 'GET', '/api/pcissue' => 'GET'] as $uri => $method) {
  201. $this->assertContains(MemberMaintenance::class, $router->getRoutes()->match(Request::create($uri, $method))->middleware());
  202. }
  203. foreach (['/api/pay/notify', '/api/pay/harvest', '/api/onMessage', '/api/pcissue/verify'] as $uri) {
  204. $this->assertNotContains(MemberMaintenance::class, $router->getRoutes()->match(Request::create($uri, 'POST'))->middleware());
  205. }
  206. $request = $this->request(); $request->user->id = 99;
  207. $this->assertSame(-1, (new OperationsAdminMiddleware())->handle($request, fn () => new JsonResponse(['code' => 0]))->getData(true)['code']);
  208. $this->request(['id' => $this->id(), 'enabled' => 1]);
  209. $this->assertSame(0, (new MaintenanceController())->submit($this->service)->getData(true)['code']);
  210. }
  211. }