PromotionActivitiesTest.php 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. <?php
  2. namespace Tests\Integration;
  3. use App\Http\Controllers\admin\ActivityReward as AdminActivity;
  4. use App\Models\PromotionActivity as ActivityReward;
  5. use App\Models\BalanceLog;
  6. use App\Services\PromotionAdminService;
  7. use App\Services\PromotionFacts;
  8. use App\Services\PromotionService;
  9. use App\Support\PromotionRules;
  10. use Carbon\Carbon;
  11. use Illuminate\Config\Repository;
  12. use Illuminate\Database\Capsule\Manager;
  13. use Illuminate\Database\Schema\Blueprint;
  14. use Illuminate\Foundation\Application;
  15. use Illuminate\Http\Request;
  16. use Illuminate\Support\Facades\DB;
  17. use Illuminate\Support\Facades\Facade;
  18. use Illuminate\Translation\ArrayLoader;
  19. use Illuminate\Translation\Translator;
  20. use Illuminate\Validation\Factory;
  21. use Illuminate\Validation\ValidationException;
  22. use PHPUnit\Framework\TestCase;
  23. /** Runs real migrations, qualification, wallet writes and state machines in SQLite, without .env/providers. */
  24. class PromotionActivitiesTest extends TestCase
  25. {
  26. private Application $app;
  27. private PromotionService $service;
  28. private string $originalTimezone;
  29. protected function setUp(): void
  30. {
  31. $this->originalTimezone = date_default_timezone_get(); date_default_timezone_set('Asia/Shanghai'); Carbon::setTestNow(Carbon::parse('2026-10-26 12:00:00', 'Asia/Shanghai'));
  32. Facade::clearResolvedInstances(); $this->app = new Application(dirname(__DIR__, 2));
  33. $this->app->instance('config', new Repository(['app' => ['locale' => 'zh', 'timezone' => 'Asia/Shanghai'], 'third_game' => ['currency' => 'CNY']])); Facade::setFacadeApplication($this->app);
  34. $db = new Manager($this->app); $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'bot_']);
  35. $db->setAsGlobal(); $db->bootEloquent(); $this->app->instance('db', $db->getDatabaseManager()); $this->app->bind('db.schema', fn () => $db->schema());
  36. $this->app->instance('translator', new Translator(new ArrayLoader(), 'zh'));
  37. $this->app->instance('validator', new Factory($this->app['translator'], $this->app));
  38. $this->app->instance('log', new \Psr\Log\NullLogger()); $this->app->instance('request', Request::create('/api/promotion/progress'));
  39. $this->app->instance(\Illuminate\Contracts\Routing\ResponseFactory::class, new \Tests\Support\JsonResponseFactory());
  40. Request::macro('validate', function ($rules) { return app('validator')->make($this->all(), $rules)->validate(); });
  41. foreach ([
  42. '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',
  43. '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',
  44. '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',
  45. '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',
  46. 'share_members' => 'user_id INTEGER PRIMARY KEY,parent_user_id INTEGER,bound_at TEXT',
  47. 'share_policies' => 'id INTEGER PRIMARY KEY,effective_date TEXT,valid_member_min_deposit TEXT,valid_member_min_effective_bet TEXT',
  48. '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',
  49. 'user_login' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,user_id TEXT,status INTEGER,platform TEXT,created_at TEXT',
  50. 'reporting_activity' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,user_id INTEGER,session_hash TEXT,observed_at TEXT',
  51. 'share_levels' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,level INTEGER UNIQUE,name TEXT',
  52. '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',
  53. ] as $table => $columns) DB::statement('CREATE TABLE bot_' . $table . ' (' . $columns . ')');
  54. 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();
  55. $this->member(1); $this->member(2, 1);
  56. DB::table('share_policies')->insert(['id' => 1, 'effective_date' => '2026-10-01', 'valid_member_min_deposit' => '200', 'valid_member_min_effective_bet' => '300']);
  57. $this->service = new PromotionService();
  58. }
  59. protected function tearDown(): void { Carbon::setTestNow(); date_default_timezone_set($this->originalTimezone); DB::disconnect(); Facade::clearResolvedInstances(); parent::tearDown(); }
  60. private function travel(string $time): void { Carbon::setTestNow(Carbon::parse($time, 'Asia/Shanghai')); }
  61. private function member(int $id, ?int $parent = null, string $at = '2026-10-01 00:00:00'): void
  62. {
  63. DB::table('users')->insert(['id' => $id, 'member_id' => 'm' . $id, 'user_id' => 'u' . $id, 'language' => 'zh', 'from' => 1, 'created_at' => $at, 'updated_at' => $at]);
  64. DB::table('wallets')->insert(['member_id' => 'm' . $id, 'available_balance' => '0', 'frozen_balance' => '0']);
  65. if ($parent) DB::table('share_members')->insert(['user_id' => $id, 'parent_user_id' => $parent, 'bound_at' => $at]);
  66. }
  67. private function activity(int $type = 9, array $params = [], int $status = 1): int
  68. {
  69. $input = ['translations' => $this->texts(), 'type' => $type, 'status' => $status,
  70. 'start_time' => '2026-10-01 00:00:00', 'end_time' => '2026-12-31 23:59:59', 'lang' => 'zh', 'params' => $params];
  71. if (in_array($type, PromotionRules::FIXED, true)) $input['id'] = (int) DB::table('promotion_activities')->where('type', $type)->value('id');
  72. return (int) (new PromotionAdminService())->save($input)['id'];
  73. }
  74. private function texts(): array
  75. {
  76. return ['zh' => ['title' => '测试活动', 'content' => '<p>中文活动正文</p>'],
  77. 'en' => ['title' => 'Test promotion', 'content' => '<p>English content</p>'],
  78. 'vi' => ['title' => 'Khuyến mãi', 'content' => '<p>Nội dung</p>']];
  79. }
  80. private function deposit(int $id, string $amount, ?string $time = null, string $type = '充值'): BalanceLog
  81. {
  82. return BalanceLog::create(['member_id' => 'm' . $id, 'type' => 1, 'amount' => $amount, 'change_type' => $type, 'created_at' => $time ?? PromotionFacts::now()]);
  83. }
  84. private function rawDeposit(int $id, string $amount, string $time, string $type = '充值'): int
  85. {
  86. return DB::table('balance_logs')->insertGetId(['member_id' => 'm' . $id, 'type' => 1, 'amount' => $amount, 'change_type' => $type, 'created_at' => $time, 'updated_at' => $time]);
  87. }
  88. private function bet(int $id, string $stake, string $profit, string $time, array $extra = []): int
  89. {
  90. $next = (int)DB::table('share_bet_facts')->max('id') + 1;
  91. return DB::table('share_bet_facts')->insertGetId($extra + ['user_id' => $id, 'source' => 'sport_order', 'source_id' => (string)$next,
  92. 'bet_at' => $time, 'bet_amount' => $stake, 'net_profit' => $profit, 'effective_amount' => '999999', 'currency' => 'CNY', 'settled' => 1, 'voided' => 0]);
  93. }
  94. private function invalid(callable $callback, string $message): void
  95. {
  96. try { $callback(); $this->fail('Expected validation failure: ' . $message); }
  97. catch (ValidationException $e) { $this->assertStringContainsString($message, $e->validator->errors()->first()); }
  98. }
  99. private function complete(int $activity): array
  100. {
  101. $this->rawDeposit(1, '3000', '2026-10-26 12:01:00'); $this->rawDeposit(2, '500', '2026-10-26 12:01:00');
  102. $this->bet(1, '6000', '-5000', '2026-10-26 12:01:00'); $this->bet(2, '4000', '-3000', '2026-10-26 12:01:00');
  103. DB::table('user_login')->insert(['user_id' => 'm1', 'status' => 1, 'platform' => 'H5', 'created_at' => '2026-10-26 12:01:00']);
  104. 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')]);
  105. $this->travel('2026-10-26 14:00:00'); return $this->service->progress($activity, 1, 'H5');
  106. }
  107. public function test_background_sync_skips_page_metrics_and_duplicate_task_writes_but_observes_corrections(): void
  108. {
  109. $id = $this->activity(9); $before = $this->complete($id);
  110. $this->assertTrue($before['conditions_complete']);
  111. DB::enableQueryLog(); DB::flushQueryLog();
  112. try {
  113. $this->service->syncAccount($id, 1);
  114. $queries = DB::getQueryLog();
  115. $this->assertLessThanOrEqual(50, count($queries));
  116. $this->assertCount(0, array_filter($queries, fn ($q) => str_contains($q['query'], 'from "bot_promotion_rewards"')));
  117. $this->assertCount(0, array_filter($queries, fn ($q) => preg_match('/^(insert.*"bot_promotion_task_grants"|update "bot_promotion_rounds")/', $q['query'])));
  118. $this->assertLessThanOrEqual(4, count(array_filter($queries, fn ($q) => str_contains($q['query'], 'from "bot_share_bet_facts"'))));
  119. } finally { DB::disableQueryLog(); DB::flushQueryLog(); }
  120. $after = $this->service->detail($id, 1);
  121. $this->assertSame($before['completed_tasks'], $after['completed_tasks']);
  122. $this->assertSame($before['spins'], $after['spins']);
  123. DB::table('share_bet_facts')->where('user_id', 2)->update(['net_profit' => '0']);
  124. $this->service->syncAccount($id, 1);
  125. $corrected = $this->service->detail($id, 1);
  126. $this->assertFalse($corrected['completed_tasks']['invite']);
  127. $this->assertFalse($corrected['completed_tasks']['team_bet']);
  128. $this->assertSame(7, DB::table('promotion_task_grants')->count());
  129. }
  130. public function test_third_party_cursor_uses_one_query_and_original_order_ids(): void
  131. {
  132. DB::statement('CREATE TABLE bot_third_game_orders (id INTEGER PRIMARY KEY,order_key TEXT UNIQUE)');
  133. foreach (range(1, 20) as $id) {
  134. $key = str_pad(dechex($id), 64, '0', STR_PAD_LEFT);
  135. DB::table('third_game_orders')->insert(['id' => $id, 'order_key' => $key]);
  136. $this->bet(1, '10', '-10', '2026-10-26 11:00:00', ['source' => 'third_game_orders', 'source_id' => $key]);
  137. }
  138. $this->bet(1, '999', '-999', '2026-10-26 11:00:00', ['source' => 'third_game_orders', 'source_id' => str_repeat('f', 64)]);
  139. DB::enableQueryLog(); DB::flushQueryLog();
  140. try {
  141. $result = (new PromotionFacts())->betting([1], '2026-10-01 00:00:00', null, ['third_game_orders' => 10]);
  142. $this->assertLessThanOrEqual(6, count(DB::getQueryLog()));
  143. } finally { DB::disableQueryLog(); DB::flushQueryLog(); }
  144. $this->assertSame('100.0000000000', $result['effective']['2026-10-26']);
  145. $this->assertSame('-100.0000000000', $result['profit']);
  146. }
  147. public function test_images_are_only_configurable_for_first_deposit_not_fixed_loss_or_wheel_campaigns(): void
  148. {
  149. $admin = new PromotionAdminService();
  150. foreach ([7, 8, 9] as $type) {
  151. $id = $this->activity($type);
  152. DB::table('promotion_activities')->where('id', $id)->update(['image' => 'previous.png']);
  153. $input = $admin->detail($id); $input['image'] = $type === 8 ? 'first-deposit.png' : ['ignored-legacy-upload'];
  154. $saved = $admin->save($input);
  155. foreach ([$saved, $admin->detail($id), $admin->listing(['type' => $type])['data'][0], $this->service->listing(1, 'H5', 'zh', $type)['data'][0]] as $row) {
  156. $this->assertSame($type === 8, array_key_exists('image', $row));
  157. }
  158. $this->assertSame($type === 8 ? 'first-deposit.png' : 'previous.png', DB::table('promotion_activities')->where('id', $id)->value('image'));
  159. }
  160. }
  161. public function test_subtitles_are_not_required_saved_or_returned_for_any_independent_activity(): void
  162. {
  163. $admin = new PromotionAdminService();
  164. foreach ([7, 8, 9] as $type) {
  165. $id = $this->activity($type); $legacy = $this->texts();
  166. foreach ($legacy as &$text) $text['sub_title'] = 'Historical subtitle'; unset($text);
  167. DB::table('promotion_activities')->where('id', $id)->update(['sub_title' => 'Historical subtitle', 'translations' => json_encode($legacy)]);
  168. $detail = $admin->detail($id);
  169. $this->assertArrayNotHasKey('sub_title', $detail);
  170. foreach ($detail['translations'] as $text) $this->assertSame(['title', 'content'], array_keys($text));
  171. $input = $detail; $input['sub_title'] = 'Ignored legacy input';
  172. foreach ($input['translations'] as &$text) $text['sub_title'] = ['ignored legacy input']; unset($text);
  173. $saved = $admin->save($input);
  174. $this->assertSame($this->texts(), $saved['translations']);
  175. $this->assertSame('Historical subtitle', DB::table('promotion_activities')->where('id', $id)->value('sub_title'));
  176. foreach ([$saved, $admin->listing(['type' => $type])['data'][0], $admin->status($id, 1),
  177. $this->service->listing(1, 'H5', 'zh', $type)['data'][0], $this->service->detail($id, 1, 'H5', 'zh')] as $row) {
  178. $this->assertArrayNotHasKey('sub_title', $row);
  179. }
  180. }
  181. }
  182. public function test_three_languages_edit_one_campaign_and_keep_rules_history_and_other_tabs(): void
  183. {
  184. $admin = new PromotionAdminService();
  185. foreach ([7, 8, 9] as $type) {
  186. $id = $this->activity($type); $before = $admin->detail($id);
  187. $count = DB::table('promotion_activities')->count();
  188. $input = $before; $input['translations']['en']['title'] = 'Updated English title';
  189. $saved = $admin->save($input);
  190. $this->assertSame($id, $saved['id']);
  191. $this->assertSame($count, DB::table('promotion_activities')->count());
  192. $this->assertSame($before['translations']['zh'], $saved['translations']['zh']);
  193. $this->assertSame($before['translations']['vi'], $saved['translations']['vi']);
  194. $this->assertSame('Updated English title', $admin->detail($id)['translations']['en']['title']);
  195. foreach (['params', 'rewarded_count', 'budget_used', 'first_published_at'] as $field) $this->assertSame($before[$field], $saved[$field]);
  196. foreach (['zh', 'en', 'vi'] as $lang) {
  197. $rows = $this->service->listing(1, 'H5', $lang, $type)['data'];
  198. $this->assertCount(1, $rows); $this->assertSame($id, $rows[0]['activity_id']);
  199. $this->assertSame($saved['translations'][$lang]['title'], $rows[0]['title']);
  200. $state = $this->service->detail($id, 1, 'H5', $lang);
  201. $this->assertSame($lang, $state['lang']);
  202. $this->assertSame($saved['translations'][$lang]['title'], $state['title']);
  203. $this->assertSame($saved['translations'][$lang]['content'], $state['content']);
  204. }
  205. }
  206. $this->assertSame(['zh', 'en', 'vi'], array_column($admin->options()['languages'], 'value'));
  207. }
  208. public function test_all_six_text_fields_are_required_and_invalid_tabs_cannot_overwrite_saved_content(): void
  209. {
  210. $id = $this->activity(9); $admin = new PromotionAdminService(); $input = $admin->detail($id);
  211. $before = DB::table('promotion_activities')->where('id', $id)->first();
  212. foreach (['zh', 'en', 'vi'] as $lang) {
  213. foreach (['title', 'content'] as $field) {
  214. $bad = $input; unset($bad['translations'][$lang][$field]);
  215. try { $admin->save($bad); $this->fail('Missing language text was accepted'); }
  216. catch (ValidationException $e) { $this->assertTrue($e->validator->errors()->has('translations.' . $lang . '.' . $field)); }
  217. $bad = $input; $bad['translations'][$lang][$field] = '<p>&nbsp;<br></p>';
  218. $this->invalid(fn () => $admin->save($bad), '不能为空');
  219. }
  220. $bad = $input; unset($bad['translations'][$lang]);
  221. $this->invalid(fn () => $admin->save($bad), '完整填写');
  222. }
  223. $bad = $input; unset($bad['translations']); $bad['title'] = '旧单语言表单';
  224. $this->invalid(fn () => $admin->save($bad), '完整填写');
  225. $bad = $input; $bad['translations']['fr'] = $input['translations']['en'];
  226. try { $admin->save($bad); $this->fail('Unknown language was accepted'); }
  227. catch (ValidationException $e) { $this->assertTrue($e->validator->errors()->has('translations')); }
  228. $bad = $input; $bad['translations']['en']['title'] = str_repeat('a', 141);
  229. try { $admin->save($bad); $this->fail('Oversized title was accepted'); }
  230. catch (ValidationException $e) { $this->assertTrue($e->validator->errors()->has('translations.en.title')); }
  231. $this->assertEquals($before, DB::table('promotion_activities')->where('id', $id)->first());
  232. }
  233. public function test_admin_http_save_returns_all_tabs_and_rejects_partial_language_payloads(): void
  234. {
  235. $controller = new \App\Http\Controllers\admin\Promotion(); $admin = new PromotionAdminService();
  236. $input = ['type' => 8, 'status' => 0, 'start_time' => '2026-10-26', 'end_time' => '2026-12-31', 'translations' => $this->texts()];
  237. $this->app->instance('request', Request::create('/admin/promotion/submit', 'POST', $input));
  238. $saved = $controller->submit($admin)->getData(true);
  239. $this->assertSame(0, $saved['code']); $this->assertSame($this->texts(), $saved['data']['translations']);
  240. $input['id'] = $saved['data']['id']; unset($input['translations']['en']);
  241. $this->app->instance('request', Request::create('/admin/promotion/submit', 'POST', $input));
  242. $failed = $controller->submit($admin)->getData(true);
  243. $this->assertSame(-3, $failed['code']); $this->assertStringContainsString('英文', $failed['msg']);
  244. $this->assertSame($this->texts(), $admin->detail($input['id'])['translations']);
  245. }
  246. public function test_incomplete_legacy_activity_can_be_hidden_but_cannot_be_published_without_all_tabs(): void
  247. {
  248. $id = (int) DB::table('promotion_activities')->where('type', 7)->value('id');
  249. $admin = new PromotionAdminService();
  250. $this->assertSame(0, (int) $admin->status($id, 0)['status']);
  251. $this->invalid(fn () => $admin->status($id, 1), '不能为空');
  252. $this->assertSame(0, (int) DB::table('promotion_activities')->where('id', $id)->value('status'));
  253. $this->assertNull(DB::table('promotion_campaigns')->where('activity_id', $id)->value('first_published_at'));
  254. }
  255. public function test_first_deposit_translation_does_not_split_or_duplicate_awards(): void
  256. {
  257. $id = $this->activity(8, ['min_deposit' => 100, 'reward_amount' => 25]);
  258. DB::table('users')->where('id', 1)->update(['language' => 'vi']);
  259. $deposit = $this->deposit(1, '100'); $this->service->onDeposit($deposit);
  260. $this->assertSame(1, DB::table('promotion_rewards')->where('activity_id', $id)->count());
  261. DB::table('users')->where('id', 1)->update(['language' => 'en']);
  262. $this->service->onDeposit($deposit);
  263. $this->assertSame(1, DB::table('promotion_rewards')->where('activity_id', $id)->count());
  264. $this->assertSame('25.0000000000', (string) DB::table('wallets')->where('member_id', 'm1')->value('available_balance'));
  265. $this->assertSame(1, DB::table('promotion_accounts')->where('activity_id', $id)->count());
  266. }
  267. public function test_translation_migration_preserves_legacy_texts_and_campaign_identity(): void
  268. {
  269. $migration = require dirname(__DIR__, 2) . '/database/migrations/2026_10_27_140000_add_promotion_activity_translations.php';
  270. $migration->down();
  271. $id = DB::table('promotion_activities')->where('type', 7)->value('id');
  272. DB::table('promotion_activities')->where('id', $id)->update(['lang' => 'en', 'title' => 'Existing title', 'sub_title' => 'Existing subtitle', 'content' => '<p>Existing content</p>']);
  273. $rows = DB::table('promotion_activities')->orderBy('id')->get();
  274. $published = DB::table('promotion_campaigns')->orderBy('activity_id')->get();
  275. $migration->up();
  276. foreach ($rows as $row) {
  277. $saved = DB::table('promotion_activities')->where('id', $row->id)->first();
  278. foreach ((array) $row as $field => $value) $this->assertSame($value, $saved->$field);
  279. }
  280. $texts = (new PromotionAdminService())->detail((int) $id)['translations'];
  281. $this->assertSame(['title' => 'Existing title', 'content' => '<p>Existing content</p>'], $texts['en']);
  282. $this->assertSame('', $texts['zh']['title']);
  283. $this->assertEquals($published, DB::table('promotion_campaigns')->orderBy('activity_id')->get());
  284. $this->assertSame(0, DB::table('menus')->count());
  285. $this->assertSame(0, $this->service->listing(1, 'H5', 'vi', 7)['total']);
  286. }
  287. public function test_probability_default_zero_boundaries_and_incomplete_gate(): void
  288. {
  289. $this->assertSame('20.00', PromotionRules::normalize(9, [])['completion_probability']);
  290. $this->assertSame('0.00', PromotionRules::normalize(9, ['completion_probability' => 0])['completion_probability']);
  291. $this->assertTrue(PromotionRules::draw(66599, true, '20.00', fn ($a, $b) => $a === 1 ? 2000 : 0)['reached']);
  292. $this->assertFalse(PromotionRules::draw(66599, true, '20.00', fn ($a, $b) => $a === 1 ? 2001 : 0)['reached']);
  293. $this->assertFalse(PromotionRules::draw(66599, false, '100.00', fn ($a, $b) => $a)['reached']);
  294. $this->invalid(fn () => PromotionRules::normalize(9, ['completion_probability' => 100.01]), 'between');
  295. }
  296. public function test_day_amounts_do_not_add_together_but_completed_flags_survive_midnight(): void
  297. {
  298. $id = $this->activity(); $this->service->progress($id, 1);
  299. $this->rawDeposit(1, '2000', '2026-10-26 13:00:00');
  300. $this->travel('2026-10-27 14:00:00'); $this->rawDeposit(1, '1000', '2026-10-27 12:00:00');
  301. $state = $this->service->progress($id, 1);
  302. $this->assertFalse($state['completed_tasks']['deposit']); $this->assertSame(0, (int)$state['spins']);
  303. $this->rawDeposit(1, '2000', '2026-10-27 13:00:00'); $state = $this->service->progress($id, 1);
  304. $this->assertTrue($state['completed_tasks']['deposit']); $this->assertSame(1, (int)$state['spins']);
  305. $this->travel('2026-10-28 14:00:00'); $state = $this->service->progress($id, 1);
  306. $this->assertTrue($state['completed_tasks']['deposit']); $this->assertSame(1, (int)$state['spins']);
  307. }
  308. public function test_repeated_rounds_keep_unused_spins_and_daily_flags_but_require_new_other_events(): void
  309. {
  310. $id = $this->activity(9, ['completion_probability' => 100]); $state = $this->complete($id);
  311. $this->assertTrue($state['conditions_complete']); $this->assertSame(7, (int)$state['spins']);
  312. $spin = $this->service->spin($id, 1, 'request_spin_00001');
  313. $this->assertTrue($spin['spin']['reached']); $this->assertSame('666.00', $spin['spin']['coins']);
  314. $this->assertSame($spin['spin'], $this->service->spin($id, 1, 'request_spin_00001')['spin']);
  315. $claim = $this->service->claim($id, 1, 1); $this->assertSame(2, $claim['round_no']); $this->assertSame(6, (int)$claim['spins']);
  316. $this->assertTrue($this->service->claim($id, 1, 1)['replayed']);
  317. $state = $this->service->progress($id, 1); $this->assertSame('0.00', $state['coins']);
  318. $this->assertSame(6, (int)$state['spins']); $this->assertTrue($state['completed_tasks']['online']); $this->assertTrue($state['completed_tasks']['login']);
  319. foreach (['invite', 'deposit', 'team_deposit', 'bet', 'team_bet'] as $task) $this->assertFalse($state['completed_tasks'][$task]);
  320. $this->rawDeposit(1, '3000', '2026-10-26 14:00:00'); $this->rawDeposit(2, '500', '2026-10-26 14:00:00');
  321. $this->bet(1, '6000', '-5000', '2026-10-26 14:00:00'); $this->bet(2, '4000', '-3000', '2026-10-26 14:00:00');
  322. $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');
  323. $state = $this->service->progress($id, 1); $this->assertTrue($state['conditions_complete']); $this->assertSame(11, (int)$state['spins']);
  324. $this->assertTrue($this->service->spin($id, 1, 'request_spin_00002')['spin']['reached']); $this->service->claim($id, 1, 2);
  325. $this->assertSame('1332.0000000000', (string)DB::table('wallets')->where('member_id', 'm1')->value('available_balance'));
  326. $this->assertSame(2, DB::table('promotion_rewards')->count()); $this->assertSame(1, (int)DB::table('promotion_activities')->where('id', $id)->value('rewarded_count'));
  327. }
  328. public function test_probability_changes_affect_new_spins_and_reserved_reward_can_be_claimed_after_down(): void
  329. {
  330. $id = $this->activity(9, ['completion_probability' => 0]); $this->complete($id);
  331. $first = $this->service->spin($id, 1, 'request_spin_00001'); $this->assertFalse($first['spin']['reached']);
  332. $row = ActivityReward::find($id); $rules = json_decode($row->params, true); $rules['completion_probability'] = '100.00'; $row->params = json_encode($rules); $row->save();
  333. $next = $this->service->spin($id, 1, 'request_spin_00002'); $this->assertTrue($next['spin']['reached']);
  334. $this->assertSame('0', (string)DB::table('promotion_spins')->orderBy('id')->value('probability'));
  335. DB::table('promotion_activities')->where('id', $id)->update(['status' => 0]);
  336. $this->service->claim($id, 1, 1); $this->invalid(fn () => $this->service->progress($id, 1), '未上架');
  337. $this->assertTrue($this->service->claim($id, 1, 1)['replayed']);
  338. }
  339. public function test_first_deposit_is_historical_first_and_does_not_refill_on_relisting(): void
  340. {
  341. $id = $this->activity(8, ['min_deposit' => '100', 'reward_amount' => '25']);
  342. $first = $this->deposit(1, '99'); $this->service->onDeposit($first); $this->service->onDeposit($first);
  343. $second = $this->deposit(1, '1000'); $this->service->onDeposit($second);
  344. $this->assertSame(0, DB::table('promotion_rewards')->count());
  345. $other = $this->deposit(2, '100'); $this->service->onDeposit($other); $this->service->onDeposit($other);
  346. $this->assertSame(1, DB::table('promotion_rewards')->count());
  347. $this->assertSame('25.0000000000', (string)DB::table('wallets')->where('member_id', 'm2')->value('available_balance'));
  348. $published = DB::table('promotion_campaigns')->where('activity_id', $id)->value('first_published_at');
  349. $this->travel('2026-10-27 12:00:00'); $row = ActivityReward::find($id); $row->status = 0; $row->save(); PromotionService::publish($row);
  350. $row->status = 1; $row->save(); PromotionService::publish($row);
  351. $this->assertSame($published, DB::table('promotion_campaigns')->where('activity_id', $id)->value('first_published_at'));
  352. $this->service->onDeposit($this->deposit(2, '500')); $this->assertSame(1, DB::table('promotion_rewards')->count());
  353. }
  354. public function test_loss_uses_post_publication_net_profit_then_only_new_direct_invitees_with_both_thresholds(): void
  355. {
  356. $this->bet(1, '900', '-900', '2026-10-25 12:00:00'); $id = $this->activity(7);
  357. $this->invalid(fn () => $this->service->apply($id, 1), '净亏');
  358. $this->bet(1, '600', '-600', '2026-10-26 12:00:00'); $this->bet(1, '200', '100', '2026-10-26 12:00:00');
  359. // A referral created in the same second, but before applying, is still an existing user.
  360. DB::table('users')->where('id', 2)->update(['created_at' => '2026-10-26 12:00:00']);
  361. DB::table('share_members')->where('user_id', 2)->update(['bound_at' => '2026-10-26 12:00:00']);
  362. $this->service->apply($id, 1); $this->service->apply($id, 1);
  363. $this->rawDeposit(2, '500', '2026-10-26 12:00:00'); $this->bet(2, '300', '-300', '2026-10-26 12:00:00');
  364. foreach ([3, 4, 5] as $child) {
  365. $this->member($child, 1, '2026-10-26 12:00:00'); $this->rawDeposit($child, '200', '2026-10-26 12:00:00');
  366. if ($child !== 5) $this->bet($child, '300', '-300', '2026-10-26 12:00:00');
  367. }
  368. $this->invalid(fn () => $this->service->claim($id, 1, 1), '人数不足');
  369. $this->bet(5, '1000', '-300', '2026-10-26 12:00:00'); $this->service->claim($id, 1, 1); $this->service->claim($id, 1, 1);
  370. $this->assertSame(1, DB::table('promotion_rewards')->count()); $this->assertSame('500.0000000000', (string)DB::table('wallets')->where('member_id', 'm1')->value('available_balance'));
  371. }
  372. public function test_coupon_mode_issues_inviter_and_counted_invitee_coupons_once_without_cash(): void
  373. {
  374. $coupons = ['reward_mode' => 'coupon', 'reward_amount' => '300', 'invite_count' => 2,
  375. 'coupon_valid_from' => '2026-10-26 00:00:00', 'coupon_valid_until' => '2026-11-30 23:59:59', 'coupon_categories' => ['self:lottery', 'self:sport'],
  376. 'inviter_coupons' => [['min_amount' => '100', 'discount' => '50', 'quantity' => 2], ['min_amount' => '200', 'discount' => '100', 'quantity' => 1]],
  377. 'invitee_coupons' => [['min_amount' => '20', 'discount' => '10', 'quantity' => 1]]];
  378. $this->invalid(fn () => $this->activity(7, array_replace($coupons, ['reward_amount' => '150'])), '优惠券抵扣总额不能超过奖励金额');
  379. $this->invalid(fn () => $this->activity(7, array_replace($coupons, ['coupon_categories' => []])), '可用游戏类型');
  380. $this->invalid(fn () => $this->activity(7, array_replace($coupons, ['inviter_coupons' => [['min_amount' => '40', 'discount' => '50', 'quantity' => 1]]])), '使用门槛');
  381. $id = $this->activity(7, $coupons);
  382. $this->assertSame(['self:sport', 'self:lottery'], (new PromotionAdminService())->detail(null, 7)['params']['coupon_categories']);
  383. $this->bet(1, '600', '-600', '2026-10-26 12:00:00'); $this->service->apply($id, 1);
  384. $this->travel('2026-10-26 13:00:00');
  385. foreach ([3, 4, 5] as $child) {
  386. $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');
  387. }
  388. $this->service->claim($id, 1, 1); $this->service->claim($id, 1, 1);
  389. $reward = DB::table('promotion_rewards')->first();
  390. // The amount is the inviter's own coupons; the invitee coupons only count toward the budget.
  391. $this->assertSame('paid', $reward->status); $this->assertEquals(200, $reward->amount); $this->assertEquals(0, $reward->required_flow);
  392. $this->assertSame('220.00', json_decode($reward->rule_snapshot, true)['coupon_face_value']);
  393. $this->assertSame('0', (string)DB::table('wallets')->where('member_id', 'm1')->value('available_balance'));
  394. $this->assertSame(0, DB::table('balance_logs')->where('change_type', '优惠活动')->count());
  395. $this->assertSame(3, DB::table('promotion_coupons')->where('user_id', 1)->where('role', 'inviter')->count());
  396. // Only the first invite_count qualified invitees are counted and receive coupons.
  397. $this->assertSame([3, 4], DB::table('promotion_coupons')->where('role', 'invitee')->orderBy('user_id')->pluck('user_id')->map(fn ($v) => (int)$v)->all());
  398. $state = $this->service->detail($id, 1, 'H5');
  399. $this->assertSame('not_applied', $state['status']); $this->assertSame(2, (int)$state['round_no']); $this->assertSame('coupon', $state['rules']['reward_mode']);
  400. $this->assertSame([2, 1], array_column($state['coupons'], 'quantity'));
  401. $this->assertEquals(220, DB::table('promotion_activities')->where('id', $id)->value('budget_used'));
  402. // Switching back to cash keeps the coupon settings for the next switch.
  403. $this->activity(7, ['reward_mode' => 'cash']);
  404. $this->assertCount(2, json_decode(DB::table('promotion_activities')->where('id', $id)->value('params'), true)['inviter_coupons']);
  405. $records = (new PromotionAdminService())->records(['activity_id' => $id, 'kind' => 'coupons', 'user_id' => 1]);
  406. $this->assertSame(5, $records['total']);
  407. }
  408. public function test_loss_invite_repeats_with_net_loss_from_previous_claim_and_new_invitees(): void
  409. {
  410. $id = $this->activity(7, ['invite_count' => 1]);
  411. $this->bet(1, '600', '-600', '2026-10-26 12:00:00'); $this->service->apply($id, 1);
  412. $this->travel('2026-10-26 13:00:00');
  413. $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');
  414. $this->assertSame(2, $this->service->claim($id, 1, 1)['round_no']);
  415. $state = $this->service->detail($id, 1, 'H5');
  416. $this->assertSame('not_applied', $state['status']); $this->assertSame(2, (int)$state['round_no']);
  417. $this->assertSame('0.00', $state['loss']); $this->assertSame('2026-10-26 13:00:00', $state['loss_from']);
  418. // Loss before the claim is not counted again; the server picks the round, so a retry before reapplying replays.
  419. $this->invalid(fn () => $this->service->apply($id, 1), '净亏');
  420. $this->assertTrue($this->service->claim($id, 1, 1)['replayed']);
  421. $replay = $this->service->claim($id, 1);
  422. $this->assertTrue($replay['replayed']); $this->assertSame(1, (int)$replay['reward']['round_no']);
  423. $this->travel('2026-10-27 12:00:00');
  424. $this->bet(1, '500', '-500', '2026-10-27 12:00:00'); $this->service->apply($id, 1);
  425. // The invitee counted in round 1 registered before this application.
  426. $this->invalid(fn () => $this->service->claim($id, 1), '人数不足');
  427. $this->travel('2026-10-27 13:00:00');
  428. $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');
  429. // A client still sending round_no=1 claims the current round.
  430. $claim = $this->service->claim($id, 1, 1);
  431. $this->assertFalse($claim['replayed']); $this->assertSame(3, $claim['round_no']); $this->assertSame(2, (int)$claim['reward']['round_no']);
  432. $rewards = DB::table('promotion_rewards')->orderBy('round_no')->get();
  433. $this->assertSame([1, 2], $rewards->pluck('round_no')->map(fn ($v) => (int)$v)->all());
  434. $this->assertSame('1000.0000000000', (string)DB::table('wallets')->where('member_id', 'm1')->value('available_balance'));
  435. $this->assertEquals(600, json_decode($rewards[0]->rule_snapshot, true)['application']['loss']);
  436. $this->assertSame([4], json_decode($rewards[1]->rule_snapshot, true)['qualified_invitees']);
  437. $this->assertEquals(1, DB::table('promotion_activities')->where('id', $id)->value('rewarded_count'));
  438. $row = (new PromotionAdminService())->records(['activity_id' => $id, 'kind' => 'accounts'])['data'][0];
  439. $this->assertSame(2, $row->claimed_count); $this->assertSame(2, $row->reward_round_no); $this->assertNull($row->applied_at);
  440. $this->assertSame([4], array_column($row->invitees, 'id'));
  441. }
  442. public function test_repeat_migration_moves_claimed_members_to_next_round_and_keeps_only_inviter_coupon_amount(): void
  443. {
  444. $id = $this->activity(7);
  445. $snapshot = ['reward_mode' => 'coupon', 'inviter_coupons' => [['min_amount' => '100', 'discount' => '50', 'quantity' => 10]], 'invitee_coupons' => [['min_amount' => '100', 'discount' => '40', 'quantity' => 1]]];
  446. $account = DB::table('promotion_accounts')->insertGetId(['activity_id' => $id, 'user_id' => 1, 'round_no' => 1, 'spins' => 0,
  447. 'applied_at' => '2026-10-26 12:00:00', 'application_snapshot' => json_encode(['loss' => '550', 'rules' => $snapshot])]);
  448. DB::table('promotion_rewards')->insert(['activity_id' => $id, 'user_id' => 1, 'account_id' => $account, 'round_no' => 1, 'amount' => '620',
  449. 'status' => 'paid', 'rule_snapshot' => json_encode($snapshot), 'created_at' => '2026-10-26 13:00:00']);
  450. $migration = require dirname(__DIR__, 2) . '/database/migrations/2026_11_03_170000_repeat_loss_invite_rounds.php';
  451. $migration->up(); $migration->up();
  452. $reward = DB::table('promotion_rewards')->first(); $rules = json_decode($reward->rule_snapshot, true);
  453. $this->assertEquals(500, $reward->amount); $this->assertSame('620.00', $rules['coupon_face_value']); $this->assertSame('550', $rules['application']['loss']);
  454. $row = DB::table('promotion_accounts')->where('id', $account)->first();
  455. $this->assertSame(2, (int)$row->round_no); $this->assertNull($row->applied_at); $this->assertNull($row->application_snapshot);
  456. }
  457. public function test_successful_online_time_deduplicates_devices_and_does_not_count_closed_session_as_online(): void
  458. {
  459. $id = $this->activity();
  460. foreach (['a', 'b'] as $session) for ($i = 0; $i <= 30; ++$i) DB::table('reporting_activity')->insert(['user_id' => 1, 'session_hash' => $session,
  461. 'observed_at' => Carbon::parse('2026-10-26 12:00:00')->addMinutes($i)->format('Y-m-d H:i:s')]);
  462. $this->travel('2026-10-26 16:00:00'); $state = $this->service->progress($id, 1);
  463. $this->assertArrayNotHasKey('online', $state['completed_tasks']);
  464. $this->assertSame(1800, (new PromotionFacts())->online(1, '2026-10-26 12:00:00')['2026-10-26']);
  465. }
  466. public function test_effective_minimum_void_pending_and_next_day_policy_are_respected(): void
  467. {
  468. DB::table('share_policies')->insert(['id' => 2, 'effective_date' => '2026-10-27', 'valid_member_min_deposit' => '9999', 'valid_member_min_effective_bet' => '9999']);
  469. $facts = new PromotionFacts(); $this->assertSame(1, $facts->policy()['id']);
  470. $this->bet(1, '1000', '50', '2026-10-26 12:00:00'); $this->bet(1, '500', '-500', '2026-10-26 12:00:00', ['voided' => 1]);
  471. $this->bet(1, '500', '-500', '2026-10-26 12:00:00', ['settled' => 0]);
  472. $this->assertSame('50.0000000000', $facts->total($facts->betting([1], '2026-10-26 12:00:00')['effective']));
  473. $this->travel('2026-10-27 00:00:00'); $this->assertSame(2, $facts->policy()['id']);
  474. }
  475. public function test_turnover_rewards_are_paid_to_available_balance_and_never_locked(): void
  476. {
  477. // 活动奖金不再冻结:直接进入可用余额,流水要求计入统一提现打码量(required_flow 仍保留在奖励记录上)
  478. $id = $this->activity(8, ['min_deposit' => 100, 'reward_amount' => 25, 'turnover_ratio' => 2]);
  479. $this->service->onDeposit($this->deposit(1, '100'));
  480. $reward = DB::table('promotion_rewards')->where('activity_id', $id)->first();
  481. $this->assertSame('paid', $reward->status);
  482. $this->assertSame(0, bccomp('50', (string)$reward->required_flow, 2));
  483. $this->assertSame('25.0000000000', (string)DB::table('wallets')->where('member_id', 'm1')->value('available_balance'));
  484. $this->assertSame('0', (string)DB::table('wallets')->where('member_id', 'm1')->value('frozen_balance'));
  485. $this->assertSame(1, (int)DB::table('balance_logs')->where('change_type', '优惠活动')->where('type', 1)->count());
  486. $this->bet(1, '1000', '-100', '2026-10-26 12:00:00'); $this->assertSame(0, $this->service->unlock(1));
  487. }
  488. public function test_quota_is_checked_before_consuming_a_spin_and_a_win_reserves_its_slot(): void
  489. {
  490. $id = $this->activity(9, ['completion_probability' => 100]); $this->complete($id);
  491. DB::table('promotion_activities')->where('id', $id)->update(['reward_quota' => 0]);
  492. $this->invalid(fn () => $this->service->spin($id, 1, 'request_spin_00001'), '份数');
  493. $this->assertSame(7, (int)DB::table('promotion_accounts')->value('spins'));
  494. DB::table('promotion_activities')->where('id', $id)->update(['reward_quota' => 1]);
  495. $this->service->spin($id, 1, 'request_spin_00001');
  496. $this->assertSame('reserved', DB::table('promotion_rewards')->value('status')); $this->assertSame(1, (int)DB::table('promotion_activities')->where('id', $id)->value('rewarded_count'));
  497. }
  498. public function test_independent_campaigns_do_not_touch_old_catalog_and_member_routes_live_in_member_project(): void
  499. {
  500. $id = $this->activity(9); $this->activity(7); $this->activity(8);
  501. $this->assertSame(0, DB::table('activity_rewards')->count());
  502. $this->assertArrayNotHasKey(9, \App\Support\ActivityCatalog::activityTypes());
  503. $this->assertSame(3, $this->service->listing(1, 'H5')['total']);
  504. $this->assertSame($id, $this->service->listing(1, 'H5', 'zh', 9)['data'][0]['activity_id']);
  505. $this->assertSame(0, DB::table('menus')->count(), 'Activity setup must leave menus to the frontend');
  506. $router = new \Illuminate\Routing\Router(new \Illuminate\Events\Dispatcher($this->app), $this->app); $this->app->instance('router', $router);
  507. $router->group(['prefix' => 'api'], function () { require dirname(__DIR__, 2) . '/routes/api.php'; });
  508. $memberRoutes=array_filter($router->getRoutes()->getRoutes(),fn ($route)=>str_starts_with($route->uri(),'api/promotion'));
  509. $this->assertSame([],$memberRoutes,'Member promotion routes must be owned by melbet_sport-api');
  510. $router->group(['prefix' => 'admin'], function () { require dirname(__DIR__, 2) . '/routes/admin.php'; });
  511. $route = $router->getRoutes()->match(Request::create('/admin/promotion/submit', 'POST'));
  512. $this->assertContains('admin.jwt', $route->middleware()); $this->assertContains('check.button.uri', $route->middleware());
  513. }
  514. public function test_promotion_migration_preserves_frontend_owned_menus_on_up_and_down(): void
  515. {
  516. DB::table('menus')->insert([
  517. ['id' => 1, 'parent_id' => 0, 'title' => '前端活动菜单', 'uri' => 'promotion', 'permission_name' => 'promotion.manage', 'type' => 1],
  518. ['id' => 2, 'parent_id' => 1, 'title' => '前端活动记录', 'uri' => 'admin/promotion/records', 'permission_name' => 'admin.promotion.records', 'type' => 2],
  519. ['id' => 3, 'parent_id' => 0, 'title' => '其他菜单', 'uri' => 'other', 'permission_name' => 'other.manage', 'type' => 1],
  520. ]);
  521. $before = DB::table('menus')->orderBy('id')->get()->toJson();
  522. $migration = require dirname(__DIR__, 2) . '/database/migrations/2026_10_26_160000_create_promotion_activities.php';
  523. $migration->down();
  524. $this->assertSame($before, DB::table('menus')->orderBy('id')->get()->toJson(), 'Rollback must preserve frontend menus and permissions');
  525. $this->assertFalse(DB::connection()->getSchemaBuilder()->hasTable('promotion_activities'));
  526. $migration->up();
  527. $this->assertSame($before, DB::table('menus')->orderBy('id')->get()->toJson(), 'Migration must not add or modify frontend menus and permissions');
  528. $this->assertTrue(DB::connection()->getSchemaBuilder()->hasTable('promotion_activities'));
  529. }
  530. public function test_admin_http_amounts_are_compact_without_changing_saved_rules_or_counters(): void
  531. {
  532. $id = $this->activity(8, ['min_deposit' => '200', 'reward_amount' => '10.12']);
  533. $request = Request::create('/admin/promotion/detail', 'GET', ['id' => $id]); $this->app->instance('request', $request);
  534. $response = (new \App\Http\Controllers\admin\Promotion())->detail(new PromotionAdminService())->getData(true);
  535. $this->assertSame(0, $response['code']);
  536. $this->assertSame('200', $response['data']['params']['min_deposit']);
  537. $this->assertSame('10.12', $response['data']['params']['reward_amount']);
  538. $this->assertSame($id, $response['data']['id']);
  539. $saved = json_decode(DB::table('promotion_activities')->where('id', $id)->value('params'), true);
  540. $this->assertSame('200.00', $saved['min_deposit']);
  541. $this->assertSame('10.12', $saved['reward_amount']);
  542. }
  543. public function test_ended_activities_are_taken_off_the_shelf_and_cannot_be_relisted(): void
  544. {
  545. $ended = $this->activity(8); $running = $this->activity(9);
  546. DB::table('promotion_activities')->where('id', $ended)->update(['end_time' => Carbon::parse('2026-10-26 11:59:59')->timestamp]);
  547. $this->assertSame(1, PromotionAdminService::expire());
  548. $this->assertSame(0, (int) DB::table('promotion_activities')->where('id', $ended)->value('status'));
  549. $this->assertSame(1, (int) DB::table('promotion_activities')->where('id', $running)->value('status'));
  550. $this->assertSame(0, PromotionAdminService::expire());
  551. $admin = new PromotionAdminService();
  552. $this->invalid(fn () => $admin->status($ended, 1), '活动已结束');
  553. $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'];
  554. $this->invalid(fn () => $admin->save($input), '活动已结束');
  555. $this->assertSame(0, (int) $admin->save(['status' => 0] + $input)['status']);
  556. }
  557. public function test_fixed_activities_are_initialized_disabled_without_publishing_or_creating_menus(): void
  558. {
  559. $this->assertSame(3, DB::table('promotion_activities')->count());
  560. foreach ([7, 9, 10] as $type) {
  561. $row = DB::table('promotion_activities')->where('type', $type)->first();
  562. $this->assertNotNull($row); $this->assertSame(0, (int) $row->status);
  563. $this->assertNull(DB::table('promotion_campaigns')->where('activity_id', $row->id)->value('first_published_at'));
  564. }
  565. $options = (new PromotionAdminService())->options();
  566. $this->assertSame([7, 8, 9, 10], array_column($options['types'], 'value'));
  567. $this->assertSame([8], array_column($options['create_types'], 'value'));
  568. $this->assertSame(0, DB::table('menus')->count());
  569. }
  570. public function test_fixed_types_cannot_be_created_even_when_no_configuration_exists(): void
  571. {
  572. $admin = new PromotionAdminService();
  573. foreach ([7, 9, 10] as $type) {
  574. $input = ['translations' => $this->texts(), 'type' => $type, 'status' => 0,
  575. 'start_time' => '2026-10-01 00:00:00', 'end_time' => '2026-12-31 23:59:59'];
  576. $this->invalid(fn () => $admin->save($input), '不支持新增');
  577. $this->assertSame(1, DB::table('promotion_activities')->where('type', $type)->count());
  578. $id = DB::table('promotion_activities')->where('type', $type)->value('id');
  579. DB::table('promotion_campaigns')->where('activity_id', $id)->delete();
  580. DB::table('promotion_activities')->where('id', $id)->delete();
  581. $this->invalid(fn () => $admin->save($input), '不支持新增');
  582. $this->assertSame(0, DB::table('promotion_activities')->where('type', $type)->count());
  583. }
  584. }
  585. public function test_first_deposit_still_allows_multiple_new_configurations_and_type_change_is_rejected(): void
  586. {
  587. $first = $this->activity(8); $second = $this->activity(8);
  588. $this->assertNotSame($first, $second);
  589. $this->assertSame(2, DB::table('promotion_activities')->where('type', 8)->count());
  590. $this->invalid(fn () => (new PromotionAdminService())->save(['id' => $first, 'translations' => $this->texts(), 'type' => 9, 'status' => 0,
  591. 'start_time' => '2026-10-01 00:00:00', 'end_time' => '2026-12-31 23:59:59']), '不能变更活动类型');
  592. $this->assertSame(8, (int) DB::table('promotion_activities')->where('id', $first)->value('type'));
  593. }
  594. public function test_fixed_initialization_and_relisting_do_not_replace_existing_activity_or_reset_its_history(): void
  595. {
  596. $id = $this->activity(9, ['completion_probability' => 0]);
  597. DB::table('promotion_activities')->where('id', $id)->update(['rewarded_count' => 3, 'budget_used' => '1998']);
  598. $before = (array) DB::table('promotion_activities')->where('id', $id)->first();
  599. $published = DB::table('promotion_campaigns')->where('activity_id', $id)->value('first_published_at');
  600. $migration = require dirname(__DIR__, 2) . '/database/migrations/2026_10_27_130000_initialize_fixed_promotion_activities.php';
  601. $this->travel('2026-10-27 12:00:00'); $migration->up(); $migration->down();
  602. $this->assertSame($before, (array) DB::table('promotion_activities')->where('id', $id)->first());
  603. $this->assertSame(3, DB::table('promotion_activities')->count());
  604. $admin = new PromotionAdminService(); $admin->status($id, 0); $admin->status($id, 1);
  605. $this->assertSame($published, DB::table('promotion_campaigns')->where('activity_id', $id)->value('first_published_at'));
  606. $this->assertSame(3, (int) DB::table('promotion_activities')->where('id', $id)->value('rewarded_count'));
  607. }
  608. public function test_admin_partial_rule_edit_preserves_other_settings_and_zero_probability(): void
  609. {
  610. $id = $this->activity(9, ['turnover_ratio' => 3, 'deposit_amount' => 5000]);
  611. $saved = (new PromotionAdminService())->save(['id' => $id, 'translations' => $this->texts(), 'type' => 9, 'status' => 1,
  612. 'start_time' => '2026-10-01', 'end_time' => '2026-12-31', 'params' => ['completion_probability' => 0]]);
  613. $this->assertSame('0.00', $saved['params']['completion_probability']); $this->assertSame('3.00', $saved['params']['turnover_ratio']);
  614. $this->assertSame('5000.00', $saved['params']['deposit_amount']); $this->assertSame(0, DB::table('activity_rewards')->count());
  615. }
  616. public function test_voided_task_progress_is_not_eligible_for_completion_probability(): void
  617. {
  618. $id = $this->activity(9, ['completion_probability' => 100]); $this->complete($id);
  619. DB::table('share_bet_facts')->where('user_id', 2)->update(['voided' => 1]);
  620. $state = $this->service->progress($id, 1); $this->assertFalse($state['conditions_complete']);
  621. $this->assertFalse($state['completed_tasks']['invite']); $this->assertFalse($state['completed_tasks']['team_bet']);
  622. $this->assertFalse($this->service->spin($id, 1, 'request_spin_voided')['spin']['reached']);
  623. }
  624. public function test_real_chain_credit_hook_awards_first_deposit_once_and_rolls_back_a_failed_award(): void
  625. {
  626. foreach ([
  627. 'config' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,field TEXT,val TEXT',
  628. 'level' => 'id INTEGER PRIMARY KEY,level INTEGER,recharge TEXT',
  629. 'recharge_channel_group' => 'id INTEGER PRIMARY KEY,activity_type TEXT,deleted_at TEXT',
  630. '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',
  631. 'recharges' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,member_id TEXT,status INTEGER,amount TEXT,created_at TEXT,updated_at TEXT',
  632. ] as $table => $columns) DB::statement('CREATE TABLE bot_' . $table . ' (' . $columns . ')');
  633. foreach (['huishui_percentage' => '0', 'huishui_restriction' => '0', 'recharge_rate' => '0'] as $field => $val) DB::table('config')->insert(compact('field', 'val'));
  634. $id = $this->activity(8, ['min_deposit' => 100, 'reward_amount' => 25]);
  635. $source = DB::table('recharges')->insertGetId(['member_id' => 'm1', 'status' => 0, 'amount' => 100]);
  636. $recharge = \App\Models\Recharge::find($source);
  637. $this->assertTrue(\App\Services\RechargeService::creditConfirmedRecharge($recharge, ['status' => 1], '100.00'));
  638. $this->assertFalse(\App\Services\RechargeService::creditConfirmedRecharge($recharge, ['status' => 1], '100.00'));
  639. $this->assertSame('125.0000000000', (string)DB::table('wallets')->where('member_id', 'm1')->value('available_balance'));
  640. $this->assertSame(1, DB::table('promotion_rewards')->count());
  641. $source = DB::table('recharges')->insertGetId(['member_id' => 'm2', 'status' => 0, 'amount' => 100]);
  642. DB::statement("CREATE TRIGGER reject_award BEFORE INSERT ON bot_promotion_rewards BEGIN SELECT RAISE(ABORT, 'award failure'); END");
  643. try { \App\Services\RechargeService::creditConfirmedRecharge(\App\Models\Recharge::find($source), ['status' => 1], '100.00'); $this->fail('Expected failed award'); }
  644. catch (\Illuminate\Database\QueryException $e) { $this->assertStringContainsString('award failure', $e->getMessage()); }
  645. $this->assertSame(0, (int)DB::table('recharges')->where('id', $source)->value('status'));
  646. $this->assertSame('0', (string)DB::table('wallets')->where('member_id', 'm2')->value('available_balance'));
  647. $this->assertSame(0, DB::table('balance_logs')->where('member_id', 'm2')->count());
  648. }
  649. public function test_promotion_heartbeat_records_login_once_and_online_without_other_reporting_tables(): void
  650. {
  651. DB::statement('DROP TABLE bot_reporting_activity'); $id = $this->activity();
  652. for ($i = 0; $i <= 60; ++$i) {
  653. $this->travel(Carbon::parse('2026-10-26 12:00:00')->addMinutes($i)->format('Y-m-d H:i:s'));
  654. $this->service->heartbeat(1, 'secret-token', 'H5'); $this->service->heartbeat(1, 'secret-token', 'H5');
  655. }
  656. $state = $this->service->progress($id, 1);
  657. $this->assertTrue($state['completed_tasks']['online']); $this->assertTrue($state['completed_tasks']['login']); $this->assertSame(2, (int)$state['spins']);
  658. $this->assertSame(61, DB::table('promotion_presence')->count());
  659. $this->assertStringNotContainsString('secret-token', DB::table('promotion_presence')->first()->session_hash);
  660. $this->assertCount(7, $state['tasks']); $this->assertSame(0, $state['tasks'][0]['remaining_seconds']);
  661. $this->travel('2026-10-27 00:01:00'); $this->service->heartbeat(1, 'secret-token', 'H5');
  662. $this->assertSame(3, (int)$this->service->progress($id, 1)['spins']);
  663. }
  664. public function test_missing_old_first_deposit_hook_is_not_back_awarded_when_campaign_starts_later(): void
  665. {
  666. $deposit = $this->deposit(1, '1000'); $this->travel('2026-10-26 13:00:00'); $this->activity(8);
  667. $this->service->onDeposit($deposit);
  668. $this->assertSame(0, DB::table('promotion_rewards')->count());
  669. }
  670. public function test_manual_payment_approval_keeps_first_deposit_bonus_instead_of_overwriting_it_with_principal(): void
  671. {
  672. foreach ([
  673. 'config' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,field TEXT,val TEXT',
  674. 'level' => 'id INTEGER PRIMARY KEY,level INTEGER,recharge TEXT',
  675. 'recharge_channel_group' => 'id INTEGER PRIMARY KEY,activity_type TEXT,deleted_at TEXT',
  676. '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',
  677. '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',
  678. ] as $table => $columns) DB::statement('CREATE TABLE bot_' . $table . ' (' . $columns . ')');
  679. foreach (['huishui_percentage' => '0', 'huishui_restriction' => '0', 'recharge_rate' => '0'] as $field => $val) DB::table('config')->insert(compact('field', 'val'));
  680. $this->activity(8, ['min_deposit' => 100, 'reward_amount' => 25]);
  681. DB::table('payment_orders')->insert(['id' => 1, 'member_id' => 'm1', 'status' => 5, 'type' => 3, 'amount' => '100']);
  682. $this->app->instance('request', Request::create('/admin/paymentOrder/manualAudit', 'POST', ['id' => 1, 'status' => 2]));
  683. $body = (new \App\Http\Controllers\admin\PaymentOrder())->manualAudit()->getData(true);
  684. $this->assertSame(0, $body['code'], $body['msg']);
  685. $this->assertSame('125.0000000000', (string)DB::table('wallets')->where('member_id', 'm1')->value('available_balance'));
  686. $deposit = DB::table('balance_logs')->where('change_type', '充值')->first();
  687. $this->assertSame('0', (string)$deposit->before_balance); $this->assertSame('100.0000000000', (string)$deposit->after_balance);
  688. $this->assertSame(1, DB::table('promotion_rewards')->count());
  689. $this->assertNotSame(0, (new \App\Http\Controllers\admin\PaymentOrder())->manualAudit()->getData(true)['code']);
  690. $this->assertSame(1, DB::table('promotion_rewards')->count());
  691. }
  692. public function test_upgrade_invite_tiers_are_validated_sorted_and_must_exist_before_publishing(): void
  693. {
  694. foreach ([1 => '等级1', 2 => 'VIP2', 3 => 'VIP3', 4 => 'VIP4'] as $level => $name) DB::table('share_levels')->insert(['level' => $level, 'name' => $name]);
  695. $admin = new PromotionAdminService();
  696. $this->assertSame(['tiers' => []], $admin->options()['defaults'][10]);
  697. $this->assertSame([2, 3, 4], array_slice(array_column($admin->options()['share_levels'], 'level'), 1));
  698. $id = (int) DB::table('promotion_activities')->where('type', 10)->value('id');
  699. $this->assertSame($id, $admin->detail(null, 10)['id']);
  700. $this->assertArrayNotHasKey('image', $admin->detail(null, 10));
  701. $this->invalid(fn () => $this->activity(10, ['tiers' => []]), '至少配置一档');
  702. $this->activity(10, ['tiers' => []], 0);
  703. $this->invalid(fn () => $admin->status($id, 1), '至少配置一档');
  704. foreach ([
  705. [[['level' => 1, 'amount' => '8']], '2及以上'],
  706. [[['level' => 2, 'amount' => '8'], ['level' => 2, 'amount' => '9']], '重复'],
  707. [[['level' => 2, 'amount' => '0']], '大于0'],
  708. [[['level' => 2, 'amount' => '8.001']], '两位小数'],
  709. [[['level' => 2]], 'level和amount'],
  710. [[['level' => 9, 'amount' => '8']], '分享等级9不存在'],
  711. [['level' => 2, 'amount' => '8'], 'tiers参数错误'],
  712. ] as [$tiers, $message]) $this->invalid(fn () => $this->activity(10, ['tiers' => $tiers]), $message);
  713. $this->activity(10, ['tiers' => [['level' => '4', 'amount' => '18'], ['level' => 2, 'amount' => 8]]]);
  714. $saved = $admin->detail(null, 10);
  715. $this->assertSame([['level' => 2, 'amount' => '8.00'], ['level' => 4, 'amount' => '18.00']], $saved['params']['tiers']);
  716. $this->assertSame(1, (int) $saved['status']);
  717. $this->assertNotNull(DB::table('promotion_campaigns')->where('activity_id', $id)->value('first_published_at'));
  718. $this->assertSame(1, DB::table('promotion_activities')->where('type', 10)->count());
  719. }
  720. public function test_upgrade_invite_has_body_text_only_without_titles(): void
  721. {
  722. DB::table('share_levels')->insert(['level' => 2, 'name' => 'VIP2']);
  723. $admin = new PromotionAdminService();
  724. $id = (int) DB::table('promotion_activities')->where('type', 10)->value('id');
  725. $base = ['id' => $id, 'type' => 10, 'status' => 1, 'start_time' => '2026-10-01 00:00:00', 'end_time' => '2026-12-31 23:59:59',
  726. 'params' => ['tiers' => [['level' => 2, 'amount' => '8']]]];
  727. $texts = ['zh' => ['content' => '<p>中文正文</p>'], 'en' => ['content' => '<p>English</p>'], 'vi' => ['content' => '<p>Nội dung</p>']];
  728. $this->invalid(fn () => $admin->save($base + ['translations' => array_replace($texts, ['en' => ['content' => '<p> </p>']])]), '英文正文不能为空');
  729. $saved = $admin->save($base + ['translations' => array_replace_recursive($texts, ['zh' => ['title' => '会被忽略']])]);
  730. $this->assertSame(['content' => '<p>中文正文</p>'], $saved['translations']['zh']);
  731. $this->assertSame('邀请升级奖励', $saved['title']);
  732. $row = DB::table('promotion_activities')->where('id', $id)->first();
  733. $this->assertSame(['lang' => 'en', 'content' => '<p>English</p>'], \App\Support\PromotionTranslations::select((array) $row, 'en'));
  734. $admin->status($id, 0); $this->assertSame(1, (int) $admin->status($id, 1)['status']);
  735. $this->invalid(fn () => $admin->save(['id' => (int) DB::table('promotion_activities')->where('type', 7)->value('id'), 'type' => 7, 'status' => 0,
  736. 'start_time' => '2026-10-01 00:00:00', 'end_time' => '2026-12-31 23:59:59', 'translations' => $texts]), '标题');
  737. }
  738. public function test_upgrade_invite_records_list_each_paid_tier_with_both_accounts(): void
  739. {
  740. foreach ([2 => 'VIP2', 4 => 'VIP4'] as $level => $name) DB::table('share_levels')->insert(['level' => $level, 'name' => $name]);
  741. $id = (int) DB::table('promotion_activities')->where('type', 10)->value('id');
  742. DB::table('users')->whereIn('id', [1, 2])->update(['account' => DB::raw("'acc' || id")]);
  743. $this->member(3, 1);
  744. foreach ([[2, 2], [2, 4], [3, 2]] as $i => [$invitee, $level]) DB::table('promotion_upgrade_grants')->insert(['activity_id' => $id, 'reward_id' => 1,
  745. 'inviter_user_id' => 1, 'invitee_user_id' => $invitee, 'level' => $level, 'amount' => $level === 2 ? '8.00' : '18.00', 'invitee_level' => 4]);
  746. $admin = new PromotionAdminService();
  747. $all = $admin->records(['activity_id' => $id, 'kind' => 'upgrades']);
  748. $this->assertSame(3, $all['total']);
  749. $first = $all['data'][2];
  750. $this->assertSame(['acc1', 'acc2', 'VIP2', 'VIP4'], [$first->inviter_account, $first->invitee_account, $first->level_name, $first->invitee_level_name]);
  751. $this->assertSame(2, $admin->records(['activity_id' => $id, 'kind' => 'upgrades', 'user_id' => 2])['total']);
  752. $this->assertSame(3, $admin->records(['activity_id' => $id, 'kind' => 'upgrades', 'user_id' => 1])['total']);
  753. $this->assertNull($admin->records(['activity_id' => $id, 'kind' => 'upgrades', 'user_id' => 3])['data'][0]->invitee_account);
  754. $this->assertSame(3, $admin->records(['activity_id' => $id, 'type' => 10, 'kind' => 'upgrades'])['total']);
  755. $loss = (int) DB::table('promotion_activities')->where('type', 7)->value('id');
  756. $this->invalid(fn () => $admin->records(['activity_id' => $loss, 'type' => 10, 'kind' => 'rewards']), 'activity_id与type不匹配');
  757. $this->invalid(fn () => $admin->records(['activity_id' => $loss, 'kind' => 'upgrades']), 'upgrades仅用于邀请升级奖励');
  758. $this->invalid(fn () => $admin->records(['activity_id' => 99999, 'kind' => 'rewards']), '独立活动不存在');
  759. $this->assertSame(0, $admin->records(['activity_id' => $loss, 'type' => 7, 'kind' => 'rewards'])['total']);
  760. }
  761. }