BannerPublicationTest.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. <?php
  2. namespace Tests\Integration;
  3. use App\Constants\HttpStatus;
  4. use App\Http\Controllers\admin\Banner as AdminBanner;
  5. use App\Http\Middleware\CheckButtonPermission;
  6. use App\Models\Banner;
  7. use App\Services\BannerVisibilityService;
  8. use Illuminate\Config\Repository;
  9. use Illuminate\Database\Capsule\Manager;
  10. use Illuminate\Database\Schema\Blueprint;
  11. use Illuminate\Events\Dispatcher;
  12. use Illuminate\Foundation\Application;
  13. use Illuminate\Http\JsonResponse;
  14. use Illuminate\Http\Request;
  15. use Illuminate\Routing\Router;
  16. use Illuminate\Support\Facades\DB;
  17. use Illuminate\Support\Facades\Facade;
  18. use Illuminate\Support\Facades\Schema;
  19. use Illuminate\Translation\ArrayLoader;
  20. use Illuminate\Translation\Translator;
  21. use Illuminate\Validation\Factory;
  22. use PHPUnit\Framework\TestCase;
  23. /** Exercises real banner controllers and queries against an isolated, prefixed SQLite database. */
  24. class BannerPublicationTest extends TestCase
  25. {
  26. private Application $app;
  27. protected function setUp(): void
  28. {
  29. Facade::clearResolvedInstances();
  30. $this->app = new Application(dirname(__DIR__, 2));
  31. $this->app->instance('config', new Repository([
  32. 'app' => ['locale' => 'zh', 'url' => 'https://banner.example.test', 'timezone' => 'Asia/Shanghai'],
  33. ]));
  34. Facade::setFacadeApplication($this->app);
  35. $db = new Manager($this->app);
  36. $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'bot_']);
  37. $db->setAsGlobal();
  38. $db->bootEloquent();
  39. $this->app->instance('db', $db->getDatabaseManager());
  40. $this->app->bind('db.schema', fn () => $db->schema());
  41. $translator = new Translator(new ArrayLoader(), 'zh');
  42. $this->app->instance('translator', $translator);
  43. $this->app->instance('validator', new Factory($translator, $this->app));
  44. $this->app->instance(\Illuminate\Contracts\Routing\ResponseFactory::class, new class {
  45. public function json($data, $status = 200, $headers = [], $options = 0) {
  46. return new JsonResponse($data, $status, $headers, $options);
  47. }
  48. });
  49. Request::macro('validate', function (array $rules) {
  50. return app('validator')->make($this->all(), $rules)->validate();
  51. });
  52. $db->schema()->create('banner', function (Blueprint $t) {
  53. $t->id(); $t->string('title'); $t->string('image'); $t->string('link')->nullable();
  54. $t->string('type'); $t->integer('sort')->default(0); $t->string('lang'); $t->timestamps();
  55. });
  56. $this->migration()->up();
  57. $db->schema()->create('activity_rewards', function (Blueprint $t) {
  58. $t->id(); $t->integer('status')->default(1);
  59. $t->integer('start_time'); $t->integer('end_time');
  60. });
  61. $this->request('index');
  62. }
  63. protected function tearDown(): void
  64. {
  65. DB::disconnect();
  66. Facade::clearResolvedInstances();
  67. parent::tearDown();
  68. }
  69. private function migration()
  70. {
  71. return require dirname(__DIR__, 2) . '/database/migrations/2026_10_24_140000_add_status_to_banner.php';
  72. }
  73. private function request(string $action, array $params = []): void
  74. {
  75. $this->app->instance('request', Request::create('/admin/banner/' . $action,
  76. $action === 'index' ? 'GET' : 'POST', $params));
  77. }
  78. private function form(array $overrides = []): array
  79. {
  80. return $overrides + [
  81. 'title' => '轮播图', 'image' => '/banner.png', 'type' => 'pc', 'lang' => 'zh',
  82. ];
  83. }
  84. private function save(array $params = []): array
  85. {
  86. $this->request('update', $this->form($params));
  87. return (new AdminBanner())->update()->getData(true);
  88. }
  89. private function status(array $params): array
  90. {
  91. $this->request('status', $params);
  92. return (new AdminBanner())->status()->getData(true);
  93. }
  94. private function listing(array $params = []): array
  95. {
  96. $this->request('index', $params);
  97. $result = (new AdminBanner())->index()->getData(true);
  98. $this->assertSame(HttpStatus::OK, $result['code'], $result['msg']);
  99. return $result['data'];
  100. }
  101. private function banner(array $params = []): int
  102. {
  103. return DB::table('banner')->insertGetId($params + $this->form() + ['link' => null, 'sort' => 0, 'status' => 1]);
  104. }
  105. private function activity(int $id, int $start, int $end, int $status = 1): void
  106. {
  107. DB::table('activity_rewards')->insert([
  108. 'id' => $id, 'status' => $status, 'start_time' => $start, 'end_time' => $end,
  109. ]);
  110. }
  111. private function decorated(int $now): array
  112. {
  113. return collect(BannerVisibilityService::decorate(Banner::query()->orderBy('id')->get(), $now))->keyBy('id')->all();
  114. }
  115. private function assertState(array $row, int $manual, int $effective, ?string $reason, ?string $activityId): void
  116. {
  117. $this->assertSame($manual, $row['status']);
  118. $this->assertSame($effective, $row['effective_status']);
  119. $this->assertSame($reason, $row['offline_reason']);
  120. $this->assertSame($activityId, $row['activity_id']);
  121. }
  122. public function test_migration_publishes_existing_banners_by_default_and_rolls_back_only_its_column(): void
  123. {
  124. $this->migration()->down();
  125. $this->assertFalse(Schema::hasColumn('banner', 'status'));
  126. $id = DB::table('banner')->insertGetId($this->form(['title' => '历史轮播图', 'sort' => 23]) + ['link' => 'https://example.test']);
  127. $this->migration()->up();
  128. $row = DB::table('banner')->find($id);
  129. $this->assertSame(1, (int) $row->status);
  130. $this->assertSame('历史轮播图', $row->title);
  131. $this->assertSame(23, (int) $row->sort);
  132. $this->assertSame('https://example.test', $row->link);
  133. $newId = DB::table('banner')->insertGetId($this->form());
  134. $this->assertSame(1, (int) DB::table('banner')->where('id', $newId)->value('status'));
  135. $this->migration()->down();
  136. $this->assertFalse(Schema::hasColumn('banner', 'status'));
  137. $this->assertSame(2, DB::table('banner')->count());
  138. $this->assertSame('历史轮播图', DB::table('banner')->where('id', $id)->value('title'));
  139. }
  140. public function test_create_defaults_to_manual_on_and_legacy_edit_preserves_omitted_status_link_and_sort(): void
  141. {
  142. $result = $this->save(['sort' => 27, 'link' => 'https://example.test/promotion', 'type' => 'app', 'lang' => 'en']);
  143. $this->assertSame(HttpStatus::OK, $result['code'], $result['msg']);
  144. $banner = Banner::query()->firstOrFail();
  145. $this->assertSame(1, $banner->status);
  146. $this->assertSame('app', $banner->type);
  147. $this->assertSame('en', $banner->lang);
  148. $this->assertSame(27, (int) $banner->sort);
  149. $this->assertSame(HttpStatus::OK, $this->status(['id' => $banner->id, 'status' => 0])['code']);
  150. $result = $this->save(['id' => $banner->id, 'title' => '编辑标题', 'type' => 'app', 'lang' => 'en']);
  151. $this->assertSame(HttpStatus::OK, $result['code'], $result['msg']);
  152. $banner->refresh();
  153. $this->assertSame('编辑标题', $banner->title);
  154. $this->assertSame(0, $banner->status);
  155. $this->assertSame('https://example.test/promotion', $banner->link);
  156. $this->assertSame(27, (int) $banner->sort);
  157. $this->assertSame('app', $banner->type);
  158. $this->assertSame('en', $banner->lang);
  159. $this->assertSame('/banner.png', $banner->getRawOriginal('image'));
  160. $this->assertSame('https://banner.example.test/banner.png', $banner->image);
  161. }
  162. public function test_status_endpoint_accepts_repeated_zero_and_one_without_changing_banner_content(): void
  163. {
  164. $id = $this->banner(['sort' => 19, 'lang' => 'en', 'link' => 'https://example.test']);
  165. foreach ([0, 0, 1, 1, '0', '1'] as $status) {
  166. $result = $this->status(['id' => $id, 'status' => $status]);
  167. $this->assertSame(HttpStatus::OK, $result['code'], $result['msg']);
  168. $row = DB::table('banner')->find($id);
  169. $this->assertSame((int) $status, (int) $row->status);
  170. $this->assertSame('https://example.test', $row->link);
  171. $this->assertSame(19, (int) $row->sort);
  172. $this->assertSame('en', $row->lang);
  173. }
  174. }
  175. public function test_create_accepts_manual_off_and_invalid_publication_values_leave_rows_unchanged(): void
  176. {
  177. $result = $this->save(['status' => 0]);
  178. $this->assertSame(HttpStatus::OK, $result['code'], $result['msg']);
  179. $id = DB::table('banner')->value('id');
  180. $this->assertSame(0, (int) DB::table('banner')->where('id', $id)->value('status'));
  181. foreach ([null, -1, 2, 'invalid'] as $status) {
  182. $result = $this->save(['id' => $id, 'title' => '不应保存', 'status' => $status]);
  183. $this->assertSame(HttpStatus::VALIDATION_FAILED, $result['code']);
  184. $row = DB::table('banner')->find($id);
  185. $this->assertSame(0, (int) $row->status);
  186. $this->assertSame('轮播图', $row->title);
  187. }
  188. $this->assertSame(1, DB::table('banner')->count());
  189. }
  190. public function test_status_endpoint_rejects_missing_invalid_status_and_missing_banner(): void
  191. {
  192. $id = $this->banner();
  193. foreach ([[], ['id' => $id], ['status' => 0], ['id' => $id, 'status' => -1],
  194. ['id' => $id, 'status' => 2], ['id' => $id, 'status' => 'invalid'],
  195. ['id' => $id, 'status' => null], ['id' => 0, 'status' => 0],
  196. ['id' => 'invalid', 'status' => 0]] as $params) {
  197. $this->assertSame(HttpStatus::VALIDATION_FAILED, $this->status($params)['code']);
  198. $this->assertSame(1, (int) DB::table('banner')->where('id', $id)->value('status'));
  199. }
  200. $result = $this->status(['id' => 999999, 'status' => 0]);
  201. $this->assertSame(HttpStatus::CUSTOM_ERROR, $result['code']);
  202. $this->assertStringContainsString('数据不存在', $result['msg']);
  203. $this->assertSame(1, DB::table('banner')->count());
  204. }
  205. public function test_bound_visibility_uses_raw_seconds_and_includes_start_but_excludes_end(): void
  206. {
  207. $now = strtotime('2026-10-24 12:30:00 UTC');
  208. $expected = [];
  209. foreach ([
  210. 1 => [$now - 1, $now + 1, 1, null],
  211. 2 => [$now + 1, $now + 120, 1, 'activity_not_started'],
  212. 3 => [$now - 120, $now - 1, 1, 'activity_ended'],
  213. 4 => [$now, $now + 1, 1, null],
  214. 5 => [$now - 1, $now, 1, 'activity_ended'],
  215. 6 => [$now - 1, $now + 1, 0, 'activity_offline'],
  216. ] as $activityId => [$start, $end, $status, $reason]) {
  217. $this->activity($activityId, $start, $end, $status);
  218. $id = $this->banner(['link' => (string) $activityId]);
  219. $expected[$id] = [$reason, (string) $activityId];
  220. }
  221. $id = $this->banner(['link' => '999']);
  222. $expected[$id] = ['activity_missing', '999'];
  223. $rows = $this->decorated($now);
  224. foreach ($expected as $id => [$reason, $activityId]) {
  225. $this->assertState($rows[$id], 1, $reason === null ? 1 : 0, $reason, $activityId);
  226. $this->assertSame(1, (int) DB::table('banner')->where('id', $id)->value('status'));
  227. }
  228. }
  229. public function test_null_empty_zero_and_url_links_follow_only_the_manual_setting(): void
  230. {
  231. $expected = [];
  232. foreach ([null, '', '0', '000', 'https://example.test/activity/7'] as $link) {
  233. foreach ([0, 1] as $manual) {
  234. $id = $this->banner(['link' => $link, 'status' => $manual]);
  235. $expected[$id] = $manual;
  236. }
  237. }
  238. DB::connection()->enableQueryLog();
  239. $rows = $this->decorated(1000);
  240. $queries = DB::connection()->getQueryLog();
  241. DB::connection()->disableQueryLog();
  242. foreach ($expected as $id => $manual) {
  243. $this->assertState($rows[$id], $manual, $manual, $manual ? null : 'manual', null);
  244. }
  245. $this->assertCount(1, $queries, 'Unbound banners should not query activities.');
  246. }
  247. public function test_manual_on_cannot_override_ended_activity_and_reopening_respects_manual_off(): void
  248. {
  249. $now = time();
  250. $this->activity(7, $now - 100, $now - 10);
  251. $on = $this->banner(['link' => '7', 'status' => 0]);
  252. $off = $this->banner(['link' => '7', 'status' => 0]);
  253. $this->assertSame(HttpStatus::OK, $this->status(['id' => $on, 'status' => 1])['code']);
  254. $rows = $this->decorated($now);
  255. $this->assertState($rows[$on], 1, 0, 'activity_ended', '7');
  256. $this->assertState($rows[$off], 0, 0, 'manual', '7');
  257. DB::table('activity_rewards')->where('id', 7)->update(['end_time' => $now + 100]);
  258. $rows = $this->decorated($now);
  259. $this->assertState($rows[$on], 1, 1, null, '7');
  260. $this->assertState($rows[$off], 0, 0, 'manual', '7');
  261. DB::table('activity_rewards')->where('id', 7)->update(['status' => 0]);
  262. $this->assertState($this->decorated($now)[$on], 1, 0, 'activity_offline', '7');
  263. DB::table('activity_rewards')->where('id', 7)->update(['status' => 1]);
  264. $this->assertState($this->decorated($now)[$on], 1, 1, null, '7');
  265. $this->assertSame(0, (int) DB::table('banner')->where('id', $off)->value('status'));
  266. }
  267. public function test_integer_and_leading_zero_activity_links_are_validated_and_canonicalized(): void
  268. {
  269. $this->activity(7, 1, 4102444799);
  270. foreach ([7, '7', '0007'] as $link) {
  271. $result = $this->save(['link' => $link]);
  272. $this->assertSame(HttpStatus::OK, $result['code'], $result['msg']);
  273. $this->assertSame('7', DB::table('banner')->latest('id')->value('link'));
  274. }
  275. foreach ([999, '000999'] as $link) {
  276. $result = $this->save(['link' => $link]);
  277. $this->assertSame(HttpStatus::VALIDATION_FAILED, $result['code']);
  278. $this->assertStringContainsString('绑定的活动不存在', $result['msg']);
  279. }
  280. $this->assertSame(3, DB::table('banner')->count());
  281. $id = DB::table('banner')->value('id');
  282. $result = $this->save(['id' => $id, 'link' => '999']);
  283. $this->assertSame(HttpStatus::VALIDATION_FAILED, $result['code']);
  284. $this->assertSame('7', DB::table('banner')->where('id', $id)->value('link'));
  285. $result = $this->save(['link' => ['id' => 7]]);
  286. $this->assertSame(HttpStatus::VALIDATION_FAILED, $result['code']);
  287. $this->assertSame(3, DB::table('banner')->count());
  288. }
  289. public function test_stale_missing_activity_link_can_be_edited_unchanged_and_taken_offline(): void
  290. {
  291. $id = $this->banner(['link' => '500', 'sort' => 31]);
  292. $result = $this->save(['id' => $id, 'title' => '已删除活动的轮播图']);
  293. $this->assertSame(HttpStatus::OK, $result['code'], $result['msg']);
  294. $this->assertSame('500', DB::table('banner')->where('id', $id)->value('link'));
  295. $this->assertSame(31, (int) DB::table('banner')->where('id', $id)->value('sort'));
  296. $result = $this->save(['id' => $id, 'link' => '000500', 'status' => 0]);
  297. $this->assertSame(HttpStatus::OK, $result['code'], $result['msg']);
  298. $this->assertState($this->decorated(time())[$id], 0, 0, 'manual', '500');
  299. $this->assertSame(HttpStatus::OK, $this->status(['id' => $id, 'status' => 1])['code']);
  300. $this->assertState($this->decorated(time())[$id], 1, 0, 'activity_missing', '500');
  301. $this->assertSame(HttpStatus::OK, $this->status(['id' => $id, 'status' => 0])['code']);
  302. }
  303. public function test_admin_pagination_counts_hidden_rows_and_batches_activity_queries(): void
  304. {
  305. $now = time();
  306. $this->activity(7, $now - 100, $now + 100);
  307. $this->activity(8, $now - 100, $now - 10);
  308. for ($i = 0; $i < 24; $i++) {
  309. $this->banner(['title' => '轮播图 ' . $i, 'link' => $i % 2 ? '7' : '8',
  310. 'status' => $i % 3 ? 1 : 0, 'sort' => $i]);
  311. }
  312. DB::connection()->enableQueryLog();
  313. $page = $this->listing(['limit' => 20, 'page' => 1]);
  314. $queries = DB::connection()->getQueryLog();
  315. DB::connection()->disableQueryLog();
  316. $this->assertSame(24, $page['total']);
  317. $this->assertCount(20, $page['data']);
  318. $this->assertCount(3, $queries, 'Admin list should use one count, one page, and one batched activity query.');
  319. $this->assertSame(range(23, 4), array_column($page['data'], 'sort'));
  320. $this->assertNotEmpty(array_filter($page['data'], fn ($row) => $row['effective_status'] === 0));
  321. $this->assertNotEmpty(array_filter($page['data'], fn ($row) => $row['effective_status'] === 1));
  322. $last = $this->listing(['limit' => 20, 'page' => 2]);
  323. $this->assertSame(24, $last['total']);
  324. $this->assertCount(4, $last['data']);
  325. $this->assertSame(range(3, 0), array_column($last['data'], 'sort'));
  326. }
  327. public function test_admin_type_filter_and_sort_order_preserve_language_and_hidden_rows(): void
  328. {
  329. $first = $this->banner(['type' => 'app', 'lang' => 'en', 'sort' => 9, 'status' => 0]);
  330. $second = $this->banner(['type' => 'app', 'lang' => 'zh', 'sort' => 9]);
  331. $third = $this->banner(['type' => 'app', 'lang' => 'zh', 'sort' => 2]);
  332. $this->banner(['type' => 'pc', 'lang' => 'en', 'sort' => 100]);
  333. $page = $this->listing(['type' => 'app', 'limit' => 20]);
  334. $this->assertSame(3, $page['total']);
  335. $this->assertSame([$second, $first, $third], array_column($page['data'], 'id'));
  336. $this->assertSame(['zh', 'en', 'zh'], array_column($page['data'], 'lang'));
  337. $this->assertSame(['app', 'app', 'app'], array_column($page['data'], 'type'));
  338. $this->assertSame([1, 0, 1], array_column($page['data'], 'effective_status'));
  339. }
  340. public function test_status_route_requires_existing_banner_edit_permission_and_preserves_superadmin_access(): void
  341. {
  342. Schema::create('menus', function (Blueprint $t) {
  343. $t->id(); $t->string('uri'); $t->integer('type'); $t->integer('status');
  344. });
  345. Schema::create('roles', function (Blueprint $t) {
  346. $t->id(); $t->string('name');
  347. });
  348. Schema::create('role_user', function (Blueprint $t) {
  349. $t->id(); $t->integer('user_id'); $t->integer('role_id');
  350. });
  351. Schema::create('role_menu', function (Blueprint $t) {
  352. $t->id(); $t->integer('role_id'); $t->integer('menu_id');
  353. });
  354. $editMenu = DB::table('menus')->insertGetId([
  355. 'uri' => 'admin/banner/update', 'type' => 2, 'status' => 1,
  356. ]);
  357. $otherMenu = DB::table('menus')->insertGetId([
  358. 'uri' => 'admin/banner/delete', 'type' => 2, 'status' => 1,
  359. ]);
  360. $router = new Router(new Dispatcher($this->app), $this->app);
  361. $this->app->instance('router', $router);
  362. $router->group(['prefix' => 'admin'], function () {
  363. require dirname(__DIR__, 2) . '/routes/admin.php';
  364. });
  365. $route = $router->getRoutes()->match(Request::create('/admin/banner/status', 'POST'));
  366. $this->assertSame('admin/banner/update', $route->defaults['permission_uri']);
  367. $this->assertContains('admin.jwt', $route->middleware());
  368. $this->assertContains('check.button.uri', $route->middleware());
  369. $this->assertSame(AdminBanner::class . '@status', $route->getAction('uses'));
  370. $id = $this->banner();
  371. $changeStatus = function (int $userId, int $status) use ($router, $id): array {
  372. $this->request('status', ['id' => $id, 'status' => $status, 'user' => (object) ['id' => $userId]]);
  373. $request = $this->app['request'];
  374. $route = $router->getRoutes()->match($request);
  375. $request->setRouteResolver(fn () => $route);
  376. return (new CheckButtonPermission())->handle($request,
  377. fn () => (new AdminBanner())->status())->getData(true);
  378. };
  379. // The status URI has no separate menu: it must inherit the existing edit button gate.
  380. $this->assertSame(0, DB::table('menus')->where('uri', 'admin/banner/status')->count());
  381. $result = $changeStatus(20, 0);
  382. $this->assertSame(-1, $result['code']);
  383. $this->assertSame('无权限访问', $result['msg']);
  384. $this->assertSame(1, (int) DB::table('banner')->where('id', $id)->value('status'));
  385. DB::table('roles')->insert(['id' => 5, 'name' => 'editor']);
  386. DB::table('role_user')->insert(['user_id' => 20, 'role_id' => 5]);
  387. DB::table('role_menu')->insert(['role_id' => 5, 'menu_id' => $otherMenu]);
  388. $this->assertSame(-1, $changeStatus(20, 0)['code']);
  389. $this->assertSame(1, (int) DB::table('banner')->where('id', $id)->value('status'));
  390. DB::table('role_menu')->insert(['role_id' => 5, 'menu_id' => $editMenu]);
  391. $result = $changeStatus(20, 0);
  392. $this->assertSame(HttpStatus::OK, $result['code'], $result['msg']);
  393. $this->assertSame(0, (int) DB::table('banner')->where('id', $id)->value('status'));
  394. $result = $changeStatus(1, 1);
  395. $this->assertSame(HttpStatus::OK, $result['code'], $result['msg']);
  396. $this->assertSame(1, (int) DB::table('banner')->where('id', $id)->value('status'));
  397. $this->assertSame(0, DB::table('role_user')->where('user_id', 1)->count());
  398. }
  399. }