AutomaticRewardGrantTest.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. <?php
  2. namespace Tests\Integration;
  3. use App\Console\Commands\AutoGrantRewards;
  4. use App\Http\Controllers\admin\Backflow as BackflowController;
  5. use App\Http\Controllers\admin\Rebate as RebateController;
  6. use App\Http\Controllers\admin\RewardGrantSettings;
  7. use App\Http\Controllers\admin\RewardRules;
  8. use App\Models\Rebate;
  9. use App\Services\AutomaticRewardGrantService;
  10. use App\Services\BackflowService;
  11. use App\Services\RebateService;
  12. use App\Services\RewardBaseSyncService;
  13. use App\Services\RewardGrantService;
  14. use App\Services\RewardGrantSettingsService;
  15. use Carbon\Carbon;
  16. use Illuminate\Config\Repository;
  17. use Illuminate\Database\Capsule\Manager;
  18. use Illuminate\Database\Schema\Blueprint;
  19. use Illuminate\Events\Dispatcher;
  20. use Illuminate\Foundation\Application;
  21. use Illuminate\Http\JsonResponse;
  22. use Illuminate\Http\Request;
  23. use Illuminate\Routing\Router;
  24. use Illuminate\Support\Facades\DB;
  25. use Illuminate\Support\Facades\Facade;
  26. use Illuminate\Support\Facades\Schema;
  27. use Illuminate\Translation\ArrayLoader;
  28. use Illuminate\Translation\Translator;
  29. use Illuminate\Validation\Factory;
  30. use PHPUnit\Framework\Attributes\DataProvider;
  31. use PHPUnit\Framework\TestCase;
  32. use Symfony\Component\Console\Tester\CommandTester;
  33. /** Real payout controllers, command, wallets and ledgers; no project boot, .env or live database. */
  34. class AutomaticRewardGrantTest extends TestCase
  35. {
  36. private Application $app;
  37. protected function setUp(): void
  38. {
  39. parent::setUp();
  40. Carbon::setTestNow(Carbon::parse('2026-10-25 14:30:00', 'Asia/Shanghai'));
  41. Facade::clearResolvedInstances();
  42. $this->app = new Application(dirname(__DIR__, 2));
  43. $this->app->instance('config', new Repository(['app' => ['locale' => 'zh', 'timezone' => 'Asia/Shanghai']]));
  44. Facade::setFacadeApplication($this->app);
  45. $db = new Manager($this->app);
  46. $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'bot_']);
  47. $db->setEventDispatcher(new Dispatcher($this->app));
  48. $db->setAsGlobal(); $db->bootEloquent();
  49. $this->app->instance('db', $db->getDatabaseManager());
  50. $this->app->bind('db.schema', fn () => $db->schema());
  51. $translator = new Translator(new ArrayLoader(), 'zh');
  52. $this->app->instance('translator', $translator);
  53. $this->app->instance('validator', new Factory($translator, $this->app));
  54. $this->app->instance('log', new \Psr\Log\NullLogger());
  55. $this->app->instance(\Illuminate\Contracts\Routing\ResponseFactory::class, new \Tests\Support\JsonResponseFactory());
  56. Request::macro('validate', function (array $rules) {
  57. return app('validator')->make($this->all(), $rules)->validate();
  58. });
  59. Schema::create('config', function (Blueprint $t) { $t->id(); $t->string('field'); $t->string('val'); });
  60. DB::table('config')->insert([
  61. ['field' => 'rebate', 'val' => '0.005'],
  62. ['field' => 'huishui_restriction', 'val' => '100'],
  63. ['field' => 'huishui_percentage', 'val' => '0.05'],
  64. ]);
  65. Schema::create('users', function (Blueprint $t) {
  66. $t->id(); $t->string('member_id')->unique(); $t->integer('level')->default(1);
  67. $t->string('username')->default(''); $t->string('first_name')->default('');
  68. });
  69. Schema::create('level', function (Blueprint $t) { $t->id(); $t->integer('level'); $t->string('level_name'); });
  70. DB::table('level')->insert([['level' => 1, 'level_name' => 'VIP1'], ['level' => 2, 'level_name' => 'VIP2']]);
  71. Schema::create('share_bet_facts', function (Blueprint $t) {
  72. $t->id(); $t->string('source', 32); $t->string('source_id', 64); $t->unsignedBigInteger('user_id'); $t->string('member_id', 64);
  73. $t->string('category', 32); $t->dateTime('bet_at'); $t->date('bet_date'); $t->dateTime('settled_at')->nullable();
  74. foreach (['bet_amount', 'net_profit', 'effective_amount'] as $c) $t->decimal($c, 24, 10)->default(0);
  75. $t->boolean('settled')->default(false); $t->boolean('voided')->default(false);
  76. $t->string('currency', 8)->default('CNY'); $t->string('source_version', 64)->default(''); $t->timestamps();
  77. });
  78. Schema::create('share_system_state', function (Blueprint $t) { $t->string('key')->primary(); $t->text('value'); $t->timestamps(); });
  79. Schema::create('wallet_bonus', function (Blueprint $t) {
  80. $t->id(); $t->string('member_id'); $t->integer('type')->default(0); $t->unsignedBigInteger('activity_id')->default(0);
  81. $t->unsignedBigInteger('related_id'); foreach (['amount', 'need_flow', 'remaind_flow'] as $c) $t->decimal($c, 24, 2);
  82. $t->integer('status'); $t->timestamps();
  83. });
  84. Schema::create('wallets', function (Blueprint $t) {
  85. $t->id(); $t->string('member_id'); $t->decimal('available_balance', 24, 10)->default(0); $t->timestamps();
  86. });
  87. DB::table('wallets')->insert(['member_id' => '1001', 'available_balance' => '20.00']);
  88. Schema::create('balance_logs', function (Blueprint $t) {
  89. $t->id(); $t->string('member_id'); $t->string('change_type'); $t->unsignedBigInteger('related_id');
  90. foreach (['amount', 'before_balance', 'after_balance'] as $field) $t->decimal($field, 24, 10);
  91. $t->string('remark'); $t->timestamps();
  92. });
  93. Schema::create('rebates', function (Blueprint $t) {
  94. $t->id(); $t->string('member_id'); $t->string('date');
  95. $t->decimal('betting_amount', 24, 2); $t->decimal('effective_betting_amount', 24, 2);
  96. $t->decimal('rebate_ratio', 12, 4)->default(0); $t->decimal('amount', 24, 2)->default(0);
  97. $t->decimal('profit', 24, 2)->default(0); $t->string('username')->default(''); $t->string('first_name')->default('');
  98. $t->integer('status')->default(0); $t->string('audited_by')->nullable(); $t->bigInteger('grant_time')->default(0); $t->timestamps();
  99. });
  100. Schema::create('backflow', function (Blueprint $t) {
  101. $t->id(); $t->string('member_id'); $t->string('date');
  102. foreach (['recharge_amount', 'withdrawal_amount', 'backflow_ratio', 'amount'] as $field) $t->decimal($field, 24, 4)->default(0);
  103. $t->integer('status')->default(0); $t->bigInteger('grant_time')->default(0); $t->timestamps();
  104. });
  105. $this->migration()->up();
  106. $this->rulesMigration()->up();
  107. DB::table('rebate_rules')->insert(['category' => 'self:lottery', 'level' => 1, 'min_effective_amount' => 0, 'percentage' => '0.5', 'turnover_multiple' => 0]);
  108. DB::table('backflow_rules')->insert(['category' => 'self:lottery', 'min_loss_amount' => 100, 'reward_amount' => 35, 'turnover_multiple' => 0]);
  109. $this->request('/admin/rebate');
  110. }
  111. protected function tearDown(): void
  112. {
  113. Carbon::setTestNow(); DB::disconnect(); Facade::clearResolvedInstances();
  114. parent::tearDown();
  115. }
  116. private function migration()
  117. {
  118. return require dirname(__DIR__, 2) . '/database/migrations/2026_10_25_180000_create_reward_grant_settings.php';
  119. }
  120. private function rulesMigration()
  121. {
  122. return require dirname(__DIR__, 2) . '/database/migrations/2026_11_03_160000_create_reward_rules.php';
  123. }
  124. private function request(string $path, array $params = [], string $method = 'GET'): void
  125. {
  126. $request = Request::create($path, $method, $params);
  127. $request->user = (object) ['id' => 1, 'username' => 'operator-one'];
  128. $this->app->instance('request', $request);
  129. }
  130. private function user(string $memberId, int $level = 1): int
  131. {
  132. DB::table('users')->insertOrIgnore(['member_id' => $memberId, 'level' => $level]);
  133. return (int) DB::table('users')->where('member_id', $memberId)->value('id');
  134. }
  135. /** Legacy PC28 rows: no facts, so the stored effective bet is the payout basis. */
  136. private function rebate(array $values = []): int
  137. {
  138. $this->user((string) ($values['member_id'] ?? '1001'));
  139. return DB::table('rebates')->insertGetId($values + ['member_id' => '1001', 'date' => '2026-10-23',
  140. 'betting_amount' => '1000.00', 'effective_betting_amount' => '800.00']);
  141. }
  142. /** The month's lottery loss mirrors the old |recharge + withdrawal| fixture. */
  143. private function backflow(array $values = []): int
  144. {
  145. $values += ['member_id' => '1001', 'date' => '2026-09', 'recharge_amount' => '1000.00', 'withdrawal_amount' => '-300.00'];
  146. if (($values['status'] ?? 0) === 0) {
  147. $loss = bcadd((string) $values['recharge_amount'], (string) $values['withdrawal_amount'], 2);
  148. $this->fact($values['member_id'], 'self:lottery', $values['date'] . '-10 12:00:00', '0', bcsub('0', $loss, 2));
  149. }
  150. return DB::table('backflow')->insertGetId($values);
  151. }
  152. private function fact(string $memberId, string $category, string $betAt, string $effective, string $profit, array $values = []): void
  153. {
  154. static $sequence = 0;
  155. DB::table('share_bet_facts')->insert($values + ['source' => 'test', 'source_id' => (string) ++$sequence,
  156. 'user_id' => $this->user($memberId), 'member_id' => $memberId, 'category' => $category, 'bet_at' => $betAt,
  157. 'bet_date' => substr($betAt, 0, 10), 'bet_amount' => $effective, 'effective_amount' => $effective,
  158. 'net_profit' => $profit, 'settled' => 1, 'voided' => 0, 'currency' => 'CNY',
  159. 'created_at' => now()->format('Y-m-d H:i:s'), 'updated_at' => now()->format('Y-m-d H:i:s')]);
  160. }
  161. private function enable(string $type, string $time = '14:30'): void
  162. {
  163. RewardGrantSettingsService::save($type, ['auto_enabled' => 1, 'grant_time' => $time]);
  164. }
  165. private function runRewards(): array { return (new AutomaticRewardGrantService())->run(); }
  166. private function scheduledEvents(): array
  167. {
  168. $this->app['config']->set('cache', ['default' => 'array', 'stores' => ['array' => ['driver' => 'array']]]);
  169. $this->app->register(\Illuminate\Cache\CacheServiceProvider::class);
  170. $schedule = new \Illuminate\Console\Scheduling\Schedule('Asia/Shanghai');
  171. $kernel = new \App\Console\Kernel($this->app, new Dispatcher($this->app));
  172. $method = new \ReflectionMethod($kernel, 'schedule');
  173. $method->setAccessible(true);
  174. $method->invoke($kernel, $schedule);
  175. return $schedule->events();
  176. }
  177. public function test_console_scheduler_registers_the_automatic_payout_command_every_minute_with_overlap_protection(): void
  178. {
  179. $events = array_values(array_filter($this->scheduledEvents(), fn ($event) => str_contains($event->command ?? '', 'rewards:auto-grant')));
  180. $this->assertCount(1, $events);
  181. $this->assertSame('* * * * *', $events[0]->expression);
  182. $this->assertTrue($events[0]->withoutOverlapping);
  183. $this->assertSame(60, $events[0]->expiresAt);
  184. }
  185. public function test_console_scheduler_refreshes_reward_bases_and_wagers_after_bet_facts(): void
  186. {
  187. $commands = ['share:sync-facts --write', 'rewards:sync-bases', 'wagering:sync'];
  188. $scheduled = [];
  189. foreach ($this->scheduledEvents() as $event) {
  190. foreach ($commands as $command) {
  191. if (!str_ends_with($event->command ?? '', ' ' . $command)) continue;
  192. $this->assertSame('* * * * *', $event->expression);
  193. $this->assertTrue($event->withoutOverlapping);
  194. $scheduled[] = $command;
  195. }
  196. }
  197. $this->assertSame($commands, $scheduled);
  198. }
  199. public function test_migration_defaults_to_manual_and_both_settings_routes_keep_admin_and_existing_grant_permissions(): void
  200. {
  201. $id = $this->rebate(); $this->backflow();
  202. foreach (['rebate', 'backflow'] as $type) {
  203. $this->assertSame(['type' => $type, 'auto_enabled' => 0, 'grant_time' => '03:00', 'timezone' => 'Asia/Shanghai'], RewardGrantSettingsService::get($type));
  204. }
  205. $this->assertSame(0, $this->runRewards()['rebate']['granted']);
  206. $this->assertSame(0, DB::table('rebates')->where('id', $id)->value('status'));
  207. $this->assertSame(0, DB::table('balance_logs')->count());
  208. $router = new Router(new Dispatcher($this->app), $this->app);
  209. $this->app->instance('router', $router);
  210. $router->group(['prefix' => 'admin'], function () { require dirname(__DIR__, 2) . '/routes/admin.php'; });
  211. foreach (['rebate' => 'submit', 'backflow' => 'grant'] as $type => $permission) {
  212. foreach (['GET', 'POST'] as $method) {
  213. $route = $router->getRoutes()->match(Request::create('/admin/' . $type . '/grant-settings', $method));
  214. $this->assertContains('admin.jwt', $route->middleware());
  215. $this->assertContains('check.button.uri', $route->middleware());
  216. $this->assertSame('admin/' . $type . '/' . $permission, $route->defaults['permission_uri']);
  217. }
  218. }
  219. $this->migration()->down();
  220. $this->assertFalse(Schema::hasTable('reward_grant_settings'));
  221. }
  222. public function test_settings_api_persists_independent_times_and_disabling_preserves_the_previous_time_without_paying(): void
  223. {
  224. $this->rebate();
  225. $this->request('/admin/rebate/grant-settings', ['auto_enabled' => true, 'grant_time' => '14:30'], 'POST');
  226. $body = (new RewardGrantSettings())->saveRebate()->getData(true);
  227. $this->assertSame(0, $body['code']);
  228. $this->assertSame(1, $body['data']['auto_enabled']);
  229. $this->assertSame('14:30', $body['data']['grant_time']);
  230. $this->assertSame(0, RewardGrantSettingsService::get('backflow')['auto_enabled']);
  231. $this->request('/admin/backflow/grant-settings', ['auto_enabled' => 1, 'grant_time' => '20:15'], 'POST');
  232. $this->assertSame(0, (new RewardGrantSettings())->saveBackflow()->getData(true)['code']);
  233. $this->assertSame('20:15', RewardGrantSettingsService::get('backflow')['grant_time']);
  234. $this->request('/admin/rebate/grant-settings', ['auto_enabled' => 0], 'POST');
  235. $body = (new RewardGrantSettings())->saveRebate()->getData(true);
  236. $this->assertSame(0, $body['data']['auto_enabled']);
  237. $this->assertSame('14:30', $body['data']['grant_time']);
  238. $this->assertSame(0, DB::table('balance_logs')->count());
  239. $this->assertSame(0, (new RewardGrantSettings())->rebate()->getData(true)['code']);
  240. }
  241. #[DataProvider('invalidSettings')]
  242. public function test_invalid_settings_do_not_change_the_switch_or_time(array $values): void
  243. {
  244. $this->request('/admin/rebate/grant-settings', $values, 'POST');
  245. $this->assertSame(-3, (new RewardGrantSettings())->saveRebate()->getData(true)['code']);
  246. $this->assertSame(0, RewardGrantSettingsService::get('rebate')['auto_enabled']);
  247. $this->assertSame('03:00', RewardGrantSettingsService::get('rebate')['grant_time']);
  248. }
  249. public static function invalidSettings(): array
  250. {
  251. return [[[]], [['auto_enabled' => 2]], [['auto_enabled' => 'auto']], [['auto_enabled' => 1]],
  252. [['auto_enabled' => true]], [['auto_enabled' => 1, 'grant_time' => '']],
  253. [['auto_enabled' => 1, 'grant_time' => '24:00']], [['auto_enabled' => 1, 'grant_time' => '9:00']],
  254. [['auto_enabled' => 1, 'grant_time' => '12:60']], [['auto_enabled' => 0, 'grant_time' => ['03:00']]]];
  255. }
  256. public function test_exact_minute_pays_both_types_once_and_retries_do_not_duplicate_wallet_or_ledger(): void
  257. {
  258. $rebate = $this->rebate(); $backflow = $this->backflow();
  259. $this->rebate(['date' => '2026-10-25']); $this->backflow(['date' => '2026-10']);
  260. $this->rebate(['status' => 1]); $this->backflow(['status' => 1]);
  261. $this->enable('rebate'); $this->enable('backflow');
  262. Carbon::setTestNow(Carbon::parse('2026-10-25 14:29:59', 'Asia/Shanghai'));
  263. $this->assertSame(0, $this->runRewards()['rebate']['granted']);
  264. $this->assertSame(0, DB::table('balance_logs')->count());
  265. Carbon::setTestNow(Carbon::parse('2026-10-25 14:30:00', 'Asia/Shanghai'));
  266. $result = $this->runRewards();
  267. $this->assertSame(1, $result['rebate']['granted']); $this->assertSame(1, $result['backflow']['granted']);
  268. $this->assertEquals(59, DB::table('wallets')->value('available_balance'));
  269. $this->assertEquals(4, DB::table('rebates')->where('id', $rebate)->value('amount'));
  270. $this->assertEquals(35, DB::table('backflow')->where('id', $backflow)->value('amount'));
  271. $this->assertSame('system:auto-grant', DB::table('rebates')->where('id', $rebate)->value('audited_by'));
  272. $this->assertSame(now()->timestamp, DB::table('backflow')->where('id', $backflow)->value('grant_time'));
  273. $this->assertSame(2, DB::table('balance_logs')->count());
  274. $this->assertSame(0, $this->runRewards()['rebate']['granted']);
  275. $this->assertSame(2, DB::table('balance_logs')->count());
  276. $this->assertEquals(59, DB::table('wallets')->value('available_balance'));
  277. }
  278. public function test_scheduled_cutoffs_keep_new_york_days_and_shanghai_months_even_when_catching_up_later(): void
  279. {
  280. Carbon::setTestNow(Carbon::parse('2026-11-01 03:00:00', 'Asia/Shanghai'));
  281. $old = $this->rebate(['date' => '2026-10-30']);
  282. $notYetEndedAtSchedule = $this->rebate(['date' => '2026-10-31']);
  283. $lastMonth = $this->backflow(['date' => '2026-10']);
  284. $currentMonth = $this->backflow(['date' => '2026-11']);
  285. $this->enable('rebate', '03:00'); $this->enable('backflow', '03:00');
  286. // At 14:00 the New York day has changed, but this run still belongs to the 03:00 schedule.
  287. Carbon::setTestNow(Carbon::parse('2026-11-01 14:00:00', 'Asia/Shanghai'));
  288. $this->runRewards();
  289. $this->assertSame(1, DB::table('rebates')->where('id', $old)->value('status'));
  290. $this->assertSame(0, DB::table('rebates')->where('id', $notYetEndedAtSchedule)->value('status'));
  291. $this->assertSame(1, DB::table('backflow')->where('id', $lastMonth)->value('status'));
  292. $this->assertSame(0, DB::table('backflow')->where('id', $currentMonth)->value('status'));
  293. Carbon::setTestNow(Carbon::parse('2026-11-02 02:59:59', 'Asia/Shanghai'));
  294. $this->assertSame(0, $this->runRewards()['rebate']['granted']);
  295. Carbon::setTestNow(Carbon::parse('2026-11-02 03:00:00', 'Asia/Shanghai'));
  296. $this->assertSame(1, $this->runRewards()['rebate']['granted']);
  297. $this->assertSame(1, DB::table('rebates')->where('id', $notYetEndedAtSchedule)->value('status'));
  298. }
  299. public function test_disabled_switch_stops_auto_but_both_manual_controllers_still_work_and_stale_calls_cannot_pay_twice(): void
  300. {
  301. $id = $this->rebate(); $backflow = $this->backflow();
  302. $stale = Rebate::findOrFail($id);
  303. $this->enable('rebate');
  304. RewardGrantSettingsService::save('rebate', ['auto_enabled' => 0]);
  305. $this->assertSame(0, $this->runRewards()['rebate']['granted']);
  306. $this->request('/admin/rebate/submit', ['id' => $id], 'POST');
  307. $this->assertSame(0, (new RebateController())->store()->getData(true)['code']);
  308. $this->assertSame(-3, (new RebateController())->store()->getData(true)['code']);
  309. $this->assertSame('operator-one', DB::table('rebates')->where('id', $id)->value('audited_by'));
  310. $this->request('/admin/backflow/grant', ['id' => $backflow], 'POST');
  311. $this->assertSame(0, (new BackflowController())->grant()->getData(true)['code']);
  312. $this->assertSame(-3, (new BackflowController())->grant()->getData(true)['code']);
  313. $this->enable('rebate'); $this->enable('backflow');
  314. $this->runRewards();
  315. $this->assertFalse(RewardGrantService::grant('rebate', $id, 'auto', true));
  316. $this->assertSame(2, DB::table('balance_logs')->count());
  317. try { RebateService::BibiReturn($stale, '999999'); $this->fail('A stale row must not pay again'); }
  318. catch (\RuntimeException $e) { $this->assertSame(-3, $e->getCode()); }
  319. $this->assertEquals(59, DB::table('wallets')->value('available_balance'));
  320. }
  321. public function test_payout_reads_fresh_effective_bet_and_zero_rewards_are_finalized_without_ledger_credits(): void
  322. {
  323. $id = $this->rebate(); $stale = Rebate::findOrFail($id);
  324. DB::table('rebates')->where('id', $id)->update(['effective_betting_amount' => 100]);
  325. RebateService::BibiReturn($stale, '800');
  326. $this->assertEquals(0.5, DB::table('rebates')->where('id', $id)->value('amount'));
  327. $this->rebate(['effective_betting_amount' => 0]);
  328. $below = $this->backflow(['recharge_amount' => 50, 'withdrawal_amount' => 0]);
  329. $this->enable('rebate'); $this->enable('backflow'); $this->runRewards();
  330. $this->assertSame(1, DB::table('backflow')->where('id', $below)->value('status'));
  331. $this->assertEquals(0, DB::table('backflow')->where('id', $below)->value('amount'));
  332. $this->assertSame(1, DB::table('balance_logs')->count());
  333. $this->assertEquals(20.5, DB::table('wallets')->value('available_balance'));
  334. }
  335. public function test_ledger_failure_rolls_back_wallet_and_reward_then_automatic_retry_credits_once(): void
  336. {
  337. $id = $this->rebate(); $this->enable('rebate');
  338. DB::statement("CREATE TRIGGER reject_reward_ledger BEFORE INSERT ON bot_balance_logs BEGIN SELECT RAISE(ABORT, 'ledger unavailable'); END");
  339. $this->assertSame(1, $this->runRewards()['rebate']['failed']);
  340. $this->assertEquals(20, DB::table('wallets')->value('available_balance'));
  341. $this->assertSame(0, DB::table('rebates')->where('id', $id)->value('status'));
  342. $this->assertSame(0, DB::table('rebates')->where('id', $id)->value('grant_time'));
  343. $this->assertSame(0, DB::table('balance_logs')->count());
  344. DB::statement('DROP TRIGGER reject_reward_ledger');
  345. $this->assertSame(1, $this->runRewards()['rebate']['granted']);
  346. $this->assertEquals(24, DB::table('wallets')->value('available_balance'));
  347. $this->assertSame(1, DB::table('balance_logs')->count());
  348. }
  349. public function test_status_save_failure_rolls_back_backflow_wallet_and_ledger_and_missing_wallet_does_not_stop_other_rows(): void
  350. {
  351. $id = $this->backflow(); $this->enable('backflow');
  352. DB::statement("CREATE TRIGGER reject_backflow_status BEFORE UPDATE ON bot_backflow BEGIN SELECT RAISE(ABORT, 'reward unavailable'); END");
  353. $this->assertSame(1, $this->runRewards()['backflow']['failed']);
  354. $this->assertSame(0, DB::table('backflow')->where('id', $id)->value('status'));
  355. $this->assertSame(0, DB::table('balance_logs')->count());
  356. $this->assertEquals(20, DB::table('wallets')->value('available_balance'));
  357. DB::statement('DROP TRIGGER reject_backflow_status');
  358. $bad = $this->rebate(['member_id' => 'no-wallet']); $good = $this->rebate(); $this->enable('rebate');
  359. $result = $this->runRewards();
  360. $this->assertSame(1, $result['rebate']['failed']); $this->assertSame(1, $result['rebate']['granted']);
  361. $this->assertSame(0, DB::table('rebates')->where('id', $bad)->value('status'));
  362. $this->assertSame(1, DB::table('rebates')->where('id', $good)->value('status'));
  363. $this->assertSame(1, $result['backflow']['granted']);
  364. }
  365. public function test_switch_and_time_are_rechecked_between_records_and_before_retrying(): void
  366. {
  367. $this->rebate(); $second = $this->rebate(); $this->enable('rebate');
  368. $changed = false;
  369. $this->app['db']->connection()->listen(function ($event) use (&$changed) {
  370. if (!$changed && str_starts_with(strtolower($event->sql), 'update "bot_rebates"')) {
  371. $changed = true;
  372. RewardGrantSettingsService::save('rebate', ['auto_enabled' => 0]);
  373. }
  374. });
  375. $this->assertSame(1, $this->runRewards()['rebate']['granted']);
  376. $this->assertSame(0, DB::table('rebates')->where('id', $second)->value('status'));
  377. $this->assertSame(1, DB::table('balance_logs')->count());
  378. $this->enable('rebate', '15:00');
  379. $this->assertSame(0, $this->runRewards()['rebate']['granted']);
  380. Carbon::setTestNow(Carbon::parse('2026-10-25 15:00:00', 'Asia/Shanghai'));
  381. $this->assertSame(1, $this->runRewards()['rebate']['granted']);
  382. }
  383. public function test_chunked_processing_does_not_skip_rows_and_command_reports_failure_without_forcing_disabled_rewards(): void
  384. {
  385. for ($i = 0; $i < 105; ++$i) $this->rebate(['effective_betting_amount' => 0]);
  386. $command = new AutoGrantRewards(); $command->setLaravel($this->app);
  387. $tester = new CommandTester($command);
  388. $tester->execute([]);
  389. $this->assertSame(0, $tester->getStatusCode());
  390. $this->assertSame(105, DB::table('rebates')->where('status', 0)->count());
  391. $this->enable('rebate'); $tester->execute([]);
  392. $this->assertSame(0, $tester->getStatusCode());
  393. $this->assertStringContainsString('"granted":105', $tester->getDisplay());
  394. $this->assertSame(105, DB::table('rebates')->where('status', 1)->count());
  395. $this->rebate(['member_id' => 'missing']); $tester->execute([]);
  396. $this->assertSame(1, $tester->getStatusCode());
  397. }
  398. public function test_rules_api_lists_categories_and_levels_replaces_one_category_and_rejects_bad_tiers(): void
  399. {
  400. $body = (new RewardRules())->rebate()->getData(true);
  401. $this->assertSame(0, $body['code']);
  402. $this->assertContains(['value' => 'third:1', 'label' => '真人'], $body['data']['categories']);
  403. $this->assertSame([['level' => 1, 'level_name' => 'VIP1'], ['level' => 2, 'level_name' => 'VIP2']], $body['data']['levels']);
  404. $this->assertSame([], $body['data']['rules']['third:2']);
  405. $this->request('/admin/rebate/rules', ['category' => 'third:2', 'rules' => [
  406. ['level' => 2, 'min_effective_amount' => 1000, 'percentage' => '1', 'turnover_multiple' => 3],
  407. ['level' => 2, 'min_effective_amount' => 0, 'percentage' => '0.5', 'turnover_multiple' => 0],
  408. ]], 'POST');
  409. $body = (new RewardRules())->saveRebate()->getData(true);
  410. $this->assertSame(0, $body['code']);
  411. $this->assertSame(['0.00', '1000.00'], array_column($body['data']['rules']['third:2'], 'min_effective_amount'));
  412. $this->assertSame('3.00', $body['data']['rules']['third:2'][1]['turnover_multiple']);
  413. $this->assertCount(1, $body['data']['rules']['self:lottery']);
  414. foreach ([['category' => 'third:9', 'rules' => []],
  415. ['category' => 'third:2', 'rules' => [['level' => 7, 'min_effective_amount' => 0, 'percentage' => 1, 'turnover_multiple' => 0]]],
  416. ['category' => 'third:2', 'rules' => [['level' => 1, 'min_effective_amount' => '1e3', 'percentage' => 1, 'turnover_multiple' => 0]]],
  417. ['category' => 'third:2', 'rules' => [['level' => 1, 'min_effective_amount' => 0, 'percentage' => 101, 'turnover_multiple' => 0]]],
  418. ['category' => 'third:2', 'rules' => [['level' => 1, 'min_effective_amount' => 5, 'percentage' => 1, 'turnover_multiple' => 0],
  419. ['level' => 1, 'min_effective_amount' => 5, 'percentage' => 2, 'turnover_multiple' => 0]]]] as $bad) {
  420. $this->request('/admin/rebate/rules', $bad, 'POST');
  421. $this->assertSame(-3, (new RewardRules())->saveRebate()->getData(true)['code']);
  422. }
  423. $this->assertSame(2, DB::table('rebate_rules')->where('category', 'third:2')->count());
  424. $this->request('/admin/backflow/rules', ['category' => 'third:1', 'rules' => [
  425. ['min_loss_amount' => 2000, 'reward_amount' => 60, 'turnover_multiple' => 2]]], 'POST');
  426. $body = (new RewardRules())->saveBackflow()->getData(true);
  427. $this->assertSame([['id' => 2, 'category' => 'third:1', 'min_loss_amount' => '2000.00', 'reward_amount' => '60.00',
  428. 'turnover_multiple' => '2.00']], $body['data']['rules']['third:1']);
  429. $this->request('/admin/backflow/rules', ['category' => 'third:1', 'rules' => []], 'POST');
  430. $this->assertSame(0, (new RewardRules())->saveBackflow()->getData(true)['code']);
  431. $this->assertSame(0, DB::table('backflow_rules')->where('category', 'third:1')->count());
  432. $router = new Router(new Dispatcher($this->app), $this->app);
  433. $this->app->instance('router', $router);
  434. $router->group(['prefix' => 'admin'], function () { require dirname(__DIR__, 2) . '/routes/admin.php'; });
  435. foreach (['rebate' => 'submit', 'backflow' => 'grant'] as $type => $permission) {
  436. foreach (['GET', 'POST'] as $method) {
  437. $route = $router->getRoutes()->match(Request::create('/admin/' . $type . '/rules', $method));
  438. $this->assertContains('check.button.uri', $route->middleware());
  439. $this->assertSame('admin/' . $type . '/' . $permission, $route->defaults['permission_uri']);
  440. }
  441. }
  442. }
  443. public function test_rebate_sums_every_category_by_new_york_day_and_uses_the_members_level_tier_and_turnover(): void
  444. {
  445. $this->user('2001', 2);
  446. DB::table('wallets')->insert(['member_id' => '2001', 'available_balance' => '0']);
  447. DB::table('rebate_rules')->insert([
  448. ['category' => 'third:2', 'level' => 2, 'min_effective_amount' => 0, 'percentage' => '0.5', 'turnover_multiple' => 0],
  449. ['category' => 'third:2', 'level' => 2, 'min_effective_amount' => 1000, 'percentage' => '1', 'turnover_multiple' => 3],
  450. ['category' => 'third:2', 'level' => 1, 'min_effective_amount' => 0, 'percentage' => '2', 'turnover_multiple' => 0],
  451. ['category' => 'self:sport', 'level' => 2, 'min_effective_amount' => 500, 'percentage' => '1', 'turnover_multiple' => 0],
  452. ]);
  453. // New York 2026-10-23 is Shanghai 2026-10-23 12:00 to 2026-10-24 11:59:59.
  454. $this->fact('2001', 'third:2', '2026-10-23 20:00:00', '1000', '-1000');
  455. $this->fact('2001', 'third:2', '2026-10-24 10:00:00', '500', '500');
  456. $this->fact('2001', 'self:sport', '2026-10-24 11:00:00', '300', '-300');
  457. $this->fact('2001', 'third:2', '2026-10-24 11:30:00', '9999', '0', ['voided' => 1]);
  458. $this->fact('2001', 'third:2', '2026-10-24 13:00:00', '7777', '-7777');
  459. $this->assertSame(['rebates' => 2, 'backflow' => 1, 'failed' => 0], (new RewardBaseSyncService())->run());
  460. $row = DB::table('rebates')->where('member_id', '2001')->where('date', '2026-10-23')->first();
  461. $this->assertEquals(1800, $row->betting_amount);
  462. $this->assertEquals(1800, $row->effective_betting_amount);
  463. $this->assertEquals(15, $row->amount);
  464. $this->assertEquals(45, $row->need_flow);
  465. $this->assertSame(['self:sport', 'third:2'], array_column(json_decode($row->details, true), 'category'));
  466. $this->assertTrue(RewardGrantService::grant('rebate', (int) $row->id, 'operator-one'));
  467. $this->assertEquals(15, DB::table('wallets')->where('member_id', '2001')->value('available_balance'));
  468. $bonus = DB::table('wallet_bonus')->first();
  469. $this->assertSame('2001', $bonus->member_id);
  470. $this->assertEquals(45, $bonus->need_flow);
  471. $this->assertEquals(15, $bonus->amount);
  472. $this->assertSame((int) $row->id, (int) $bonus->related_id);
  473. $this->assertStringContainsString('电子:1500.00×1.0000%', DB::table('balance_logs')->value('remark'));
  474. // A paid day is never rewritten by later facts.
  475. $this->fact('2001', 'third:2', '2026-10-24 09:00:00', '100', '-100');
  476. (new RewardBaseSyncService())->run();
  477. $this->assertEquals(1800, DB::table('rebates')->where('id', $row->id)->value('effective_betting_amount'));
  478. $this->assertSame(1, DB::table('wallet_bonus')->count());
  479. }
  480. public function test_backflow_pays_fixed_rewards_for_each_categorys_monthly_net_loss(): void
  481. {
  482. $this->user('2001');
  483. DB::table('wallets')->insert(['member_id' => '2001', 'available_balance' => '0']);
  484. DB::table('backflow_rules')->insert([
  485. ['category' => 'third:1', 'min_loss_amount' => 1000, 'reward_amount' => 20, 'turnover_multiple' => 0],
  486. ['category' => 'third:1', 'min_loss_amount' => 2000, 'reward_amount' => 60, 'turnover_multiple' => 2],
  487. ['category' => 'third:2', 'min_loss_amount' => 0, 'reward_amount' => 99, 'turnover_multiple' => 0],
  488. ['category' => 'self:sport', 'min_loss_amount' => 100, 'reward_amount' => 5, 'turnover_multiple' => 0],
  489. ]);
  490. $this->fact('2001', 'third:1', '2026-09-03 10:00:00', '2000', '-2000');
  491. $this->fact('2001', 'third:1', '2026-09-28 10:00:00', '500', '-500');
  492. $this->fact('2001', 'third:2', '2026-09-05 10:00:00', '100', '100');
  493. $this->fact('2001', 'self:sport', '2026-09-30 23:00:00', '50', '-50');
  494. $this->fact('2001', 'self:sport', '2026-10-01 00:30:00', '900', '-900');
  495. (new RewardBaseSyncService())->run();
  496. $row = DB::table('backflow')->where('member_id', '2001')->where('date', '2026-09')->first();
  497. $this->assertEquals(2550, $row->loss_amount);
  498. $this->assertEquals(60, $row->amount);
  499. $this->assertTrue(RewardGrantService::grant('backflow', (int) $row->id, 'operator-one'));
  500. $this->assertEquals(60, DB::table('wallets')->where('member_id', '2001')->value('available_balance'));
  501. $this->assertEquals(120, DB::table('wallet_bonus')->value('need_flow'));
  502. $this->assertEquals(120, DB::table('backflow')->where('id', $row->id)->value('need_flow'));
  503. }
  504. public function test_sync_cursor_only_revisits_changed_facts_and_backfill_range_creates_missing_rows(): void
  505. {
  506. $this->fact('3001', 'third:1', '2026-10-20 13:00:00', '100', '-100', ['updated_at' => '2026-10-20 13:00:00']);
  507. $this->assertSame(0, (new RewardBaseSyncService())->run()['rebates']);
  508. $this->assertSame(['rebates' => 1, 'backflow' => 1, 'failed' => 0], (new RewardBaseSyncService())->run('2026-10-20', '2026-10-20'));
  509. $this->assertEquals(100, DB::table('rebates')->where('member_id', '3001')->value('effective_betting_amount'));
  510. $this->assertNotNull(DB::table('share_system_state')->where('key', 'reward_bases_cursor')->value('value'));
  511. $this->expectException(\InvalidArgumentException::class);
  512. (new RewardBaseSyncService())->run('2026-10-20', null);
  513. }
  514. public function test_rules_migration_removes_the_three_global_settings_and_rollback_restores_them(): void
  515. {
  516. $this->assertSame(['huishui_restriction'], DB::table('config')->pluck('field')->all());
  517. $this->assertTrue(Schema::hasColumns('rebates', ['details', 'need_flow']));
  518. $this->rulesMigration()->down();
  519. $this->assertEqualsCanonicalizing(['rebate', 'huishui_restriction', 'huishui_percentage'], DB::table('config')->pluck('field')->all());
  520. $this->assertSame('0.005', DB::table('config')->where('field', 'rebate')->value('val'));
  521. $this->assertFalse(Schema::hasTable('rebate_rules'));
  522. $this->assertFalse(Schema::hasColumn('backflow', 'loss_amount'));
  523. }
  524. }