AutomaticRewardGrantTest.php 20 KB

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