WageringTest.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. <?php
  2. namespace Tests\Integration;
  3. use App\Console\Commands\MigrateFrozenRewards;
  4. use App\Models\Wallet;
  5. use App\Models\Withdraw;
  6. use App\Services\BalanceLogService;
  7. use App\Services\ManualAuditService;
  8. use App\Services\WageringService;
  9. use App\Services\WalletFreezeService;
  10. use App\Services\WithdrawFundsService;
  11. use Illuminate\Config\Repository;
  12. use Illuminate\Database\Capsule\Manager;
  13. use Illuminate\Database\Schema\Blueprint;
  14. use Illuminate\Foundation\Application;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Support\Facades\Facade;
  17. use PHPUnit\Framework\TestCase;
  18. use Symfony\Component\Console\Input\ArrayInput;
  19. use Symfony\Component\Console\Output\BufferedOutput;
  20. /** 统一提现打码量、人工冻结/解冻与提现冻结,直接跑真实服务和上线迁移(SQLite)。 */
  21. class WageringTest extends TestCase
  22. {
  23. private Application $app;
  24. protected function setUp(): void
  25. {
  26. Facade::clearResolvedInstances();
  27. $this->app = new Application(dirname(__DIR__, 2));
  28. $this->app->instance('config', new Repository(['app' => ['timezone' => 'Asia/Shanghai'], 'third_game' => ['currency' => 'CNY']]));
  29. Facade::setFacadeApplication($this->app);
  30. $db = new Manager($this->app);
  31. $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'bot_']);
  32. $db->setAsGlobal();
  33. $db->bootEloquent();
  34. $this->app->instance('db', $db->getDatabaseManager());
  35. $this->app->bind('db.schema', fn () => $db->schema());
  36. $schema = $db->schema();
  37. $schema->create('users', function (Blueprint $t) {
  38. $t->id(); $t->string('member_id')->unique(); $t->string('account')->default(''); $t->string('username')->default('');
  39. $t->string('first_name')->default(''); $t->integer('from')->default(1); $t->integer('level')->default(0);
  40. $t->integer('recharge_channel_group_id')->default(1); $t->string('agent_user_code')->nullable(); $t->string('user_code')->nullable();
  41. $t->string('language')->default('zh'); $t->timestamps();
  42. });
  43. $schema->create('wallets', function (Blueprint $t) {
  44. $t->id(); $t->unsignedBigInteger('user_id')->nullable(); $t->string('member_id')->unique();
  45. $t->decimal('available_balance', 30, 10)->default(0); $t->decimal('frozen_balance', 30, 10)->default(0);
  46. $t->decimal('flow_balance', 10, 2)->default(0); $t->timestamps();
  47. });
  48. $schema->create('balance_logs', function (Blueprint $t) {
  49. $t->id(); $t->string('member_id'); $t->integer('type')->default(1); $t->string('change_type'); $t->decimal('amount', 30, 10);
  50. $t->decimal('before_balance', 30, 10)->nullable(); $t->decimal('after_balance', 30, 10)->nullable();
  51. $t->integer('related_id')->nullable(); $t->integer('room_id')->nullable(); $t->integer('frozen_status')->nullable();
  52. $t->text('remark')->nullable(); $t->timestamps();
  53. });
  54. $schema->create('config', function (Blueprint $t) {
  55. $t->id(); $t->string('field'); $t->string('val'); $t->string('remark')->default(''); $t->integer('group_id')->default(1); $t->timestamps();
  56. });
  57. $schema->create('level', function (Blueprint $t) { $t->id(); $t->integer('level'); $t->decimal('recharge', 20, 2); $t->timestamps(); });
  58. $schema->create('recharge_channel_group', function (Blueprint $t) { $t->id(); $t->text('activity_type')->nullable(); $t->softDeletes(); $t->timestamps(); });
  59. $schema->create('backflow', function (Blueprint $t) {
  60. $t->id(); $t->string('member_id'); $t->string('date');
  61. foreach (['recharge_amount', 'withdrawal_amount', 'backflow_ratio', 'amount'] as $field) $t->decimal($field, 20, 2)->default(0);
  62. $t->timestamps();
  63. });
  64. $schema->create('withdraws', function (Blueprint $t) {
  65. $t->id(); $t->string('member_id'); $t->decimal('amount', 30, 10); $t->decimal('service_charge', 30, 10)->default(0);
  66. $t->decimal('to_account', 30, 10)->default(0); $t->string('address')->default(''); $t->decimal('exchange_rate', 20, 4)->default(1);
  67. $t->integer('status')->default(0); $t->decimal('after_balance', 30, 10)->nullable(); $t->string('remark')->nullable(); $t->timestamps();
  68. });
  69. $schema->create('payment_orders', function (Blueprint $t) {
  70. $t->id(); $t->string('member_id'); $t->integer('type'); $t->integer('status'); $t->decimal('amount', 30, 10); $t->timestamps();
  71. });
  72. $schema->create('share_bet_facts', function (Blueprint $t) {
  73. $t->id(); $t->string('source', 32); $t->string('source_id', 64); $t->unsignedBigInteger('user_id'); $t->string('member_id', 64);
  74. $t->string('category', 32)->default('lottery'); $t->dateTime('bet_at'); $t->date('bet_date'); $t->dateTime('settled_at')->nullable();
  75. foreach (['bet_amount', 'net_profit', 'effective_amount'] as $c) $t->decimal($c, 24, 10)->default(0);
  76. $t->boolean('settled')->default(true); $t->boolean('voided')->default(false); $t->string('currency', 8)->default('CNY');
  77. $t->string('source_version', 64)->default('1'); $t->timestamps();
  78. });
  79. $schema->create('admin', function (Blueprint $t) { $t->id(); $t->string('username'); $t->timestamps(); });
  80. DB::table('config')->insert([
  81. ['field' => 'huishui_percentage', 'val' => '0'], ['field' => 'huishui_restriction', 'val' => '999999'], ['field' => 'recharge_rate', 'val' => '0'],
  82. ]);
  83. DB::table('level')->insert(['level' => 0, 'recharge' => '0']);
  84. DB::table('admin')->insert(['id' => 9, 'username' => 'auditor']);
  85. DB::table('recharge_channel_group')->insert(['id' => 1, 'activity_type' => '']);
  86. DB::table('users')->insert(['id' => 1, 'member_id' => 'm1', 'account' => 'acc1', 'created_at' => '2026-01-01 00:00:00']);
  87. DB::table('wallets')->insert(['user_id' => 1, 'member_id' => 'm1', 'available_balance' => '100', 'created_at' => '2026-01-01 00:00:00']);
  88. WageringService::flushSchemaCache();
  89. (require dirname(__DIR__, 2) . '/database/migrations/2026_11_04_140000_create_wagering_and_wallet_freezes.php')->up();
  90. WageringService::flushSchemaCache();
  91. DB::table('config')->where('field', WageringService::CONFIG_FIELD)->update(['val' => '2']);
  92. }
  93. protected function tearDown(): void
  94. {
  95. WageringService::flushSchemaCache();
  96. DB::disconnect();
  97. Facade::clearResolvedInstances();
  98. parent::tearDown();
  99. }
  100. private function wallet(): Wallet
  101. {
  102. return Wallet::where('member_id', 'm1')->first();
  103. }
  104. private function bet(string $stake, string $profit): void
  105. {
  106. static $id = 0;
  107. $now = now('Asia/Shanghai')->format('Y-m-d H:i:s');
  108. DB::table('share_bet_facts')->insert(['source' => 'lhc_order_item', 'source_id' => (string)++$id, 'user_id' => 1, 'member_id' => 'm1',
  109. 'bet_at' => $now, 'bet_date' => substr($now, 0, 10), 'bet_amount' => $stake, 'net_profit' => $profit, 'created_at' => $now, 'updated_at' => $now]);
  110. }
  111. private function hold(string $amount): Withdraw
  112. {
  113. [$order] = WithdrawFundsService::hold('m1', $amount, '提现', '', WithdrawFundsService::WITHDRAWS,
  114. fn ($before, $after) => Withdraw::create(['member_id' => 'm1', 'amount' => $amount, 'status' => 0, 'after_balance' => $after]));
  115. return $order;
  116. }
  117. private function money($value): string
  118. {
  119. return bcadd((string)$value, '0', 2);
  120. }
  121. private function assertBlocked(callable $work, string $message): void
  122. {
  123. try { $work(); $this->fail('Expected: ' . $message); }
  124. catch (\Exception $e) { $this->assertStringContainsString($message, $e->getMessage()); }
  125. }
  126. public function test_migration_starts_a_cycle_and_configures_the_platform_multiple(): void
  127. {
  128. $wallet = $this->wallet();
  129. $this->assertSame('2026-01-01 00:00:00', (string)$wallet->wager_cycle_from);
  130. $this->assertSame('[]', (string)$wallet->wager_cycle_cursors);
  131. $this->assertSame('2.0000000000', WageringService::multiple());
  132. $this->assertSame(1, DB::table('config')->where('field', WageringService::CONFIG_FIELD)->count());
  133. }
  134. public function test_deposit_requirement_blocks_withdrawal_until_effective_bets_complete_it_then_resets(): void
  135. {
  136. BalanceLogService::addLog('m1', '100', '0', '100', '人工充值', null, '');
  137. $this->assertSame('200.00', $this->money($this->wallet()->wager_required));
  138. $this->assertSame('recharge', DB::table('wager_records')->value('source'));
  139. $this->bet('150', '-150');
  140. $this->assertBlocked(fn () => $this->hold('50'), '剩余打码量:50.00');
  141. $this->bet('100', '1'); // 有效投注 = min(本金, |盈亏|) = 1
  142. $this->assertBlocked(fn () => $this->hold('50'), '剩余打码量:49.00');
  143. $this->bet('49', '49');
  144. $this->assertSame(['wager_required' => '200.00', 'wager_completed' => '200.00', 'wager_remaining' => '0.00'],
  145. WageringService::summary(tap($this->wallet(), fn ($w) => WageringService::refresh($w))));
  146. $order = $this->hold('50');
  147. $wallet = $this->wallet();
  148. $this->assertSame('50.00', $this->money($wallet->available_balance));
  149. $this->assertSame('50.00', $this->money($wallet->frozen_balance));
  150. $this->assertSame('50.00', $this->money($order->fresh()->frozen_amount));
  151. $this->assertSame(['wager_required' => '0.00', 'wager_completed' => '0.00', 'wager_remaining' => '0.00'], WageringService::summary($wallet));
  152. $this->assertSame(1, (int)$wallet->wager_cycle_id);
  153. $this->assertSame('holding', DB::table('wallet_freeze_records')->where('type', 'withdraw_hold')->value('status'));
  154. $this->assertSame('-50.00', $this->money(DB::table('balance_logs')->where('change_type', '提现')->value('amount')));
  155. // 新周期只统计重置后的新注单
  156. WageringService::refresh($wallet);
  157. $this->assertSame('0.00', $this->money($wallet->fresh()->wager_completed));
  158. }
  159. public function test_requirements_from_several_sources_add_up_and_any_unfinished_one_blocks(): void
  160. {
  161. $wallet = $this->wallet();
  162. WageringService::addRequirement($wallet, '30', 'activity:即充即送', 1);
  163. WageringService::addRequirement($wallet, '20', 'activity:promotion', 2);
  164. $this->bet('45', '-45');
  165. $this->assertBlocked(fn () => $this->hold('10'), '剩余打码量:5.00');
  166. $this->bet('5', '-5');
  167. $this->hold('10');
  168. $this->assertSame('90.00', $this->money($this->wallet()->available_balance));
  169. }
  170. public function test_requirement_increment_is_kept_when_the_caller_holds_a_stale_wallet(): void
  171. {
  172. $stale = $this->wallet();
  173. WageringService::addRequirementFor('m1', '50', 'recharge', 1);
  174. WageringService::addRequirement($stale, '20', 'activity:promotion', 2);
  175. $this->assertSame('70.00', $this->money($this->wallet()->wager_required));
  176. $this->assertSame('50.00', $this->money(DB::table('wager_records')->where('source_id', '2')->value('before_required')));
  177. }
  178. public function test_reward_without_requirement_is_withdrawable_and_requirement_never_goes_negative(): void
  179. {
  180. $wallet = $this->wallet();
  181. $this->assertNull(WageringService::addRequirement($wallet, '0', 'activity:即充即送', 1));
  182. WageringService::addRequirement($wallet, '-5', 'freeze', 1);
  183. $this->assertSame('0.00', $this->money($wallet->fresh()->wager_required));
  184. $this->hold('10');
  185. $this->assertSame('90.00', $this->money($this->wallet()->available_balance));
  186. }
  187. public function test_reject_releases_and_approve_settles_the_frozen_withdrawal_exactly_once(): void
  188. {
  189. $order = $this->hold('40');
  190. $this->assertNotNull(WithdrawFundsService::release(WithdrawFundsService::WITHDRAWS, $order, '999', '提现', ''));
  191. $this->assertNull(WithdrawFundsService::release(WithdrawFundsService::WITHDRAWS, $order, '999', '提现', ''));
  192. $wallet = $this->wallet();
  193. $this->assertSame('100.00', $this->money($wallet->available_balance));
  194. $this->assertSame('0.00', $this->money($wallet->frozen_balance));
  195. $this->assertSame('released', DB::table('wallet_freeze_records')->value('status'));
  196. $this->assertSame('40.00', $this->money(DB::table('balance_logs')->where('change_type', '提现')->where('amount', '>', 0)->value('amount')));
  197. $order = $this->hold('30');
  198. WithdrawFundsService::settle(WithdrawFundsService::WITHDRAWS, $order);
  199. WithdrawFundsService::settle(WithdrawFundsService::WITHDRAWS, $order);
  200. $wallet = $this->wallet();
  201. $this->assertSame('70.00', $this->money($wallet->available_balance));
  202. $this->assertSame('0.00', $this->money($wallet->frozen_balance));
  203. $this->assertSame('settled', DB::table('wallet_freeze_records')->orderByDesc('id')->value('status'));
  204. }
  205. public function test_orders_created_before_launch_keep_the_old_refund_behaviour(): void
  206. {
  207. $legacy = Withdraw::create(['member_id' => 'm1', 'amount' => '25', 'status' => 0]);
  208. WithdrawFundsService::settle(WithdrawFundsService::WITHDRAWS, $legacy);
  209. $this->assertSame('100.00', $this->money($this->wallet()->available_balance));
  210. WithdrawFundsService::release(WithdrawFundsService::WITHDRAWS, $legacy, '25', '提现', '');
  211. $wallet = $this->wallet();
  212. $this->assertSame('125.00', $this->money($wallet->available_balance));
  213. $this->assertSame('0.00', $this->money($wallet->frozen_balance));
  214. }
  215. public function test_manual_freeze_and_unfreeze_move_balance_and_adjust_wagering(): void
  216. {
  217. WageringService::addRequirement($this->wallet(), '100', 'recharge', 1);
  218. $frozen = WalletFreezeService::freeze('11111111-1111-4111-8111-111111111111', 9, 'm1', '30', '40', '风控冻结');
  219. $this->assertSame('人工冻结', $frozen['type_text']);
  220. $wallet = $this->wallet();
  221. $this->assertSame('70.00', $this->money($wallet->available_balance));
  222. $this->assertSame('30.00', $this->money($wallet->frozen_balance));
  223. $this->assertSame('60.00', $this->money($wallet->wager_required));
  224. $this->assertSame('-30.00', $this->money(DB::table('balance_logs')->where('change_type', '人工冻结')->value('amount')));
  225. // 提现冻结的资金不能被人工解冻
  226. $this->bet('60', '-60');
  227. $this->hold('10');
  228. $this->assertSame('40.00', $this->money($this->wallet()->frozen_balance));
  229. $this->assertBlocked(fn () => WalletFreezeService::unfreeze('22222222-2222-4222-8222-222222222222', 9, 'm1', '35', '0', 'x'), '最多可解冻:30.00');
  230. WalletFreezeService::unfreeze('33333333-3333-4333-8333-333333333333', 9, 'm1', '20', '15', '核实解冻');
  231. $wallet = $this->wallet();
  232. $this->assertSame('80.00', $this->money($wallet->available_balance));
  233. $this->assertSame('20.00', $this->money($wallet->frozen_balance));
  234. $this->assertSame('15.00', $this->money($wallet->wager_required)); // 提现已把周期重置为0,解冻再加15
  235. $this->assertSame('10.0000000000', WalletFreezeService::manualFrozen('m1'));
  236. // 同一 request_id 重放返回原记录,不同内容拒绝
  237. $replay = WalletFreezeService::unfreeze('33333333-3333-4333-8333-333333333333', 9, 'm1', '20', '15', '核实解冻');
  238. $this->assertSame(3, DB::table('wallet_freeze_records')->whereIn('type', ['manual_freeze', 'manual_unfreeze', 'withdraw_hold'])->count());
  239. $this->assertSame('20.00', $replay['amount']);
  240. $this->assertBlocked(fn () => WalletFreezeService::unfreeze('33333333-3333-4333-8333-333333333333', 9, 'm1', '21', '15', 'x'), 'request_id');
  241. $list = WalletFreezeService::list(['member_id' => 'm1']);
  242. $this->assertSame(3, $list['total']);
  243. $this->assertSame('acc1', $list['data'][0]['account']);
  244. $this->assertSame('auditor', $list['data'][0]['admin_name']);
  245. }
  246. public function test_manual_balance_adjustment_wagering_rules(): void
  247. {
  248. $this->assertSame([WageringService::platformRequirement('10'), false], ManualAuditService::wagerDelta(false, '10', '人工充值', null, '999'));
  249. $this->assertSame('20.0000000000', WageringService::platformRequirement('10'));
  250. $this->assertSame(['30.0000000000', true], ManualAuditService::wagerDelta(false, '10', '注册赠送', null, '30'));
  251. $this->assertSame(['0.0000000000', true], ManualAuditService::wagerDelta(false, '10', '优惠活动', null, null));
  252. $this->assertSame(['-20.0000000000', true], ManualAuditService::wagerDelta(true, '10', '人工扣款', '人工充值', '999'));
  253. $this->assertSame(['-5.0000000000', true], ManualAuditService::wagerDelta(true, '10', '人工扣款', '优惠活动', '5'));
  254. $this->assertSame(['0', false], ManualAuditService::wagerDelta(true, '10', '人工扣款', null, null));
  255. }
  256. public function test_refresh_never_overwrites_a_cycle_that_was_reset_meanwhile(): void
  257. {
  258. $stale = $this->wallet();
  259. $this->bet('80', '-80');
  260. Wallet::where('id', $stale->id)->update(['wager_cycle_id' => 5, 'wager_completed' => 0]);
  261. WageringService::refresh($stale);
  262. $this->assertSame('0.00', $this->money($this->wallet()->wager_completed));
  263. WageringService::refresh($this->wallet());
  264. $this->assertSame('80.00', $this->money($this->wallet()->wager_completed));
  265. }
  266. public function test_one_time_migration_moves_frozen_rewards_to_available_and_carries_their_wagering(): void
  267. {
  268. DB::table('wallets')->where('member_id', 'm1')->update(['frozen_balance' => '25', 'flow_balance' => '4']);
  269. DB::table('balance_logs')->insert([
  270. ['member_id' => 'm1', 'type' => 2, 'change_type' => '即充即送', 'amount' => '10', 'related_id' => 7, 'frozen_status' => 1],
  271. ['member_id' => 'm1', 'type' => 2, 'change_type' => '老用户回归', 'amount' => '10', 'related_id' => 7, 'frozen_status' => 1],
  272. ['member_id' => 'm1', 'type' => 2, 'change_type' => '老用户回归', 'amount' => '5', 'related_id' => 8, 'frozen_status' => 1],
  273. ]);
  274. DB::connection()->getSchemaBuilder()->create('wallet_bonus', function (Blueprint $t) {
  275. $t->id(); $t->string('member_id'); $t->integer('activity_id'); $t->integer('related_id')->nullable();
  276. $t->decimal('amount', 20, 2); $t->decimal('need_flow', 20, 2); $t->decimal('remaind_flow', 20, 2); $t->integer('status'); $t->timestamps();
  277. });
  278. // 同一笔充值的两条同额奖励各自对应一条 wallet_bonus
  279. DB::table('wallet_bonus')->insert([
  280. ['member_id' => 'm1', 'activity_id' => 1, 'related_id' => 7, 'amount' => '10', 'need_flow' => '30', 'remaind_flow' => '30', 'status' => 1],
  281. ['member_id' => 'm1', 'activity_id' => 2, 'related_id' => 7, 'amount' => '10', 'need_flow' => '10', 'remaind_flow' => '10', 'status' => 1],
  282. ]);
  283. $run = function (array $options) {
  284. $command = new MigrateFrozenRewards();
  285. $command->setLaravel($this->app);
  286. $output = new BufferedOutput();
  287. $command->run(new ArrayInput($options), $output);
  288. return $output->fetch();
  289. };
  290. $run(['--dry-run' => true]);
  291. $this->assertSame('25.00', $this->money($this->wallet()->frozen_balance));
  292. $this->assertSame(0, DB::table('wager_records')->count());
  293. // 进行中的申请活动:一条是上线前的(迁移剩余打码量),一条已按新流程记过打码量(跳过)
  294. DB::connection()->getSchemaBuilder()->create('activity_user', function (Blueprint $t) {
  295. $t->id(); $t->string('member_id'); $t->integer('status'); $t->decimal('betting_amount', 20, 2); $t->decimal('effective_betting_amount', 20, 2);
  296. });
  297. DB::table('activity_user')->insert([
  298. ['id' => 1, 'member_id' => 'm1', 'status' => \App\Models\ActivityUser::STATUS_IN_PROGRESS, 'betting_amount' => '20', 'effective_betting_amount' => '5'],
  299. ['id' => 2, 'member_id' => 'm1', 'status' => \App\Models\ActivityUser::STATUS_IN_PROGRESS, 'betting_amount' => '100', 'effective_betting_amount' => '0'],
  300. ]);
  301. WageringService::addRequirement($this->wallet(), '100', 'activity:activity_user', 2, '新流程发奖');
  302. $run([]);
  303. $run([]); // 重复执行不重复处理
  304. $wallet = $this->wallet();
  305. $this->assertSame('0.00', $this->money($wallet->frozen_balance));
  306. $this->assertSame('125.00', $this->money($wallet->available_balance));
  307. // 新流程已记 100;两条同额奖励分别取 30 和 10,无记录的按1倍5,减去旧流水余额4;上线前的申请活动剩余 15
  308. $this->assertSame('156.00', $this->money($wallet->wager_required));
  309. $this->assertSame(0, DB::table('balance_logs')->where('type', 2)->where('frozen_status', 1)->count());
  310. $this->assertSame(3, DB::table('balance_logs')->where('change_type', '流水解冻')->where('type', 1)->count());
  311. }
  312. }