| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772 |
- <?php
- namespace Tests\Integration;
- use App\Console\Commands\BackfillShareCommissions;
- use App\Http\Controllers\admin\ShareEarning;
- use App\Models\BalanceLog;
- use App\Models\ShareCommissionRecord;
- use App\Services\BalanceLogService;
- use App\Services\ShareCommissionRecorder;
- use App\Services\ShareCommissionDiagnostics;
- use App\Services\ShareEarningReportService;
- use Illuminate\Config\Repository;
- use Illuminate\Database\Capsule\Manager;
- use Illuminate\Database\Schema\Blueprint;
- use Illuminate\Foundation\Application;
- use Illuminate\Http\JsonResponse;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Facade;
- use Illuminate\Translation\ArrayLoader;
- use Illuminate\Translation\Translator;
- use Illuminate\Validation\Factory;
- use PHPUnit\Framework\TestCase;
- use Symfony\Component\Console\Tester\CommandTester;
- /** Real ledger, report controller and command against an isolated in-memory database. */
- class ShareCommissionRecordingTest extends TestCase
- {
- private Application $app;
- protected function setUp(): void
- {
- Facade::clearResolvedInstances();
- $this->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());
- }
- public function test_omitting_dates_is_not_full_history_and_all_can_backfill_old_receipts(): void
- {
- $rebate = $this->historicalRebate(['created_at' => '2020-01-01 00:00:00', 'updated_at' => '2020-01-01 00:00:00']);
- $default = $this->command([]);
- $this->assertSame(0, $default->getStatusCode());
- $this->assertStringContainsString('省略日期仍默认最近31天', $default->getDisplay());
- $this->assertSame(0, ShareCommissionRecord::count());
- $all = $this->command(['--all' => true]);
- $this->assertSame(0, $all->getStatusCode());
- $this->assertStringContainsString('全部历史', $all->getDisplay());
- $this->assertSame(0, ShareCommissionRecord::count());
- $written = $this->command(['--all' => true, '--write' => true]);
- $this->assertSame(0, $written->getStatusCode());
- $this->assertSame((string)$rebate->id, ShareCommissionRecord::firstOrFail()->source_id);
- $this->assertSame('2020-01-01', ShareCommissionRecord::firstOrFail()->stat_date->format('Y-m-d'));
- $this->assertEquals('22.50', DB::table('wallets')->where('member_id', '1001')->value('available_balance'));
- }
- private function depositForDiagnosis(): void
- {
- BalanceLog::create(['member_id' => '1002', 'type' => 1, 'change_type' => '充值',
- 'amount' => '100.00', 'before_balance' => '0.00', 'after_balance' => '100.00', 'remark' => '']);
- }
- public function test_diagnostics_show_a_zero_legacy_rate_despite_configured_share_settings_without_writing(): void
- {
- $this->depositForDiagnosis();
- DB::table('config')->where('field', 'recharge_rate')->update(['val' => '0']);
- DB::connection()->getSchemaBuilder()->create('share_settings', function (Blueprint $t) {
- $t->id(); $t->integer('enabled'); $t->decimal('tier_one_rate', 8, 4); $t->decimal('tier_two_rate', 8, 4);
- });
- DB::table('share_settings')->insert(['enabled' => 1, 'tier_one_rate' => '4.00', 'tier_two_rate' => '6.00']);
- $tables = ['users', 'wallets', 'balance_logs', 'share_commission_records', 'config', 'share_settings'];
- $before = [];
- foreach ($tables as $table) $before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
- $data = (new ShareCommissionDiagnostics())->inspect(null);
- $this->assertSame(':memory:', $data['database']);
- $this->assertSame('bot_', $data['table_prefix']);
- $this->assertSame('0', $data['recharge_rate']);
- $this->assertArrayNotHasKey('tier_one_rate', $data);
- $this->assertArrayNotHasKey('tier_two_rate', $data);
- $this->assertSame(0, $data['counts']['rebate_logs_all']);
- $this->assertSame(1, $data['counts']['real_invitee_deposit_logs_all']);
- $this->assertSame(1, $data['counts']['linked_real_invitee_deposit_logs_all']);
- $this->assertSame(1, $data['counts']['with_promoter_wallet_deposit_logs_all']);
- $run = $this->command(['--diagnose' => true, '--all' => true]);
- $this->assertSame(0, $run->getStatusCode(), $run->getDisplay());
- $this->assertStringContainsString('全部历史没有', $run->getDisplay());
- $this->assertStringContainsString('当前 recharge_rate 缺失、无效或为0', $run->getDisplay());
- $this->assertStringContainsString('share_enabled: 1', $run->getDisplay());
- foreach ($tables as $table) $this->assertSame($before[$table], DB::table($table)->orderBy('id')->get()->toJson(), $table);
- }
- public function test_diagnostics_separate_type_amount_and_date_filters(): void
- {
- $this->historicalRebate(['created_at' => '2020-01-01 00:00:00']);
- $this->historicalRebate(['type' => 2]);
- $this->historicalRebate(['amount' => '0', 'after_balance' => '20']);
- $selected = $this->historicalRebate();
- (new ShareCommissionRecorder())->record($selected);
- $data = (new ShareCommissionDiagnostics())->inspect(['2026-10-01 00:00:00', '2026-10-02 23:59:59']);
- $this->assertSame(4, $data['counts']['rebate_logs_all']);
- $this->assertSame(3, $data['counts']['type1_rebate_logs_all']);
- $this->assertSame(2, $data['counts']['positive_type1_rebate_logs_all']);
- $this->assertSame(1, $data['counts']['selected_rebate_logs']);
- $this->assertSame('2020-01-01 00:00:00', $data['first_rebate_at']);
- $this->assertSame('2026-10-01 01:02:03', $data['last_rebate_at']);
- $this->assertSame(1, $data['counts']['active_commission_records_selected']);
- }
- public static function brokenReferralStages(): array
- {
- return [
- [2, 'PROMO', false, [0, 0, 0, 0, 0]],
- [1, 'MISSING', false, [1, 0, 1, 0, 0]],
- [1, 'PROMO', true, [1, 1, 1, 1, 0]],
- ];
- }
- /** @dataProvider brokenReferralStages */
- public function test_diagnostics_locate_real_user_referral_and_wallet_gaps(int $from, string $code, bool $missingWallet, array $expected): void
- {
- DB::table('users')->where('member_id', '1002')->update(['from' => $from, 'agent_user_code' => $code]);
- if ($missingWallet) DB::table('wallets')->where('member_id', '1001')->delete();
- $this->depositForDiagnosis();
- $counts = (new ShareCommissionDiagnostics())->inspect(null)['counts'];
- $this->assertSame(1, $counts['invited_members_all']);
- foreach (['real_invited_members_all', 'linked_real_invited_members_all', 'real_invitee_deposit_logs_all',
- 'linked_real_invitee_deposit_logs_all', 'with_promoter_wallet_deposit_logs_all'] as $i => $key) {
- $this->assertSame($expected[$i], $counts[$key], $key);
- }
- }
- public function test_read_only_diagnostics_cannot_be_combined_with_write_or_all_with_dates(): void
- {
- $this->historicalRebate();
- $run = $this->command(['--diagnose' => true, '--write' => true]);
- $this->assertSame(1, $run->getStatusCode());
- $this->assertSame(0, ShareCommissionRecord::count());
- $conflict = $this->command(['--all' => true, '--start-date' => '2026-10-01', '--write' => true]);
- $this->assertSame(1, $conflict->getStatusCode());
- $this->assertSame(0, ShareCommissionRecord::count());
- }
- public function test_diagnostic_referral_matches_the_existing_php_empty_zero_code_rule(): void
- {
- DB::table('users')->where('member_id', '1001')->update(['user_code' => '0']);
- DB::table('users')->where('member_id', '1002')->update(['agent_user_code' => '0']);
- $this->depositForDiagnosis();
- $counts = (new ShareCommissionDiagnostics())->inspect(null)['counts'];
- $this->assertSame(1, $counts['invited_members_all']);
- $this->assertSame(1, $counts['real_invited_members_all']);
- $this->assertSame(0, $counts['linked_real_invited_members_all']);
- $this->assertSame(0, $counts['linked_real_invitee_deposit_logs_all']);
- $this->assertSame(0, $counts['with_promoter_wallet_deposit_logs_all']);
- }
- private function summaryHistory(): void
- {
- DB::table('users')->insert(['id' => 99, 'member_id' => '1003', 'account' => 'other', 'first_name' => '其他推广人', 'user_code' => 'OTHER']);
- foreach ([
- ['2020-01-01', 7, 'commission', '100.0000', '2.5000', '2.5000', 1],
- ['2020-01-01', 7, 'fee_waiver', '40.0000', '2.5000', '1.0000', 1],
- ['2026-10-01', 7, 'commission', '200.0000', '2.5000', '5.0000', 1],
- ['2026-10-02', 7, 'commission', '1000.0000', '10.0000', '100.0000', 0],
- ['2026-10-05', 99, 'commission', '1000.0000', '10.0000', '100.0000', 1],
- ] as $i => [$day, $promoter, $type, $base, $rate, $amount, $status]) {
- ShareCommissionRecord::create([
- 'stat_date' => $day, 'promoter_user_id' => $promoter, 'type' => $type,
- 'category' => 'recharge', 'base_amount' => $base, 'rate' => $rate, 'amount' => $amount,
- 'source_type' => 'summary_test', 'source_id' => (string)$i, 'status' => $status,
- ]);
- }
- }
- private function summaryResponse(array $params): array
- {
- $request = Request::create('/admin/shareEarning/summary', 'GET', $params);
- return (new \App\Http\Middleware\TrimStrings())->handle($request, function ($request) {
- return (new \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull())->handle($request, function ($request) {
- $this->app->instance('request', $request);
- return (new ShareEarning())->summary(new ShareEarningReportService());
- });
- })->getData(true);
- }
- public static function clearedReportDates(): array
- {
- return [
- 'omitted' => [[]],
- 'null' => [['start_date' => null, 'end_date' => null]],
- 'empty strings from date picker' => [['start_date' => '', 'end_date' => '']],
- ];
- }
- /** @dataProvider clearedReportDates */
- public function test_summary_without_dates_includes_all_history_and_keeps_pagination_and_global_totals(array $dates): void
- {
- $this->summaryHistory();
- $before = DB::table('share_commission_records')->orderBy('id')->get()->toJson();
- $result = $this->summaryResponse($dates + ['account' => '', 'page' => 1, 'limit' => 1]);
- $this->assertSame(0, $result['code']);
- $this->assertSame(3, $result['data']['total']);
- $this->assertCount(1, $result['data']['data']);
- $this->assertSame('2026-10-05', $result['data']['data'][0]['date']);
- $this->assertSame('107.5000', $result['data']['summary']['total_commission']);
- $this->assertSame('2.5000', $result['data']['summary']['highest_fee_waiver_rate']);
- $last = $this->summaryResponse($dates + ['page' => 3, 'limit' => 1]);
- $this->assertSame('2020-01-01', $last['data']['data'][0]['date']);
- $this->assertSame('40.0000', $last['data']['data'][0]['sales_amount']);
- $this->assertSame($before, DB::table('share_commission_records')->orderBy('id')->get()->toJson());
- }
- public static function selectedSummaryDates(): array
- {
- return [
- ['2020-01-01', '2020-01-01', '2.5000', '2.5000'],
- ['2026-10-01', '2026-10-02', '5.0000', '0.0000'],
- ];
- }
- /** @dataProvider selectedSummaryDates */
- public function test_summary_explicit_dates_apply_to_list_count_and_totals(string $start, string $end, string $commission, string $feeRate): void
- {
- $this->summaryHistory();
- $result = $this->summaryResponse(['start_date' => $start, 'end_date' => $end, 'page' => 1, 'limit' => 10]);
- $this->assertSame(0, $result['code']);
- $this->assertSame(1, $result['data']['total']);
- $this->assertCount(1, $result['data']['data']);
- $this->assertSame($start, $result['data']['data'][0]['date']);
- $this->assertSame($commission, $result['data']['summary']['total_commission']);
- $this->assertSame($feeRate, $result['data']['summary']['highest_fee_waiver_rate']);
- }
- public function test_summary_default_all_history_still_applies_account_and_status_filters(): void
- {
- $this->summaryHistory();
- $result = $this->summaryResponse(['account' => 'prom', 'page' => 1, 'limit' => 10]);
- $this->assertSame(0, $result['code']);
- $this->assertSame(2, $result['data']['total']);
- $this->assertSame('7.5000', $result['data']['summary']['total_commission']);
- $this->assertSame('2.5000', $result['data']['summary']['highest_fee_waiver_rate']);
- $this->assertSame(['promoter', 'promoter'], array_column($result['data']['data'], 'promoter_account'));
- }
- public function test_summary_explicit_range_limit_remains_enforced(): void
- {
- $this->summaryHistory();
- $invalid = $this->summaryResponse(['start_date' => '2020-01-01', 'end_date' => '2026-10-01']);
- $this->assertSame(-3, $invalid['code']);
- $this->assertStringContainsString('366', $invalid['msg']);
- }
- private function memberHistory(): void
- {
- DB::connection()->getSchemaBuilder()->create('share_settings', function (Blueprint $t) {
- $t->id(); $t->decimal('valid_member_min_deposit', 20, 2);
- $t->decimal('tier_one_rate', 8, 4)->default(4);
- });
- DB::table('share_settings')->insert(['valid_member_min_deposit' => 20]);
- DB::connection()->getSchemaBuilder()->create('user_login', function (Blueprint $t) {
- $t->id(); $t->string('user_id'); $t->integer('status'); $t->string('platform');
- });
- DB::table('users')->where('id', 42)->update(['created_at' => '2020-01-01 00:00:00']);
- foreach ([
- [43, '1003', 'OTHER', '2020-01-01 23:59:59'],
- [44, '1004', 'PROMO', '2021-06-15 12:00:00'],
- [45, '1005', 'PROMO', date('Y-m-d') . ' 12:00:00'],
- [46, '1006', null, '2019-01-01 12:00:00'],
- [47, '1007', '', '2018-01-01 12:00:00'],
- ] as [$id, $memberId, $code, $createdAt]) {
- DB::table('users')->insert([
- 'id' => $id, 'member_id' => $memberId, 'account' => 'member' . $memberId,
- 'first_name' => '会员', 'user_code' => 'CODE' . $memberId,
- 'agent_user_code' => $code, 'created_at' => $createdAt,
- ]);
- }
- foreach ([
- ['1002', '充值', 100], ['1002', '提现', -10],
- ['1002', '投注', -20], ['1002', '优惠活动', 5], ['1003', '三方充值', 30],
- ] as [$memberId, $type, $amount]) {
- DB::table('balance_logs')->insert([
- 'member_id' => $memberId, 'change_type' => $type, 'amount' => $amount,
- 'before_balance' => 100, 'after_balance' => 100 + $amount,
- 'created_at' => date('Y-m-d H:i:s'),
- ]);
- }
- DB::table('user_login')->insert([
- ['user_id' => '1002', 'status' => 0, 'platform' => 'Android'],
- ['user_id' => '1002', 'status' => 1, 'platform' => 'H5'],
- ['user_id' => '1002', 'status' => 1, 'platform' => 'Android'],
- ['user_id' => '1003', 'status' => 1, 'platform' => 'Android'],
- ['user_id' => '1004', 'status' => 1, 'platform' => 'iOS'],
- ]);
- }
- private function membersResponse(array $params): array
- {
- $request = Request::create('/admin/shareEarning/members', 'GET', $params);
- return (new \App\Http\Middleware\TrimStrings())->handle($request, function ($request) {
- return (new \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull())->handle($request, function ($request) {
- $this->app->instance('request', $request);
- return (new ShareEarning())->memberList(new ShareEarningReportService());
- });
- })->getData(true);
- }
- /** @dataProvider clearedReportDates */
- public function test_members_without_dates_includes_historical_registration_days_without_backfill(array $dates): void
- {
- $this->memberHistory();
- $users = DB::table('users')->orderBy('id')->get()->toJson();
- $logs = DB::table('balance_logs')->orderBy('id')->get()->toJson();
- $result = $this->membersResponse($dates + ['page' => 1, 'limit' => 1]);
- $this->assertSame(0, $result['code']);
- $this->assertSame(3, $result['data']['total']);
- $this->assertCount(1, $result['data']['data']);
- $this->assertSame(date('Y-m-d'), $result['data']['data'][0]['date']);
- $last = $this->membersResponse($dates + ['page' => 3, 'limit' => 1]);
- $this->assertSame(3, $last['data']['total']);
- $row = $last['data']['data'][0];
- $this->assertSame('2020-01-01', $row['date']);
- $this->assertSame(2, $row['registered_members']);
- $this->assertSame(2, $row['promoter_count']);
- $this->assertSame(1, $row['h5_registered']);
- $this->assertSame(1, $row['android_registered']);
- $this->assertSame(0, $row['ios_registered']);
- $this->assertSame('130.0000', $row['deposit_total']);
- $this->assertSame('20.0000', $row['consume_total']);
- $this->assertSame('115.0000', $row['company_profit']);
- $this->assertSame($users, DB::table('users')->orderBy('id')->get()->toJson());
- $this->assertSame($logs, DB::table('balance_logs')->orderBy('id')->get()->toJson());
- $this->assertSame(0, ShareCommissionRecord::count());
- }
- public function test_members_explicit_dates_filter_registration_days_but_keep_lifetime_money_metrics(): void
- {
- $this->memberHistory();
- $result = $this->membersResponse(['start_date' => '2020-01-01', 'end_date' => '2020-01-01']);
- $this->assertSame(0, $result['code']);
- $this->assertSame(1, $result['data']['total']);
- $this->assertCount(1, $result['data']['data']);
- $row = $result['data']['data'][0];
- $this->assertSame('2020-01-01', $row['date']);
- $this->assertSame(2, $row['registered_members']);
- $this->assertSame('130.0000', $row['deposit_total']);
- $other = $this->membersResponse(['start_date' => '2021-06-15', 'end_date' => '2021-06-15']);
- $this->assertSame(0, $other['code']);
- $this->assertSame(1, $other['data']['total']);
- $this->assertSame(1, $other['data']['data'][0]['ios_registered']);
- $this->assertSame('0.0000', $other['data']['data'][0]['deposit_total']);
- }
- public function test_members_empty_days_and_explicit_range_limit(): void
- {
- $this->memberHistory();
- $empty = $this->membersResponse(['start_date' => '2019-01-01', 'end_date' => '2019-01-01']);
- $this->assertSame(0, $empty['code']);
- $this->assertSame(0, $empty['data']['total']);
- $this->assertSame([], $empty['data']['data']);
- $pastLastPage = $this->membersResponse(['page' => 4, 'limit' => 1]);
- $this->assertSame(3, $pastLastPage['data']['total']);
- $this->assertSame([], $pastLastPage['data']['data']);
- $invalid = $this->membersResponse(['start_date' => '2020-01-01', 'end_date' => '2026-10-01']);
- $this->assertSame(-3, $invalid['code']);
- $this->assertStringContainsString('366', $invalid['msg']);
- }
- private function promotersResponse(array $params): array
- {
- $request = Request::create('/admin/shareEarning/members/promoters', 'GET', $params);
- return (new \App\Http\Middleware\TrimStrings())->handle($request, function ($request) {
- return (new \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull())->handle($request, function ($request) {
- $this->app->instance('request', $request);
- return (new ShareEarning())->promoterDetails(new ShareEarningReportService());
- });
- })->getData(true);
- }
- public function test_promoter_details_preserves_historical_codes_when_no_current_promoter_matches(): void
- {
- $this->memberHistory();
- DB::table('users')->whereIn('id', [42, 43])->update(['created_at' => '2026-05-08 12:00:00']);
- DB::table('users')->where('id', 7)->update(['user_code' => 'CHANGED']);
- $before = DB::table('users')->orderBy('id')->get()->toJson();
- $days = $this->membersResponse(['start_date' => '2026-05-08', 'end_date' => '2026-05-08']);
- $result = $this->promotersResponse(['date' => '2026-05-08', 'page' => 1, 'limit' => 10, 'member_id' => '', 'account' => '']);
- $this->assertSame(0, $result['code']);
- $this->assertSame($days['data']['data'][0]['promoter_count'], $result['data']['total']);
- $this->assertCount(2, $result['data']['data']);
- $rows = array_column($result['data']['data'], null, 'promoter_code');
- $this->assertSame('100.0000', $rows['PROMO']['deposit_total']);
- $this->assertSame('30.0000', $rows['OTHER']['deposit_total']);
- foreach ($rows as $row) {
- $this->assertSame('2026-05-08', $row['date']);
- $this->assertSame('missing', $row['promoter_status']);
- $this->assertSame('', $row['member_id']);
- $this->assertSame('', $row['account']);
- $this->assertSame('', $row['nickname']);
- $this->assertSame(1, $row['registered_count']);
- $this->assertSame('0.0000', $row['commission']);
- }
- $this->assertSame($before, DB::table('users')->orderBy('id')->get()->toJson());
- $this->assertSame(0, ShareCommissionRecord::count());
- }
- public function test_promoter_details_keeps_matched_identity_commission_and_missing_code_in_same_report(): void
- {
- $this->memberHistory();
- foreach ([['2020-01-01', 1, '2.5000'], ['2020-01-01', 0, '100.0000'], ['2021-06-15', 1, '50.0000']] as $i => [$day, $status, $amount]) {
- ShareCommissionRecord::create([
- 'stat_date' => $day, 'promoter_user_id' => 7, 'type' => 'commission', 'category' => 'recharge',
- 'base_amount' => '100.0000', 'rate' => '2.5000', 'amount' => $amount,
- 'source_type' => 'promoter_test', 'source_id' => (string)$i, 'status' => $status,
- ]);
- }
- $result = $this->promotersResponse(['date' => '2020-01-01']);
- $this->assertSame(0, $result['code']);
- $this->assertSame(2, $result['data']['total']);
- $rows = array_column($result['data']['data'], null, 'promoter_code');
- $this->assertSame('matched', $rows['PROMO']['promoter_status']);
- $this->assertSame('1001', $rows['PROMO']['member_id']);
- $this->assertSame('promoter', $rows['PROMO']['account']);
- $this->assertSame('推广人', $rows['PROMO']['nickname']);
- $this->assertSame('100.0000', $rows['PROMO']['deposit_total']);
- $this->assertSame(1, $rows['PROMO']['registered_count']);
- $this->assertSame('2.5000', $rows['PROMO']['commission']);
- $this->assertSame('0.0000', $rows['PROMO']['current_fee_rate']);
- $this->assertSame('missing', $rows['OTHER']['promoter_status']);
- $this->assertSame('30.0000', $rows['OTHER']['deposit_total']);
- }
- public function test_promoter_details_pagination_filters_and_empty_dates_still_apply(): void
- {
- $this->memberHistory();
- $first = $this->promotersResponse(['date' => '2020-01-01', 'page' => 1, 'limit' => 1]);
- $this->assertSame(0, $first['code']);
- $this->assertSame(2, $first['data']['total']);
- $this->assertCount(1, $first['data']['data']);
- $this->assertSame('PROMO', $first['data']['data'][0]['promoter_code']);
- $last = $this->promotersResponse(['date' => '2020-01-01', 'page' => 2, 'limit' => 1]);
- $this->assertSame(2, $last['data']['total']);
- $this->assertSame('OTHER', $last['data']['data'][0]['promoter_code']);
- foreach ([['member_id' => '1001'], ['account' => 'prom']] as $filter) {
- $result = $this->promotersResponse($filter + ['date' => '2020-01-01']);
- $this->assertSame(0, $result['code']);
- $this->assertSame(1, $result['data']['total']);
- $this->assertSame('PROMO', $result['data']['data'][0]['promoter_code']);
- }
- foreach ([['date' => '2019-01-01'], ['date' => '2020-01-01', 'page' => 3, 'limit' => 1],
- ['date' => '2020-01-01', 'member_id' => '1002'], ['date' => '2020-01-01', 'account' => 'OTHER']] as $params) {
- $result = $this->promotersResponse($params);
- $this->assertSame(0, $result['code']);
- $this->assertSame([], $result['data']['data']);
- }
- }
- public function test_promoter_details_does_not_assign_an_ambiguous_code_to_one_of_several_users(): void
- {
- $this->memberHistory();
- DB::table('users')->insert([
- 'id' => 99, 'member_id' => '1009', 'account' => 'duplicate',
- 'first_name' => '重复邀请码', 'user_code' => 'PROMO',
- ]);
- $result = $this->promotersResponse(['date' => '2020-01-01']);
- $this->assertSame(0, $result['code']);
- $this->assertSame(2, $result['data']['total']);
- $rows = array_column($result['data']['data'], null, 'promoter_code');
- $this->assertSame('ambiguous', $rows['PROMO']['promoter_status']);
- $this->assertSame('', $rows['PROMO']['member_id']);
- $this->assertSame('', $rows['PROMO']['account']);
- $this->assertSame('100.0000', $rows['PROMO']['deposit_total']);
- $this->assertSame(1, $rows['PROMO']['registered_count']);
- $this->assertSame('0.0000', $rows['PROMO']['commission']);
- }
- }
|