app = new Application(dirname(__DIR__, 2)); $this->app->instance('config', new Repository(['app' => ['locale' => 'zh', 'timezone' => 'Asia/Shanghai']])); Facade::setFacadeApplication($this->app); $db = new Manager($this->app); $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'bot_']); $db->setAsGlobal(); $db->bootEloquent(); $this->app->instance('db', $db->getDatabaseManager()); $translator = new Translator(new ArrayLoader(), 'zh'); $this->app->instance('translator', $translator); $this->app->instance('validator', new Factory($translator, $this->app)); $this->app->instance(\Illuminate\Contracts\Routing\ResponseFactory::class, new class { public function json($data, $status = 200, $headers = [], $options = 0) { return new JsonResponse($data, $status, $headers, $options); } }); Request::macro('validate', function (array $rules) { return app('validator')->make($this->all(), $rules)->validate(); }); $db->schema()->create('users', function (Blueprint $t) { $t->id(); $t->string('member_id')->unique(); $t->string('account'); $t->string('first_name'); $t->string('user_code'); $t->string('agent_user_code')->nullable(); $t->integer('from')->default(1); $t->integer('level')->default(0); $t->integer('recharge_channel_group_id')->default(1); $t->timestamps(); }); $db->schema()->create('wallets', function (Blueprint $t) { $t->id(); $t->string('member_id')->unique(); $t->decimal('available_balance', 24, 10)->default(0); $t->decimal('frozen_balance', 24, 10)->default(0); $t->timestamps(); }); $db->schema()->create('balance_logs', function (Blueprint $t) { $t->id(); $t->string('member_id'); $t->integer('type')->default(1); $t->string('change_type'); $t->decimal('amount', 24, 10); $t->decimal('before_balance', 24, 10); $t->decimal('after_balance', 24, 10); $t->integer('related_id')->nullable(); $t->text('remark')->nullable(); $t->timestamps(); }); $db->schema()->create('share_commission_records', function (Blueprint $t) { $t->id(); $t->date('stat_date'); $t->integer('promoter_user_id'); $t->integer('invitee_user_id')->nullable(); $t->string('type'); $t->string('category'); $t->decimal('base_amount', 20, 4); $t->decimal('rate', 8, 4); $t->decimal('amount', 20, 4); $t->string('source_type'); $t->string('source_id'); $t->integer('status'); $t->timestamps(); $t->unique(['source_type', 'source_id', 'type', 'promoter_user_id'], 'uniq_share_source'); }); $db->schema()->create('config', function (Blueprint $t) { $t->id(); $t->string('field'); $t->string('val'); $t->timestamps(); }); $db->schema()->create('level', function (Blueprint $t) { $t->id(); $t->integer('level'); $t->decimal('recharge', 20, 2); $t->timestamps(); }); $db->schema()->create('recharge_channel_group', function (Blueprint $t) { $t->id(); $t->text('activity_type')->nullable(); $t->softDeletes(); $t->timestamps(); }); $db->schema()->create('backflow', function (Blueprint $t) { $t->id(); $t->string('member_id'); $t->string('date'); foreach (['recharge_amount', 'withdrawal_amount', 'backflow_ratio', 'amount'] as $field) { $t->decimal($field, 20, 2)->default(0); } $t->timestamps(); }); DB::table('config')->insert([ ['field' => 'recharge_rate', 'val' => '2.5000'], ['field' => 'huishui_percentage', 'val' => '0'], ['field' => 'huishui_restriction', 'val' => '999999'], ]); DB::table('level')->insert(['level' => 0, 'recharge' => 0]); DB::table('recharge_channel_group')->insert(['id' => 1, 'activity_type' => '']); DB::table('backflow')->insert(['member_id' => '1002', 'date' => date('Y-m')]); DB::table('users')->insert([ ['id' => 7, 'member_id' => '1001', 'account' => 'promoter', 'first_name' => '推广人', 'user_code' => 'PROMO', 'agent_user_code' => null], ['id' => 42, 'member_id' => '1002', 'account' => 'invitee', 'first_name' => '被邀请人', 'user_code' => 'CHILD', 'agent_user_code' => 'PROMO'], ]); DB::table('wallets')->insert([ ['member_id' => '1001', 'available_balance' => '20.00'], ['member_id' => '1002', 'available_balance' => '100.00'], ]); $this->app->instance('request', Request::create('/admin/shareEarning/summary', 'GET', [])); } protected function tearDown(): void { DB::disconnect(); Facade::clearResolvedInstances(); parent::tearDown(); } public static function depositTypes(): array { return [['充值'], ['三方充值']]; } /** @dataProvider depositTypes */ public function test_existing_rebate_payment_registers_real_commission_and_is_visible_in_summary(string $type): void { BalanceLogService::addLog('1002', '100.00', '0.00', '100.00', $type, 88, ''); $rebate = BalanceLog::where('change_type', '充值返现')->firstOrFail(); $record = ShareCommissionRecord::firstOrFail(); $this->assertSame(7, (int)$record->promoter_user_id); $this->assertSame(42, (int)$record->invitee_user_id); $this->assertSame('100.0000', $record->base_amount); $this->assertSame('2.5000', $record->rate); $this->assertSame('2.5000', $record->amount); $this->assertSame(ShareCommissionRecorder::SOURCE_TYPE, $record->source_type); $this->assertSame((string)$rebate->id, $record->source_id); $this->assertEquals('22.50', DB::table('wallets')->where('member_id', '1001')->value('available_balance')); $this->assertEquals('100.00', DB::table('wallets')->where('member_id', '1002')->value('available_balance')); $body = (new ShareEarning())->summary(new ShareEarningReportService())->getData(true); $this->assertSame(0, $body['code']); $this->assertSame(1, $body['data']['total']); $this->assertSame('promoter', $body['data']['data'][0]['promoter_account']); $this->assertSame('100.0000', $body['data']['data'][0]['deposit']); $this->assertSame('2.5000', $body['data']['summary']['total_commission']); } public function test_live_record_keeps_original_rate_and_base_precision(): void { BalanceLogService::addLog('1002', '100.1256789012', '0.00', '100.1256789012', '充值', 88, ''); $record = ShareCommissionRecord::firstOrFail(); $this->assertSame('100.1257', $record->base_amount); $this->assertSame('2.5000', $record->rate); $this->assertSame('2.5000', $record->amount); } public static function unrelatedDeposits(): array { return [['人工充值', 'PROMO', 1], ['优惠活动', 'PROMO', 1], ['充值', '', 1], ['充值', 'MISSING', 1], ['充值', 'PROMO', 2]]; } /** @dataProvider unrelatedDeposits */ public function test_recording_does_not_expand_the_existing_payment_rules(string $type, string $code, int $from): void { DB::table('users')->where('member_id', '1002')->update(['agent_user_code' => $code, 'from' => $from]); BalanceLogService::addLog('1002', '100.00', '0.00', '100.00', $type, 88, ''); $this->assertSame(0, ShareCommissionRecord::count()); $this->assertSame(0, BalanceLog::where('change_type', '充值返现')->count()); $this->assertEquals('20.00', DB::table('wallets')->where('member_id', '1001')->value('available_balance')); } public function test_commission_insert_failure_rolls_back_the_rebate_wallet_and_ledger(): void { DB::statement("CREATE TRIGGER fail_share_insert BEFORE INSERT ON bot_share_commission_records BEGIN SELECT RAISE(ABORT, 'injected share failure'); END"); try { BalanceLogService::addLog('1002', '100.00', '0.00', '100.00', '充值', 88, ''); $this->fail('Commission failure must abort the rebate payment.'); } catch (\Illuminate\Database\QueryException $e) { $this->assertStringContainsString('injected share failure', $e->getMessage()); } $this->assertSame(0, DB::transactionLevel()); $this->assertEquals('20.00', DB::table('wallets')->where('member_id', '1001')->value('available_balance')); $this->assertSame(0, BalanceLog::where('change_type', '充值返现')->count()); $this->assertSame(0, ShareCommissionRecord::count()); $this->assertSame(1, BalanceLog::where('change_type', '充值')->count()); } public function test_live_record_respects_the_callers_transaction_rollback(): void { DB::beginTransaction(); BalanceLogService::addLog('1002', '100.00', '0.00', '100.00', '三方充值', 88, ''); $this->assertSame(1, DB::transactionLevel()); $this->assertSame(1, ShareCommissionRecord::count()); DB::rollBack(); $this->assertEquals('20.00', DB::table('wallets')->where('member_id', '1001')->value('available_balance')); $this->assertSame(0, BalanceLog::count()); $this->assertSame(0, ShareCommissionRecord::count()); } private function historicalRebate(array $extra = []): BalanceLog { DB::table('wallets')->where('member_id', '1001')->update(['available_balance' => '22.50']); $log = new BalanceLog(); $log->forceFill($extra + [ 'member_id' => '1001', 'type' => 1, 'change_type' => '充值返现', 'related_id' => 88, 'amount' => '2.50', 'before_balance' => '20.00', 'after_balance' => '22.50', 'remark' => '被邀请人:1002充值金额为:100.00', 'created_at' => '2026-10-01 01:02:03', 'updated_at' => '2026-10-01 01:02:03', ])->save(); return $log; } public function test_historical_registration_is_idempotent_and_never_credits_again(): void { $rebate = $this->historicalRebate(); DB::table('config')->where('field', 'recharge_rate')->update(['val' => '99']); DB::table('users')->where('member_id', '1002')->update(['agent_user_code' => 'CHANGED']); $wallets = DB::table('wallets')->orderBy('id')->get()->toJson(); $ledger = DB::table('balance_logs')->orderBy('id')->get()->toJson(); $recorder = new ShareCommissionRecorder(); $this->assertSame('pending', $recorder->preview($rebate)['status']); $this->assertSame(0, ShareCommissionRecord::count()); $this->assertSame('created', $recorder->record($rebate)['status']); $this->assertSame('existing', $recorder->record($rebate)['status']); $this->assertSame(1, ShareCommissionRecord::count()); $record = ShareCommissionRecord::firstOrFail(); $this->assertSame('2026-10-01', $record->stat_date->format('Y-m-d')); $this->assertSame('2.5000', $record->rate); $this->assertSame('100.0000', $record->base_amount); $this->assertSame(42, (int)$record->invitee_user_id); $this->assertSame($wallets, DB::table('wallets')->orderBy('id')->get()->toJson()); $this->assertSame($ledger, DB::table('balance_logs')->orderBy('id')->get()->toJson()); } public function test_unknown_historical_details_keep_actual_payment_without_inventing_a_base(): void { $rebate = $this->historicalRebate(['remark' => '历史返现']); $result = (new ShareCommissionRecorder())->record($rebate); $this->assertSame('created', $result['status']); $this->assertTrue($result['incomplete_metadata']); $record = ShareCommissionRecord::firstOrFail(); $this->assertNull($record->invitee_user_id); $this->assertSame('0.0000', $record->base_amount); $this->assertSame('0.0000', $record->rate); $this->assertSame('2.5000', $record->amount); } public function test_historical_balance_comparison_uses_delta_before_rounding(): void { $rebate = $this->historicalRebate(['before_balance' => '20.0000499999', 'after_balance' => '22.5000500001']); $result = (new ShareCommissionRecorder())->record($rebate); $this->assertSame('created', $result['status']); $this->assertSame('2.5000', ShareCommissionRecord::firstOrFail()->amount); } public function test_same_payout_source_is_not_duplicated_when_user_rows_are_replaced(): void { $rebate = $this->historicalRebate(); $recorder = new ShareCommissionRecorder(); $recorder->record($rebate); DB::table('users')->where('id', 7)->delete(); DB::table('users')->insert(['id' => 9, 'member_id' => '1001', 'account' => 'reimported', 'first_name' => '重建账户', 'user_code' => 'PROMO']); $this->assertSame('existing', $recorder->record($rebate)['status']); $this->assertSame(1, ShareCommissionRecord::count()); $this->assertSame(7, (int)ShareCommissionRecord::firstOrFail()->promoter_user_id); } public static function invalidHistoricalLogs(): array { return [ [['amount' => '0.00', 'after_balance' => '20.00'], 'invalid_amount'], [['after_balance' => '20.00'], 'unbalanced_log'], [['member_id' => '9999'], 'missing_promoter'], [['type' => 2], 'not_recharge_rebate'], [['change_type' => '优惠活动'], 'not_recharge_rebate'], ]; } /** @dataProvider invalidHistoricalLogs */ public function test_invalid_historical_logs_are_reported_instead_of_booked(array $extra, string $reason): void { $rebate = $this->historicalRebate($extra); $result = (new ShareCommissionRecorder())->record($rebate); $this->assertSame('skipped', $result['status']); $this->assertSame($reason, $result['reason']); $this->assertSame(0, ShareCommissionRecord::count()); } public function test_backfill_does_not_reactivate_a_manually_voided_record(): void { $rebate = $this->historicalRebate(); $recorder = new ShareCommissionRecorder(); $recorder->record($rebate); ShareCommissionRecord::query()->update(['status' => 0]); $this->assertSame('existing', $recorder->record($rebate)['status']); $this->assertSame(0, ShareCommissionRecord::firstOrFail()->status); } private function command(array $options): CommandTester { $command = new BackfillShareCommissions(); $command->setLaravel($this->app); $tester = new CommandTester($command); $tester->execute($options); return $tester; } public function test_backfill_command_defaults_to_preview_and_write_is_repeatable(): void { $this->historicalRebate(); $options = ['--start-date' => '2026-10-01', '--end-date' => '2026-10-02', '--chunk' => 1]; $wallets = DB::table('wallets')->orderBy('id')->get()->toJson(); $preview = $this->command($options); $this->assertSame(0, $preview->getStatusCode()); $this->assertStringContainsString('只读预览', $preview->getDisplay()); $this->assertSame(0, ShareCommissionRecord::count()); $written = $this->command($options + ['--write' => true]); $this->assertSame(0, $written->getStatusCode(), $written->getDisplay()); $this->assertSame(1, ShareCommissionRecord::count()); $again = $this->command($options + ['--write' => true]); $this->assertSame(0, $again->getStatusCode()); $this->assertSame(1, ShareCommissionRecord::count()); $this->assertSame($wallets, DB::table('wallets')->orderBy('id')->get()->toJson()); } public function test_backfill_command_rejects_invalid_ranges_without_writing(): void { $this->historicalRebate(); $result = $this->command(['--start-date' => '2026-10-03', '--end-date' => '2026-10-01', '--write' => true]); $this->assertSame(1, $result->getStatusCode()); $this->assertSame(0, ShareCommissionRecord::count()); } }