| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063 |
- <?php
- namespace Tests\Integration;
- use App\Http\Controllers\admin\ActivityReward as AdminActivity;
- use App\Models\PromotionActivity as ActivityReward;
- use App\Models\BalanceLog;
- use App\Services\PromotionAdminService;
- use App\Services\PromotionFacts;
- use App\Services\PromotionService;
- use App\Services\TelegramFirstDeposit;
- use App\Models\User;
- use App\Support\FirstDepositChoice;
- use App\Support\PromotionRules;
- use Carbon\Carbon;
- use Illuminate\Config\Repository;
- use Illuminate\Database\Capsule\Manager;
- use Illuminate\Database\Schema\Blueprint;
- use Illuminate\Foundation\Application;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Facade;
- use Illuminate\Translation\ArrayLoader;
- use Illuminate\Translation\Translator;
- use Illuminate\Validation\Factory;
- use Illuminate\Validation\ValidationException;
- use PHPUnit\Framework\TestCase;
- /** Runs real migrations, qualification, wallet writes and state machines in SQLite, without .env/providers. */
- class PromotionActivitiesTest extends TestCase
- {
- private Application $app;
- private PromotionService $service;
- private string $originalTimezone;
- protected function setUp(): void
- {
- $this->originalTimezone = date_default_timezone_get(); date_default_timezone_set('Asia/Shanghai'); Carbon::setTestNow(Carbon::parse('2026-10-26 12:00:00', 'Asia/Shanghai'));
- Facade::clearResolvedInstances(); $this->app = new Application(dirname(__DIR__, 2));
- $this->app->instance('config', new Repository(['app' => ['locale' => 'zh', 'timezone' => 'Asia/Shanghai'], 'third_game' => ['currency' => 'CNY']])); 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());
- $this->app->instance('translator', new Translator(new ArrayLoader(), 'zh'));
- $this->app->instance('validator', new Factory($this->app['translator'], $this->app));
- $this->app->instance('log', new \Psr\Log\NullLogger()); $this->app->instance('request', Request::create('/api/promotion/progress'));
- $this->app->instance(\Illuminate\Contracts\Routing\ResponseFactory::class, new \Tests\Support\JsonResponseFactory());
- Request::macro('validate', function ($rules) { return app('validator')->make($this->all(), $rules)->validate(); });
- foreach ([
- 'activity_rewards' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,title TEXT,sub_title TEXT,type INTEGER,status INTEGER,start_time INTEGER,end_time INTEGER,lang TEXT,params TEXT,detail_image TEXT,pc_image TEXT,detail_banner TEXT,pc_banner TEXT,content TEXT,created_at TEXT,updated_at TEXT',
- 'users' => 'id INTEGER PRIMARY KEY,member_id TEXT UNIQUE,user_id TEXT,account TEXT,language TEXT,"from" INTEGER,level INTEGER DEFAULT 0,recharge_channel_group_id INTEGER DEFAULT 1,created_at TEXT,updated_at TEXT',
- 'wallets' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,member_id TEXT UNIQUE,available_balance TEXT DEFAULT "0",frozen_balance TEXT DEFAULT "0",created_at TEXT,updated_at TEXT',
- 'balance_logs' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,member_id TEXT,type INTEGER DEFAULT 1,amount TEXT,change_type TEXT,before_balance TEXT,after_balance TEXT,related_id INTEGER,remark TEXT,frozen_status INTEGER,created_at TEXT,updated_at TEXT',
- 'share_members' => 'user_id INTEGER PRIMARY KEY,parent_user_id INTEGER,bound_at TEXT',
- 'share_policies' => 'id INTEGER PRIMARY KEY,effective_date TEXT,valid_member_min_deposit TEXT,valid_member_min_effective_bet TEXT',
- 'share_bet_facts' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,user_id INTEGER,source TEXT,source_id TEXT,bet_at TEXT,bet_amount TEXT,net_profit TEXT,effective_amount TEXT,currency TEXT,settled INTEGER DEFAULT 1,voided INTEGER DEFAULT 0',
- 'user_login' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,user_id TEXT,status INTEGER,platform TEXT,created_at TEXT',
- 'reporting_activity' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,user_id INTEGER,session_hash TEXT,observed_at TEXT',
- 'share_levels' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,level INTEGER UNIQUE,name TEXT',
- 'config' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,field TEXT,val TEXT',
- 'menus' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,parent_id INTEGER,title TEXT,icon TEXT,uri TEXT,permission_name TEXT,sort INTEGER,status INTEGER,type INTEGER,created_at TEXT,updated_at TEXT',
- ] as $table => $columns) DB::statement('CREATE TABLE bot_' . $table . ' (' . $columns . ')');
- foreach (['2026_10_13_120000_add_activity_eligibility_fields.php', '2026_10_14_120000_add_activity_reward_quotas.php', '2026_10_25_120000_add_game_category_to_activity_rewards.php', '2026_10_26_160000_create_promotion_activities.php', '2026_10_27_130000_initialize_fixed_promotion_activities.php', '2026_10_27_140000_add_promotion_activity_translations.php', '2026_11_03_120000_add_promotion_coupons.php', '2026_11_03_170000_repeat_loss_invite_rounds.php', '2026_11_04_120000_create_upgrade_invite_promotion.php'] as $migration) (require dirname(__DIR__, 2) . '/database/migrations/' . $migration)->up();
- (require dirname(__DIR__, 2) . '/database/migrations/2026_11_07_180000_allow_permanent_activities.php')->up();
- (require dirname(__DIR__, 2) . '/database/migrations/2026_11_12_120000_add_first_deposit_join_choice.php')->up();
- (require dirname(__DIR__, 2) . '/database/migrations/2026_11_12_130000_bind_first_deposit_choices.php')->up();
- $this->member(1); $this->member(2, 1);
- DB::table('share_policies')->insert(['id' => 1, 'effective_date' => '2026-10-01', 'valid_member_min_deposit' => '200', 'valid_member_min_effective_bet' => '300']);
- $this->service = new PromotionService();
- }
- protected function tearDown(): void { Carbon::setTestNow(); date_default_timezone_set($this->originalTimezone); DB::disconnect(); Facade::clearResolvedInstances(); parent::tearDown(); }
- private function travel(string $time): void { Carbon::setTestNow(Carbon::parse($time, 'Asia/Shanghai')); }
- private function member(int $id, ?int $parent = null, string $at = '2026-10-01 00:00:00'): void
- {
- DB::table('users')->insert(['id' => $id, 'member_id' => 'm' . $id, 'user_id' => 'u' . $id, 'language' => 'zh', 'from' => 1, 'created_at' => $at, 'updated_at' => $at]);
- DB::table('wallets')->insert(['member_id' => 'm' . $id, 'available_balance' => '0', 'frozen_balance' => '0']);
- if ($parent) DB::table('share_members')->insert(['user_id' => $id, 'parent_user_id' => $parent, 'bound_at' => $at]);
- }
- private function activity(int $type = 9, array $params = [], int $status = 1): int
- {
- $input = ['translations' => $this->texts(), 'type' => $type, 'status' => $status,
- 'start_time' => '2026-10-01 00:00:00', 'end_time' => '2026-12-31 23:59:59', 'lang' => 'zh', 'params' => $params];
- if (in_array($type, PromotionRules::FIXED, true)) $input['id'] = (int) DB::table('promotion_activities')->where('type', $type)->value('id');
- return (int) (new PromotionAdminService())->save($input)['id'];
- }
- private function texts(): array
- {
- return ['zh' => ['title' => '测试活动', 'content' => '<p>中文活动正文</p>'],
- 'en' => ['title' => 'Test promotion', 'content' => '<p>English content</p>'],
- 'vi' => ['title' => 'Khuyến mãi', 'content' => '<p>Nội dung</p>']];
- }
- /** 会员在首笔充值前勾选参加首充活动。 */
- private function join(int $id, $value = 1): bool
- {
- $joined = FirstDepositChoice::parse($value);
- $offer = null;
- if ($joined) {
- $activity = $this->service->listing($id, 'H5', 'zh', 8)['data'][0];
- $offer = FirstDepositChoice::offer($activity['activity_id'], 'H5', $activity['rules'], $activity['start_time'], $activity['end_time']);
- }
- return FirstDepositChoice::record(User::find($id), $joined, 'test', $offer);
- }
- /** 全部首充活动共用的禁止投注大类。 */
- private function restrict($categories): array
- {
- return (new PromotionAdminService())->saveFirstDepositRestriction(['categories' => $categories]);
- }
- private function deposit(int $id, string $amount, ?string $time = null, string $type = '充值'): BalanceLog
- {
- return BalanceLog::create(['member_id' => 'm' . $id, 'type' => 1, 'amount' => $amount, 'change_type' => $type, 'created_at' => $time ?? PromotionFacts::now()]);
- }
- private function rawDeposit(int $id, string $amount, string $time, string $type = '充值'): int
- {
- return DB::table('balance_logs')->insertGetId(['member_id' => 'm' . $id, 'type' => 1, 'amount' => $amount, 'change_type' => $type, 'created_at' => $time, 'updated_at' => $time]);
- }
- private function bet(int $id, string $stake, string $profit, string $time, array $extra = []): int
- {
- $next = (int)DB::table('share_bet_facts')->max('id') + 1;
- return DB::table('share_bet_facts')->insertGetId($extra + ['user_id' => $id, 'source' => 'sport_order', 'source_id' => (string)$next,
- 'bet_at' => $time, 'bet_amount' => $stake, 'net_profit' => $profit, 'effective_amount' => '999999', 'currency' => 'CNY', 'settled' => 1, 'voided' => 0]);
- }
- private function invalid(callable $callback, string $message): void
- {
- try { $callback(); $this->fail('Expected validation failure: ' . $message); }
- catch (ValidationException $e) { $this->assertStringContainsString($message, $e->validator->errors()->first()); }
- }
- private function complete(int $activity): array
- {
- $this->rawDeposit(1, '3000', '2026-10-26 12:01:00'); $this->rawDeposit(2, '500', '2026-10-26 12:01:00');
- $this->bet(1, '6000', '-5000', '2026-10-26 12:01:00'); $this->bet(2, '4000', '-3000', '2026-10-26 12:01:00');
- DB::table('user_login')->insert(['user_id' => 'm1', 'status' => 1, 'platform' => 'H5', 'created_at' => '2026-10-26 12:01:00']);
- for ($i = 0; $i <= 60; ++$i) DB::table('reporting_activity')->insert(['user_id' => 1, 'session_hash' => 'a', 'observed_at' => Carbon::parse('2026-10-26 12:01:00')->addMinutes($i)->format('Y-m-d H:i:s')]);
- $this->travel('2026-10-26 14:00:00'); return $this->service->progress($activity, 1, 'H5');
- }
- public function test_all_independent_activities_support_permanent_dates_and_reject_half_dates(): void
- {
- $admin = new PromotionAdminService();
- DB::table('share_levels')->insert(['level' => 2, 'name' => '二级']);
- foreach ([7, 8, 9, 10] as $type) {
- $id = $this->activity($type, [], 0);
- $input = ['id' => $id, 'type' => $type, 'status' => 0, 'translations' => $this->texts(), 'start_time' => null, 'end_time' => ''];
- if ($type === 10) $input['params'] = ['tiers' => [['level' => 2, 'amount' => '10']]];
- $saved = $admin->save($input);
- $this->assertNull($saved['start_time']); $this->assertNull($saved['end_time']);
- $this->assertNull($admin->detail($id)['end_time']);
- $before = DB::table('promotion_activities')->where('id', $id)->first();
- foreach ([['start_time' => '2026-10-01', 'end_time' => null], ['start_time' => null, 'end_time' => '2026-12-31']] as $half) {
- $this->invalid(fn () => $admin->save(array_replace($input, $half)), '同时填写或同时留空');
- $this->assertEquals($before, DB::table('promotion_activities')->where('id', $id)->first());
- }
- // Publishing a permanent activity must not mistake null end_time for 1970.
- $admin->status($id, 1);
- $this->assertSame($id, (int)$this->service->listing(1, 'PC', 'zh', $type)['data'][0]['activity_id']);
- $detail = $this->service->detail($id, 1, 'PC', 'zh');
- $this->assertNull($detail['start_time']); $this->assertNull($detail['end_time']);
- }
- $this->assertSame(0, PromotionAdminService::expire());
- $id = (int)DB::table('promotion_activities')->where('type', 8)->value('id');
- $this->join(1); $this->service->onDeposit($this->deposit(1, '100'));
- $this->assertSame(1, DB::table('promotion_rewards')->where('activity_id', $id)->count());
- }
- public function test_new_independent_activities_omit_dates_for_permanence_and_keep_dates_on_partial_edit(): void
- {
- $admin = new PromotionAdminService();
- $input = ['type' => 8, 'status' => 0, 'translations' => $this->texts()];
- $saved = $admin->save($input);
- $this->assertNull($saved['start_time']); $this->assertNull($saved['end_time']);
- $saved = $admin->save($input + ['id' => $saved['id'], 'start_time' => '2026-10-01', 'end_time' => '2026-12-31']);
- $edited = $admin->save($input + ['id' => $saved['id']]);
- $this->assertSame($saved['start_time'], $edited['start_time']);
- $this->assertSame($saved['end_time'], $edited['end_time']);
- foreach (['start_time', 'end_time'] as $field) {
- $this->invalid(fn () => $admin->save($input + [$field => '2026-12-01']), '同时填写或同时留空');
- }
- }
- public function test_background_sync_skips_page_metrics_and_duplicate_task_writes_but_observes_corrections(): void
- {
- $id = $this->activity(9); $before = $this->complete($id);
- $this->assertTrue($before['conditions_complete']);
- DB::enableQueryLog(); DB::flushQueryLog();
- try {
- $this->service->syncAccount($id, 1);
- $queries = DB::getQueryLog();
- $this->assertLessThanOrEqual(50, count($queries));
- $this->assertCount(0, array_filter($queries, fn ($q) => str_contains($q['query'], 'from "bot_promotion_rewards"')));
- $this->assertCount(0, array_filter($queries, fn ($q) => preg_match('/^(insert.*"bot_promotion_task_grants"|update "bot_promotion_rounds")/', $q['query'])));
- $this->assertLessThanOrEqual(4, count(array_filter($queries, fn ($q) => str_contains($q['query'], 'from "bot_share_bet_facts"'))));
- } finally { DB::disableQueryLog(); DB::flushQueryLog(); }
- $after = $this->service->detail($id, 1);
- $this->assertSame($before['completed_tasks'], $after['completed_tasks']);
- $this->assertSame($before['spins'], $after['spins']);
- DB::table('share_bet_facts')->where('user_id', 2)->update(['net_profit' => '0']);
- $this->service->syncAccount($id, 1);
- $corrected = $this->service->detail($id, 1);
- $this->assertFalse($corrected['completed_tasks']['invite']);
- $this->assertFalse($corrected['completed_tasks']['team_bet']);
- $this->assertSame(7, DB::table('promotion_task_grants')->count());
- }
- public function test_third_party_cursor_uses_one_query_and_original_order_ids(): void
- {
- DB::statement('CREATE TABLE bot_third_game_orders (id INTEGER PRIMARY KEY,order_key TEXT UNIQUE)');
- foreach (range(1, 20) as $id) {
- $key = str_pad(dechex($id), 64, '0', STR_PAD_LEFT);
- DB::table('third_game_orders')->insert(['id' => $id, 'order_key' => $key]);
- $this->bet(1, '10', '-10', '2026-10-26 11:00:00', ['source' => 'third_game_orders', 'source_id' => $key]);
- }
- $this->bet(1, '999', '-999', '2026-10-26 11:00:00', ['source' => 'third_game_orders', 'source_id' => str_repeat('f', 64)]);
- DB::enableQueryLog(); DB::flushQueryLog();
- try {
- $result = (new PromotionFacts())->betting([1], '2026-10-01 00:00:00', null, ['third_game_orders' => 10]);
- $this->assertLessThanOrEqual(6, count(DB::getQueryLog()));
- } finally { DB::disableQueryLog(); DB::flushQueryLog(); }
- $this->assertSame('100.0000000000', $result['effective']['2026-10-26']);
- $this->assertSame('-100.0000000000', $result['profit']);
- }
- public function test_images_are_only_configurable_for_first_deposit_not_fixed_loss_or_wheel_campaigns(): void
- {
- $admin = new PromotionAdminService();
- foreach ([7, 8, 9] as $type) {
- $id = $this->activity($type);
- DB::table('promotion_activities')->where('id', $id)->update(['image' => 'previous.png']);
- $input = $admin->detail($id); $input['image'] = $type === 8 ? 'first-deposit.png' : ['ignored-legacy-upload'];
- $saved = $admin->save($input);
- foreach ([$saved, $admin->detail($id), $admin->listing(['type' => $type])['data'][0], $this->service->listing(1, 'H5', 'zh', $type)['data'][0]] as $row) {
- $this->assertSame($type === 8, array_key_exists('image', $row));
- }
- $this->assertSame($type === 8 ? 'first-deposit.png' : 'previous.png', DB::table('promotion_activities')->where('id', $id)->value('image'));
- }
- }
- public function test_subtitles_are_not_required_saved_or_returned_for_any_independent_activity(): void
- {
- $admin = new PromotionAdminService();
- foreach ([7, 8, 9] as $type) {
- $id = $this->activity($type); $legacy = $this->texts();
- foreach ($legacy as &$text) $text['sub_title'] = 'Historical subtitle'; unset($text);
- DB::table('promotion_activities')->where('id', $id)->update(['sub_title' => 'Historical subtitle', 'translations' => json_encode($legacy)]);
- $detail = $admin->detail($id);
- $this->assertArrayNotHasKey('sub_title', $detail);
- foreach ($detail['translations'] as $text) $this->assertSame(['title', 'content'], array_keys($text));
- $input = $detail; $input['sub_title'] = 'Ignored legacy input';
- foreach ($input['translations'] as &$text) $text['sub_title'] = ['ignored legacy input']; unset($text);
- $saved = $admin->save($input);
- $this->assertSame($this->texts(), $saved['translations']);
- $this->assertSame('Historical subtitle', DB::table('promotion_activities')->where('id', $id)->value('sub_title'));
- foreach ([$saved, $admin->listing(['type' => $type])['data'][0], $admin->status($id, 1),
- $this->service->listing(1, 'H5', 'zh', $type)['data'][0], $this->service->detail($id, 1, 'H5', 'zh')] as $row) {
- $this->assertArrayNotHasKey('sub_title', $row);
- }
- }
- }
- public function test_three_languages_edit_one_campaign_and_keep_rules_history_and_other_tabs(): void
- {
- $admin = new PromotionAdminService();
- foreach ([7, 8, 9] as $type) {
- $id = $this->activity($type); $before = $admin->detail($id);
- $count = DB::table('promotion_activities')->count();
- $input = $before; $input['translations']['en']['title'] = 'Updated English title';
- $saved = $admin->save($input);
- $this->assertSame($id, $saved['id']);
- $this->assertSame($count, DB::table('promotion_activities')->count());
- $this->assertSame($before['translations']['zh'], $saved['translations']['zh']);
- $this->assertSame($before['translations']['vi'], $saved['translations']['vi']);
- $this->assertSame('Updated English title', $admin->detail($id)['translations']['en']['title']);
- foreach (['params', 'rewarded_count', 'budget_used', 'first_published_at'] as $field) $this->assertSame($before[$field], $saved[$field]);
- foreach (['zh', 'en', 'vi'] as $lang) {
- $rows = $this->service->listing(1, 'H5', $lang, $type)['data'];
- $this->assertCount(1, $rows); $this->assertSame($id, $rows[0]['activity_id']);
- $this->assertSame($saved['translations'][$lang]['title'], $rows[0]['title']);
- $state = $this->service->detail($id, 1, 'H5', $lang);
- $this->assertSame($lang, $state['lang']);
- $this->assertSame($saved['translations'][$lang]['title'], $state['title']);
- $this->assertSame($saved['translations'][$lang]['content'], $state['content']);
- }
- }
- $this->assertSame(['zh', 'en', 'vi'], array_column($admin->options()['languages'], 'value'));
- }
- public function test_all_six_text_fields_are_required_and_invalid_tabs_cannot_overwrite_saved_content(): void
- {
- $id = $this->activity(9); $admin = new PromotionAdminService(); $input = $admin->detail($id);
- $before = DB::table('promotion_activities')->where('id', $id)->first();
- foreach (['zh', 'en', 'vi'] as $lang) {
- foreach (['title', 'content'] as $field) {
- $bad = $input; unset($bad['translations'][$lang][$field]);
- try { $admin->save($bad); $this->fail('Missing language text was accepted'); }
- catch (ValidationException $e) { $this->assertTrue($e->validator->errors()->has('translations.' . $lang . '.' . $field)); }
- $bad = $input; $bad['translations'][$lang][$field] = '<p> <br></p>';
- $this->invalid(fn () => $admin->save($bad), '不能为空');
- }
- $bad = $input; unset($bad['translations'][$lang]);
- $this->invalid(fn () => $admin->save($bad), '完整填写');
- }
- $bad = $input; unset($bad['translations']); $bad['title'] = '旧单语言表单';
- $this->invalid(fn () => $admin->save($bad), '完整填写');
- $bad = $input; $bad['translations']['fr'] = $input['translations']['en'];
- try { $admin->save($bad); $this->fail('Unknown language was accepted'); }
- catch (ValidationException $e) { $this->assertTrue($e->validator->errors()->has('translations')); }
- $bad = $input; $bad['translations']['en']['title'] = str_repeat('a', 141);
- try { $admin->save($bad); $this->fail('Oversized title was accepted'); }
- catch (ValidationException $e) { $this->assertTrue($e->validator->errors()->has('translations.en.title')); }
- $this->assertEquals($before, DB::table('promotion_activities')->where('id', $id)->first());
- }
- public function test_admin_http_save_returns_all_tabs_and_rejects_partial_language_payloads(): void
- {
- $controller = new \App\Http\Controllers\admin\Promotion(); $admin = new PromotionAdminService();
- $input = ['type' => 8, 'status' => 0, 'start_time' => '2026-10-26', 'end_time' => '2026-12-31', 'translations' => $this->texts()];
- $this->app->instance('request', Request::create('/admin/promotion/submit', 'POST', $input));
- $saved = $controller->submit($admin)->getData(true);
- $this->assertSame(0, $saved['code']); $this->assertSame($this->texts(), $saved['data']['translations']);
- $input['id'] = $saved['data']['id']; unset($input['translations']['en']);
- $this->app->instance('request', Request::create('/admin/promotion/submit', 'POST', $input));
- $failed = $controller->submit($admin)->getData(true);
- $this->assertSame(-3, $failed['code']); $this->assertStringContainsString('英文', $failed['msg']);
- $this->assertSame($this->texts(), $admin->detail($input['id'])['translations']);
- }
- public function test_incomplete_legacy_activity_can_be_hidden_but_cannot_be_published_without_all_tabs(): void
- {
- $id = (int) DB::table('promotion_activities')->where('type', 7)->value('id');
- $admin = new PromotionAdminService();
- $this->assertSame(0, (int) $admin->status($id, 0)['status']);
- $this->invalid(fn () => $admin->status($id, 1), '不能为空');
- $this->assertSame(0, (int) DB::table('promotion_activities')->where('id', $id)->value('status'));
- $this->assertNull(DB::table('promotion_campaigns')->where('activity_id', $id)->value('first_published_at'));
- }
- public function test_first_deposit_translation_does_not_split_or_duplicate_awards(): void
- {
- $id = $this->activity(8, ['min_deposit' => 100, 'reward_amount' => 25]);
- DB::table('users')->where('id', 1)->update(['language' => 'vi']); $this->join(1);
- $deposit = $this->deposit(1, '100'); $this->service->onDeposit($deposit);
- $this->assertSame(1, DB::table('promotion_rewards')->where('activity_id', $id)->count());
- DB::table('users')->where('id', 1)->update(['language' => 'en']);
- $this->service->onDeposit($deposit);
- $this->assertSame(1, DB::table('promotion_rewards')->where('activity_id', $id)->count());
- $this->assertSame('25.0000000000', (string) DB::table('wallets')->where('member_id', 'm1')->value('available_balance'));
- $this->assertSame(1, DB::table('promotion_accounts')->where('activity_id', $id)->count());
- }
- public function test_translation_migration_preserves_legacy_texts_and_campaign_identity(): void
- {
- $migration = require dirname(__DIR__, 2) . '/database/migrations/2026_10_27_140000_add_promotion_activity_translations.php';
- $migration->down();
- $id = DB::table('promotion_activities')->where('type', 7)->value('id');
- DB::table('promotion_activities')->where('id', $id)->update(['lang' => 'en', 'title' => 'Existing title', 'sub_title' => 'Existing subtitle', 'content' => '<p>Existing content</p>']);
- $rows = DB::table('promotion_activities')->orderBy('id')->get();
- $published = DB::table('promotion_campaigns')->orderBy('activity_id')->get();
- $migration->up();
- foreach ($rows as $row) {
- $saved = DB::table('promotion_activities')->where('id', $row->id)->first();
- foreach ((array) $row as $field => $value) $this->assertSame($value, $saved->$field);
- }
- $texts = (new PromotionAdminService())->detail((int) $id)['translations'];
- $this->assertSame(['title' => 'Existing title', 'content' => '<p>Existing content</p>'], $texts['en']);
- $this->assertSame('', $texts['zh']['title']);
- $this->assertEquals($published, DB::table('promotion_campaigns')->orderBy('activity_id')->get());
- $this->assertSame(0, DB::table('menus')->count());
- $this->assertSame(0, $this->service->listing(1, 'H5', 'vi', 7)['total']);
- }
- public function test_probability_default_zero_boundaries_and_incomplete_gate(): void
- {
- $this->assertSame('20.00', PromotionRules::normalize(9, [])['completion_probability']);
- $this->assertSame('0.00', PromotionRules::normalize(9, ['completion_probability' => 0])['completion_probability']);
- $this->assertTrue(PromotionRules::draw(66599, true, '20.00', fn ($a, $b) => $a === 1 ? 2000 : 0)['reached']);
- $this->assertFalse(PromotionRules::draw(66599, true, '20.00', fn ($a, $b) => $a === 1 ? 2001 : 0)['reached']);
- $this->assertFalse(PromotionRules::draw(66599, false, '100.00', fn ($a, $b) => $a)['reached']);
- $this->invalid(fn () => PromotionRules::normalize(9, ['completion_probability' => 100.01]), 'between');
- }
- public function test_wheel_limits_early_prizes_and_leaves_room_for_ten_misses_at_twenty_percent(): void
- {
- // Choose the floating sector, force a miss, then take the maximum allowed amount.
- $maxFloat = fn ($min, $max) => $min === 0 ? 0 : $max;
- $this->assertSame(16625, PromotionRules::draw(0, false, '20.00', $maxFloat)['amount_cents']);
- // 未完成任务时600后不再归零,按剩余空间的1/20继续发放,并始终给完成阶段留1元。
- $this->assertSame(325, PromotionRules::draw(60000, false, '100.00', $maxFloat)['amount_cents']);
- $this->assertSame(1, PromotionRules::draw(66499, false, '100.00', $maxFloat)['amount_cents']);
- $this->assertSame(0, PromotionRules::draw(66500, false, '100.00', $maxFloat)['amount_cents']);
- $fixed = PromotionRules::draw(0, false, '20.00', fn ($min, $max) => $max);
- $this->assertSame(6, $fixed['prize_index']);
- $this->assertSame(15000, $fixed['amount_cents']);
- $coins = 60000;
- for ($i = 0; $i < 10; ++$i) {
- $draw = PromotionRules::draw($coins, true, '20.00', $maxFloat);
- $this->assertFalse($draw['reached']);
- $this->assertGreaterThan(0, $draw['amount_cents']);
- $coins += $draw['amount_cents'];
- }
- $this->assertLessThan(66500, $coins);
- $this->assertSame(99, PromotionRules::draw(65600, true, '20.00', $maxFloat)['amount_cents']);
- $this->assertSame(600, PromotionRules::draw(65600, true, '50.00', $maxFloat)['amount_cents']);
- $this->assertSame(1, PromotionRules::draw(66598, true, '0.00', $maxFloat)['amount_cents']);
- $this->assertSame(0, PromotionRules::draw(66599, true, '0.00', $maxFloat)['amount_cents']);
- }
- public function test_day_amounts_do_not_add_together_but_completed_flags_survive_midnight(): void
- {
- $id = $this->activity(); $this->service->progress($id, 1);
- $this->rawDeposit(1, '2000', '2026-10-26 13:00:00');
- $this->travel('2026-10-27 14:00:00'); $this->rawDeposit(1, '1000', '2026-10-27 12:00:00');
- $state = $this->service->progress($id, 1);
- $this->assertFalse($state['completed_tasks']['deposit']); $this->assertSame(0, (int)$state['spins']);
- $this->rawDeposit(1, '2000', '2026-10-27 13:00:00'); $state = $this->service->progress($id, 1);
- $this->assertTrue($state['completed_tasks']['deposit']); $this->assertSame(1, (int)$state['spins']);
- $this->travel('2026-10-28 14:00:00'); $state = $this->service->progress($id, 1);
- $this->assertTrue($state['completed_tasks']['deposit']); $this->assertSame(1, (int)$state['spins']);
- }
- public function test_repeated_rounds_keep_unused_spins_and_daily_flags_but_require_new_other_events(): void
- {
- $id = $this->activity(9, ['completion_probability' => 100]); $state = $this->complete($id);
- $this->assertTrue($state['conditions_complete']); $this->assertSame(7, (int)$state['spins']);
- $spin = $this->service->spin($id, 1, 'request_spin_00001');
- $this->assertTrue($spin['spin']['reached']); $this->assertSame('666.00', $spin['spin']['coins']);
- $this->assertSame($spin['spin'], $this->service->spin($id, 1, 'request_spin_00001')['spin']);
- $claim = $this->service->claim($id, 1, 1); $this->assertSame(2, $claim['round_no']); $this->assertSame(6, (int)$claim['spins']);
- $this->assertTrue($this->service->claim($id, 1, 1)['replayed']);
- $state = $this->service->progress($id, 1); $this->assertSame('0.00', $state['coins']);
- $this->assertSame(6, (int)$state['spins']); $this->assertTrue($state['completed_tasks']['online']); $this->assertTrue($state['completed_tasks']['login']);
- foreach (['invite', 'deposit', 'team_deposit', 'bet', 'team_bet'] as $task) $this->assertFalse($state['completed_tasks'][$task]);
- $this->rawDeposit(1, '3000', '2026-10-26 14:00:00'); $this->rawDeposit(2, '500', '2026-10-26 14:00:00');
- $this->bet(1, '6000', '-5000', '2026-10-26 14:00:00'); $this->bet(2, '4000', '-3000', '2026-10-26 14:00:00');
- $this->member(3, 1, '2026-10-26 14:00:00'); $this->rawDeposit(3, '200', '2026-10-26 14:00:00'); $this->bet(3, '300', '-300', '2026-10-26 14:00:00');
- $state = $this->service->progress($id, 1); $this->assertTrue($state['conditions_complete']); $this->assertSame(11, (int)$state['spins']);
- $this->assertTrue($this->service->spin($id, 1, 'request_spin_00002')['spin']['reached']); $this->service->claim($id, 1, 2);
- $this->assertSame('1332.0000000000', (string)DB::table('wallets')->where('member_id', 'm1')->value('available_balance'));
- $this->assertSame(2, DB::table('promotion_rewards')->count()); $this->assertSame(1, (int)DB::table('promotion_activities')->where('id', $id)->value('rewarded_count'));
- }
- public function test_probability_changes_affect_new_spins_and_reserved_reward_can_be_claimed_after_down(): void
- {
- $id = $this->activity(9, ['completion_probability' => 0]); $this->complete($id);
- $first = $this->service->spin($id, 1, 'request_spin_00001'); $this->assertFalse($first['spin']['reached']);
- $row = ActivityReward::find($id); $rules = json_decode($row->params, true); $rules['completion_probability'] = '100.00'; $row->params = json_encode($rules); $row->save();
- $next = $this->service->spin($id, 1, 'request_spin_00002'); $this->assertTrue($next['spin']['reached']);
- $this->assertSame('0', (string)DB::table('promotion_spins')->orderBy('id')->value('probability'));
- DB::table('promotion_activities')->where('id', $id)->update(['status' => 0]);
- $this->service->claim($id, 1, 1); $this->invalid(fn () => $this->service->progress($id, 1), '未上架');
- $this->assertTrue($this->service->claim($id, 1, 1)['replayed']);
- }
- public function test_first_deposit_is_historical_first_and_does_not_refill_on_relisting(): void
- {
- $id = $this->activity(8, ['min_deposit' => '100', 'reward_amount' => '25']); $this->join(1); $this->join(2);
- $first = $this->deposit(1, '99'); $this->service->onDeposit($first); $this->service->onDeposit($first);
- $second = $this->deposit(1, '1000'); $this->service->onDeposit($second);
- $this->assertSame(0, DB::table('promotion_rewards')->count());
- $other = $this->deposit(2, '100'); $this->service->onDeposit($other); $this->service->onDeposit($other);
- $this->assertSame(1, DB::table('promotion_rewards')->count());
- $this->assertSame('25.0000000000', (string)DB::table('wallets')->where('member_id', 'm2')->value('available_balance'));
- $published = DB::table('promotion_campaigns')->where('activity_id', $id)->value('first_published_at');
- $this->travel('2026-10-27 12:00:00'); $row = ActivityReward::find($id); $row->status = 0; $row->save(); PromotionService::publish($row);
- $row->status = 1; $row->save(); PromotionService::publish($row);
- $this->assertSame($published, DB::table('promotion_campaigns')->where('activity_id', $id)->value('first_published_at'));
- $this->service->onDeposit($this->deposit(2, '500')); $this->assertSame(1, DB::table('promotion_rewards')->count());
- }
- public function test_loss_uses_post_publication_net_profit_then_only_new_direct_invitees_with_both_thresholds(): void
- {
- $this->bet(1, '900', '-900', '2026-10-25 12:00:00'); $id = $this->activity(7);
- $this->invalid(fn () => $this->service->apply($id, 1), '净亏');
- $this->bet(1, '600', '-600', '2026-10-26 12:00:00'); $this->bet(1, '200', '100', '2026-10-26 12:00:00');
- // A referral created in the same second, but before applying, is still an existing user.
- DB::table('users')->where('id', 2)->update(['created_at' => '2026-10-26 12:00:00']);
- DB::table('share_members')->where('user_id', 2)->update(['bound_at' => '2026-10-26 12:00:00']);
- $this->service->apply($id, 1); $this->service->apply($id, 1);
- $this->rawDeposit(2, '500', '2026-10-26 12:00:00'); $this->bet(2, '300', '-300', '2026-10-26 12:00:00');
- foreach ([3, 4, 5] as $child) {
- $this->member($child, 1, '2026-10-26 12:00:00'); $this->rawDeposit($child, '200', '2026-10-26 12:00:00');
- if ($child !== 5) $this->bet($child, '300', '-300', '2026-10-26 12:00:00');
- }
- $this->invalid(fn () => $this->service->claim($id, 1, 1), '人数不足');
- $this->bet(5, '1000', '-300', '2026-10-26 12:00:00'); $this->service->claim($id, 1, 1); $this->service->claim($id, 1, 1);
- $this->assertSame(1, DB::table('promotion_rewards')->count()); $this->assertSame('500.0000000000', (string)DB::table('wallets')->where('member_id', 'm1')->value('available_balance'));
- }
- public function test_coupon_mode_issues_inviter_and_counted_invitee_coupons_once_without_cash(): void
- {
- $coupons = ['reward_mode' => 'coupon', 'reward_amount' => '300', 'invite_count' => 2,
- 'coupon_valid_from' => '2026-10-26 00:00:00', 'coupon_valid_until' => '2026-11-30 23:59:59', 'coupon_categories' => ['self:lottery', 'self:sport'],
- 'inviter_coupons' => [['min_amount' => '100', 'discount' => '50', 'quantity' => 2], ['min_amount' => '200', 'discount' => '100', 'quantity' => 1]],
- 'invitee_coupons' => [['min_amount' => '20', 'discount' => '10', 'quantity' => 1]]];
- $this->invalid(fn () => $this->activity(7, array_replace($coupons, ['reward_amount' => '150'])), '优惠券抵扣总额不能超过奖励金额');
- $this->invalid(fn () => $this->activity(7, array_replace($coupons, ['coupon_categories' => []])), '可用游戏类型');
- $this->invalid(fn () => $this->activity(7, array_replace($coupons, ['inviter_coupons' => [['min_amount' => '40', 'discount' => '50', 'quantity' => 1]]])), '使用门槛');
- $id = $this->activity(7, $coupons);
- $this->assertSame(['self:sport', 'self:lottery'], (new PromotionAdminService())->detail(null, 7)['params']['coupon_categories']);
- $this->bet(1, '600', '-600', '2026-10-26 12:00:00'); $this->service->apply($id, 1);
- $this->travel('2026-10-26 13:00:00');
- foreach ([3, 4, 5] as $child) {
- $this->member($child, 1, '2026-10-26 13:00:00'); $this->rawDeposit($child, '200', '2026-10-26 13:00:00'); $this->bet($child, '300', '-300', '2026-10-26 13:00:00');
- }
- $this->service->claim($id, 1, 1); $this->service->claim($id, 1, 1);
- $reward = DB::table('promotion_rewards')->first();
- // The amount is the inviter's own coupons; the invitee coupons only count toward the budget.
- $this->assertSame('paid', $reward->status); $this->assertEquals(200, $reward->amount); $this->assertEquals(0, $reward->required_flow);
- $this->assertSame('220.00', json_decode($reward->rule_snapshot, true)['coupon_face_value']);
- $this->assertSame('0', (string)DB::table('wallets')->where('member_id', 'm1')->value('available_balance'));
- $this->assertSame(0, DB::table('balance_logs')->where('change_type', '优惠活动')->count());
- $this->assertSame(3, DB::table('promotion_coupons')->where('user_id', 1)->where('role', 'inviter')->count());
- // Only the first invite_count qualified invitees are counted and receive coupons.
- $this->assertSame([3, 4], DB::table('promotion_coupons')->where('role', 'invitee')->orderBy('user_id')->pluck('user_id')->map(fn ($v) => (int)$v)->all());
- $state = $this->service->detail($id, 1, 'H5');
- $this->assertSame('not_applied', $state['status']); $this->assertSame(2, (int)$state['round_no']); $this->assertSame('coupon', $state['rules']['reward_mode']);
- $this->assertSame([2, 1], array_column($state['coupons'], 'quantity'));
- $this->assertEquals(220, DB::table('promotion_activities')->where('id', $id)->value('budget_used'));
- // Switching back to cash keeps the coupon settings for the next switch.
- $this->activity(7, ['reward_mode' => 'cash']);
- $this->assertCount(2, json_decode(DB::table('promotion_activities')->where('id', $id)->value('params'), true)['inviter_coupons']);
- $records = (new PromotionAdminService())->records(['activity_id' => $id, 'kind' => 'coupons', 'user_id' => 1]);
- $this->assertSame(5, $records['total']);
- }
- public function test_loss_invite_repeats_with_net_loss_from_previous_claim_and_new_invitees(): void
- {
- $id = $this->activity(7, ['invite_count' => 1]);
- $this->bet(1, '600', '-600', '2026-10-26 12:00:00'); $this->service->apply($id, 1);
- $this->travel('2026-10-26 13:00:00');
- $this->member(3, 1, '2026-10-26 13:00:00'); $this->rawDeposit(3, '200', '2026-10-26 13:00:00'); $this->bet(3, '300', '-300', '2026-10-26 13:00:00');
- $this->assertSame(2, $this->service->claim($id, 1, 1)['round_no']);
- $state = $this->service->detail($id, 1, 'H5');
- $this->assertSame('not_applied', $state['status']); $this->assertSame(2, (int)$state['round_no']);
- $this->assertSame('0.00', $state['loss']); $this->assertSame('2026-10-26 13:00:00', $state['loss_from']);
- // Loss before the claim is not counted again; the server picks the round, so a retry before reapplying replays.
- $this->invalid(fn () => $this->service->apply($id, 1), '净亏');
- $this->assertTrue($this->service->claim($id, 1, 1)['replayed']);
- $replay = $this->service->claim($id, 1);
- $this->assertTrue($replay['replayed']); $this->assertSame(1, (int)$replay['reward']['round_no']);
- $this->travel('2026-10-27 12:00:00');
- $this->bet(1, '500', '-500', '2026-10-27 12:00:00'); $this->service->apply($id, 1);
- // The invitee counted in round 1 registered before this application.
- $this->invalid(fn () => $this->service->claim($id, 1), '人数不足');
- $this->travel('2026-10-27 13:00:00');
- $this->member(4, 1, '2026-10-27 13:00:00'); $this->rawDeposit(4, '200', '2026-10-27 13:00:00'); $this->bet(4, '300', '-300', '2026-10-27 13:00:00');
- // A client still sending round_no=1 claims the current round.
- $claim = $this->service->claim($id, 1, 1);
- $this->assertFalse($claim['replayed']); $this->assertSame(3, $claim['round_no']); $this->assertSame(2, (int)$claim['reward']['round_no']);
- $rewards = DB::table('promotion_rewards')->orderBy('round_no')->get();
- $this->assertSame([1, 2], $rewards->pluck('round_no')->map(fn ($v) => (int)$v)->all());
- $this->assertSame('1000.0000000000', (string)DB::table('wallets')->where('member_id', 'm1')->value('available_balance'));
- $this->assertEquals(600, json_decode($rewards[0]->rule_snapshot, true)['application']['loss']);
- $this->assertSame([4], json_decode($rewards[1]->rule_snapshot, true)['qualified_invitees']);
- $this->assertEquals(1, DB::table('promotion_activities')->where('id', $id)->value('rewarded_count'));
- $row = (new PromotionAdminService())->records(['activity_id' => $id, 'kind' => 'accounts'])['data'][0];
- $this->assertSame(2, $row->claimed_count); $this->assertSame(2, $row->reward_round_no); $this->assertNull($row->applied_at);
- $this->assertSame([4], array_column($row->invitees, 'id'));
- }
- public function test_repeat_migration_moves_claimed_members_to_next_round_and_keeps_only_inviter_coupon_amount(): void
- {
- $id = $this->activity(7);
- $snapshot = ['reward_mode' => 'coupon', 'inviter_coupons' => [['min_amount' => '100', 'discount' => '50', 'quantity' => 10]], 'invitee_coupons' => [['min_amount' => '100', 'discount' => '40', 'quantity' => 1]]];
- $account = DB::table('promotion_accounts')->insertGetId(['activity_id' => $id, 'user_id' => 1, 'round_no' => 1, 'spins' => 0,
- 'applied_at' => '2026-10-26 12:00:00', 'application_snapshot' => json_encode(['loss' => '550', 'rules' => $snapshot])]);
- DB::table('promotion_rewards')->insert(['activity_id' => $id, 'user_id' => 1, 'account_id' => $account, 'round_no' => 1, 'amount' => '620',
- 'status' => 'paid', 'rule_snapshot' => json_encode($snapshot), 'created_at' => '2026-10-26 13:00:00']);
- $migration = require dirname(__DIR__, 2) . '/database/migrations/2026_11_03_170000_repeat_loss_invite_rounds.php';
- $migration->up(); $migration->up();
- $reward = DB::table('promotion_rewards')->first(); $rules = json_decode($reward->rule_snapshot, true);
- $this->assertEquals(500, $reward->amount); $this->assertSame('620.00', $rules['coupon_face_value']); $this->assertSame('550', $rules['application']['loss']);
- $row = DB::table('promotion_accounts')->where('id', $account)->first();
- $this->assertSame(2, (int)$row->round_no); $this->assertNull($row->applied_at); $this->assertNull($row->application_snapshot);
- }
- public function test_successful_online_time_deduplicates_devices_and_does_not_count_closed_session_as_online(): void
- {
- $id = $this->activity();
- foreach (['a', 'b'] as $session) for ($i = 0; $i <= 30; ++$i) DB::table('reporting_activity')->insert(['user_id' => 1, 'session_hash' => $session,
- 'observed_at' => Carbon::parse('2026-10-26 12:00:00')->addMinutes($i)->format('Y-m-d H:i:s')]);
- $this->travel('2026-10-26 16:00:00'); $state = $this->service->progress($id, 1);
- $this->assertArrayNotHasKey('online', $state['completed_tasks']);
- $this->assertSame(1800, (new PromotionFacts())->online(1, '2026-10-26 12:00:00')['2026-10-26']);
- }
- public function test_effective_minimum_void_pending_and_next_day_policy_are_respected(): void
- {
- DB::table('share_policies')->insert(['id' => 2, 'effective_date' => '2026-10-27', 'valid_member_min_deposit' => '9999', 'valid_member_min_effective_bet' => '9999']);
- $facts = new PromotionFacts(); $this->assertSame(1, $facts->policy()['id']);
- $this->bet(1, '1000', '50', '2026-10-26 12:00:00'); $this->bet(1, '500', '-500', '2026-10-26 12:00:00', ['voided' => 1]);
- $this->bet(1, '500', '-500', '2026-10-26 12:00:00', ['settled' => 0]);
- $this->assertSame('50.0000000000', $facts->total($facts->betting([1], '2026-10-26 12:00:00')['effective']));
- $this->travel('2026-10-27 00:00:00'); $this->assertSame(2, $facts->policy()['id']);
- }
- public function test_turnover_rewards_are_paid_to_available_balance_and_never_locked(): void
- {
- // 活动奖金不再冻结:直接进入可用余额,流水要求计入统一提现打码量(required_flow 仍保留在奖励记录上)
- $id = $this->activity(8, ['min_deposit' => 100, 'reward_amount' => 25, 'turnover_ratio' => 2]);
- $this->join(1); $this->service->onDeposit($this->deposit(1, '100'));
- $reward = DB::table('promotion_rewards')->where('activity_id', $id)->first();
- $this->assertSame('paid', $reward->status);
- $this->assertSame(0, bccomp('50', (string)$reward->required_flow, 2));
- $this->assertSame('25.0000000000', (string)DB::table('wallets')->where('member_id', 'm1')->value('available_balance'));
- $this->assertSame('0', (string)DB::table('wallets')->where('member_id', 'm1')->value('frozen_balance'));
- $this->assertSame(1, (int)DB::table('balance_logs')->where('change_type', '优惠活动')->where('type', 1)->count());
- $this->bet(1, '1000', '-100', '2026-10-26 12:00:00'); $this->assertSame(0, $this->service->unlock(1));
- }
- public function test_quota_is_checked_before_consuming_a_spin_and_a_win_reserves_its_slot(): void
- {
- $id = $this->activity(9, ['completion_probability' => 100]); $this->complete($id);
- DB::table('promotion_activities')->where('id', $id)->update(['reward_quota' => 0]);
- $this->invalid(fn () => $this->service->spin($id, 1, 'request_spin_00001'), '份数');
- $this->assertSame(7, (int)DB::table('promotion_accounts')->value('spins'));
- DB::table('promotion_activities')->where('id', $id)->update(['reward_quota' => 1]);
- $this->service->spin($id, 1, 'request_spin_00001');
- $this->assertSame('reserved', DB::table('promotion_rewards')->value('status')); $this->assertSame(1, (int)DB::table('promotion_activities')->where('id', $id)->value('rewarded_count'));
- }
- public function test_independent_campaigns_do_not_touch_old_catalog_and_member_routes_live_in_member_project(): void
- {
- $id = $this->activity(9); $this->activity(7); $this->activity(8);
- $this->assertSame(0, DB::table('activity_rewards')->count());
- $this->assertArrayNotHasKey(9, \App\Support\ActivityCatalog::activityTypes());
- $this->assertSame(3, $this->service->listing(1, 'H5')['total']);
- $this->assertSame($id, $this->service->listing(1, 'H5', 'zh', 9)['data'][0]['activity_id']);
- $this->assertSame(0, DB::table('menus')->count(), 'Activity setup must leave menus to the frontend');
- $router = new \Illuminate\Routing\Router(new \Illuminate\Events\Dispatcher($this->app), $this->app); $this->app->instance('router', $router);
- $router->group(['prefix' => 'api'], function () { require dirname(__DIR__, 2) . '/routes/api.php'; });
- $memberRoutes=array_filter($router->getRoutes()->getRoutes(),fn ($route)=>str_starts_with($route->uri(),'api/promotion'));
- $this->assertSame([],$memberRoutes,'Member promotion routes must be owned by melbet_sport-api');
- $router->group(['prefix' => 'admin'], function () { require dirname(__DIR__, 2) . '/routes/admin.php'; });
- $route = $router->getRoutes()->match(Request::create('/admin/promotion/submit', 'POST'));
- $this->assertContains('admin.jwt', $route->middleware()); $this->assertContains('check.button.uri', $route->middleware());
- }
- public function test_promotion_migration_preserves_frontend_owned_menus_on_up_and_down(): void
- {
- DB::table('menus')->insert([
- ['id' => 1, 'parent_id' => 0, 'title' => '前端活动菜单', 'uri' => 'promotion', 'permission_name' => 'promotion.manage', 'type' => 1],
- ['id' => 2, 'parent_id' => 1, 'title' => '前端活动记录', 'uri' => 'admin/promotion/records', 'permission_name' => 'admin.promotion.records', 'type' => 2],
- ['id' => 3, 'parent_id' => 0, 'title' => '其他菜单', 'uri' => 'other', 'permission_name' => 'other.manage', 'type' => 1],
- ]);
- $before = DB::table('menus')->orderBy('id')->get()->toJson();
- $migration = require dirname(__DIR__, 2) . '/database/migrations/2026_10_26_160000_create_promotion_activities.php';
- $migration->down();
- $this->assertSame($before, DB::table('menus')->orderBy('id')->get()->toJson(), 'Rollback must preserve frontend menus and permissions');
- $this->assertFalse(DB::connection()->getSchemaBuilder()->hasTable('promotion_activities'));
- $migration->up();
- $this->assertSame($before, DB::table('menus')->orderBy('id')->get()->toJson(), 'Migration must not add or modify frontend menus and permissions');
- $this->assertTrue(DB::connection()->getSchemaBuilder()->hasTable('promotion_activities'));
- }
- public function test_admin_http_amounts_are_compact_without_changing_saved_rules_or_counters(): void
- {
- $id = $this->activity(8, ['min_deposit' => '200', 'reward_amount' => '10.12']);
- $request = Request::create('/admin/promotion/detail', 'GET', ['id' => $id]); $this->app->instance('request', $request);
- $response = (new \App\Http\Controllers\admin\Promotion())->detail(new PromotionAdminService())->getData(true);
- $this->assertSame(0, $response['code']);
- $this->assertSame('200', $response['data']['params']['min_deposit']);
- $this->assertSame('10.12', $response['data']['params']['reward_amount']);
- $this->assertSame($id, $response['data']['id']);
- $saved = json_decode(DB::table('promotion_activities')->where('id', $id)->value('params'), true);
- $this->assertSame('200.00', $saved['min_deposit']);
- $this->assertSame('10.12', $saved['reward_amount']);
- }
- public function test_ended_activities_are_taken_off_the_shelf_and_cannot_be_relisted(): void
- {
- $ended = $this->activity(8); $running = $this->activity(9);
- DB::table('promotion_activities')->where('id', $ended)->update(['end_time' => Carbon::parse('2026-10-26 11:59:59')->timestamp]);
- $this->assertSame(1, PromotionAdminService::expire());
- $this->assertSame(0, (int) DB::table('promotion_activities')->where('id', $ended)->value('status'));
- $this->assertSame(1, (int) DB::table('promotion_activities')->where('id', $running)->value('status'));
- $this->assertSame(0, PromotionAdminService::expire());
- $admin = new PromotionAdminService();
- $this->invalid(fn () => $admin->status($ended, 1), '活动已结束');
- $input = ['id' => $ended, 'translations' => $this->texts(), 'type' => 8, 'status' => 1, 'start_time' => '2026-10-01 00:00:00', 'end_time' => '2026-10-26 11:00:00'];
- $this->invalid(fn () => $admin->save($input), '活动已结束');
- $this->assertSame(0, (int) $admin->save(['status' => 0] + $input)['status']);
- }
- public function test_sync_command_expires_both_activity_catalogs_without_repeating_changes(): void
- {
- $promotion = $this->activity(8);
- DB::table('promotion_activities')->where('id', $promotion)->update(['end_time'=>now()->timestamp - 1]);
- $legacy = DB::table('activity_rewards')->insertGetId(['type'=>3, 'status'=>1, 'end_time'=>now()->timestamp - 1]);
- $command = new \App\Console\Commands\SyncPromotions();
- $command->setLaravel($this->app);
- $tester = new \Symfony\Component\Console\Tester\CommandTester($command);
- $this->assertSame(0, $tester->execute([]));
- $this->assertSame(0, (int)DB::table('activity_rewards')->where('id', $legacy)->value('status'));
- $this->assertSame(0, (int)DB::table('promotion_activities')->where('id', $promotion)->value('status'));
- $this->assertStringContainsString('到期下架:2', $tester->getDisplay());
- $this->assertSame(0, $tester->execute([]));
- $this->assertStringContainsString('到期下架:0', $tester->getDisplay());
- }
- public function test_catalog_expiry_failure_does_not_skip_independent_promotion_expiry(): void
- {
- $promotion = $this->activity(8);
- DB::table('promotion_activities')->where('id', $promotion)->update(['end_time'=>now()->timestamp - 1]);
- $legacy = DB::table('activity_rewards')->insertGetId(['type'=>3, 'status'=>1, 'end_time'=>now()->timestamp - 1]);
- DB::statement("CREATE TRIGGER reject_catalog_expiry BEFORE UPDATE ON bot_activity_rewards BEGIN SELECT RAISE(ABORT, 'simulated update failure'); END");
- $command = new \App\Console\Commands\SyncPromotions();
- $command->setLaravel($this->app);
- $tester = new \Symfony\Component\Console\Tester\CommandTester($command);
- $this->assertSame(1, $tester->execute([]));
- $this->assertSame(1, (int)DB::table('activity_rewards')->where('id', $legacy)->value('status'));
- $this->assertSame(0, (int)DB::table('promotion_activities')->where('id', $promotion)->value('status'));
- $this->assertStringContainsString('到期下架:1', $tester->getDisplay());
- $this->assertStringContainsString('失败数:1', $tester->getDisplay());
- }
- public function test_fixed_activities_are_initialized_disabled_without_publishing_or_creating_menus(): void
- {
- $this->assertSame(3, DB::table('promotion_activities')->count());
- foreach ([7, 9, 10] as $type) {
- $row = DB::table('promotion_activities')->where('type', $type)->first();
- $this->assertNotNull($row); $this->assertSame(0, (int) $row->status);
- $this->assertNull(DB::table('promotion_campaigns')->where('activity_id', $row->id)->value('first_published_at'));
- }
- $options = (new PromotionAdminService())->options();
- $this->assertSame([7, 8, 9, 10], array_column($options['types'], 'value'));
- $this->assertSame([8], array_column($options['create_types'], 'value'));
- $this->assertSame(0, DB::table('menus')->count());
- }
- public function test_fixed_types_cannot_be_created_even_when_no_configuration_exists(): void
- {
- $admin = new PromotionAdminService();
- foreach ([7, 9, 10] as $type) {
- $input = ['translations' => $this->texts(), 'type' => $type, 'status' => 0,
- 'start_time' => '2026-10-01 00:00:00', 'end_time' => '2026-12-31 23:59:59'];
- $this->invalid(fn () => $admin->save($input), '不支持新增');
- $this->assertSame(1, DB::table('promotion_activities')->where('type', $type)->count());
- $id = DB::table('promotion_activities')->where('type', $type)->value('id');
- DB::table('promotion_campaigns')->where('activity_id', $id)->delete();
- DB::table('promotion_activities')->where('id', $id)->delete();
- $this->invalid(fn () => $admin->save($input), '不支持新增');
- $this->assertSame(0, DB::table('promotion_activities')->where('type', $type)->count());
- }
- }
- public function test_first_deposit_still_allows_multiple_new_configurations_and_type_change_is_rejected(): void
- {
- $first = $this->activity(8); $second = $this->activity(8);
- $this->assertNotSame($first, $second);
- $this->assertSame(2, DB::table('promotion_activities')->where('type', 8)->count());
- $this->invalid(fn () => (new PromotionAdminService())->save(['id' => $first, 'translations' => $this->texts(), 'type' => 9, 'status' => 0,
- 'start_time' => '2026-10-01 00:00:00', 'end_time' => '2026-12-31 23:59:59']), '不能变更活动类型');
- $this->assertSame(8, (int) DB::table('promotion_activities')->where('id', $first)->value('type'));
- }
- public function test_fixed_initialization_and_relisting_do_not_replace_existing_activity_or_reset_its_history(): void
- {
- $id = $this->activity(9, ['completion_probability' => 0]);
- DB::table('promotion_activities')->where('id', $id)->update(['rewarded_count' => 3, 'budget_used' => '1998']);
- $before = (array) DB::table('promotion_activities')->where('id', $id)->first();
- $published = DB::table('promotion_campaigns')->where('activity_id', $id)->value('first_published_at');
- $migration = require dirname(__DIR__, 2) . '/database/migrations/2026_10_27_130000_initialize_fixed_promotion_activities.php';
- $this->travel('2026-10-27 12:00:00'); $migration->up(); $migration->down();
- $this->assertSame($before, (array) DB::table('promotion_activities')->where('id', $id)->first());
- $this->assertSame(3, DB::table('promotion_activities')->count());
- $admin = new PromotionAdminService(); $admin->status($id, 0); $admin->status($id, 1);
- $this->assertSame($published, DB::table('promotion_campaigns')->where('activity_id', $id)->value('first_published_at'));
- $this->assertSame(3, (int) DB::table('promotion_activities')->where('id', $id)->value('rewarded_count'));
- }
- public function test_admin_partial_rule_edit_preserves_other_settings_and_zero_probability(): void
- {
- $id = $this->activity(9, ['turnover_ratio' => 3, 'deposit_amount' => 5000]);
- $saved = (new PromotionAdminService())->save(['id' => $id, 'translations' => $this->texts(), 'type' => 9, 'status' => 1,
- 'start_time' => '2026-10-01', 'end_time' => '2026-12-31', 'params' => ['completion_probability' => 0]]);
- $this->assertSame('0.00', $saved['params']['completion_probability']); $this->assertSame('3.00', $saved['params']['turnover_ratio']);
- $this->assertSame('5000.00', $saved['params']['deposit_amount']); $this->assertSame(0, DB::table('activity_rewards')->count());
- }
- public function test_voided_task_progress_is_not_eligible_for_completion_probability(): void
- {
- $id = $this->activity(9, ['completion_probability' => 100]); $this->complete($id);
- DB::table('share_bet_facts')->where('user_id', 2)->update(['voided' => 1]);
- $state = $this->service->progress($id, 1); $this->assertFalse($state['conditions_complete']);
- $this->assertFalse($state['completed_tasks']['invite']); $this->assertFalse($state['completed_tasks']['team_bet']);
- $this->assertFalse($this->service->spin($id, 1, 'request_spin_voided')['spin']['reached']);
- }
- public function test_real_chain_credit_hook_awards_first_deposit_once_and_rolls_back_a_failed_award(): void
- {
- foreach ([
- 'level' => 'id INTEGER PRIMARY KEY,level INTEGER,recharge TEXT',
- 'recharge_channel_group' => 'id INTEGER PRIMARY KEY,activity_type TEXT,deleted_at TEXT',
- 'backflow' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,date TEXT,member_id TEXT,recharge_amount TEXT DEFAULT "0",withdrawal_amount TEXT DEFAULT "0",backflow_ratio TEXT,amount TEXT,created_at TEXT,updated_at TEXT',
- 'recharges' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,member_id TEXT,status INTEGER,amount TEXT,created_at TEXT,updated_at TEXT',
- ] as $table => $columns) DB::statement('CREATE TABLE bot_' . $table . ' (' . $columns . ')');
- foreach (['huishui_percentage' => '0', 'huishui_restriction' => '0', 'recharge_rate' => '0'] as $field => $val) DB::table('config')->insert(compact('field', 'val'));
- $id = $this->activity(8, ['min_deposit' => 100, 'reward_amount' => 25]); $this->join(1); $this->join(2);
- $source = DB::table('recharges')->insertGetId(['member_id' => 'm1', 'status' => 0, 'amount' => 100]);
- $recharge = \App\Models\Recharge::find($source);
- $this->assertTrue(\App\Services\RechargeService::creditConfirmedRecharge($recharge, ['status' => 1], '100.00'));
- $this->assertFalse(\App\Services\RechargeService::creditConfirmedRecharge($recharge, ['status' => 1], '100.00'));
- $this->assertSame('125.0000000000', (string)DB::table('wallets')->where('member_id', 'm1')->value('available_balance'));
- $this->assertSame(1, DB::table('promotion_rewards')->count());
- $source = DB::table('recharges')->insertGetId(['member_id' => 'm2', 'status' => 0, 'amount' => 100]);
- DB::statement("CREATE TRIGGER reject_award BEFORE INSERT ON bot_promotion_rewards BEGIN SELECT RAISE(ABORT, 'award failure'); END");
- try { \App\Services\RechargeService::creditConfirmedRecharge(\App\Models\Recharge::find($source), ['status' => 1], '100.00'); $this->fail('Expected failed award'); }
- catch (\Illuminate\Database\QueryException $e) { $this->assertStringContainsString('award failure', $e->getMessage()); }
- $this->assertSame(0, (int)DB::table('recharges')->where('id', $source)->value('status'));
- $this->assertSame('0', (string)DB::table('wallets')->where('member_id', 'm2')->value('available_balance'));
- $this->assertSame(0, DB::table('balance_logs')->where('member_id', 'm2')->count());
- }
- public function test_promotion_heartbeat_records_login_once_and_online_without_other_reporting_tables(): void
- {
- DB::statement('DROP TABLE bot_reporting_activity'); $id = $this->activity();
- for ($i = 0; $i <= 60; ++$i) {
- $this->travel(Carbon::parse('2026-10-26 12:00:00')->addMinutes($i)->format('Y-m-d H:i:s'));
- $this->service->heartbeat(1, 'secret-token', 'H5'); $this->service->heartbeat(1, 'secret-token', 'H5');
- }
- $state = $this->service->progress($id, 1);
- $this->assertTrue($state['completed_tasks']['online']); $this->assertTrue($state['completed_tasks']['login']); $this->assertSame(2, (int)$state['spins']);
- $this->assertSame(61, DB::table('promotion_presence')->count());
- $this->assertStringNotContainsString('secret-token', DB::table('promotion_presence')->first()->session_hash);
- $this->assertCount(7, $state['tasks']); $this->assertSame(0, $state['tasks'][0]['remaining_seconds']);
- $this->travel('2026-10-27 00:01:00'); $this->service->heartbeat(1, 'secret-token', 'H5');
- $this->assertSame(3, (int)$this->service->progress($id, 1)['spins']);
- }
- public function test_missing_old_first_deposit_hook_is_not_back_awarded_when_campaign_starts_later(): void
- {
- $deposit = $this->deposit(1, '1000'); $this->travel('2026-10-26 13:00:00'); $this->activity(8);
- $this->service->onDeposit($deposit);
- $this->assertSame(0, DB::table('promotion_rewards')->count());
- }
- public function test_manual_payment_approval_keeps_first_deposit_bonus_instead_of_overwriting_it_with_principal(): void
- {
- foreach ([
- 'level' => 'id INTEGER PRIMARY KEY,level INTEGER,recharge TEXT',
- 'recharge_channel_group' => 'id INTEGER PRIMARY KEY,activity_type TEXT,deleted_at TEXT',
- 'backflow' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,date TEXT,member_id TEXT,recharge_amount TEXT DEFAULT "0",withdrawal_amount TEXT DEFAULT "0",backflow_ratio TEXT,amount TEXT,created_at TEXT,updated_at TEXT',
- 'payment_orders' => 'id INTEGER PRIMARY KEY,member_id TEXT,status INTEGER,type INTEGER,amount TEXT,remark TEXT,state INTEGER,created_at TEXT,updated_at TEXT',
- ] as $table => $columns) DB::statement('CREATE TABLE bot_' . $table . ' (' . $columns . ')');
- foreach (['huishui_percentage' => '0', 'huishui_restriction' => '0', 'recharge_rate' => '0'] as $field => $val) DB::table('config')->insert(compact('field', 'val'));
- $this->activity(8, ['min_deposit' => 100, 'reward_amount' => 25]); $this->join(1);
- DB::table('payment_orders')->insert(['id' => 1, 'member_id' => 'm1', 'status' => 5, 'type' => 3, 'amount' => '100']);
- $this->app->instance('request', Request::create('/admin/paymentOrder/manualAudit', 'POST', ['id' => 1, 'status' => 2]));
- $body = (new \App\Http\Controllers\admin\PaymentOrder())->manualAudit()->getData(true);
- $this->assertSame(0, $body['code'], $body['msg']);
- $this->assertSame('125.0000000000', (string)DB::table('wallets')->where('member_id', 'm1')->value('available_balance'));
- $deposit = DB::table('balance_logs')->where('change_type', '充值')->first();
- $this->assertSame('0', (string)$deposit->before_balance); $this->assertSame('100.0000000000', (string)$deposit->after_balance);
- $this->assertSame(1, DB::table('promotion_rewards')->count());
- $this->assertNotSame(0, (new \App\Http\Controllers\admin\PaymentOrder())->manualAudit()->getData(true)['code']);
- $this->assertSame(1, DB::table('promotion_rewards')->count());
- }
- public function test_upgrade_invite_tiers_are_validated_sorted_and_must_exist_before_publishing(): void
- {
- foreach ([1 => '等级1', 2 => 'VIP2', 3 => 'VIP3', 4 => 'VIP4'] as $level => $name) DB::table('share_levels')->insert(['level' => $level, 'name' => $name]);
- $admin = new PromotionAdminService();
- $this->assertSame(['tiers' => []], $admin->options()['defaults'][10]);
- $this->assertSame([2, 3, 4], array_slice(array_column($admin->options()['share_levels'], 'level'), 1));
- $id = (int) DB::table('promotion_activities')->where('type', 10)->value('id');
- $this->assertSame($id, $admin->detail(null, 10)['id']);
- $this->assertArrayNotHasKey('image', $admin->detail(null, 10));
- $this->invalid(fn () => $this->activity(10, ['tiers' => []]), '至少配置一档');
- $this->activity(10, ['tiers' => []], 0);
- $this->invalid(fn () => $admin->status($id, 1), '至少配置一档');
- foreach ([
- [[['level' => 1, 'amount' => '8']], '2及以上'],
- [[['level' => 2, 'amount' => '8'], ['level' => 2, 'amount' => '9']], '重复'],
- [[['level' => 2, 'amount' => '0']], '大于0'],
- [[['level' => 2, 'amount' => '8.001']], '两位小数'],
- [[['level' => 2]], 'level和amount'],
- [[['level' => 9, 'amount' => '8']], '分享等级9不存在'],
- [['level' => 2, 'amount' => '8'], 'tiers参数错误'],
- ] as [$tiers, $message]) $this->invalid(fn () => $this->activity(10, ['tiers' => $tiers]), $message);
- $this->activity(10, ['tiers' => [['level' => '4', 'amount' => '18'], ['level' => 2, 'amount' => 8]]]);
- $saved = $admin->detail(null, 10);
- $this->assertSame([['level' => 2, 'amount' => '8.00'], ['level' => 4, 'amount' => '18.00']], $saved['params']['tiers']);
- $this->assertSame(1, (int) $saved['status']);
- $this->assertNotNull(DB::table('promotion_campaigns')->where('activity_id', $id)->value('first_published_at'));
- $this->assertSame(1, DB::table('promotion_activities')->where('type', 10)->count());
- }
- public function test_upgrade_invite_has_body_text_only_without_titles(): void
- {
- DB::table('share_levels')->insert(['level' => 2, 'name' => 'VIP2']);
- $admin = new PromotionAdminService();
- $id = (int) DB::table('promotion_activities')->where('type', 10)->value('id');
- $base = ['id' => $id, 'type' => 10, 'status' => 1, 'start_time' => '2026-10-01 00:00:00', 'end_time' => '2026-12-31 23:59:59',
- 'params' => ['tiers' => [['level' => 2, 'amount' => '8']]]];
- $texts = ['zh' => ['content' => '<p>中文正文</p>'], 'en' => ['content' => '<p>English</p>'], 'vi' => ['content' => '<p>Nội dung</p>']];
- $this->invalid(fn () => $admin->save($base + ['translations' => array_replace($texts, ['en' => ['content' => '<p> </p>']])]), '英文正文不能为空');
- $saved = $admin->save($base + ['translations' => array_replace_recursive($texts, ['zh' => ['title' => '会被忽略']])]);
- $this->assertSame(['content' => '<p>中文正文</p>'], $saved['translations']['zh']);
- $this->assertSame('邀请升级奖励', $saved['title']);
- $row = DB::table('promotion_activities')->where('id', $id)->first();
- $this->assertSame(['lang' => 'en', 'content' => '<p>English</p>'], \App\Support\PromotionTranslations::select((array) $row, 'en'));
- $admin->status($id, 0); $this->assertSame(1, (int) $admin->status($id, 1)['status']);
- $this->invalid(fn () => $admin->save(['id' => (int) DB::table('promotion_activities')->where('type', 7)->value('id'), 'type' => 7, 'status' => 0,
- 'start_time' => '2026-10-01 00:00:00', 'end_time' => '2026-12-31 23:59:59', 'translations' => $texts]), '标题');
- }
- public function test_upgrade_invite_records_list_each_paid_tier_with_both_accounts(): void
- {
- foreach ([2 => 'VIP2', 4 => 'VIP4'] as $level => $name) DB::table('share_levels')->insert(['level' => $level, 'name' => $name]);
- $id = (int) DB::table('promotion_activities')->where('type', 10)->value('id');
- DB::table('users')->whereIn('id', [1, 2])->update(['account' => DB::raw("'acc' || id")]);
- $this->member(3, 1);
- foreach ([[2, 2], [2, 4], [3, 2]] as $i => [$invitee, $level]) DB::table('promotion_upgrade_grants')->insert(['activity_id' => $id, 'reward_id' => 1,
- 'inviter_user_id' => 1, 'invitee_user_id' => $invitee, 'level' => $level, 'amount' => $level === 2 ? '8.00' : '18.00', 'invitee_level' => 4]);
- $admin = new PromotionAdminService();
- $all = $admin->records(['activity_id' => $id, 'kind' => 'upgrades']);
- $this->assertSame(3, $all['total']);
- $first = $all['data'][2];
- $this->assertSame(['acc1', 'acc2', 'VIP2', 'VIP4'], [$first->inviter_account, $first->invitee_account, $first->level_name, $first->invitee_level_name]);
- $this->assertSame(2, $admin->records(['activity_id' => $id, 'kind' => 'upgrades', 'user_id' => 2])['total']);
- $this->assertSame(3, $admin->records(['activity_id' => $id, 'kind' => 'upgrades', 'user_id' => 1])['total']);
- $this->assertNull($admin->records(['activity_id' => $id, 'kind' => 'upgrades', 'user_id' => 3])['data'][0]->invitee_account);
- $this->assertSame(3, $admin->records(['activity_id' => $id, 'type' => 10, 'kind' => 'upgrades'])['total']);
- $loss = (int) DB::table('promotion_activities')->where('type', 7)->value('id');
- $this->invalid(fn () => $admin->records(['activity_id' => $loss, 'type' => 10, 'kind' => 'rewards']), 'activity_id与type不匹配');
- $this->invalid(fn () => $admin->records(['activity_id' => $loss, 'kind' => 'upgrades']), 'upgrades仅用于邀请升级奖励');
- $this->invalid(fn () => $admin->records(['activity_id' => 99999, 'kind' => 'rewards']), '独立活动不存在');
- $this->assertSame(0, $admin->records(['activity_id' => $loss, 'type' => 7, 'kind' => 'rewards'])['total']);
- }
- public function test_first_deposit_is_automatic_without_opt_in(): void
- {
- $id = $this->activity(8, ['min_deposit' => 100, 'reward_amount' => 25]);
- // 不需要勾选:没有任何选择记录的会员首笔到账也发奖,第二笔起不再算首充。
- $this->service->onDeposit($this->deposit(1, '100'));
- $this->service->onDeposit($this->deposit(1, '1000'));
- $this->assertSame(1, DB::table('promotion_rewards')->where('activity_id', $id)->where('user_id', 1)->count());
- $this->assertSame(1, DB::table('promotion_first_deposits')->where('user_id', 1)->count());
- // 旧前端保存过「不参加」也照样发奖。
- $this->assertTrue($this->join(2, '0'));
- $this->service->onDeposit($this->deposit(2, '100'));
- $this->assertSame(1, DB::table('promotion_rewards')->where('activity_id', $id)->where('user_id', 2)->count());
- // 首笔没达到门槛就不发,后面的充值也不再补。
- $this->member(3);
- $this->service->onDeposit($this->deposit(3, '50')); $this->service->onDeposit($this->deposit(3, '500'));
- $this->assertSame(0, DB::table('promotion_rewards')->where('user_id', 3)->count());
- }
- public function test_first_deposit_restriction_is_one_setting_shared_by_every_campaign(): void
- {
- $admin = new PromotionAdminService();
- $options = $admin->options();
- $this->assertArrayNotHasKey('forbidden_categories', $options);
- $this->assertArrayNotHasKey('forbidden_categories', $options['defaults'][8]);
- $setting = $admin->firstDepositRestriction();
- $this->assertSame([], $setting['categories']);
- $this->assertSame(array_keys(\App\Services\Sharing\ShareDefaults::commissionCategories()), array_column($setting['options'], 'value'));
- $this->assertNotContains('third:3', array_column($setting['options'], 'value'));
- $this->assertSame(['third:1', 'third:2', 'self:sport'], $this->restrict(['self:sport', 'third:2', 'third:1'])['categories']);
- $this->assertSame(['third:1', 'third:2', 'self:sport'], $admin->firstDepositRestriction()['categories']);
- foreach ([['third:3'], ['third:1', 'third:1'], 'third:1', ['x' => 'third:1'], [4]] as $bad) $this->invalid(fn () => $this->restrict($bad), 'categories参数错误');
- $this->invalid(fn () => $this->restrict(array_keys(\App\Services\Sharing\ShareDefaults::commissionCategories())), '至少保留一个可投注的游戏大类');
- $this->invalid(fn () => $admin->saveFirstDepositRestriction([]), '请传categories');
- $this->assertSame(['third:1', 'third:2', 'self:sport'], $admin->firstDepositRestriction()['categories']);
- // 活动里不再保存、返回禁止大类;旧前端仍传该参数时忽略。
- $first = $this->activity(8, ['min_deposit' => 100, 'reward_amount' => 25, 'forbidden_categories' => ['third:5']]);
- $second = $this->activity(8, ['min_deposit' => 50, 'reward_amount' => 10]);
- $this->assertArrayNotHasKey('forbidden_categories', json_decode(DB::table('promotion_activities')->where('id', $first)->value('params'), true));
- DB::table('promotion_activities')->where('id', $second)->update(['params' => json_encode(['min_deposit' => '50.00', 'reward_amount' => '10.00', 'turnover_ratio' => '0.00', 'forbidden_categories' => ['third:5']])]);
- foreach ([$admin->detail($first), $admin->detail($second), $admin->listing(['type' => 8])['data'][0]] as $row) {
- $this->assertArrayNotHasKey('forbidden_categories', $row);
- $this->assertArrayNotHasKey('forbidden_categories', $row['params']);
- }
- $saved = $admin->save(['id' => $second, 'type' => 8, 'status' => 1, 'translations' => $this->texts(), 'params' => ['reward_amount' => 12]]);
- $this->assertArrayNotHasKey('forbidden_categories', json_decode(DB::table('promotion_activities')->where('id', $second)->value('params'), true));
- $this->assertSame('12.00', $saved['params']['reward_amount']);
- // 每个首充活动都使用同一设置;发奖快照记录到账时的设置。
- foreach ($this->service->listing(1, 'H5', 'zh', 8)['data'] as $item) $this->assertSame(['third:1', 'third:2', 'self:sport'], $item['rules']['forbidden_categories']);
- $admin->save(['id' => $first, 'type' => 8, 'status' => 1, 'translations' => $this->texts(), 'sort' => 9, 'params' => ['turnover_ratio' => 2]]);
- $this->restrict(['third:5']);
- $this->service->onDeposit($this->deposit(1, '100'));
- $snapshot = json_decode(DB::table('promotion_rewards')->where('user_id', 1)->value('rule_snapshot'), true);
- $this->assertSame(['third:5'], $snapshot['forbidden_categories']);
- foreach ($this->service->listing(2, 'H5', 'zh', 8)['data'] as $item) $this->assertSame(['third:5'], $item['rules']['forbidden_categories']);
- }
- public function test_first_deposit_pays_the_highest_tier_the_deposit_reaches(): void
- {
- // 100 送 10、1000 送 50:充 1000 发 50,充 500 发 10,充 50 不发;高档份数用完发下一档。
- $low = $this->activity(8, ['min_deposit' => 100, 'reward_amount' => 10]);
- $high = $this->activity(8, ['min_deposit' => 1000, 'reward_amount' => 50, 'turnover_ratio' => 2]);
- $this->restrict(['self:lottery']);
- $this->service->onDeposit($this->deposit(1, '1000'));
- $reward = DB::table('promotion_rewards')->where('user_id', 1)->first();
- $this->assertSame([$high, '50.00', '100.00'], [(int) $reward->activity_id, number_format((float) $reward->amount, 2, '.', ''), number_format((float) $reward->required_flow, 2, '.', '')]);
- $this->assertSame(['self:lottery'], json_decode($reward->rule_snapshot, true)['forbidden_categories'], 'restriction set at credit time');
- $this->service->onDeposit($this->deposit(2, '500'));
- $this->assertSame($low, (int) DB::table('promotion_rewards')->where('user_id', 2)->value('activity_id'));
- $this->member(3);
- $this->service->onDeposit($this->deposit(3, '50'));
- $this->assertSame(0, DB::table('promotion_rewards')->where('user_id', 3)->count());
- DB::table('promotion_activities')->where('id', $high)->update(['reward_quota' => 1, 'rewarded_count' => 1]);
- $this->member(4);
- $this->service->onDeposit($this->deposit(4, '2000'));
- $this->assertSame($low, (int) DB::table('promotion_rewards')->where('user_id', 4)->value('activity_id'));
- }
- public function test_legacy_campaign_params_cannot_forbid_every_category_any_more(): void
- {
- $all = array_keys(\App\Services\Sharing\ShareDefaults::commissionCategories());
- $draft = $this->activity(8, [], 0);
- DB::table('promotion_activities')->where('id', $draft)->update(['params' => json_encode(['turnover_ratio' => 2, 'forbidden_categories' => $all])]);
- (new PromotionAdminService())->status($draft, 1);
- $this->assertSame([], $this->service->listing(1, 'H5', 'zh', 8)['data'][0]['rules']['forbidden_categories']);
- }
- public function test_telegram_choice_is_bound_to_the_member_and_its_restriction_lifts_after_turnover(): void
- {
- \Illuminate\Support\Facades\Cache::swap(new \Illuminate\Cache\Repository(new \Illuminate\Cache\ArrayStore()));
- $activity = $this->activity(8, ['reward_amount' => 25, 'turnover_ratio' => 2]);
- $this->restrict(['self:sport']);
- $member = User::find(1);
- $reply = TelegramFirstDeposit::menu($member);
- $button = json_decode($reply['reply_markup'], true)['inline_keyboard'][0][0]['callback_data'];
- TelegramFirstDeposit::callback(User::find(2), $button);
- $this->assertNull(FirstDepositChoice::selection(2));
- TelegramFirstDeposit::callback($member, $button);
- $this->assertSame($activity, (int) FirstDepositChoice::selection(1)->activity_id);
- $this->service->onDeposit($this->deposit(1, '100'));
- $this->assertFalse($this->service->lotteryRestricted('m1'));
- // 禁投 F1彩票 时 Telegram 没有可参加的首充活动,网页端仍可参加。
- $this->restrict(['self:lottery']);
- $this->member(3);
- $this->assertSame(1, count(json_decode(TelegramFirstDeposit::menu(User::find(3))['reply_markup'], true)['inline_keyboard']));
- $this->assertTrue($this->join(2));
- $this->assertSame($activity, (int) FirstDepositChoice::selection(2)->activity_id);
- $this->service->onDeposit($this->deposit(2, '100'));
- $this->assertTrue($this->service->lotteryRestricted('m2'));
- $this->bet(2, '50', '-50', PromotionFacts::now());
- $this->assertFalse($this->service->lotteryRestricted('m2'));
- }
- public function test_admin_http_reads_and_saves_the_shared_first_deposit_restriction(): void
- {
- $controller = new \App\Http\Controllers\admin\Promotion(); $admin = new PromotionAdminService();
- $this->app->instance('request', Request::create('/admin/promotion/first-deposit-restriction', 'POST', ['categories' => ['self:lottery', 'third:2']]));
- $saved = $controller->firstDepositRestriction($admin)->getData(true);
- $this->assertSame(0, $saved['code']); $this->assertSame(['third:2', 'self:lottery'], $saved['data']['categories']);
- $this->app->instance('request', Request::create('/admin/promotion/first-deposit-restriction', 'POST', ['categories' => ['third:3']]));
- $failed = $controller->firstDepositRestriction($admin)->getData(true);
- $this->assertSame(-3, $failed['code']); $this->assertStringContainsString('categories参数错误', $failed['msg']);
- $this->app->instance('request', Request::create('/admin/promotion/first-deposit-restriction', 'GET'));
- $read = $controller->firstDepositRestriction($admin)->getData(true);
- $this->assertSame(['third:2', 'self:lottery'], $read['data']['categories']);
- $this->assertCount(8, $read['data']['options']);
- }
- }
|