AutomaticRewardGrantTest.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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\Models\Rebate;
  8. use App\Services\AutomaticRewardGrantService;
  9. use App\Services\BackflowService;
  10. use App\Services\RebateService;
  11. use App\Services\RewardGrantService;
  12. use App\Services\RewardGrantSettingsService;
  13. use Carbon\Carbon;
  14. use Illuminate\Config\Repository;
  15. use Illuminate\Database\Capsule\Manager;
  16. use Illuminate\Database\Schema\Blueprint;
  17. use Illuminate\Events\Dispatcher;
  18. use Illuminate\Foundation\Application;
  19. use Illuminate\Http\JsonResponse;
  20. use Illuminate\Http\Request;
  21. use Illuminate\Routing\Router;
  22. use Illuminate\Support\Facades\DB;
  23. use Illuminate\Support\Facades\Facade;
  24. use Illuminate\Support\Facades\Schema;
  25. use Illuminate\Translation\ArrayLoader;
  26. use Illuminate\Translation\Translator;
  27. use Illuminate\Validation\Factory;
  28. use PHPUnit\Framework\Attributes\DataProvider;
  29. use PHPUnit\Framework\TestCase;
  30. use Symfony\Component\Console\Tester\CommandTester;
  31. /** Real payout controllers, command, wallets and ledgers; no project boot, .env or live database. */
  32. class AutomaticRewardGrantTest extends TestCase
  33. {
  34. private Application $app;
  35. protected function setUp(): void
  36. {
  37. parent::setUp();
  38. Carbon::setTestNow(Carbon::parse('2026-10-25 14:30:00', 'Asia/Shanghai'));
  39. Facade::clearResolvedInstances();
  40. $this->app = new Application(dirname(__DIR__, 2));
  41. $this->app->instance('config', new Repository(['app' => ['locale' => 'zh', 'timezone' => 'Asia/Shanghai']]));
  42. Facade::setFacadeApplication($this->app);
  43. $db = new Manager($this->app);
  44. $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'bot_']);
  45. $db->setEventDispatcher(new Dispatcher($this->app));
  46. $db->setAsGlobal(); $db->bootEloquent();
  47. $this->app->instance('db', $db->getDatabaseManager());
  48. $this->app->bind('db.schema', fn () => $db->schema());
  49. $translator = new Translator(new ArrayLoader(), 'zh');
  50. $this->app->instance('translator', $translator);
  51. $this->app->instance('validator', new Factory($translator, $this->app));
  52. $this->app->instance('log', new \Psr\Log\NullLogger());
  53. $this->app->instance(\Illuminate\Contracts\Routing\ResponseFactory::class, new \Tests\Support\JsonResponseFactory());
  54. Request::macro('validate', function (array $rules) {
  55. return app('validator')->make($this->all(), $rules)->validate();
  56. });
  57. Schema::create('config', function (Blueprint $t) { $t->id(); $t->string('field'); $t->string('val'); });
  58. DB::table('config')->insert([
  59. ['field' => 'rebate', 'val' => '0.005'],
  60. ['field' => 'huishui_restriction', 'val' => '100'],
  61. ['field' => 'huishui_percentage', 'val' => '0.05'],
  62. ]);
  63. Schema::create('wallets', function (Blueprint $t) {
  64. $t->id(); $t->string('member_id'); $t->decimal('available_balance', 24, 10)->default(0); $t->timestamps();
  65. });
  66. DB::table('wallets')->insert(['member_id' => '1001', 'available_balance' => '20.00']);
  67. Schema::create('balance_logs', function (Blueprint $t) {
  68. $t->id(); $t->string('member_id'); $t->string('change_type'); $t->unsignedBigInteger('related_id');
  69. foreach (['amount', 'before_balance', 'after_balance'] as $field) $t->decimal($field, 24, 10);
  70. $t->string('remark'); $t->timestamps();
  71. });
  72. Schema::create('rebates', function (Blueprint $t) {
  73. $t->id(); $t->string('member_id'); $t->string('date');
  74. $t->decimal('betting_amount', 24, 2); $t->decimal('effective_betting_amount', 24, 2);
  75. $t->decimal('rebate_ratio', 12, 4)->default(0); $t->decimal('amount', 24, 2)->default(0);
  76. $t->integer('status')->default(0); $t->string('audited_by')->nullable(); $t->bigInteger('grant_time')->default(0); $t->timestamps();
  77. });
  78. Schema::create('backflow', function (Blueprint $t) {
  79. $t->id(); $t->string('member_id'); $t->string('date');
  80. foreach (['recharge_amount', 'withdrawal_amount', 'backflow_ratio', 'amount'] as $field) $t->decimal($field, 24, 4)->default(0);
  81. $t->integer('status')->default(0); $t->bigInteger('grant_time')->default(0); $t->timestamps();
  82. });
  83. $this->migration()->up();
  84. $this->request('/admin/rebate');
  85. }
  86. protected function tearDown(): void
  87. {
  88. Carbon::setTestNow(); DB::disconnect(); Facade::clearResolvedInstances();
  89. parent::tearDown();
  90. }
  91. private function migration()
  92. {
  93. return require dirname(__DIR__, 2) . '/database/migrations/2026_10_25_180000_create_reward_grant_settings.php';
  94. }
  95. private function request(string $path, array $params = [], string $method = 'GET'): void
  96. {
  97. $request = Request::create($path, $method, $params);
  98. $request->user = (object) ['id' => 1, 'username' => 'operator-one'];
  99. $this->app->instance('request', $request);
  100. }
  101. private function rebate(array $values = []): int
  102. {
  103. return DB::table('rebates')->insertGetId($values + ['member_id' => '1001', 'date' => '2026-10-23',
  104. 'betting_amount' => '1000.00', 'effective_betting_amount' => '800.00']);
  105. }
  106. private function backflow(array $values = []): int
  107. {
  108. return DB::table('backflow')->insertGetId($values + ['member_id' => '1001', 'date' => '2026-09',
  109. 'recharge_amount' => '1000.00', 'withdrawal_amount' => '-300.00']);
  110. }
  111. private function enable(string $type, string $time = '14:30'): void
  112. {
  113. RewardGrantSettingsService::save($type, ['auto_enabled' => 1, 'grant_time' => $time]);
  114. }
  115. private function runRewards(): array { return (new AutomaticRewardGrantService())->run(); }
  116. public function test_console_scheduler_registers_the_automatic_payout_command_every_minute_with_overlap_protection(): void
  117. {
  118. $this->app['config']->set('cache', ['default' => 'array', 'stores' => ['array' => ['driver' => 'array']]]);
  119. $this->app->register(\Illuminate\Cache\CacheServiceProvider::class);
  120. $schedule = new \Illuminate\Console\Scheduling\Schedule('Asia/Shanghai');
  121. $kernel = new \App\Console\Kernel($this->app, new Dispatcher($this->app));
  122. $method = new \ReflectionMethod($kernel, 'schedule');
  123. $method->setAccessible(true);
  124. $method->invoke($kernel, $schedule);
  125. $events = array_values(array_filter($schedule->events(), fn ($event) => str_contains($event->command ?? '', 'rewards:auto-grant')));
  126. $this->assertCount(1, $events);
  127. $this->assertSame('* * * * *', $events[0]->expression);
  128. $this->assertTrue($events[0]->withoutOverlapping);
  129. $this->assertSame(60, $events[0]->expiresAt);
  130. }
  131. public function test_migration_defaults_to_manual_and_both_settings_routes_keep_admin_and_existing_grant_permissions(): void
  132. {
  133. $id = $this->rebate(); $this->backflow();
  134. foreach (['rebate', 'backflow'] as $type) {
  135. $this->assertSame(['type' => $type, 'auto_enabled' => 0, 'grant_time' => '03:00', 'timezone' => 'Asia/Shanghai'], RewardGrantSettingsService::get($type));
  136. }
  137. $this->assertSame(0, $this->runRewards()['rebate']['granted']);
  138. $this->assertSame(0, DB::table('rebates')->where('id', $id)->value('status'));
  139. $this->assertSame(0, DB::table('balance_logs')->count());
  140. $router = new Router(new Dispatcher($this->app), $this->app);
  141. $this->app->instance('router', $router);
  142. $router->group(['prefix' => 'admin'], function () { require dirname(__DIR__, 2) . '/routes/admin.php'; });
  143. foreach (['rebate' => 'submit', 'backflow' => 'grant'] as $type => $permission) {
  144. foreach (['GET', 'POST'] as $method) {
  145. $route = $router->getRoutes()->match(Request::create('/admin/' . $type . '/grant-settings', $method));
  146. $this->assertContains('admin.jwt', $route->middleware());
  147. $this->assertContains('check.button.uri', $route->middleware());
  148. $this->assertSame('admin/' . $type . '/' . $permission, $route->defaults['permission_uri']);
  149. }
  150. }
  151. $this->migration()->down();
  152. $this->assertFalse(Schema::hasTable('reward_grant_settings'));
  153. }
  154. public function test_settings_api_persists_independent_times_and_disabling_preserves_the_previous_time_without_paying(): void
  155. {
  156. $this->rebate();
  157. $this->request('/admin/rebate/grant-settings', ['auto_enabled' => true, 'grant_time' => '14:30'], 'POST');
  158. $body = (new RewardGrantSettings())->saveRebate()->getData(true);
  159. $this->assertSame(0, $body['code']);
  160. $this->assertSame(1, $body['data']['auto_enabled']);
  161. $this->assertSame('14:30', $body['data']['grant_time']);
  162. $this->assertSame(0, RewardGrantSettingsService::get('backflow')['auto_enabled']);
  163. $this->request('/admin/backflow/grant-settings', ['auto_enabled' => 1, 'grant_time' => '20:15'], 'POST');
  164. $this->assertSame(0, (new RewardGrantSettings())->saveBackflow()->getData(true)['code']);
  165. $this->assertSame('20:15', RewardGrantSettingsService::get('backflow')['grant_time']);
  166. $this->request('/admin/rebate/grant-settings', ['auto_enabled' => 0], 'POST');
  167. $body = (new RewardGrantSettings())->saveRebate()->getData(true);
  168. $this->assertSame(0, $body['data']['auto_enabled']);
  169. $this->assertSame('14:30', $body['data']['grant_time']);
  170. $this->assertSame(0, DB::table('balance_logs')->count());
  171. $this->assertSame(0, (new RewardGrantSettings())->rebate()->getData(true)['code']);
  172. }
  173. #[DataProvider('invalidSettings')]
  174. public function test_invalid_settings_do_not_change_the_switch_or_time(array $values): void
  175. {
  176. $this->request('/admin/rebate/grant-settings', $values, 'POST');
  177. $this->assertSame(-3, (new RewardGrantSettings())->saveRebate()->getData(true)['code']);
  178. $this->assertSame(0, RewardGrantSettingsService::get('rebate')['auto_enabled']);
  179. $this->assertSame('03:00', RewardGrantSettingsService::get('rebate')['grant_time']);
  180. }
  181. public static function invalidSettings(): array
  182. {
  183. return [[[]], [['auto_enabled' => 2]], [['auto_enabled' => 'auto']], [['auto_enabled' => 1]],
  184. [['auto_enabled' => true]], [['auto_enabled' => 1, 'grant_time' => '']],
  185. [['auto_enabled' => 1, 'grant_time' => '24:00']], [['auto_enabled' => 1, 'grant_time' => '9:00']],
  186. [['auto_enabled' => 1, 'grant_time' => '12:60']], [['auto_enabled' => 0, 'grant_time' => ['03:00']]]];
  187. }
  188. public function test_exact_minute_pays_both_types_once_and_retries_do_not_duplicate_wallet_or_ledger(): void
  189. {
  190. $rebate = $this->rebate(); $backflow = $this->backflow();
  191. $this->rebate(['date' => '2026-10-25']); $this->backflow(['date' => '2026-10']);
  192. $this->rebate(['status' => 1]); $this->backflow(['status' => 1]);
  193. $this->enable('rebate'); $this->enable('backflow');
  194. Carbon::setTestNow(Carbon::parse('2026-10-25 14:29:59', 'Asia/Shanghai'));
  195. $this->assertSame(0, $this->runRewards()['rebate']['granted']);
  196. $this->assertSame(0, DB::table('balance_logs')->count());
  197. Carbon::setTestNow(Carbon::parse('2026-10-25 14:30:00', 'Asia/Shanghai'));
  198. $result = $this->runRewards();
  199. $this->assertSame(1, $result['rebate']['granted']); $this->assertSame(1, $result['backflow']['granted']);
  200. $this->assertEquals(59, DB::table('wallets')->value('available_balance'));
  201. $this->assertEquals(4, DB::table('rebates')->where('id', $rebate)->value('amount'));
  202. $this->assertEquals(35, DB::table('backflow')->where('id', $backflow)->value('amount'));
  203. $this->assertSame('system:auto-grant', DB::table('rebates')->where('id', $rebate)->value('audited_by'));
  204. $this->assertSame(now()->timestamp, DB::table('backflow')->where('id', $backflow)->value('grant_time'));
  205. $this->assertSame(2, DB::table('balance_logs')->count());
  206. $this->assertSame(0, $this->runRewards()['rebate']['granted']);
  207. $this->assertSame(2, DB::table('balance_logs')->count());
  208. $this->assertEquals(59, DB::table('wallets')->value('available_balance'));
  209. }
  210. public function test_scheduled_cutoffs_keep_new_york_days_and_shanghai_months_even_when_catching_up_later(): void
  211. {
  212. Carbon::setTestNow(Carbon::parse('2026-11-01 03:00:00', 'Asia/Shanghai'));
  213. $old = $this->rebate(['date' => '2026-10-30']);
  214. $notYetEndedAtSchedule = $this->rebate(['date' => '2026-10-31']);
  215. $lastMonth = $this->backflow(['date' => '2026-10']);
  216. $currentMonth = $this->backflow(['date' => '2026-11']);
  217. $this->enable('rebate', '03:00'); $this->enable('backflow', '03:00');
  218. // At 14:00 the New York day has changed, but this run still belongs to the 03:00 schedule.
  219. Carbon::setTestNow(Carbon::parse('2026-11-01 14:00:00', 'Asia/Shanghai'));
  220. $this->runRewards();
  221. $this->assertSame(1, DB::table('rebates')->where('id', $old)->value('status'));
  222. $this->assertSame(0, DB::table('rebates')->where('id', $notYetEndedAtSchedule)->value('status'));
  223. $this->assertSame(1, DB::table('backflow')->where('id', $lastMonth)->value('status'));
  224. $this->assertSame(0, DB::table('backflow')->where('id', $currentMonth)->value('status'));
  225. Carbon::setTestNow(Carbon::parse('2026-11-02 02:59:59', 'Asia/Shanghai'));
  226. $this->assertSame(0, $this->runRewards()['rebate']['granted']);
  227. Carbon::setTestNow(Carbon::parse('2026-11-02 03:00:00', 'Asia/Shanghai'));
  228. $this->assertSame(1, $this->runRewards()['rebate']['granted']);
  229. $this->assertSame(1, DB::table('rebates')->where('id', $notYetEndedAtSchedule)->value('status'));
  230. }
  231. public function test_disabled_switch_stops_auto_but_both_manual_controllers_still_work_and_stale_calls_cannot_pay_twice(): void
  232. {
  233. $id = $this->rebate(); $backflow = $this->backflow();
  234. $stale = Rebate::findOrFail($id);
  235. $this->enable('rebate');
  236. RewardGrantSettingsService::save('rebate', ['auto_enabled' => 0]);
  237. $this->assertSame(0, $this->runRewards()['rebate']['granted']);
  238. $this->request('/admin/rebate/submit', ['id' => $id], 'POST');
  239. $this->assertSame(0, (new RebateController())->store()->getData(true)['code']);
  240. $this->assertSame(-3, (new RebateController())->store()->getData(true)['code']);
  241. $this->assertSame('operator-one', DB::table('rebates')->where('id', $id)->value('audited_by'));
  242. $this->request('/admin/backflow/grant', ['id' => $backflow], 'POST');
  243. $this->assertSame(0, (new BackflowController())->grant()->getData(true)['code']);
  244. $this->assertSame(-3, (new BackflowController())->grant()->getData(true)['code']);
  245. $this->enable('rebate'); $this->enable('backflow');
  246. $this->runRewards();
  247. $this->assertFalse(RewardGrantService::grant('rebate', $id, 'auto', true));
  248. $this->assertSame(2, DB::table('balance_logs')->count());
  249. try { RebateService::BibiReturn($stale, '999999'); $this->fail('A stale row must not pay again'); }
  250. catch (\RuntimeException $e) { $this->assertSame(-3, $e->getCode()); }
  251. $this->assertEquals(59, DB::table('wallets')->value('available_balance'));
  252. }
  253. public function test_payout_reads_fresh_effective_bet_and_zero_rewards_are_finalized_without_ledger_credits(): void
  254. {
  255. $id = $this->rebate(); $stale = Rebate::findOrFail($id);
  256. DB::table('rebates')->where('id', $id)->update(['effective_betting_amount' => 100]);
  257. RebateService::BibiReturn($stale, '800');
  258. $this->assertEquals(0.5, DB::table('rebates')->where('id', $id)->value('amount'));
  259. $this->rebate(['effective_betting_amount' => 0]);
  260. $below = $this->backflow(['recharge_amount' => 50, 'withdrawal_amount' => 0]);
  261. $this->enable('rebate'); $this->enable('backflow'); $this->runRewards();
  262. $this->assertSame(1, DB::table('backflow')->where('id', $below)->value('status'));
  263. $this->assertEquals(0, DB::table('backflow')->where('id', $below)->value('amount'));
  264. $this->assertSame(1, DB::table('balance_logs')->count());
  265. $this->assertEquals(20.5, DB::table('wallets')->value('available_balance'));
  266. }
  267. public function test_ledger_failure_rolls_back_wallet_and_reward_then_automatic_retry_credits_once(): void
  268. {
  269. $id = $this->rebate(); $this->enable('rebate');
  270. DB::statement("CREATE TRIGGER reject_reward_ledger BEFORE INSERT ON bot_balance_logs BEGIN SELECT RAISE(ABORT, 'ledger unavailable'); END");
  271. $this->assertSame(1, $this->runRewards()['rebate']['failed']);
  272. $this->assertEquals(20, DB::table('wallets')->value('available_balance'));
  273. $this->assertSame(0, DB::table('rebates')->where('id', $id)->value('status'));
  274. $this->assertSame(0, DB::table('rebates')->where('id', $id)->value('grant_time'));
  275. $this->assertSame(0, DB::table('balance_logs')->count());
  276. DB::statement('DROP TRIGGER reject_reward_ledger');
  277. $this->assertSame(1, $this->runRewards()['rebate']['granted']);
  278. $this->assertEquals(24, DB::table('wallets')->value('available_balance'));
  279. $this->assertSame(1, DB::table('balance_logs')->count());
  280. }
  281. public function test_status_save_failure_rolls_back_backflow_wallet_and_ledger_and_missing_wallet_does_not_stop_other_rows(): void
  282. {
  283. $id = $this->backflow(); $this->enable('backflow');
  284. DB::statement("CREATE TRIGGER reject_backflow_status BEFORE UPDATE ON bot_backflow BEGIN SELECT RAISE(ABORT, 'reward unavailable'); END");
  285. $this->assertSame(1, $this->runRewards()['backflow']['failed']);
  286. $this->assertSame(0, DB::table('backflow')->where('id', $id)->value('status'));
  287. $this->assertSame(0, DB::table('balance_logs')->count());
  288. $this->assertEquals(20, DB::table('wallets')->value('available_balance'));
  289. DB::statement('DROP TRIGGER reject_backflow_status');
  290. $bad = $this->rebate(['member_id' => 'no-wallet']); $good = $this->rebate(); $this->enable('rebate');
  291. $result = $this->runRewards();
  292. $this->assertSame(1, $result['rebate']['failed']); $this->assertSame(1, $result['rebate']['granted']);
  293. $this->assertSame(0, DB::table('rebates')->where('id', $bad)->value('status'));
  294. $this->assertSame(1, DB::table('rebates')->where('id', $good)->value('status'));
  295. $this->assertSame(1, $result['backflow']['granted']);
  296. }
  297. public function test_switch_and_time_are_rechecked_between_records_and_before_retrying(): void
  298. {
  299. $this->rebate(); $second = $this->rebate(); $this->enable('rebate');
  300. $changed = false;
  301. $this->app['db']->connection()->listen(function ($event) use (&$changed) {
  302. if (!$changed && str_starts_with(strtolower($event->sql), 'update "bot_rebates"')) {
  303. $changed = true;
  304. RewardGrantSettingsService::save('rebate', ['auto_enabled' => 0]);
  305. }
  306. });
  307. $this->assertSame(1, $this->runRewards()['rebate']['granted']);
  308. $this->assertSame(0, DB::table('rebates')->where('id', $second)->value('status'));
  309. $this->assertSame(1, DB::table('balance_logs')->count());
  310. $this->enable('rebate', '15:00');
  311. $this->assertSame(0, $this->runRewards()['rebate']['granted']);
  312. Carbon::setTestNow(Carbon::parse('2026-10-25 15:00:00', 'Asia/Shanghai'));
  313. $this->assertSame(1, $this->runRewards()['rebate']['granted']);
  314. }
  315. public function test_chunked_processing_does_not_skip_rows_and_command_reports_failure_without_forcing_disabled_rewards(): void
  316. {
  317. for ($i = 0; $i < 105; ++$i) $this->rebate(['effective_betting_amount' => 0]);
  318. $command = new AutoGrantRewards(); $command->setLaravel($this->app);
  319. $tester = new CommandTester($command);
  320. $tester->execute([]);
  321. $this->assertSame(0, $tester->getStatusCode());
  322. $this->assertSame(105, DB::table('rebates')->where('status', 0)->count());
  323. $this->enable('rebate'); $tester->execute([]);
  324. $this->assertSame(0, $tester->getStatusCode());
  325. $this->assertStringContainsString('"granted":105', $tester->getDisplay());
  326. $this->assertSame(105, DB::table('rebates')->where('status', 1)->count());
  327. $this->rebate(['member_id' => 'missing']); $tester->execute([]);
  328. $this->assertSame(1, $tester->getStatusCode());
  329. }
  330. }