AutomaticRewardGrantTest.php 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  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 App\Services\SiteInboxService;
  16. use Carbon\Carbon;
  17. use Illuminate\Config\Repository;
  18. use Illuminate\Database\Capsule\Manager;
  19. use Illuminate\Database\Schema\Blueprint;
  20. use Illuminate\Events\Dispatcher;
  21. use Illuminate\Foundation\Application;
  22. use Illuminate\Http\JsonResponse;
  23. use Illuminate\Http\Request;
  24. use Illuminate\Routing\Router;
  25. use Illuminate\Support\Facades\DB;
  26. use Illuminate\Support\Facades\Facade;
  27. use Illuminate\Support\Facades\Schema;
  28. use Illuminate\Translation\ArrayLoader;
  29. use Illuminate\Translation\Translator;
  30. use Illuminate\Validation\Factory;
  31. use PHPUnit\Framework\Attributes\DataProvider;
  32. use PHPUnit\Framework\TestCase;
  33. use Symfony\Component\Console\Tester\CommandTester;
  34. /** Real payout controllers, command, wallets and ledgers; no project boot, .env or live database. */
  35. class AutomaticRewardGrantTest extends TestCase
  36. {
  37. private Application $app;
  38. protected function setUp(): void
  39. {
  40. parent::setUp();
  41. Carbon::setTestNow(Carbon::parse('2026-10-25 14:30:00', 'Asia/Shanghai'));
  42. Facade::clearResolvedInstances();
  43. $this->app = new Application(dirname(__DIR__, 2));
  44. $this->app->instance('config', new Repository(['app' => ['locale' => 'zh', 'timezone' => 'Asia/Shanghai']]));
  45. Facade::setFacadeApplication($this->app);
  46. $db = new Manager($this->app);
  47. $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'bot_']);
  48. $db->setEventDispatcher(new Dispatcher($this->app));
  49. $db->setAsGlobal(); $db->bootEloquent();
  50. $this->app->instance('db', $db->getDatabaseManager());
  51. $this->app->bind('db.schema', fn () => $db->schema());
  52. $translator = new Translator(new ArrayLoader(), 'zh');
  53. $this->app->instance('translator', $translator);
  54. $this->app->instance('validator', new Factory($translator, $this->app));
  55. $this->app->instance('log', new \Psr\Log\NullLogger());
  56. $this->app->instance(\Illuminate\Contracts\Routing\ResponseFactory::class, new \Tests\Support\JsonResponseFactory());
  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('users', function (Blueprint $t) {
  67. $t->id(); $t->string('member_id')->unique(); $t->integer('level')->default(1);
  68. $t->string('username')->default(''); $t->string('first_name')->default('');
  69. $t->string('language')->nullable()->default('zh');
  70. });
  71. Schema::create('agents', function (Blueprint $t) { $t->id(); });
  72. Schema::create('operation_audits', function (Blueprint $t) {
  73. $t->id(); $t->string('resource_type'); $t->integer('resource_id'); $t->string('action'); $t->json('changes');
  74. $t->integer('operator_id')->nullable(); $t->string('operator_name'); $t->dateTime('created_at');
  75. });
  76. (require dirname(__DIR__, 2) . '/database/migrations/2026_10_26_110000_create_site_messages.php')->up();
  77. (require dirname(__DIR__, 2) . '/database/migrations/2026_10_27_150000_create_site_realtime_events.php')->up();
  78. Schema::create('level', function (Blueprint $t) { $t->id(); $t->integer('level'); $t->string('level_name'); });
  79. DB::table('level')->insert([['level' => 1, 'level_name' => 'VIP1'], ['level' => 2, 'level_name' => 'VIP2']]);
  80. Schema::create('share_bet_facts', function (Blueprint $t) {
  81. $t->id(); $t->string('source', 32); $t->string('source_id', 64); $t->unsignedBigInteger('user_id'); $t->string('member_id', 64);
  82. $t->string('category', 32); $t->dateTime('bet_at'); $t->date('bet_date'); $t->dateTime('settled_at')->nullable();
  83. foreach (['bet_amount', 'net_profit', 'effective_amount'] as $c) $t->decimal($c, 24, 10)->default(0);
  84. $t->boolean('settled')->default(false); $t->boolean('voided')->default(false);
  85. $t->string('currency', 8)->default('CNY'); $t->string('source_version', 64)->default(''); $t->timestamps();
  86. });
  87. Schema::create('share_system_state', function (Blueprint $t) { $t->string('key')->primary(); $t->text('value'); $t->timestamps(); });
  88. Schema::create('wallet_bonus', function (Blueprint $t) {
  89. $t->id(); $t->string('member_id'); $t->integer('type')->default(0); $t->unsignedBigInteger('activity_id')->default(0);
  90. $t->unsignedBigInteger('related_id'); foreach (['amount', 'need_flow', 'remaind_flow'] as $c) $t->decimal($c, 24, 2);
  91. $t->integer('status'); $t->timestamps();
  92. });
  93. Schema::create('wallets', function (Blueprint $t) {
  94. $t->id(); $t->string('member_id'); $t->decimal('available_balance', 24, 10)->default(0); $t->timestamps();
  95. });
  96. DB::table('wallets')->insert(['member_id' => '1001', 'available_balance' => '20.00']);
  97. Schema::create('balance_logs', function (Blueprint $t) {
  98. $t->id(); $t->string('member_id'); $t->string('change_type'); $t->unsignedBigInteger('related_id');
  99. foreach (['amount', 'before_balance', 'after_balance'] as $field) $t->decimal($field, 24, 10);
  100. $t->string('remark'); $t->timestamps();
  101. });
  102. Schema::create('rebates', function (Blueprint $t) {
  103. $t->id(); $t->string('member_id'); $t->string('date');
  104. $t->decimal('betting_amount', 24, 2); $t->decimal('effective_betting_amount', 24, 2);
  105. $t->decimal('rebate_ratio', 12, 4)->default(0); $t->decimal('amount', 24, 2)->default(0);
  106. $t->decimal('profit', 24, 2)->default(0); $t->string('username')->default(''); $t->string('first_name')->default('');
  107. $t->integer('status')->default(0); $t->string('audited_by')->nullable(); $t->bigInteger('grant_time')->default(0); $t->timestamps();
  108. });
  109. Schema::create('backflow', function (Blueprint $t) {
  110. $t->id(); $t->string('member_id'); $t->string('date');
  111. foreach (['recharge_amount', 'withdrawal_amount', 'backflow_ratio', 'amount'] as $field) $t->decimal($field, 24, 4)->default(0);
  112. $t->integer('status')->default(0); $t->bigInteger('grant_time')->default(0); $t->timestamps();
  113. });
  114. $this->migration()->up();
  115. $this->rulesMigration()->up();
  116. (require dirname(__DIR__, 2) . '/database/migrations/2026_11_05_160000_add_backflow_granted_amounts.php')->up();
  117. (require dirname(__DIR__, 2) . '/database/migrations/2026_11_08_120000_add_rebate_granted_amounts.php')->up();
  118. DB::table('rebate_rules')->insert(['category' => 'self:lottery', 'level' => 1, 'min_effective_amount' => 0, 'percentage' => '0.5', 'turnover_multiple' => 0]);
  119. DB::table('backflow_rules')->insert(['category' => 'self:lottery', 'min_loss_amount' => 100, 'reward_amount' => 35, 'turnover_multiple' => 0]);
  120. $this->request('/admin/rebate');
  121. }
  122. protected function tearDown(): void
  123. {
  124. Carbon::setTestNow(); DB::disconnect(); Facade::clearResolvedInstances();
  125. parent::tearDown();
  126. }
  127. private function migration()
  128. {
  129. return require dirname(__DIR__, 2) . '/database/migrations/2026_10_25_180000_create_reward_grant_settings.php';
  130. }
  131. private function rulesMigration()
  132. {
  133. return require dirname(__DIR__, 2) . '/database/migrations/2026_11_03_160000_create_reward_rules.php';
  134. }
  135. private function request(string $path, array $params = [], string $method = 'GET'): void
  136. {
  137. $request = Request::create($path, $method, $params);
  138. $request->user = (object) ['id' => 1, 'username' => 'operator-one'];
  139. $this->app->instance('request', $request);
  140. }
  141. private function user(string $memberId, int $level = 1): int
  142. {
  143. DB::table('users')->insertOrIgnore(['member_id' => $memberId, 'level' => $level]);
  144. return (int) DB::table('users')->where('member_id', $memberId)->value('id');
  145. }
  146. /** Legacy PC28 rows: no facts, so the stored effective bet is the payout basis. */
  147. private function rebate(array $values = []): int
  148. {
  149. $this->user((string) ($values['member_id'] ?? '1001'));
  150. return DB::table('rebates')->insertGetId($values + ['member_id' => '1001', 'date' => '2026-10-23',
  151. 'betting_amount' => '1000.00', 'effective_betting_amount' => '800.00']);
  152. }
  153. /** The month's lottery loss mirrors the old |recharge + withdrawal| fixture. */
  154. private function backflow(array $values = []): int
  155. {
  156. $values += ['member_id' => '1001', 'date' => '2026-09', 'recharge_amount' => '1000.00', 'withdrawal_amount' => '-300.00'];
  157. if (($values['status'] ?? 0) === 0) {
  158. $loss = bcadd((string) $values['recharge_amount'], (string) $values['withdrawal_amount'], 2);
  159. $this->fact($values['member_id'], 'self:lottery', $values['date'] . '-10 12:00:00', '0', bcsub('0', $loss, 2));
  160. }
  161. return DB::table('backflow')->insertGetId($values);
  162. }
  163. private function fact(string $memberId, string $category, string $betAt, string $effective, string $profit, array $values = []): void
  164. {
  165. static $sequence = 0;
  166. DB::table('share_bet_facts')->insert($values + ['source' => 'test', 'source_id' => (string) ++$sequence,
  167. 'user_id' => $this->user($memberId), 'member_id' => $memberId, 'category' => $category, 'bet_at' => $betAt,
  168. 'bet_date' => substr($betAt, 0, 10), 'bet_amount' => $effective, 'effective_amount' => $effective,
  169. 'net_profit' => $profit, 'settled' => 1, 'voided' => 0, 'currency' => 'CNY',
  170. 'created_at' => now()->format('Y-m-d H:i:s'), 'updated_at' => now()->format('Y-m-d H:i:s')]);
  171. }
  172. private function enable(string $type, string $time = '14:30'): void
  173. {
  174. RewardGrantSettingsService::save($type, ['auto_enabled' => 1, 'grant_time' => $time]);
  175. }
  176. private function runRewards(): array { return (new AutomaticRewardGrantService())->run(); }
  177. #[DataProvider('payoutMessageCases')]
  178. public function test_manual_and_automatic_payouts_deliver_in_the_users_language(string $type, bool $automatic, ?string $language): void
  179. {
  180. $id = $type === 'rebate' ? $this->rebate() : $this->backflow();
  181. DB::table('users')->where('member_id', '1001')->update(['language' => $language]);
  182. if ($automatic) {
  183. $this->enable($type);
  184. $this->assertSame(1, $this->runRewards()[$type]['granted']);
  185. $this->assertSame(0, $this->runRewards()[$type]['granted']);
  186. } else {
  187. $this->request('/admin/' . $type, ['id' => $id], 'POST');
  188. $controller = $type === 'rebate' ? new RebateController() : new BackflowController();
  189. $method = $type === 'rebate' ? 'store' : 'grant';
  190. $this->assertSame(0, $controller->$method()->getData(true)['code']);
  191. $this->assertSame(-3, $controller->$method()->getData(true)['code']);
  192. }
  193. $memberId = (int) DB::table('users')->where('member_id', '1001')->value('id');
  194. $language = in_array($language, ['zh', 'en', 'vi'], true) ? $language : 'zh';
  195. $titles = $type === 'rebate'
  196. ? ['zh' => '笔笔返到账通知', 'en' => 'Bet rebate credited', 'vi' => 'Hoàn cược đã được ghi có']
  197. : ['zh' => '回水到账通知', 'en' => 'Loss rebate credited', 'vi' => 'Hoàn lỗ đã được ghi có'];
  198. $inbox = new SiteInboxService();
  199. $this->assertSame(1, $inbox->unread('user', $memberId)['count']);
  200. $message = $inbox->detail('user', $memberId, (int) DB::table('site_messages')->value('id'));
  201. $this->assertSame($language, $message['language']);
  202. $this->assertSame($titles[$language], $message['title']);
  203. $this->assertStringContainsString($type === 'rebate' ? '4.00' : '35.00', $message['content']);
  204. $this->assertStringContainsString($type === 'rebate' ? '2026-10-23' : '2026-09', $message['content']);
  205. $this->assertSame('internal', $message['category']);
  206. $this->assertSame(0, $inbox->unread('user', 1001)['count']);
  207. $this->assertSame(0, $inbox->unread('agent', $memberId)['count']);
  208. $this->assertSame(1, DB::table('site_messages')->count());
  209. $this->assertSame(1, DB::table('site_message_recipients')->count());
  210. $this->assertSame(1, DB::table('site_realtime_events')->count());
  211. $this->assertSame(1, DB::table('operation_audits')->where('resource_type', 'site_message')->count());
  212. }
  213. public static function payoutMessageCases(): array
  214. {
  215. $cases = [];
  216. foreach (['rebate', 'backflow'] as $type) foreach ([false, true] as $automatic) foreach (['zh', 'en', 'vi', null, '', 'unsupported'] as $language) {
  217. $cases[$type . '-' . (int) $automatic . '-' . ($language ?? 'null')] = [$type, $automatic, $language];
  218. }
  219. return $cases;
  220. }
  221. public function test_melbet_message_lists_returns_the_rebate_and_backflow_notices(): void
  222. {
  223. $rebate = $this->rebate(); $backflow = $this->backflow();
  224. Schema::table('users', function (Blueprint $t) { $t->string('user_id')->nullable(); $t->dateTime('delete_time')->nullable(); });
  225. DB::table('users')->where('member_id', '1001')->update(['user_id' => 'login-1001', 'language' => 'en']);
  226. RewardGrantService::grant('rebate', $rebate, 'operator-one');
  227. RewardGrantService::grant('backflow', $backflow, 'operator-one');
  228. $snapshot = tempnam(sys_get_temp_dir(), 'reward-inbox-');
  229. unlink($snapshot); // VACUUM INTO requires a new file.
  230. try {
  231. DB::statement('VACUUM INTO ?', [$snapshot]);
  232. $probe = new \Symfony\Component\Process\Process([PHP_BINARY, '-d', 'xdebug.mode=off', dirname(__DIR__) . '/fixtures/reward_message_inbox_probe.php', $snapshot, 'login-1001']);
  233. $probe->mustRun();
  234. $result = json_decode($probe->getOutput(), true, 512, JSON_THROW_ON_ERROR);
  235. $this->assertSame(2, $result['listing']['count']);
  236. $this->assertEqualsCanonicalizing(['Bet rebate credited', 'Loss rebate credited'], array_column($result['listing']['list'], 'title'));
  237. $this->assertSame(['en', 'en'], array_column($result['listing']['list'], 'language'));
  238. $this->assertSame([false, false], array_column($result['listing']['list'], 'is_read'));
  239. $this->assertCount(2, $result['details']);
  240. } finally {
  241. if (is_file($snapshot)) unlink($snapshot);
  242. }
  243. }
  244. public function test_message_failure_rolls_back_the_payout_and_retry_delivers_once(): void
  245. {
  246. $id = $this->rebate(); $this->enable('rebate');
  247. DB::statement("CREATE TRIGGER reject_reward_notice BEFORE INSERT ON bot_site_message_recipients BEGIN SELECT RAISE(ABORT, 'notice unavailable'); END");
  248. $this->assertSame(1, $this->runRewards()['rebate']['failed']);
  249. $this->assertEquals(20, DB::table('wallets')->value('available_balance'));
  250. $this->assertSame(0, DB::table('rebates')->where('id', $id)->value('status'));
  251. foreach (['balance_logs', 'site_messages', 'site_message_translations', 'site_message_recipients', 'site_realtime_events', 'operation_audits'] as $table) {
  252. $this->assertSame(0, DB::table($table)->count(), $table);
  253. }
  254. DB::statement('DROP TRIGGER reject_reward_notice');
  255. $this->assertSame(1, $this->runRewards()['rebate']['granted']);
  256. $this->assertSame(0, $this->runRewards()['rebate']['granted']);
  257. $this->assertEquals(24, DB::table('wallets')->value('available_balance'));
  258. $this->assertSame(1, DB::table('site_message_recipients')->count());
  259. }
  260. private function scheduledEvents(): array
  261. {
  262. $this->app['config']->set('cache', ['default' => 'array', 'stores' => ['array' => ['driver' => 'array']]]);
  263. $this->app->register(\Illuminate\Cache\CacheServiceProvider::class);
  264. $schedule = new \Illuminate\Console\Scheduling\Schedule('Asia/Shanghai');
  265. $kernel = new \App\Console\Kernel($this->app, new Dispatcher($this->app));
  266. $method = new \ReflectionMethod($kernel, 'schedule');
  267. $method->setAccessible(true);
  268. $method->invoke($kernel, $schedule);
  269. return $schedule->events();
  270. }
  271. public function test_console_scheduler_registers_the_automatic_payout_command_every_minute_with_overlap_protection(): void
  272. {
  273. $events = array_values(array_filter($this->scheduledEvents(), fn ($event) => str_contains($event->command ?? '', 'rewards:auto-grant')));
  274. $this->assertCount(1, $events);
  275. $this->assertSame('* * * * *', $events[0]->expression);
  276. $this->assertTrue($events[0]->withoutOverlapping);
  277. $this->assertSame(60, $events[0]->expiresAt);
  278. }
  279. public function test_console_scheduler_refreshes_reward_bases_and_wagers_after_bet_facts(): void
  280. {
  281. $commands = ['share:sync-facts --write', 'rewards:sync-bases', 'wagering:sync'];
  282. $scheduled = [];
  283. foreach ($this->scheduledEvents() as $event) {
  284. foreach ($commands as $command) {
  285. if (!str_ends_with($event->command ?? '', ' ' . $command)) continue;
  286. $this->assertSame('* * * * *', $event->expression);
  287. $this->assertTrue($event->withoutOverlapping);
  288. $scheduled[] = $command;
  289. }
  290. }
  291. $this->assertSame($commands, $scheduled);
  292. }
  293. public function test_migration_defaults_to_manual_and_both_settings_routes_keep_admin_and_existing_grant_permissions(): void
  294. {
  295. $id = $this->rebate(); $this->backflow();
  296. foreach (['rebate', 'backflow'] as $type) {
  297. $this->assertSame(['type' => $type, 'auto_enabled' => 0, 'grant_time' => '03:00', 'timezone' => 'Asia/Shanghai'], RewardGrantSettingsService::get($type));
  298. }
  299. $this->assertSame(0, $this->runRewards()['rebate']['granted']);
  300. $this->assertSame(0, DB::table('rebates')->where('id', $id)->value('status'));
  301. $this->assertSame(0, DB::table('balance_logs')->count());
  302. $router = new Router(new Dispatcher($this->app), $this->app);
  303. $this->app->instance('router', $router);
  304. $router->group(['prefix' => 'admin'], function () { require dirname(__DIR__, 2) . '/routes/admin.php'; });
  305. foreach (['rebate' => 'submit', 'backflow' => 'grant'] as $type => $permission) {
  306. foreach (['GET', 'POST'] as $method) {
  307. $route = $router->getRoutes()->match(Request::create('/admin/' . $type . '/grant-settings', $method));
  308. $this->assertContains('admin.jwt', $route->middleware());
  309. $this->assertContains('check.button.uri', $route->middleware());
  310. $this->assertSame('admin/' . $type . '/' . $permission, $route->defaults['permission_uri']);
  311. }
  312. }
  313. $this->migration()->down();
  314. $this->assertFalse(Schema::hasTable('reward_grant_settings'));
  315. }
  316. public function test_settings_api_persists_independent_times_and_disabling_preserves_the_previous_time_without_paying(): void
  317. {
  318. $this->rebate();
  319. $this->request('/admin/rebate/grant-settings', ['auto_enabled' => true, 'grant_time' => '14:30'], 'POST');
  320. $body = (new RewardGrantSettings())->saveRebate()->getData(true);
  321. $this->assertSame(0, $body['code']);
  322. $this->assertSame(1, $body['data']['auto_enabled']);
  323. $this->assertSame('14:30', $body['data']['grant_time']);
  324. $this->assertSame(0, RewardGrantSettingsService::get('backflow')['auto_enabled']);
  325. $this->request('/admin/backflow/grant-settings', ['auto_enabled' => 1, 'grant_time' => '20:15'], 'POST');
  326. $this->assertSame(0, (new RewardGrantSettings())->saveBackflow()->getData(true)['code']);
  327. $this->assertSame('20:15', RewardGrantSettingsService::get('backflow')['grant_time']);
  328. $this->request('/admin/rebate/grant-settings', ['auto_enabled' => 0], 'POST');
  329. $body = (new RewardGrantSettings())->saveRebate()->getData(true);
  330. $this->assertSame(0, $body['data']['auto_enabled']);
  331. $this->assertSame('14:30', $body['data']['grant_time']);
  332. $this->assertSame(0, DB::table('balance_logs')->count());
  333. $this->assertSame(0, (new RewardGrantSettings())->rebate()->getData(true)['code']);
  334. }
  335. #[DataProvider('invalidSettings')]
  336. public function test_invalid_settings_do_not_change_the_switch_or_time(array $values): void
  337. {
  338. $this->request('/admin/rebate/grant-settings', $values, 'POST');
  339. $this->assertSame(-3, (new RewardGrantSettings())->saveRebate()->getData(true)['code']);
  340. $this->assertSame(0, RewardGrantSettingsService::get('rebate')['auto_enabled']);
  341. $this->assertSame('03:00', RewardGrantSettingsService::get('rebate')['grant_time']);
  342. }
  343. public static function invalidSettings(): array
  344. {
  345. return [[[]], [['auto_enabled' => 2]], [['auto_enabled' => 'auto']], [['auto_enabled' => 1]],
  346. [['auto_enabled' => true]], [['auto_enabled' => 1, 'grant_time' => '']],
  347. [['auto_enabled' => 1, 'grant_time' => '24:00']], [['auto_enabled' => 1, 'grant_time' => '9:00']],
  348. [['auto_enabled' => 1, 'grant_time' => '12:60']], [['auto_enabled' => 0, 'grant_time' => ['03:00']]]];
  349. }
  350. public function test_exact_minute_pays_both_types_once_and_retries_do_not_duplicate_wallet_or_ledger(): void
  351. {
  352. $rebate = $this->rebate(); $backflow = $this->backflow();
  353. $this->rebate(['date' => '2026-10-25']); $this->backflow(['date' => '2026-10']);
  354. $this->rebate(['status' => 1]); $this->backflow(['status' => 1]);
  355. $this->enable('rebate'); $this->enable('backflow');
  356. Carbon::setTestNow(Carbon::parse('2026-10-25 14:29:59', 'Asia/Shanghai'));
  357. $this->assertSame(0, $this->runRewards()['rebate']['granted']);
  358. $this->assertSame(0, DB::table('balance_logs')->count());
  359. Carbon::setTestNow(Carbon::parse('2026-10-25 14:30:00', 'Asia/Shanghai'));
  360. $result = $this->runRewards();
  361. $this->assertSame(1, $result['rebate']['granted']); $this->assertSame(1, $result['backflow']['granted']);
  362. $this->assertEquals(59, DB::table('wallets')->value('available_balance'));
  363. $this->assertEquals(4, DB::table('rebates')->where('id', $rebate)->value('amount'));
  364. $this->assertEquals(35, DB::table('backflow')->where('id', $backflow)->value('amount'));
  365. $this->assertSame('system:auto-grant', DB::table('rebates')->where('id', $rebate)->value('audited_by'));
  366. $this->assertSame(now()->timestamp, DB::table('backflow')->where('id', $backflow)->value('grant_time'));
  367. $this->assertSame(2, DB::table('balance_logs')->count());
  368. $this->assertSame(0, $this->runRewards()['rebate']['granted']);
  369. $this->assertSame(2, DB::table('balance_logs')->count());
  370. $this->assertEquals(59, DB::table('wallets')->value('available_balance'));
  371. }
  372. public function test_scheduled_cutoffs_keep_new_york_days_and_shanghai_months_even_when_catching_up_later(): void
  373. {
  374. Carbon::setTestNow(Carbon::parse('2026-11-01 03:00:00', 'Asia/Shanghai'));
  375. $old = $this->rebate(['date' => '2026-10-30']);
  376. $notYetEndedAtSchedule = $this->rebate(['date' => '2026-10-31']);
  377. $lastMonth = $this->backflow(['date' => '2026-10']);
  378. $currentMonth = $this->backflow(['date' => '2026-11']);
  379. $this->enable('rebate', '03:00'); $this->enable('backflow', '03:00');
  380. // At 14:00 the New York day has changed, but this run still belongs to the 03:00 schedule.
  381. Carbon::setTestNow(Carbon::parse('2026-11-01 14:00:00', 'Asia/Shanghai'));
  382. $this->runRewards();
  383. $this->assertSame(1, DB::table('rebates')->where('id', $old)->value('status'));
  384. $this->assertSame(0, DB::table('rebates')->where('id', $notYetEndedAtSchedule)->value('status'));
  385. $this->assertSame(1, DB::table('backflow')->where('id', $lastMonth)->value('status'));
  386. $this->assertSame(0, DB::table('backflow')->where('id', $currentMonth)->value('status'));
  387. Carbon::setTestNow(Carbon::parse('2026-11-02 02:59:59', 'Asia/Shanghai'));
  388. $this->assertSame(0, $this->runRewards()['rebate']['granted']);
  389. Carbon::setTestNow(Carbon::parse('2026-11-02 03:00:00', 'Asia/Shanghai'));
  390. $this->assertSame(1, $this->runRewards()['rebate']['granted']);
  391. $this->assertSame(1, DB::table('rebates')->where('id', $notYetEndedAtSchedule)->value('status'));
  392. }
  393. public function test_disabled_switch_stops_auto_but_both_manual_controllers_still_work_and_stale_calls_cannot_pay_twice(): void
  394. {
  395. $id = $this->rebate(); $backflow = $this->backflow();
  396. $stale = Rebate::findOrFail($id);
  397. $this->enable('rebate');
  398. RewardGrantSettingsService::save('rebate', ['auto_enabled' => 0]);
  399. $this->assertSame(0, $this->runRewards()['rebate']['granted']);
  400. $this->request('/admin/rebate/submit', ['id' => $id], 'POST');
  401. $this->assertSame(0, (new RebateController())->store()->getData(true)['code']);
  402. $this->assertSame(-3, (new RebateController())->store()->getData(true)['code']);
  403. $this->assertSame('operator-one', DB::table('rebates')->where('id', $id)->value('audited_by'));
  404. $this->request('/admin/backflow/grant', ['id' => $backflow], 'POST');
  405. $this->assertSame(0, (new BackflowController())->grant()->getData(true)['code']);
  406. $this->assertSame(-3, (new BackflowController())->grant()->getData(true)['code']);
  407. $this->enable('rebate'); $this->enable('backflow');
  408. $this->runRewards();
  409. $this->assertFalse(RewardGrantService::grant('rebate', $id, 'auto', true));
  410. $this->assertSame(2, DB::table('balance_logs')->count());
  411. try { RebateService::BibiReturn($stale, '999999'); $this->fail('A stale row must not pay again'); }
  412. catch (\RuntimeException $e) { $this->assertSame(-3, $e->getCode()); }
  413. $this->assertEquals(59, DB::table('wallets')->value('available_balance'));
  414. }
  415. public function test_payout_reads_fresh_effective_bet_and_zero_rewards_are_finalized_without_ledger_credits(): void
  416. {
  417. $id = $this->rebate(); $stale = Rebate::findOrFail($id);
  418. DB::table('rebates')->where('id', $id)->update(['effective_betting_amount' => 100]);
  419. RebateService::BibiReturn($stale, '800');
  420. $this->assertEquals(0.5, DB::table('rebates')->where('id', $id)->value('amount'));
  421. $this->rebate(['effective_betting_amount' => 0]);
  422. $below = $this->backflow(['recharge_amount' => 50, 'withdrawal_amount' => 0]);
  423. $this->enable('rebate'); $this->enable('backflow'); $this->runRewards();
  424. $this->assertSame(1, DB::table('backflow')->where('id', $below)->value('status'));
  425. $this->assertEquals(0, DB::table('backflow')->where('id', $below)->value('amount'));
  426. $this->assertSame(1, DB::table('balance_logs')->count());
  427. $this->assertEquals(20.5, DB::table('wallets')->value('available_balance'));
  428. $this->assertSame(1, DB::table('site_messages')->count(), 'Zero payouts do not send notices');
  429. }
  430. public function test_ledger_failure_rolls_back_wallet_and_reward_then_automatic_retry_credits_once(): void
  431. {
  432. $id = $this->rebate(); $this->enable('rebate');
  433. DB::statement("CREATE TRIGGER reject_reward_ledger BEFORE INSERT ON bot_balance_logs BEGIN SELECT RAISE(ABORT, 'ledger unavailable'); END");
  434. $this->assertSame(1, $this->runRewards()['rebate']['failed']);
  435. $this->assertEquals(20, DB::table('wallets')->value('available_balance'));
  436. $this->assertSame(0, DB::table('rebates')->where('id', $id)->value('status'));
  437. $this->assertSame(0, DB::table('rebates')->where('id', $id)->value('grant_time'));
  438. $this->assertSame(0, DB::table('balance_logs')->count());
  439. $this->assertSame(0, DB::table('site_messages')->count());
  440. DB::statement('DROP TRIGGER reject_reward_ledger');
  441. $this->assertSame(1, $this->runRewards()['rebate']['granted']);
  442. $this->assertEquals(24, DB::table('wallets')->value('available_balance'));
  443. $this->assertSame(1, DB::table('balance_logs')->count());
  444. }
  445. public function test_status_save_failure_rolls_back_backflow_wallet_and_ledger_and_missing_wallet_does_not_stop_other_rows(): void
  446. {
  447. $id = $this->backflow(); $this->enable('backflow');
  448. DB::statement("CREATE TRIGGER reject_backflow_status BEFORE UPDATE ON bot_backflow BEGIN SELECT RAISE(ABORT, 'reward unavailable'); END");
  449. $this->assertSame(1, $this->runRewards()['backflow']['failed']);
  450. $this->assertSame(0, DB::table('backflow')->where('id', $id)->value('status'));
  451. $this->assertSame(0, DB::table('balance_logs')->count());
  452. $this->assertEquals(20, DB::table('wallets')->value('available_balance'));
  453. DB::statement('DROP TRIGGER reject_backflow_status');
  454. $bad = $this->rebate(['member_id' => 'no-wallet']); $good = $this->rebate(); $this->enable('rebate');
  455. $result = $this->runRewards();
  456. $this->assertSame(1, $result['rebate']['failed']); $this->assertSame(1, $result['rebate']['granted']);
  457. $this->assertSame(0, DB::table('rebates')->where('id', $bad)->value('status'));
  458. $this->assertSame(1, DB::table('rebates')->where('id', $good)->value('status'));
  459. $this->assertSame(1, $result['backflow']['granted']);
  460. }
  461. public function test_switch_and_time_are_rechecked_between_records_and_before_retrying(): void
  462. {
  463. $this->rebate(); $second = $this->rebate(); $this->enable('rebate');
  464. $changed = false;
  465. $this->app['db']->connection()->listen(function ($event) use (&$changed) {
  466. if (!$changed && str_starts_with(strtolower($event->sql), 'update "bot_rebates"')) {
  467. $changed = true;
  468. RewardGrantSettingsService::save('rebate', ['auto_enabled' => 0]);
  469. }
  470. });
  471. $this->assertSame(1, $this->runRewards()['rebate']['granted']);
  472. $this->assertSame(0, DB::table('rebates')->where('id', $second)->value('status'));
  473. $this->assertSame(1, DB::table('balance_logs')->count());
  474. $this->enable('rebate', '15:00');
  475. $this->assertSame(0, $this->runRewards()['rebate']['granted']);
  476. Carbon::setTestNow(Carbon::parse('2026-10-25 15:00:00', 'Asia/Shanghai'));
  477. $this->assertSame(1, $this->runRewards()['rebate']['granted']);
  478. }
  479. public function test_chunked_processing_does_not_skip_rows_and_command_reports_failure_without_forcing_disabled_rewards(): void
  480. {
  481. for ($i = 0; $i < 105; ++$i) $this->rebate(['effective_betting_amount' => 0]);
  482. $command = new AutoGrantRewards(); $command->setLaravel($this->app);
  483. $tester = new CommandTester($command);
  484. $tester->execute([]);
  485. $this->assertSame(0, $tester->getStatusCode());
  486. $this->assertSame(105, DB::table('rebates')->where('status', 0)->count());
  487. $this->enable('rebate'); $tester->execute([]);
  488. $this->assertSame(0, $tester->getStatusCode());
  489. $this->assertStringContainsString('"granted":105', $tester->getDisplay());
  490. $this->assertSame(105, DB::table('rebates')->where('status', 1)->count());
  491. $this->rebate(['member_id' => 'missing']); $tester->execute([]);
  492. $this->assertSame(1, $tester->getStatusCode());
  493. }
  494. public function test_rules_api_lists_categories_and_levels_replaces_one_category_and_rejects_bad_tiers(): void
  495. {
  496. $body = (new RewardRules())->rebate()->getData(true);
  497. $this->assertSame(0, $body['code']);
  498. $this->assertContains(['value' => 'third:1', 'label' => '真人'], $body['data']['categories']);
  499. $this->assertSame([['level' => 1, 'level_name' => 'VIP1'], ['level' => 2, 'level_name' => 'VIP2']], $body['data']['levels']);
  500. $this->assertSame([], $body['data']['rules']['third:2']);
  501. $this->request('/admin/rebate/rules', ['category' => 'third:2', 'rules' => [
  502. ['level' => 2, 'min_effective_amount' => 1000, 'percentage' => '1', 'turnover_multiple' => 3],
  503. ['level' => 2, 'min_effective_amount' => 0, 'percentage' => '0.5', 'turnover_multiple' => 0],
  504. ]], 'POST');
  505. $body = (new RewardRules())->saveRebate()->getData(true);
  506. $this->assertSame(0, $body['code']);
  507. $this->assertSame(['0.00', '1000.00'], array_column($body['data']['rules']['third:2'], 'min_effective_amount'));
  508. $this->assertSame('3.00', $body['data']['rules']['third:2'][1]['turnover_multiple']);
  509. $this->assertCount(1, $body['data']['rules']['self:lottery']);
  510. foreach ([['category' => 'third:9', 'rules' => []],
  511. ['category' => 'third:2', 'rules' => [['level' => 7, 'min_effective_amount' => 0, 'percentage' => 1, 'turnover_multiple' => 0]]],
  512. ['category' => 'third:2', 'rules' => [['level' => 1, 'min_effective_amount' => '1e3', 'percentage' => 1, 'turnover_multiple' => 0]]],
  513. ['category' => 'third:2', 'rules' => [['level' => 1, 'min_effective_amount' => 0, 'percentage' => 101, 'turnover_multiple' => 0]]],
  514. ['category' => 'third:2', 'rules' => [['level' => 1, 'min_effective_amount' => 5, 'percentage' => 1, 'turnover_multiple' => 0],
  515. ['level' => 1, 'min_effective_amount' => 5, 'percentage' => 2, 'turnover_multiple' => 0]]]] as $bad) {
  516. $this->request('/admin/rebate/rules', $bad, 'POST');
  517. $this->assertSame(-3, (new RewardRules())->saveRebate()->getData(true)['code']);
  518. }
  519. $this->assertSame(2, DB::table('rebate_rules')->where('category', 'third:2')->count());
  520. $this->request('/admin/backflow/rules', ['category' => 'third:1', 'rules' => [
  521. ['min_loss_amount' => 2000, 'reward_amount' => 60, 'turnover_multiple' => 2]]], 'POST');
  522. $body = (new RewardRules())->saveBackflow()->getData(true);
  523. $this->assertSame([['id' => 2, 'category' => 'third:1', 'min_loss_amount' => '2000.00', 'reward_amount' => '60.00',
  524. 'turnover_multiple' => '2.00']], $body['data']['rules']['third:1']);
  525. $this->request('/admin/backflow/rules', ['category' => 'third:1', 'rules' => []], 'POST');
  526. $this->assertSame(0, (new RewardRules())->saveBackflow()->getData(true)['code']);
  527. $this->assertSame(0, DB::table('backflow_rules')->where('category', 'third:1')->count());
  528. $router = new Router(new Dispatcher($this->app), $this->app);
  529. $this->app->instance('router', $router);
  530. $router->group(['prefix' => 'admin'], function () { require dirname(__DIR__, 2) . '/routes/admin.php'; });
  531. foreach (['rebate' => 'submit', 'backflow' => 'grant'] as $type => $permission) {
  532. foreach (['GET', 'POST'] as $method) {
  533. $route = $router->getRoutes()->match(Request::create('/admin/' . $type . '/rules', $method));
  534. $this->assertContains('check.button.uri', $route->middleware());
  535. $this->assertSame('admin/' . $type . '/' . $permission, $route->defaults['permission_uri']);
  536. }
  537. }
  538. }
  539. public function test_rebate_sums_every_category_by_new_york_day_and_uses_the_members_level_tier_and_turnover(): void
  540. {
  541. $this->user('2001', 2);
  542. DB::table('wallets')->insert(['member_id' => '2001', 'available_balance' => '0']);
  543. DB::table('rebate_rules')->insert([
  544. ['category' => 'third:2', 'level' => 2, 'min_effective_amount' => 0, 'percentage' => '0.5', 'turnover_multiple' => 0],
  545. ['category' => 'third:2', 'level' => 2, 'min_effective_amount' => 1000, 'percentage' => '1', 'turnover_multiple' => 3],
  546. ['category' => 'third:2', 'level' => 1, 'min_effective_amount' => 0, 'percentage' => '2', 'turnover_multiple' => 0],
  547. ['category' => 'self:sport', 'level' => 2, 'min_effective_amount' => 500, 'percentage' => '1', 'turnover_multiple' => 0],
  548. ]);
  549. // New York 2026-10-23 is Shanghai 2026-10-23 12:00 to 2026-10-24 11:59:59.
  550. $this->fact('2001', 'third:2', '2026-10-23 20:00:00', '1000', '-1000');
  551. $this->fact('2001', 'third:2', '2026-10-24 10:00:00', '500', '500');
  552. $this->fact('2001', 'self:sport', '2026-10-24 11:00:00', '300', '-300');
  553. $this->fact('2001', 'third:2', '2026-10-24 11:30:00', '9999', '0', ['voided' => 1]);
  554. $this->fact('2001', 'third:2', '2026-10-24 13:00:00', '7777', '-7777');
  555. $this->assertSame(['rebates' => 2, 'backflow' => 1, 'failed' => 0], (new RewardBaseSyncService())->run());
  556. $row = DB::table('rebates')->where('member_id', '2001')->where('date', '2026-10-23')->first();
  557. $this->assertEquals(1800, $row->betting_amount);
  558. $this->assertEquals(1800, $row->effective_betting_amount);
  559. $this->assertEquals(15, $row->amount);
  560. $this->assertEquals(45, $row->need_flow);
  561. $this->assertSame(['self:sport', 'third:2'], array_column(json_decode($row->details, true), 'category'));
  562. $this->assertTrue(RewardGrantService::grant('rebate', (int) $row->id, 'operator-one'));
  563. $this->assertEquals(15, DB::table('wallets')->where('member_id', '2001')->value('available_balance'));
  564. $bonus = DB::table('wallet_bonus')->first();
  565. $this->assertSame('2001', $bonus->member_id);
  566. $this->assertEquals(45, $bonus->need_flow);
  567. $this->assertEquals(15, $bonus->amount);
  568. $this->assertSame((int) $row->id, (int) $bonus->related_id);
  569. $this->assertStringContainsString('电子:1500.00×1.0000%', DB::table('balance_logs')->value('remark'));
  570. // A paid day is never rewritten by later facts.
  571. $this->fact('2001', 'third:2', '2026-10-24 09:00:00', '100', '-100');
  572. (new RewardBaseSyncService())->run();
  573. $this->assertEquals(1800, DB::table('rebates')->where('id', $row->id)->value('effective_betting_amount'));
  574. $this->assertSame(1, DB::table('wallet_bonus')->count());
  575. }
  576. public function test_backflow_pays_fixed_rewards_for_each_categorys_monthly_net_loss(): void
  577. {
  578. $this->user('2001');
  579. DB::table('wallets')->insert(['member_id' => '2001', 'available_balance' => '0']);
  580. DB::table('backflow_rules')->insert([
  581. ['category' => 'third:1', 'min_loss_amount' => 1000, 'reward_amount' => 20, 'turnover_multiple' => 0],
  582. ['category' => 'third:1', 'min_loss_amount' => 2000, 'reward_amount' => 60, 'turnover_multiple' => 2],
  583. ['category' => 'third:2', 'min_loss_amount' => 0, 'reward_amount' => 99, 'turnover_multiple' => 0],
  584. ['category' => 'self:sport', 'min_loss_amount' => 100, 'reward_amount' => 5, 'turnover_multiple' => 0],
  585. ]);
  586. $this->fact('2001', 'third:1', '2026-09-03 10:00:00', '2000', '-2000');
  587. $this->fact('2001', 'third:1', '2026-09-28 10:00:00', '500', '-500');
  588. $this->fact('2001', 'third:2', '2026-09-05 10:00:00', '100', '100');
  589. $this->fact('2001', 'self:sport', '2026-09-30 23:00:00', '50', '-50');
  590. $this->fact('2001', 'self:sport', '2026-10-01 00:30:00', '900', '-900');
  591. (new RewardBaseSyncService())->run();
  592. $row = DB::table('backflow')->where('member_id', '2001')->where('date', '2026-09')->first();
  593. $this->assertEquals(2550, $row->loss_amount);
  594. $this->assertEquals(60, $row->amount);
  595. $this->assertTrue(RewardGrantService::grant('backflow', (int) $row->id, 'operator-one'));
  596. $this->assertEquals(60, DB::table('wallets')->where('member_id', '2001')->value('available_balance'));
  597. $this->assertEquals(120, DB::table('wallet_bonus')->value('need_flow'));
  598. $this->assertEquals(120, DB::table('backflow')->where('id', $row->id)->value('need_flow'));
  599. }
  600. public function test_backflow_can_be_granted_again_for_the_remainder_until_the_month_is_closed(): void
  601. {
  602. // now = 2026-10-25 14:30 上海;当月 2026-10。钱包初始 20。
  603. DB::table('backflow_rules')->insert([
  604. ['category' => 'self:lottery', 'min_loss_amount' => 10, 'reward_amount' => 8, 'turnover_multiple' => 1],
  605. ['category' => 'self:lottery', 'min_loss_amount' => 300, 'reward_amount' => 50, 'turnover_multiple' => 1],
  606. ]);
  607. $id = $this->backflow(['date' => '2026-10', 'recharge_amount' => '50.00', 'withdrawal_amount' => '0']); // 亏 50
  608. $this->enable('backflow');
  609. $this->assertSame(0, $this->runRewards()['backflow']['granted'], '自动发放不发当月');
  610. // 第一次手动发放:当月亏 50 → 8,记为部分发放
  611. $this->assertTrue(RewardGrantService::grant('backflow', $id, 'operator-one'));
  612. $row = DB::table('backflow')->where('id', $id)->first();
  613. $this->assertSame([2, '8.00', '8.00'], [(int) $row->status, bcadd($row->amount, 0, 2), bcadd($row->granted_amount, 0, 2)]);
  614. $this->assertEquals(28, DB::table('wallets')->where('member_id', '1001')->value('available_balance'));
  615. $this->assertSame(['amount' => '8.00', 'granted_amount' => '8.00', 'pending_amount' => '0.00', 'can_grant' => false, 'status_text' => '部分发放'],
  616. BackflowService::grantFields((array) $row));
  617. // 没有差额时当月不能再发
  618. try { RewardGrantService::grant('backflow', $id, 'operator-one'); $this->fail('expected exception'); }
  619. catch (\RuntimeException $e) { $this->assertSame('暂无可发放金额(按当前规则应发 8.00,已发放 8.00)', $e->getMessage()); }
  620. // 继续亏到 350:同步后应发 50,已发 8,待发 42
  621. $this->fact('1001', 'self:lottery', '2026-10-20 12:00:00', '300', '-300');
  622. (new RewardBaseSyncService())->run('2026-10-20', '2026-10-20');
  623. $fields = BackflowService::grantFields((array) DB::table('backflow')->where('id', $id)->first());
  624. $this->assertSame(['50.00', '8.00', '42.00', true], [$fields['amount'], $fields['granted_amount'], $fields['pending_amount'], $fields['can_grant']]);
  625. $this->assertTrue(RewardGrantService::grant('backflow', $id, 'operator-two'));
  626. $row = DB::table('backflow')->where('id', $id)->first();
  627. $this->assertSame([2, '50.00', '50.00'], [(int) $row->status, bcadd($row->granted_amount, 0, 2), bcadd($row->granted_need_flow, 0, 2)]);
  628. $this->assertEquals(70, DB::table('wallets')->where('member_id', '1001')->value('available_balance'));
  629. $this->assertSame(['8.0000000000', '42.0000000000'], DB::table('balance_logs')->where('change_type', '回水')->orderBy('id')->pluck('amount')
  630. ->map(fn ($v) => bcadd($v, 0, 10))->all());
  631. $this->assertStringContainsString('本次发放:42.00;累计发放:50.00', DB::table('balance_logs')->where('change_type', '回水')->orderByDesc('id')->value('remark'));
  632. $contents = DB::table('site_message_translations')->where('language', 'zh')->orderBy('id')->pluck('content')->all();
  633. $this->assertCount(2, $contents);
  634. $this->assertStringContainsString('本次已发放 8.00', $contents[0]);
  635. $this->assertStringContainsString('本次已发放 42.00', $contents[1]);
  636. // 下个月自动发放:无差额,只结清为已发放,不重复入账
  637. Carbon::setTestNow(Carbon::parse('2026-11-01 14:30:00', 'Asia/Shanghai'));
  638. $this->assertSame(1, $this->runRewards()['backflow']['granted']);
  639. $this->assertSame(1, (int) DB::table('backflow')->where('id', $id)->value('status'));
  640. $this->assertEquals(70, DB::table('wallets')->where('member_id', '1001')->value('available_balance'));
  641. $this->assertSame(2, DB::table('balance_logs')->where('change_type', '回水')->count());
  642. $this->assertSame(2, DB::table('site_messages')->count(), 'Closing without another credit must not send a notice');
  643. // 未来日期仍不能提前发放。
  644. $rebate = $this->rebate(['date' => Carbon::now('America/New_York')->addDay()->format('Y-m-d')]);
  645. $this->expectExceptionMessage('未到发放时间');
  646. RewardGrantService::grant('rebate', $rebate, 'operator-one');
  647. }
  648. public function test_manual_rebate_pays_3033_basis_then_differences_and_auto_finishes_after_day_end(): void
  649. {
  650. DB::table('rebate_rules')->update(['percentage' => 1, 'turnover_multiple' => 2]);
  651. $id = $this->rebate(['date' => '2026-10-25']);
  652. $this->fact('1001', 'self:lottery', '2026-10-25 13:00:00', '3033', '-3033');
  653. $this->enable('rebate');
  654. $this->assertSame(0, $this->runRewards()['rebate']['granted'], 'Automatic payout still waits for day end');
  655. $this->request('/admin/rebate/submit', ['id' => $id], 'POST');
  656. $controller = new RebateController();
  657. $this->assertSame(0, $controller->store()->getData(true)['code']);
  658. $row = DB::table('rebates')->where('id', $id)->first();
  659. $this->assertSame(2, (int) $row->status);
  660. $this->assertEquals(30.33, $row->granted_amount);
  661. $this->assertEquals(60.66, $row->granted_need_flow);
  662. $this->assertEquals(50.33, DB::table('wallets')->value('available_balance'));
  663. $this->assertFalse(RebateService::grantFields((array) $row)['can_grant']);
  664. $this->assertSame(-3, $controller->store()->getData(true)['code'], 'No difference cannot pay twice');
  665. $this->fact('1001', 'self:lottery', '2026-10-25 14:00:00', '1000', '-1000');
  666. (new RewardBaseSyncService())->run('2026-10-25', '2026-10-25');
  667. $fields = RebateService::grantFields((array) DB::table('rebates')->where('id', $id)->first());
  668. $this->assertSame(['40.33', '30.33', '10.00', true, '部分发放'], [$fields['amount'], $fields['granted_amount'], $fields['pending_amount'], $fields['can_grant'], $fields['status_text']]);
  669. DB::statement("CREATE TRIGGER reject_partial_notice BEFORE INSERT ON bot_site_message_recipients BEGIN SELECT RAISE(ABORT, 'notice unavailable'); END");
  670. $this->assertNotSame(0, $controller->store()->getData(true)['code']);
  671. $this->assertEquals(50.33, DB::table('wallets')->value('available_balance'));
  672. $this->assertEquals(30.33, DB::table('rebates')->where('id', $id)->value('granted_amount'));
  673. $this->assertSame(1, DB::table('site_messages')->count());
  674. $this->assertSame(1, DB::table('wallet_bonus')->count());
  675. DB::statement('DROP TRIGGER reject_partial_notice');
  676. $this->assertSame(0, $controller->store()->getData(true)['code']);
  677. $this->assertEquals(60.33, DB::table('wallets')->value('available_balance'));
  678. $this->assertEquals(80.66, DB::table('wallet_bonus')->sum('need_flow'));
  679. $this->assertSame(['30.33', '10.00'], DB::table('balance_logs')->orderBy('id')->pluck('amount')->map(fn ($v) => bcadd($v, '0', 2))->all());
  680. $contents = DB::table('site_message_translations')->where('language', 'zh')->orderBy('id')->pluck('content')->all();
  681. $this->assertStringContainsString('本次已发放 30.33', $contents[0]);
  682. $this->assertStringContainsString('本次已发放 10.00', $contents[1]);
  683. $this->fact('1001', 'self:lottery', '2026-10-25 14:20:00', '333', '-333');
  684. (new RewardBaseSyncService())->run('2026-10-25', '2026-10-25');
  685. Carbon::setTestNow(Carbon::parse('2026-10-26 14:30:00', 'Asia/Shanghai'));
  686. $this->assertSame(1, $this->runRewards()['rebate']['granted']);
  687. $row = DB::table('rebates')->where('id', $id)->first();
  688. $this->assertSame(1, (int) $row->status);
  689. $this->assertEquals(43.66, $row->granted_amount);
  690. $this->assertEquals(87.32, $row->granted_need_flow);
  691. $this->assertEquals(63.66, DB::table('wallets')->value('available_balance'));
  692. $this->assertSame(3, DB::table('site_messages')->count());
  693. $this->assertSame(0, $this->runRewards()['rebate']['granted']);
  694. $this->assertSame(3, DB::table('balance_logs')->count());
  695. }
  696. public function test_rebate_day_end_without_a_difference_does_not_credit_or_notify_again(): void
  697. {
  698. $id = $this->rebate(['date' => '2026-10-25']);
  699. $this->assertTrue(RewardGrantService::grant('rebate', $id, 'operator-one'));
  700. DB::table('rebate_rules')->update(['percentage' => '0.1', 'turnover_multiple' => 3]);
  701. Carbon::setTestNow(Carbon::parse('2026-10-26 14:30:00', 'Asia/Shanghai'));
  702. $this->enable('rebate');
  703. $this->assertSame(1, $this->runRewards()['rebate']['granted']);
  704. $row = DB::table('rebates')->where('id', $id)->first();
  705. $this->assertSame(1, (int) $row->status);
  706. $this->assertEquals(4, $row->granted_amount, 'A lower calculation never reclaims a previous credit');
  707. $this->assertEquals(0, $row->granted_need_flow, 'Unpaid turnover must not be counted as granted');
  708. $this->assertEquals(24, DB::table('wallets')->value('available_balance'));
  709. $this->assertSame(1, DB::table('site_messages')->count());
  710. $this->assertSame(1, DB::table('balance_logs')->count());
  711. $this->assertFalse(RewardGrantService::grant('rebate', $id, 'operator-one', true));
  712. }
  713. public function test_rebate_granted_amount_migration_preserves_paid_history_and_partial_totals(): void
  714. {
  715. $paid = $this->rebate(['date' => '2026-09-01', 'status' => 1, 'amount' => 30.33, 'need_flow' => 60.66]);
  716. $pending = $this->rebate(['date' => '2026-09-02', 'amount' => 99]);
  717. $partial = $this->rebate(['date' => '2026-10-25', 'status' => 2, 'amount' => 50, 'granted_amount' => 30.33, 'granted_need_flow' => 60.66]);
  718. $migration = require dirname(__DIR__, 2) . '/database/migrations/2026_11_08_120000_add_rebate_granted_amounts.php';
  719. $migration->up();
  720. $this->assertEquals(30.33, DB::table('rebates')->where('id', $paid)->value('granted_amount'));
  721. $this->assertEquals(60.66, DB::table('rebates')->where('id', $paid)->value('granted_need_flow'));
  722. $this->assertEquals(0, DB::table('rebates')->where('id', $pending)->value('granted_amount'));
  723. $this->assertEquals(30.33, DB::table('rebates')->where('id', $partial)->value('granted_amount'));
  724. $migration->down();
  725. $this->assertSame(1, (int) DB::table('rebates')->where('id', $partial)->value('status'));
  726. $this->assertFalse(Schema::hasColumn('rebates', 'granted_amount'));
  727. }
  728. public function test_granted_amount_migration_backfills_paid_rows(): void
  729. {
  730. $paid = DB::table('backflow')->insertGetId(['member_id' => '1001', 'date' => '2026-08', 'status' => 1, 'amount' => '35', 'need_flow' => '70', 'granted_amount' => 0]);
  731. $open = DB::table('backflow')->insertGetId(['member_id' => '1001', 'date' => '2026-07', 'status' => 0, 'amount' => '35', 'granted_amount' => 0]);
  732. (require dirname(__DIR__, 2) . '/database/migrations/2026_11_05_160000_add_backflow_granted_amounts.php')->up();
  733. $this->assertEquals([35, 70], array_values((array) DB::table('backflow')->where('id', $paid)->first(['granted_amount', 'granted_need_flow'])));
  734. $this->assertEquals(0, DB::table('backflow')->where('id', $open)->value('granted_amount'));
  735. }
  736. public function test_sync_cursor_only_revisits_changed_facts_and_backfill_range_creates_missing_rows(): void
  737. {
  738. $this->fact('3001', 'third:1', '2026-10-20 13:00:00', '100', '-100', ['updated_at' => '2026-10-20 13:00:00']);
  739. $this->assertSame(0, (new RewardBaseSyncService())->run()['rebates']);
  740. $this->assertSame(['rebates' => 1, 'backflow' => 1, 'failed' => 0], (new RewardBaseSyncService())->run('2026-10-20', '2026-10-20'));
  741. $this->assertEquals(100, DB::table('rebates')->where('member_id', '3001')->value('effective_betting_amount'));
  742. $this->assertNotNull(DB::table('share_system_state')->where('key', 'reward_bases_cursor')->value('value'));
  743. $this->expectException(\InvalidArgumentException::class);
  744. (new RewardBaseSyncService())->run('2026-10-20', null);
  745. }
  746. public function test_rules_migration_removes_the_three_global_settings_and_rollback_restores_them(): void
  747. {
  748. $this->assertSame(['huishui_restriction'], DB::table('config')->pluck('field')->all());
  749. $this->assertTrue(Schema::hasColumns('rebates', ['details', 'need_flow']));
  750. $this->rulesMigration()->down();
  751. $this->assertEqualsCanonicalizing(['rebate', 'huishui_restriction', 'huishui_percentage'], DB::table('config')->pluck('field')->all());
  752. $this->assertSame('0.005', DB::table('config')->where('field', 'rebate')->value('val'));
  753. $this->assertFalse(Schema::hasTable('rebate_rules'));
  754. $this->assertFalse(Schema::hasColumn('backflow', 'loss_amount'));
  755. }
  756. }