| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383 |
- <?php
- namespace Tests\Integration;
- use App\Constants\HttpStatus;
- use App\Http\Controllers\admin\ActivityReward as AdminActivityReward;
- use App\Models\ActivityReward;
- use App\Services\ActivityRewardService;
- use App\Services\Sharing\ShareDefaults;
- use App\Support\ActivityCatalog;
- use Illuminate\Config\Repository;
- use Illuminate\Database\Capsule\Manager;
- use Illuminate\Database\Schema\Blueprint;
- use Illuminate\Events\Dispatcher;
- use Illuminate\Foundation\Application;
- use Illuminate\Http\JsonResponse;
- use Illuminate\Http\Request;
- use Illuminate\Routing\Router;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Facade;
- use Illuminate\Support\Facades\Schema;
- use Illuminate\Translation\ArrayLoader;
- use Illuminate\Translation\Translator;
- use Illuminate\Validation\Factory;
- use Illuminate\Validation\ValidationException;
- use PHPUnit\Framework\TestCase;
- /** Real controllers and service validation against SQLite only; no application boot or external databases. */
- class ActivityCatalogTest extends TestCase
- {
- private Application $app;
- protected function setUp(): void
- {
- Facade::clearResolvedInstances();
- $this->app = new Application(dirname(__DIR__, 2));
- $this->app->instance('config', new Repository([
- 'app' => ['locale' => 'zh', 'url' => 'https://activity.example.test', 'timezone' => 'Asia/Shanghai'],
- ]));
- Facade::setFacadeApplication($this->app);
- $db = new Manager($this->app);
- $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'bot_']);
- $db->setAsGlobal(); $db->bootEloquent();
- $this->app->instance('db', $db->getDatabaseManager());
- $this->app->bind('db.schema', fn () => $db->schema());
- $translator = new Translator(new ArrayLoader(), 'zh');
- $this->app->instance('translator', $translator);
- $this->app->instance('validator', new Factory($translator, $this->app));
- $this->app->instance(\Illuminate\Contracts\Routing\ResponseFactory::class, new class {
- public function json($data, $status = 200, $headers = [], $options = 0) {
- return new JsonResponse($data, $status, $headers, $options);
- }
- });
- Request::macro('validate', function (array $rules) {
- return app('validator')->make($this->all(), $rules)->validate();
- });
- $db->schema()->create('activity_rewards', function (Blueprint $t) {
- $t->id(); $t->string('title'); $t->string('sub_title');
- $t->integer('start_time'); $t->integer('end_time'); $t->integer('status')->default(1);
- $t->integer('type')->default(1); $t->string('lang')->default('zh');
- foreach (['detail_image', 'pc_image', 'detail_banner', 'pc_banner', 'content', 'params'] as $field) {
- $t->text($field)->nullable();
- }
- $t->timestamps();
- });
- (require dirname(__DIR__, 2) . '/database/migrations/2026_10_13_120000_add_activity_eligibility_fields.php')->up();
- (require dirname(__DIR__, 2) . '/database/migrations/2026_10_14_120000_add_activity_reward_quotas.php')->up();
- $this->migration()->up();
- $this->request('');
- }
- protected function tearDown(): void
- {
- DB::disconnect(); Facade::clearResolvedInstances(); parent::tearDown();
- }
- private function migration()
- {
- return require dirname(__DIR__, 2) . '/database/migrations/2026_10_25_120000_add_game_category_to_activity_rewards.php';
- }
- private function request(string $action, array $params = [], string $method = 'GET'): void
- {
- $this->app->instance('request', Request::create('/admin/ActivityReward/' . $action, $method, $params));
- }
- private function form(array $overrides = []): array
- {
- return $overrides + [
- 'title' => '活动分类测试', 'sub_title' => '分类说明', 'type' => 3, 'status' => 1, 'lang' => 'zh',
- 'start_time' => '2026-10-01 12:00:00', 'end_time' => '2026-12-31 12:00:00',
- 'detail_image' => '/app.png', 'pc_image' => '/pc.png',
- 'detail_banner' => '/app-banner.png', 'pc_banner' => '/pc-banner.png',
- ];
- }
- private function save(array $params = []): array
- {
- $this->request('submit', $this->form($params), 'POST');
- return (new AdminActivityReward())->store()->getData(true);
- }
- private function listing(array $filters = []): array
- {
- $this->request('', $filters + ['page' => 1, 'limit' => 100]);
- $result = (new AdminActivityReward())->index()->getData(true);
- $this->assertSame(HttpStatus::OK, $result['code'], $result['msg']);
- return $result['data'];
- }
- private function rawActivity(array $overrides = []): int
- {
- $data = $this->form($overrides);
- $data['start_time'] = strtotime($data['start_time']);
- $data['end_time'] = strtotime($data['end_time']);
- if (isset($data['publish_platforms']) && is_array($data['publish_platforms'])) {
- $data['publish_platforms'] = json_encode($data['publish_platforms']);
- }
- return DB::table('activity_rewards')->insertGetId($data);
- }
- public function test_options_match_all_shared_game_categories_and_five_activity_types_on_an_authenticated_route(): void
- {
- $this->rawActivity(['type' => 1]);
- $before = DB::table('activity_rewards')->get()->toJson();
- $this->request('options');
- $body = (new AdminActivityReward())->options()->getData(true);
- $this->assertSame(HttpStatus::OK, $body['code'], $body['msg']);
- $financialCategories = ['third:1' => '真人', 'third:2' => '电子', 'third:3' => '彩票',
- 'third:4' => '体育', 'third:5' => '电竞', 'third:6' => '捕鱼', 'third:7' => '棋牌',
- 'self:sport' => 'F1体育', 'self:lottery' => 'F1彩票'];
- $this->assertSame($financialCategories, ShareDefaults::categories());
- $this->assertCount(9, ShareDefaults::categories());
- $this->assertArrayNotHasKey('other', ShareDefaults::categories());
- $this->assertSame($financialCategories + ['other' => '其他'], ActivityCatalog::gameTypes());
- $expectedGames = [];
- foreach ($financialCategories + ['other' => '其他'] as $value => $label) $expectedGames[] = compact('value', 'label');
- $this->assertCount(10, $expectedGames);
- $this->assertSame($expectedGames, $body['data']['game_types']);
- $this->assertNotContains('', array_column($body['data']['game_types'], 'value'));
- $this->assertNotContains('wallet', array_column($body['data']['game_types'], 'value'));
- $this->assertNotContains('all', array_column($body['data']['game_types'], 'value'));
- $this->assertSame([
- ['value' => 2, 'label' => '普通活动'],
- ['value' => 3, 'label' => '即充即送'],
- ['value' => 4, 'label' => '老用户召集令'],
- ['value' => 5, 'label' => 'USDT使用教学'],
- ['value' => 6, 'label' => '余额宝'],
- ], $body['data']['activity_types']);
- $this->assertNotContains(1, array_column($body['data']['activity_types'], 'value'));
- $router = new Router(new Dispatcher($this->app), $this->app);
- $this->app->instance('router', $router);
- $router->group(['prefix' => 'admin'], function () {
- require dirname(__DIR__, 2) . '/routes/admin.php';
- });
- $route = $router->getRoutes()->match(Request::create('/admin/ActivityReward/options', 'GET'));
- $this->assertSame(AdminActivityReward::class . '@options', $route->getAction('uses'));
- $this->assertContains('admin.jwt', $route->middleware());
- $this->assertContains('check.button.uri', $route->middleware());
- $this->assertSame($before, DB::table('activity_rewards')->get()->toJson());
- $this->assertSame(0, DB::table('activity_reward_recipients')->count());
- }
- public function test_new_omission_is_null_edit_omission_preserves_category_and_explicit_values_clear_it(): void
- {
- $result = $this->save();
- $this->assertSame(HttpStatus::OK, $result['code'], $result['msg']);
- $id = DB::table('activity_rewards')->value('id');
- $this->assertNull(DB::table('activity_rewards')->where('id', $id)->value('game_category'));
- $this->assertNull(ActivityReward::findOrFail($id)->toArray()['game_category_name']);
- $result = $this->save(['id' => $id, 'game_category' => 'third:1', 'sort' => 37, 'publish_platforms' => ['PC']]);
- $this->assertSame(HttpStatus::OK, $result['code'], $result['msg']);
- $result = $this->save(['id' => $id, 'title' => '只修改标题']);
- $this->assertSame(HttpStatus::OK, $result['code'], $result['msg']);
- $row = ActivityReward::findOrFail($id)->toArray();
- $this->assertSame('third:1', $row['game_category']);
- $this->assertSame('真人', $row['game_category_name']);
- $this->assertSame('即充即送', $row['type_name']);
- $this->assertSame(37, $row['sort']);
- $this->assertSame(['PC'], $row['publish_platforms']);
- foreach ([null, ''] as $clear) {
- $this->assertSame(HttpStatus::OK, $this->save(['id' => $id, 'game_category' => 'self:sport'])['code']);
- $result = $this->save(['id' => $id, 'game_category' => $clear]);
- $this->assertSame(HttpStatus::OK, $result['code'], $result['msg']);
- $this->assertNull(DB::table('activity_rewards')->where('id', $id)->value('game_category'));
- $row = collect($this->listing()['data'])->keyBy('id')->get($id);
- $this->assertNull($row['game_category']);
- $this->assertNull($row['game_category_name']);
- }
- $this->assertSame(1, DB::table('activity_rewards')->count());
- $this->assertSame(0, DB::table('activity_reward_recipients')->count());
- }
- public function test_every_game_category_is_saved_and_named_for_normal_and_type_two_activities(): void
- {
- foreach ([2 => '普通活动', 3 => '即充即送'] as $type => $typeName) {
- foreach (ActivityCatalog::gameTypes() as $category => $label) {
- $result = $this->save(['type' => $type, 'game_category' => $category]);
- $this->assertSame(HttpStatus::OK, $result['code'], $result['msg']);
- $row = ActivityReward::query()->latest('id')->firstOrFail()->toArray();
- $this->assertSame($type, (int) $row['type']);
- $this->assertSame($typeName, $row['type_name']);
- $this->assertSame($category, $row['game_category']);
- $this->assertSame($label, $row['game_category_name']);
- }
- }
- $this->assertSame(20, $this->listing()['total']);
- }
- public function test_other_category_is_preserved_on_omitted_edit_and_can_be_cleared_for_type_two_and_three(): void
- {
- foreach ([2, 3] as $type) {
- $result = $this->save(['type' => $type, 'game_category' => 'other']);
- $this->assertSame(HttpStatus::OK, $result['code'], $result['msg']);
- $id = DB::table('activity_rewards')->latest('id')->value('id');
- $this->assertSame('other', DB::table('activity_rewards')->where('id', $id)->value('game_category'));
- $result = $this->save(['id' => $id, 'type' => $type, 'title' => '编辑其他分类活动']);
- $this->assertSame(HttpStatus::OK, $result['code'], $result['msg']);
- $page = $this->listing(['game_category' => 'other', 'type' => (string) $type]);
- $this->assertSame(1, $page['total']);
- $this->assertSame($id, $page['data'][0]['id']);
- $this->assertSame('other', $page['data'][0]['game_category']);
- $this->assertSame('其他', $page['data'][0]['game_category_name']);
- $this->assertSame('其他', ActivityReward::findOrFail($id)->toArray()['game_category_name']);
- foreach ([null, ''] as $clear) {
- $this->assertSame(HttpStatus::OK, $this->save(['id' => $id, 'type' => $type, 'game_category' => 'other'])['code']);
- $result = $this->save(['id' => $id, 'type' => $type, 'game_category' => $clear]);
- $this->assertSame(HttpStatus::OK, $result['code'], $result['msg']);
- $this->assertNull(DB::table('activity_rewards')->where('id', $id)->value('game_category'));
- $row = collect($this->listing()['data'])->keyBy('id')->get($id);
- $this->assertNull($row['game_category']);
- $this->assertNull($row['game_category_name']);
- $this->assertSame(0, $this->listing(['game_category' => 'other', 'type' => (string) $type])['total']);
- }
- }
- $this->assertSame(2, DB::table('activity_rewards')->count());
- $this->assertSame(0, DB::table('activity_reward_recipients')->count());
- }
- public function test_invalid_categories_are_rejected_by_controller_and_service_even_for_type_two(): void
- {
- $id = $this->rawActivity(['game_category' => 'third:1']);
- $before = DB::table('activity_rewards')->get()->toJson();
- foreach (['unknown', 'third:8', 'wallet', 'all', '其他', '1', 1, ['third:1']] as $category) {
- foreach ([2, 3] as $type) {
- $result = $this->save(['id' => $id, 'type' => $type, 'title' => '不应保存', 'game_category' => $category]);
- $this->assertSame(HttpStatus::CUSTOM_ERROR, $result['code']);
- try {
- ActivityRewardService::submit($this->form(['id' => $id, 'type' => $type, 'game_category' => $category]));
- $this->fail('Expected direct service category validation');
- } catch (ValidationException $e) {
- $this->assertArrayHasKey('game_category', $e->errors());
- }
- }
- $this->request('', ['page' => 1, 'limit' => 10, 'game_category' => $category]);
- $result = (new AdminActivityReward())->index()->getData(true);
- $this->assertSame(HttpStatus::CUSTOM_ERROR, $result['code']);
- }
- $this->assertSame($before, DB::table('activity_rewards')->get()->toJson());
- }
- public function test_combined_category_filters_apply_before_count_and_pagination_with_type_two_platform_exception(): void
- {
- $base = ['title' => '目标活动', 'type' => 3, 'status' => 0, 'lang' => 'zh', 'game_category' => 'third:1', 'publish_platforms' => ['PC']];
- $matching = [];
- for ($i = 1; $i <= 5; $i++) $matching[] = $this->rawActivity(['sort' => $i] + $base);
- foreach ([['game_category' => 'third:2'], ['publish_platforms' => ['H5']], ['status' => 1],
- ['lang' => 'en'], ['title' => '其他活动'], ['type' => 4], ['game_category' => null]] as $extra) {
- $this->rawActivity($extra + ['sort' => 100] + $base);
- }
- $ordinary = $this->rawActivity(['type' => 2, 'publish_platforms' => ['H5'], 'sort' => 101] + $base);
- $before = DB::table('activity_rewards')->orderBy('id')->get()->toJson();
- $matching = array_reverse($matching);
- $filters = ['title' => '目标', 'type' => '3', 'status' => '0', 'lang' => 'zh', 'platform' => 'pc', 'game_category' => 'third:1', 'limit' => 2];
- $seen = [];
- foreach ([1, 2, 3, 4] as $page) {
- $result = $this->listing($filters + ['page' => $page]);
- $this->assertSame(5, $result['total']);
- $this->assertSame(array_slice($matching, ($page - 1) * 2, 2), array_column($result['data'], 'id'));
- foreach ($result['data'] as $row) {
- $this->assertSame('third:1', $row['game_category']);
- $this->assertSame('真人', $row['game_category_name']);
- $this->assertSame('即充即送', $row['type_name']);
- }
- $seen = array_merge($seen, array_column($result['data'], 'id'));
- }
- $this->assertSame($matching, $seen);
- $ordinaryPage = $this->listing(['type' => '2', 'platform' => 'pc', 'status' => '0', 'lang' => 'zh', 'game_category' => 'third:1']);
- $this->assertSame(1, $ordinaryPage['total']);
- $this->assertSame([$ordinary], array_column($ordinaryPage['data'], 'id'));
- $this->assertSame('普通活动', $ordinaryPage['data'][0]['type_name']);
- $all = $this->listing();
- foreach ([null, ''] as $category) {
- $result = $this->listing(['game_category' => $category]);
- $this->assertSame($all['total'], $result['total']);
- $this->assertSame(array_column($all['data'], 'id'), array_column($result['data'], 'id'));
- }
- $this->assertSame($before, DB::table('activity_rewards')->orderBy('id')->get()->toJson());
- }
- public function test_other_category_filter_combines_with_existing_filters_before_count_and_pagination(): void
- {
- $base = ['title' => '目标其他活动', 'type' => 3, 'status' => 0, 'lang' => 'zh', 'game_category' => 'other', 'publish_platforms' => ['H5']];
- $matching = [];
- for ($i = 1; $i <= 5; $i++) $matching[] = $this->rawActivity(['sort' => $i] + $base);
- foreach ([['game_category' => 'third:1'], ['game_category' => null], ['publish_platforms' => ['PC']],
- ['status' => 1], ['lang' => 'en'], ['title' => '不同标题'], ['type' => 4]] as $extra) {
- $this->rawActivity($extra + ['sort' => 100] + $base);
- }
- $before = DB::table('activity_rewards')->orderBy('id')->get()->toJson();
- $matching = array_reverse($matching);
- $filters = ['title' => '目标', 'type' => '3', 'status' => '0', 'lang' => 'zh', 'platform' => 'h5', 'game_category' => 'other', 'limit' => 2];
- $seen = [];
- foreach ([1, 2, 3, 4] as $page) {
- $result = $this->listing($filters + ['page' => $page]);
- $this->assertSame(5, $result['total']);
- $this->assertSame(array_slice($matching, ($page - 1) * 2, 2), array_column($result['data'], 'id'));
- foreach ($result['data'] as $row) {
- $this->assertSame('other', $row['game_category']);
- $this->assertSame('其他', $row['game_category_name']);
- }
- $seen = array_merge($seen, array_column($result['data'], 'id'));
- }
- $this->assertSame($matching, $seen);
- $all = $this->listing();
- $this->assertSame(12, $all['total']);
- foreach ([null, ''] as $category) {
- $page = $this->listing(['game_category' => $category]);
- $this->assertSame($all['total'], $page['total']);
- $this->assertSame(array_column($all['data'], 'id'), array_column($page['data'], 'id'));
- }
- $defaultRows = array_filter($all['data'], fn ($row) => $row['game_category'] === null);
- $this->assertCount(1, $defaultRows);
- $this->assertNull(array_values($defaultRows)[0]['game_category_name']);
- $this->assertSame($before, DB::table('activity_rewards')->orderBy('id')->get()->toJson());
- }
- public function test_legacy_type_one_remains_readable_and_editable_without_becoming_an_option(): void
- {
- $result = $this->save(['type' => 1]);
- $this->assertSame(HttpStatus::OK, $result['code'], $result['msg']);
- $id = DB::table('activity_rewards')->value('id');
- DB::table('activity_rewards')->where('id', $id)->update(['budget_used' => '12.34', 'rewarded_count' => 2]);
- $result = $this->save(['id' => $id, 'type' => 1, 'title' => '旧类型活动', 'game_category' => 'self:lottery']);
- $this->assertSame(HttpStatus::OK, $result['code'], $result['msg']);
- $row = $this->listing(['type' => '1'])['data'][0];
- $this->assertSame(1, (int) $row['type']);
- $this->assertNull($row['type_name']);
- $this->assertSame('self:lottery', $row['game_category']);
- $this->assertSame('F1彩票', $row['game_category_name']);
- $this->assertSame('12.34', $row['budget_used']);
- $this->assertSame(2, $row['rewarded_count']);
- $legacy = $this->rawActivity(['type' => 99, 'game_category' => null]);
- $this->assertNull(ActivityReward::findOrFail($legacy)->toArray()['type_name']);
- $this->request('options');
- $options = (new AdminActivityReward())->options()->getData(true)['data']['activity_types'];
- $this->assertSame([2, 3, 4, 5, 6], array_column($options, 'value'));
- }
- public function test_category_migration_adds_nullable_index_without_changing_existing_rows_and_rolls_back(): void
- {
- $this->migration()->down();
- $this->assertFalse(Schema::hasColumn('activity_rewards', 'game_category'));
- $id = $this->rawActivity(['type' => 1, 'sort' => 19]);
- $before = (array) DB::table('activity_rewards')->find($id);
- $this->migration()->up();
- $after = (array) DB::table('activity_rewards')->find($id);
- $this->assertNull($after['game_category']);
- unset($after['game_category']);
- $this->assertSame($before, $after);
- $column = collect(DB::select('PRAGMA table_info(bot_activity_rewards)'))->firstWhere('name', 'game_category');
- $this->assertSame(0, (int) $column->notnull);
- $indexes = DB::select("SELECT sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?", ['bot_activity_rewards']);
- $this->assertNotEmpty(array_filter($indexes, fn ($index) => str_contains((string) $index->sql, 'game_category')));
- $newId = $this->rawActivity();
- $this->assertNull(DB::table('activity_rewards')->where('id', $newId)->value('game_category'));
- $this->migration()->down();
- $this->assertFalse(Schema::hasColumn('activity_rewards', 'game_category'));
- $this->assertTrue(Schema::hasColumn('activity_rewards', 'reward_quota'));
- $this->assertSame($before, (array) DB::table('activity_rewards')->find($id));
- $this->assertSame(2, DB::table('activity_rewards')->count());
- }
- }
|