ShareCommissionRecordingTest.php 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  1. <?php
  2. namespace Tests\Integration;
  3. use App\Console\Commands\BackfillShareCommissions;
  4. use App\Http\Controllers\admin\PaymentOrder as AdminPaymentOrder;
  5. use App\Http\Controllers\admin\ShareEarning;
  6. use App\Models\BalanceLog;
  7. use App\Models\ShareCommissionRecord;
  8. use App\Services\BalanceLogService;
  9. use App\Services\PaymentOrderService;
  10. use App\Services\ShareCommissionRecorder;
  11. use App\Services\ShareCommissionDiagnostics;
  12. use App\Services\ShareEarningReportService;
  13. use Illuminate\Config\Repository;
  14. use Illuminate\Database\Capsule\Manager;
  15. use Illuminate\Database\Schema\Blueprint;
  16. use Illuminate\Foundation\Application;
  17. use Illuminate\Http\JsonResponse;
  18. use Illuminate\Http\Request;
  19. use Illuminate\Support\Facades\DB;
  20. use Illuminate\Support\Facades\Facade;
  21. use Illuminate\Translation\ArrayLoader;
  22. use Illuminate\Translation\Translator;
  23. use Illuminate\Validation\Factory;
  24. use PHPUnit\Framework\TestCase;
  25. use Symfony\Component\Console\Tester\CommandTester;
  26. /** Real ledger, report controller and command against an isolated in-memory database. */
  27. class ShareCommissionRecordingTest extends TestCase
  28. {
  29. private Application $app;
  30. protected function setUp(): void
  31. {
  32. Facade::clearResolvedInstances();
  33. $this->app = new Application(dirname(__DIR__, 2));
  34. $this->app->instance('config', new Repository(['app' => ['locale' => 'zh', 'timezone' => 'Asia/Shanghai']]));
  35. Facade::setFacadeApplication($this->app);
  36. $db = new Manager($this->app);
  37. $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'bot_']);
  38. $db->setAsGlobal();
  39. $db->bootEloquent();
  40. $this->app->instance('db', $db->getDatabaseManager());
  41. $translator = new Translator(new ArrayLoader(), 'zh');
  42. $this->app->instance('translator', $translator);
  43. $this->app->instance('validator', new Factory($translator, $this->app));
  44. $this->app->instance(\Illuminate\Contracts\Routing\ResponseFactory::class, new class {
  45. public function json($data, $status = 200, $headers = [], $options = 0) {
  46. return new JsonResponse($data, $status, $headers, $options);
  47. }
  48. });
  49. Request::macro('validate', function (array $rules) {
  50. return app('validator')->make($this->all(), $rules)->validate();
  51. });
  52. $db->schema()->create('users', function (Blueprint $t) {
  53. $t->id(); $t->string('member_id')->unique(); $t->string('account');
  54. $t->string('first_name'); $t->string('user_code'); $t->string('agent_user_code')->nullable();
  55. $t->integer('from')->default(1); $t->integer('level')->default(0);
  56. $t->integer('recharge_channel_group_id')->default(1); $t->timestamps();
  57. });
  58. $db->schema()->create('wallets', function (Blueprint $t) {
  59. $t->id(); $t->unsignedBigInteger('user_id')->nullable(); $t->string('member_id')->unique();
  60. $t->decimal('available_balance', 24, 10)->default(0);
  61. $t->decimal('frozen_balance', 24, 10)->default(0); $t->timestamps();
  62. });
  63. $db->schema()->create('balance_logs', function (Blueprint $t) {
  64. $t->id(); $t->string('member_id'); $t->integer('type')->default(1);
  65. $t->string('change_type'); $t->decimal('amount', 24, 10);
  66. $t->decimal('before_balance', 24, 10); $t->decimal('after_balance', 24, 10);
  67. $t->integer('related_id')->nullable(); $t->text('remark')->nullable(); $t->timestamps();
  68. });
  69. $db->schema()->create('payment_orders', function (Blueprint $t) {
  70. $t->id(); $t->string('member_id'); $t->integer('type'); $t->integer('status');
  71. $t->integer('state')->default(0); $t->string('channel'); $t->decimal('amount', 24, 10);
  72. $t->text('remark')->nullable(); $t->timestamps();
  73. });
  74. $db->schema()->create('share_commission_records', function (Blueprint $t) {
  75. $t->id(); $t->date('stat_date'); $t->integer('promoter_user_id');
  76. $t->integer('invitee_user_id')->nullable(); $t->string('type'); $t->string('category');
  77. $t->decimal('base_amount', 20, 4); $t->decimal('rate', 8, 4);
  78. $t->decimal('amount', 20, 4); $t->string('source_type'); $t->string('source_id');
  79. $t->integer('status'); $t->timestamps();
  80. $t->unique(['source_type', 'source_id', 'type', 'promoter_user_id'], 'uniq_share_source');
  81. });
  82. $db->schema()->create('config', function (Blueprint $t) {
  83. $t->id(); $t->string('field'); $t->string('val'); $t->timestamps();
  84. });
  85. $db->schema()->create('level', function (Blueprint $t) {
  86. $t->id(); $t->integer('level'); $t->decimal('recharge', 20, 2); $t->timestamps();
  87. });
  88. $db->schema()->create('recharge_channel_group', function (Blueprint $t) {
  89. $t->id(); $t->text('activity_type')->nullable(); $t->softDeletes(); $t->timestamps();
  90. });
  91. $db->schema()->create('backflow', function (Blueprint $t) {
  92. $t->id(); $t->string('member_id'); $t->string('date');
  93. foreach (['recharge_amount', 'withdrawal_amount', 'backflow_ratio', 'amount'] as $field) {
  94. $t->decimal($field, 20, 2)->default(0);
  95. }
  96. $t->timestamps();
  97. });
  98. DB::table('config')->insert([
  99. ['field' => 'recharge_rate', 'val' => '2.5000'],
  100. ['field' => 'huishui_percentage', 'val' => '0'],
  101. ['field' => 'huishui_restriction', 'val' => '999999'],
  102. ]);
  103. DB::table('level')->insert(['level' => 0, 'recharge' => 0]);
  104. DB::table('recharge_channel_group')->insert(['id' => 1, 'activity_type' => '']);
  105. DB::table('backflow')->insert(['member_id' => '1002', 'date' => date('Y-m')]);
  106. DB::table('users')->insert([
  107. ['id' => 7, 'member_id' => '1001', 'account' => 'promoter', 'first_name' => '推广人', 'user_code' => 'PROMO', 'agent_user_code' => null],
  108. ['id' => 42, 'member_id' => '1002', 'account' => 'invitee', 'first_name' => '被邀请人', 'user_code' => 'CHILD', 'agent_user_code' => 'PROMO'],
  109. ]);
  110. DB::table('wallets')->insert([
  111. ['member_id' => '1001', 'available_balance' => '20.00'],
  112. ['member_id' => '1002', 'available_balance' => '100.00'],
  113. ]);
  114. $this->app->instance('request', Request::create('/admin/shareEarning/summary', 'GET', []));
  115. }
  116. protected function tearDown(): void
  117. {
  118. DB::disconnect();
  119. Facade::clearResolvedInstances();
  120. parent::tearDown();
  121. }
  122. public static function depositTypes(): array
  123. {
  124. return [['充值'], ['三方充值']];
  125. }
  126. /** @dataProvider depositTypes */
  127. public function test_existing_rebate_payment_registers_real_commission_and_is_visible_in_summary(string $type): void
  128. {
  129. BalanceLogService::addLog('1002', '100.00', '0.00', '100.00', $type, 88, '');
  130. $rebate = BalanceLog::where('change_type', '充值返现')->firstOrFail();
  131. $record = ShareCommissionRecord::firstOrFail();
  132. $this->assertSame(7, (int)$record->promoter_user_id);
  133. $this->assertSame(42, (int)$record->invitee_user_id);
  134. $this->assertSame('100.0000', $record->base_amount);
  135. $this->assertSame('2.5000', $record->rate);
  136. $this->assertSame('2.5000', $record->amount);
  137. $this->assertSame(ShareCommissionRecorder::SOURCE_TYPE, $record->source_type);
  138. $this->assertSame((string)$rebate->id, $record->source_id);
  139. $this->assertEquals('22.50', DB::table('wallets')->where('member_id', '1001')->value('available_balance'));
  140. $this->assertEquals('100.00', DB::table('wallets')->where('member_id', '1002')->value('available_balance'));
  141. $body = (new ShareEarning())->summary(new ShareEarningReportService())->getData(true);
  142. $this->assertSame(0, $body['code']);
  143. $this->assertSame(1, $body['data']['total']);
  144. $this->assertSame('promoter', $body['data']['data'][0]['promoter_account']);
  145. $this->assertSame('100.0000', $body['data']['data'][0]['deposit']);
  146. $this->assertSame('2.5000', $body['data']['summary']['total_commission']);
  147. }
  148. public function test_live_record_keeps_original_rate_and_base_precision(): void
  149. {
  150. BalanceLogService::addLog('1002', '100.1256789012', '0.00', '100.1256789012', '充值', 88, '');
  151. $record = ShareCommissionRecord::firstOrFail();
  152. $this->assertSame('100.1257', $record->base_amount);
  153. $this->assertSame('2.5000', $record->rate);
  154. $this->assertSame('2.5000', $record->amount);
  155. }
  156. private function manualOrder(int $status = PaymentOrderService::STATUS_AUDIT, int $type = PaymentOrderService::TYPE_SELF_PAY): void
  157. {
  158. DB::table('payment_orders')->insert([
  159. 'id' => 88, 'member_id' => '1002', 'type' => $type, 'status' => $status,
  160. 'channel' => 'rgcz', 'amount' => '100.00', 'created_at' => now(), 'updated_at' => now(),
  161. ]);
  162. }
  163. private function manualAudit(int $status = PaymentOrderService::STATUS_SUCCESS): array
  164. {
  165. $this->app->instance('request', Request::create('/admin/paymentOrder/manualAudit', 'POST', [
  166. 'id' => 88, 'status' => $status, 'remark' => '凭证核对',
  167. ]));
  168. return (new AdminPaymentOrder())->manualAudit()->getData(true);
  169. }
  170. public function test_frontend_manual_deposit_approval_pays_and_records_rebate_once(): void
  171. {
  172. $this->manualOrder();
  173. $this->assertSame(0, ShareCommissionRecord::count());
  174. $this->assertSame(0, $this->manualAudit()['code']);
  175. $deposit = BalanceLog::where('member_id', '1002')->firstOrFail();
  176. $this->assertSame('充值', $deposit->change_type);
  177. $this->assertSame(88, (int)$deposit->related_id);
  178. $this->assertEquals('200.00', DB::table('wallets')->where('member_id', '1002')->value('available_balance'));
  179. $this->assertEquals('22.50', DB::table('wallets')->where('member_id', '1001')->value('available_balance'));
  180. $this->assertSame('2.5000', ShareCommissionRecord::firstOrFail()->amount);
  181. $this->assertSame(88, (int)BalanceLog::where('change_type', '充值返现')->value('related_id'));
  182. $this->assertSame(PaymentOrderService::STATUS_SUCCESS, (int)DB::table('payment_orders')->value('status'));
  183. $this->assertSame(1, (int)DB::table('payment_orders')->value('state'));
  184. $this->app->instance('request', Request::create('/admin/shareEarning/summary'));
  185. $body = (new ShareEarning())->summary(new ShareEarningReportService())->getData(true);
  186. $this->assertSame('100.0000', $body['data']['data'][0]['deposit']);
  187. $this->assertSame('2.5000', $body['data']['summary']['total_commission']);
  188. $this->assertNotSame(0, $this->manualAudit()['code']);
  189. $this->assertSame(1, ShareCommissionRecord::count());
  190. $this->assertSame(2, BalanceLog::count());
  191. $this->assertEquals('200.00', DB::table('wallets')->where('member_id', '1002')->value('available_balance'));
  192. $this->assertEquals('22.50', DB::table('wallets')->where('member_id', '1001')->value('available_balance'));
  193. }
  194. public function test_missing_promoter_wallet_identifies_the_expected_member_without_recreating_it(): void
  195. {
  196. $this->manualOrder();
  197. DB::table('wallets')->where('member_id', '1001')->delete();
  198. $response = $this->manualAudit();
  199. $this->assertNotSame(0, $response['code']);
  200. $this->assertSame('推广人钱包不存在(推广人会员ID:1001)', $response['msg']);
  201. $this->assertSame(0, DB::table('wallets')->where('member_id', '1001')->count());
  202. $this->assertSame(PaymentOrderService::STATUS_AUDIT, (int) DB::table('payment_orders')->value('status'));
  203. $this->assertSame(0, (int) DB::table('payment_orders')->value('state'));
  204. $this->assertEquals('100.00', DB::table('wallets')->where('member_id', '1002')->value('available_balance'));
  205. $this->assertSame(0, BalanceLog::count());
  206. $this->assertSame(0, ShareCommissionRecord::count());
  207. $this->assertSame(0, DB::transactionLevel());
  208. }
  209. public function test_internal_user_id_does_not_replace_the_business_member_id_in_the_promoter_wallet(): void
  210. {
  211. $this->manualOrder();
  212. DB::table('wallets')->where('member_id', '1001')->delete();
  213. DB::table('wallets')->insert(['user_id' => 7, 'member_id' => '7', 'available_balance' => '0.00']);
  214. $response = $this->manualAudit();
  215. $this->assertNotSame(0, $response['code']);
  216. $this->assertSame('推广人钱包不存在(推广人会员ID:1001)', $response['msg']);
  217. $this->assertEquals('0.00', DB::table('wallets')->where('member_id', '7')->value('available_balance'));
  218. $this->assertEquals('100.00', DB::table('wallets')->where('member_id', '1002')->value('available_balance'));
  219. $this->assertSame(0, BalanceLog::count());
  220. $this->assertSame(0, ShareCommissionRecord::count());
  221. // Simulate correcting the manually inserted record, without creating another wallet.
  222. DB::table('wallets')->where('user_id', 7)->update(['member_id' => '1001']);
  223. $this->assertSame(0, $this->manualAudit()['code']);
  224. $this->assertSame(2, DB::table('wallets')->count());
  225. $this->assertEquals('200.00', DB::table('wallets')->where('member_id', '1002')->value('available_balance'));
  226. $this->assertEquals('2.50', DB::table('wallets')->where('member_id', '1001')->value('available_balance'));
  227. $this->assertSame(1, ShareCommissionRecord::count());
  228. $this->assertNotSame(0, $this->manualAudit()['code']);
  229. $this->assertEquals('2.50', DB::table('wallets')->where('member_id', '1001')->value('available_balance'));
  230. $this->assertSame(2, BalanceLog::count());
  231. }
  232. public static function unapprovedManualOrders(): array
  233. {
  234. return [
  235. 'waiting for processing' => [0, 3], 'processing' => [1, 3],
  236. 'already successful' => [2, 3], 'rejected' => [3, 3],
  237. 'waiting for receipt' => [4, 3], 'cancelled' => [6, 3],
  238. 'provider deposit' => [5, 1], 'provider payout' => [5, 2], 'manual payout' => [5, 4],
  239. ];
  240. }
  241. /** @dataProvider unapprovedManualOrders */
  242. public function test_unapproved_or_unrelated_order_cannot_be_credited_by_manual_deposit_audit(int $status, int $type): void
  243. {
  244. $this->manualOrder($status, $type);
  245. $this->assertNotSame(0, $this->manualAudit()['code']);
  246. $this->assertSame($status, (int)DB::table('payment_orders')->value('status'));
  247. $this->assertSame(0, ShareCommissionRecord::count());
  248. $this->assertSame(0, BalanceLog::count());
  249. $this->assertEquals('100.00', DB::table('wallets')->where('member_id', '1002')->value('available_balance'));
  250. $this->assertEquals('20.00', DB::table('wallets')->where('member_id', '1001')->value('available_balance'));
  251. }
  252. public function test_rejecting_frontend_manual_deposit_does_not_pay_rewards(): void
  253. {
  254. $this->manualOrder();
  255. $this->assertSame(0, $this->manualAudit(PaymentOrderService::STATUS_FAIL)['code']);
  256. $this->assertSame(PaymentOrderService::STATUS_FAIL, (int)DB::table('payment_orders')->value('status'));
  257. $this->assertSame(0, ShareCommissionRecord::count());
  258. $this->assertSame(0, BalanceLog::count());
  259. $this->assertEquals('100.00', DB::table('wallets')->where('member_id', '1002')->value('available_balance'));
  260. $this->assertEquals('20.00', DB::table('wallets')->where('member_id', '1001')->value('available_balance'));
  261. }
  262. public function test_manual_deposit_and_rewards_roll_back_together_on_commission_failure(): void
  263. {
  264. $this->manualOrder();
  265. DB::statement("CREATE TRIGGER fail_share_insert BEFORE INSERT ON bot_share_commission_records
  266. BEGIN SELECT RAISE(ABORT, 'injected share failure'); END");
  267. $this->assertNotSame(0, $this->manualAudit()['code']);
  268. $this->assertSame(PaymentOrderService::STATUS_AUDIT, (int)DB::table('payment_orders')->value('status'));
  269. $this->assertSame(0, (int)DB::table('payment_orders')->value('state'));
  270. $this->assertSame(0, ShareCommissionRecord::count());
  271. $this->assertSame(0, BalanceLog::count());
  272. $this->assertEquals('100.00', DB::table('wallets')->where('member_id', '1002')->value('available_balance'));
  273. $this->assertEquals('20.00', DB::table('wallets')->where('member_id', '1001')->value('available_balance'));
  274. $this->assertSame(0, DB::transactionLevel());
  275. }
  276. public static function unrelatedDeposits(): array
  277. {
  278. return [['人工充值', 'PROMO', 1], ['优惠活动', 'PROMO', 1], ['充值', '', 1], ['充值', 'MISSING', 1], ['充值', 'PROMO', 2]];
  279. }
  280. /** @dataProvider unrelatedDeposits */
  281. public function test_recording_does_not_expand_the_existing_payment_rules(string $type, string $code, int $from): void
  282. {
  283. DB::table('users')->where('member_id', '1002')->update(['agent_user_code' => $code, 'from' => $from]);
  284. BalanceLogService::addLog('1002', '100.00', '0.00', '100.00', $type, 88, '');
  285. $this->assertSame(0, ShareCommissionRecord::count());
  286. $this->assertSame(0, BalanceLog::where('change_type', '充值返现')->count());
  287. $this->assertEquals('20.00', DB::table('wallets')->where('member_id', '1001')->value('available_balance'));
  288. }
  289. public function test_commission_insert_failure_rolls_back_the_rebate_wallet_and_ledger(): void
  290. {
  291. DB::statement("CREATE TRIGGER fail_share_insert BEFORE INSERT ON bot_share_commission_records
  292. BEGIN SELECT RAISE(ABORT, 'injected share failure'); END");
  293. try {
  294. BalanceLogService::addLog('1002', '100.00', '0.00', '100.00', '充值', 88, '');
  295. $this->fail('Commission failure must abort the rebate payment.');
  296. } catch (\Illuminate\Database\QueryException $e) {
  297. $this->assertStringContainsString('injected share failure', $e->getMessage());
  298. }
  299. $this->assertSame(0, DB::transactionLevel());
  300. $this->assertEquals('20.00', DB::table('wallets')->where('member_id', '1001')->value('available_balance'));
  301. $this->assertSame(0, BalanceLog::where('change_type', '充值返现')->count());
  302. $this->assertSame(0, ShareCommissionRecord::count());
  303. $this->assertSame(1, BalanceLog::where('change_type', '充值')->count());
  304. }
  305. public function test_live_record_respects_the_callers_transaction_rollback(): void
  306. {
  307. DB::beginTransaction();
  308. BalanceLogService::addLog('1002', '100.00', '0.00', '100.00', '三方充值', 88, '');
  309. $this->assertSame(1, DB::transactionLevel());
  310. $this->assertSame(1, ShareCommissionRecord::count());
  311. DB::rollBack();
  312. $this->assertEquals('20.00', DB::table('wallets')->where('member_id', '1001')->value('available_balance'));
  313. $this->assertSame(0, BalanceLog::count());
  314. $this->assertSame(0, ShareCommissionRecord::count());
  315. }
  316. private function historicalRebate(array $extra = []): BalanceLog
  317. {
  318. DB::table('wallets')->where('member_id', '1001')->update(['available_balance' => '22.50']);
  319. $log = new BalanceLog();
  320. $log->forceFill($extra + [
  321. 'member_id' => '1001', 'type' => 1, 'change_type' => '充值返现', 'related_id' => 88,
  322. 'amount' => '2.50', 'before_balance' => '20.00', 'after_balance' => '22.50',
  323. 'remark' => '被邀请人:1002充值金额为:100.00',
  324. 'created_at' => '2026-10-01 01:02:03', 'updated_at' => '2026-10-01 01:02:03',
  325. ])->save();
  326. return $log;
  327. }
  328. public function test_historical_registration_is_idempotent_and_never_credits_again(): void
  329. {
  330. $rebate = $this->historicalRebate();
  331. DB::table('config')->where('field', 'recharge_rate')->update(['val' => '99']);
  332. DB::table('users')->where('member_id', '1002')->update(['agent_user_code' => 'CHANGED']);
  333. $wallets = DB::table('wallets')->orderBy('id')->get()->toJson();
  334. $ledger = DB::table('balance_logs')->orderBy('id')->get()->toJson();
  335. $recorder = new ShareCommissionRecorder();
  336. $this->assertSame('pending', $recorder->preview($rebate)['status']);
  337. $this->assertSame(0, ShareCommissionRecord::count());
  338. $this->assertSame('created', $recorder->record($rebate)['status']);
  339. $this->assertSame('existing', $recorder->record($rebate)['status']);
  340. $this->assertSame(1, ShareCommissionRecord::count());
  341. $record = ShareCommissionRecord::firstOrFail();
  342. $this->assertSame('2026-10-01', $record->stat_date->format('Y-m-d'));
  343. $this->assertSame('2.5000', $record->rate);
  344. $this->assertSame('100.0000', $record->base_amount);
  345. $this->assertSame(42, (int)$record->invitee_user_id);
  346. $this->assertSame($wallets, DB::table('wallets')->orderBy('id')->get()->toJson());
  347. $this->assertSame($ledger, DB::table('balance_logs')->orderBy('id')->get()->toJson());
  348. }
  349. public function test_unknown_historical_details_keep_actual_payment_without_inventing_a_base(): void
  350. {
  351. $rebate = $this->historicalRebate(['remark' => '历史返现']);
  352. $result = (new ShareCommissionRecorder())->record($rebate);
  353. $this->assertSame('created', $result['status']);
  354. $this->assertTrue($result['incomplete_metadata']);
  355. $record = ShareCommissionRecord::firstOrFail();
  356. $this->assertNull($record->invitee_user_id);
  357. $this->assertSame('0.0000', $record->base_amount);
  358. $this->assertSame('0.0000', $record->rate);
  359. $this->assertSame('2.5000', $record->amount);
  360. }
  361. public function test_historical_balance_comparison_uses_delta_before_rounding(): void
  362. {
  363. $rebate = $this->historicalRebate(['before_balance' => '20.0000499999', 'after_balance' => '22.5000500001']);
  364. $result = (new ShareCommissionRecorder())->record($rebate);
  365. $this->assertSame('created', $result['status']);
  366. $this->assertSame('2.5000', ShareCommissionRecord::firstOrFail()->amount);
  367. }
  368. public function test_same_payout_source_is_not_duplicated_when_user_rows_are_replaced(): void
  369. {
  370. $rebate = $this->historicalRebate();
  371. $recorder = new ShareCommissionRecorder();
  372. $recorder->record($rebate);
  373. DB::table('users')->where('id', 7)->delete();
  374. DB::table('users')->insert(['id' => 9, 'member_id' => '1001', 'account' => 'reimported', 'first_name' => '重建账户', 'user_code' => 'PROMO']);
  375. $this->assertSame('existing', $recorder->record($rebate)['status']);
  376. $this->assertSame(1, ShareCommissionRecord::count());
  377. $this->assertSame(7, (int)ShareCommissionRecord::firstOrFail()->promoter_user_id);
  378. }
  379. public static function invalidHistoricalLogs(): array
  380. {
  381. return [
  382. [['amount' => '0.00', 'after_balance' => '20.00'], 'invalid_amount'],
  383. [['after_balance' => '20.00'], 'unbalanced_log'],
  384. [['member_id' => '9999'], 'missing_promoter'],
  385. [['type' => 2], 'not_recharge_rebate'],
  386. [['change_type' => '优惠活动'], 'not_recharge_rebate'],
  387. ];
  388. }
  389. /** @dataProvider invalidHistoricalLogs */
  390. public function test_invalid_historical_logs_are_reported_instead_of_booked(array $extra, string $reason): void
  391. {
  392. $rebate = $this->historicalRebate($extra);
  393. $result = (new ShareCommissionRecorder())->record($rebate);
  394. $this->assertSame('skipped', $result['status']);
  395. $this->assertSame($reason, $result['reason']);
  396. $this->assertSame(0, ShareCommissionRecord::count());
  397. }
  398. public function test_backfill_does_not_reactivate_a_manually_voided_record(): void
  399. {
  400. $rebate = $this->historicalRebate();
  401. $recorder = new ShareCommissionRecorder();
  402. $recorder->record($rebate);
  403. ShareCommissionRecord::query()->update(['status' => 0]);
  404. $this->assertSame('existing', $recorder->record($rebate)['status']);
  405. $this->assertSame(0, ShareCommissionRecord::firstOrFail()->status);
  406. }
  407. private function command(array $options): CommandTester
  408. {
  409. $command = new BackfillShareCommissions();
  410. $command->setLaravel($this->app);
  411. $tester = new CommandTester($command);
  412. $tester->execute($options);
  413. return $tester;
  414. }
  415. public function test_backfill_command_defaults_to_preview_and_write_is_repeatable(): void
  416. {
  417. $this->historicalRebate();
  418. $options = ['--start-date' => '2026-10-01', '--end-date' => '2026-10-02', '--chunk' => 1];
  419. $wallets = DB::table('wallets')->orderBy('id')->get()->toJson();
  420. $preview = $this->command($options);
  421. $this->assertSame(0, $preview->getStatusCode());
  422. $this->assertStringContainsString('只读预览', $preview->getDisplay());
  423. $this->assertSame(0, ShareCommissionRecord::count());
  424. $written = $this->command($options + ['--write' => true]);
  425. $this->assertSame(0, $written->getStatusCode(), $written->getDisplay());
  426. $this->assertSame(1, ShareCommissionRecord::count());
  427. $again = $this->command($options + ['--write' => true]);
  428. $this->assertSame(0, $again->getStatusCode());
  429. $this->assertSame(1, ShareCommissionRecord::count());
  430. $this->assertSame($wallets, DB::table('wallets')->orderBy('id')->get()->toJson());
  431. }
  432. public function test_backfill_command_rejects_invalid_ranges_without_writing(): void
  433. {
  434. $this->historicalRebate();
  435. $result = $this->command(['--start-date' => '2026-10-03', '--end-date' => '2026-10-01', '--write' => true]);
  436. $this->assertSame(1, $result->getStatusCode());
  437. $this->assertSame(0, ShareCommissionRecord::count());
  438. }
  439. public function test_omitting_dates_is_not_full_history_and_all_can_backfill_old_receipts(): void
  440. {
  441. $rebate = $this->historicalRebate(['created_at' => '2020-01-01 00:00:00', 'updated_at' => '2020-01-01 00:00:00']);
  442. $default = $this->command([]);
  443. $this->assertSame(0, $default->getStatusCode());
  444. $this->assertStringContainsString('省略日期仍默认最近31天', $default->getDisplay());
  445. $this->assertSame(0, ShareCommissionRecord::count());
  446. $all = $this->command(['--all' => true]);
  447. $this->assertSame(0, $all->getStatusCode());
  448. $this->assertStringContainsString('全部历史', $all->getDisplay());
  449. $this->assertSame(0, ShareCommissionRecord::count());
  450. $written = $this->command(['--all' => true, '--write' => true]);
  451. $this->assertSame(0, $written->getStatusCode());
  452. $this->assertSame((string)$rebate->id, ShareCommissionRecord::firstOrFail()->source_id);
  453. $this->assertSame('2020-01-01', ShareCommissionRecord::firstOrFail()->stat_date->format('Y-m-d'));
  454. $this->assertEquals('22.50', DB::table('wallets')->where('member_id', '1001')->value('available_balance'));
  455. }
  456. private function depositForDiagnosis(): void
  457. {
  458. BalanceLog::create(['member_id' => '1002', 'type' => 1, 'change_type' => '充值',
  459. 'amount' => '100.00', 'before_balance' => '0.00', 'after_balance' => '100.00', 'remark' => '']);
  460. }
  461. public function test_diagnostics_show_a_zero_legacy_rate_despite_configured_share_settings_without_writing(): void
  462. {
  463. $this->depositForDiagnosis();
  464. DB::table('config')->where('field', 'recharge_rate')->update(['val' => '0']);
  465. DB::connection()->getSchemaBuilder()->create('share_settings', function (Blueprint $t) {
  466. $t->id(); $t->integer('enabled'); $t->decimal('tier_one_rate', 8, 4); $t->decimal('tier_two_rate', 8, 4);
  467. });
  468. DB::table('share_settings')->insert(['enabled' => 1, 'tier_one_rate' => '4.00', 'tier_two_rate' => '6.00']);
  469. $tables = ['users', 'wallets', 'balance_logs', 'share_commission_records', 'config', 'share_settings'];
  470. $before = [];
  471. foreach ($tables as $table) $before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
  472. $data = (new ShareCommissionDiagnostics())->inspect(null);
  473. $this->assertSame(':memory:', $data['database']);
  474. $this->assertSame('bot_', $data['table_prefix']);
  475. $this->assertSame('0', $data['recharge_rate']);
  476. $this->assertArrayNotHasKey('tier_one_rate', $data);
  477. $this->assertArrayNotHasKey('tier_two_rate', $data);
  478. $this->assertSame(0, $data['counts']['rebate_logs_all']);
  479. $this->assertSame(1, $data['counts']['real_invitee_deposit_logs_all']);
  480. $this->assertSame(1, $data['counts']['linked_real_invitee_deposit_logs_all']);
  481. $this->assertSame(1, $data['counts']['with_promoter_wallet_deposit_logs_all']);
  482. $run = $this->command(['--diagnose' => true, '--all' => true]);
  483. $this->assertSame(0, $run->getStatusCode(), $run->getDisplay());
  484. $this->assertStringContainsString('全部历史没有', $run->getDisplay());
  485. $this->assertStringContainsString('当前 recharge_rate 缺失、无效或为0', $run->getDisplay());
  486. $this->assertStringContainsString('share_enabled: 1', $run->getDisplay());
  487. foreach ($tables as $table) $this->assertSame($before[$table], DB::table($table)->orderBy('id')->get()->toJson(), $table);
  488. }
  489. public function test_diagnostics_separate_type_amount_and_date_filters(): void
  490. {
  491. $this->historicalRebate(['created_at' => '2020-01-01 00:00:00']);
  492. $this->historicalRebate(['type' => 2]);
  493. $this->historicalRebate(['amount' => '0', 'after_balance' => '20']);
  494. $selected = $this->historicalRebate();
  495. (new ShareCommissionRecorder())->record($selected);
  496. $data = (new ShareCommissionDiagnostics())->inspect(['2026-10-01 00:00:00', '2026-10-02 23:59:59']);
  497. $this->assertSame(4, $data['counts']['rebate_logs_all']);
  498. $this->assertSame(3, $data['counts']['type1_rebate_logs_all']);
  499. $this->assertSame(2, $data['counts']['positive_type1_rebate_logs_all']);
  500. $this->assertSame(1, $data['counts']['selected_rebate_logs']);
  501. $this->assertSame('2020-01-01 00:00:00', $data['first_rebate_at']);
  502. $this->assertSame('2026-10-01 01:02:03', $data['last_rebate_at']);
  503. $this->assertSame(1, $data['counts']['active_commission_records_selected']);
  504. }
  505. public static function brokenReferralStages(): array
  506. {
  507. return [
  508. [2, 'PROMO', false, [0, 0, 0, 0, 0]],
  509. [1, 'MISSING', false, [1, 0, 1, 0, 0]],
  510. [1, 'PROMO', true, [1, 1, 1, 1, 0]],
  511. ];
  512. }
  513. /** @dataProvider brokenReferralStages */
  514. public function test_diagnostics_locate_real_user_referral_and_wallet_gaps(int $from, string $code, bool $missingWallet, array $expected): void
  515. {
  516. DB::table('users')->where('member_id', '1002')->update(['from' => $from, 'agent_user_code' => $code]);
  517. if ($missingWallet) DB::table('wallets')->where('member_id', '1001')->delete();
  518. $this->depositForDiagnosis();
  519. $counts = (new ShareCommissionDiagnostics())->inspect(null)['counts'];
  520. $this->assertSame(1, $counts['invited_members_all']);
  521. foreach (['real_invited_members_all', 'linked_real_invited_members_all', 'real_invitee_deposit_logs_all',
  522. 'linked_real_invitee_deposit_logs_all', 'with_promoter_wallet_deposit_logs_all'] as $i => $key) {
  523. $this->assertSame($expected[$i], $counts[$key], $key);
  524. }
  525. }
  526. public function test_read_only_diagnostics_cannot_be_combined_with_write_or_all_with_dates(): void
  527. {
  528. $this->historicalRebate();
  529. $run = $this->command(['--diagnose' => true, '--write' => true]);
  530. $this->assertSame(1, $run->getStatusCode());
  531. $this->assertSame(0, ShareCommissionRecord::count());
  532. $conflict = $this->command(['--all' => true, '--start-date' => '2026-10-01', '--write' => true]);
  533. $this->assertSame(1, $conflict->getStatusCode());
  534. $this->assertSame(0, ShareCommissionRecord::count());
  535. }
  536. public function test_diagnostic_referral_matches_the_existing_php_empty_zero_code_rule(): void
  537. {
  538. DB::table('users')->where('member_id', '1001')->update(['user_code' => '0']);
  539. DB::table('users')->where('member_id', '1002')->update(['agent_user_code' => '0']);
  540. $this->depositForDiagnosis();
  541. $counts = (new ShareCommissionDiagnostics())->inspect(null)['counts'];
  542. $this->assertSame(1, $counts['invited_members_all']);
  543. $this->assertSame(1, $counts['real_invited_members_all']);
  544. $this->assertSame(0, $counts['linked_real_invited_members_all']);
  545. $this->assertSame(0, $counts['linked_real_invitee_deposit_logs_all']);
  546. $this->assertSame(0, $counts['with_promoter_wallet_deposit_logs_all']);
  547. }
  548. private function summaryHistory(): void
  549. {
  550. DB::table('users')->insert(['id' => 99, 'member_id' => '1003', 'account' => 'other', 'first_name' => '其他推广人', 'user_code' => 'OTHER']);
  551. foreach ([
  552. ['2020-01-01', 7, 'commission', '100.0000', '2.5000', '2.5000', 1],
  553. ['2020-01-01', 7, 'fee_waiver', '40.0000', '2.5000', '1.0000', 1],
  554. ['2026-10-01', 7, 'commission', '200.0000', '2.5000', '5.0000', 1],
  555. ['2026-10-02', 7, 'commission', '1000.0000', '10.0000', '100.0000', 0],
  556. ['2026-10-05', 99, 'commission', '1000.0000', '10.0000', '100.0000', 1],
  557. ] as $i => [$day, $promoter, $type, $base, $rate, $amount, $status]) {
  558. ShareCommissionRecord::create([
  559. 'stat_date' => $day, 'promoter_user_id' => $promoter, 'type' => $type,
  560. 'category' => 'recharge', 'base_amount' => $base, 'rate' => $rate, 'amount' => $amount,
  561. 'source_type' => 'summary_test', 'source_id' => (string)$i, 'status' => $status,
  562. ]);
  563. }
  564. }
  565. private function summaryResponse(array $params): array
  566. {
  567. $request = Request::create('/admin/shareEarning/summary', 'GET', $params);
  568. return (new \App\Http\Middleware\TrimStrings())->handle($request, function ($request) {
  569. return (new \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull())->handle($request, function ($request) {
  570. $this->app->instance('request', $request);
  571. return (new ShareEarning())->summary(new ShareEarningReportService());
  572. });
  573. })->getData(true);
  574. }
  575. public static function clearedReportDates(): array
  576. {
  577. return [
  578. 'omitted' => [[]],
  579. 'null' => [['start_date' => null, 'end_date' => null]],
  580. 'empty strings from date picker' => [['start_date' => '', 'end_date' => '']],
  581. ];
  582. }
  583. /** @dataProvider clearedReportDates */
  584. public function test_summary_without_dates_includes_all_history_and_keeps_pagination_and_global_totals(array $dates): void
  585. {
  586. $this->summaryHistory();
  587. $before = DB::table('share_commission_records')->orderBy('id')->get()->toJson();
  588. $result = $this->summaryResponse($dates + ['account' => '', 'page' => 1, 'limit' => 1]);
  589. $this->assertSame(0, $result['code']);
  590. $this->assertSame(3, $result['data']['total']);
  591. $this->assertCount(1, $result['data']['data']);
  592. $this->assertSame('2026-10-05', $result['data']['data'][0]['date']);
  593. $this->assertSame('107.5000', $result['data']['summary']['total_commission']);
  594. $this->assertSame('2.5000', $result['data']['summary']['highest_fee_waiver_rate']);
  595. $last = $this->summaryResponse($dates + ['page' => 3, 'limit' => 1]);
  596. $this->assertSame('2020-01-01', $last['data']['data'][0]['date']);
  597. $this->assertSame('40.0000', $last['data']['data'][0]['sales_amount']);
  598. $this->assertSame($before, DB::table('share_commission_records')->orderBy('id')->get()->toJson());
  599. }
  600. public static function selectedSummaryDates(): array
  601. {
  602. return [
  603. ['2020-01-01', '2020-01-01', '2.5000', '2.5000'],
  604. ['2026-10-01', '2026-10-02', '5.0000', '0.0000'],
  605. ];
  606. }
  607. /** @dataProvider selectedSummaryDates */
  608. public function test_summary_explicit_dates_apply_to_list_count_and_totals(string $start, string $end, string $commission, string $feeRate): void
  609. {
  610. $this->summaryHistory();
  611. $result = $this->summaryResponse(['start_date' => $start, 'end_date' => $end, 'page' => 1, 'limit' => 10]);
  612. $this->assertSame(0, $result['code']);
  613. $this->assertSame(1, $result['data']['total']);
  614. $this->assertCount(1, $result['data']['data']);
  615. $this->assertSame($start, $result['data']['data'][0]['date']);
  616. $this->assertSame($commission, $result['data']['summary']['total_commission']);
  617. $this->assertSame($feeRate, $result['data']['summary']['highest_fee_waiver_rate']);
  618. }
  619. public function test_summary_default_all_history_still_applies_account_and_status_filters(): void
  620. {
  621. $this->summaryHistory();
  622. $result = $this->summaryResponse(['account' => 'prom', 'page' => 1, 'limit' => 10]);
  623. $this->assertSame(0, $result['code']);
  624. $this->assertSame(2, $result['data']['total']);
  625. $this->assertSame('7.5000', $result['data']['summary']['total_commission']);
  626. $this->assertSame('2.5000', $result['data']['summary']['highest_fee_waiver_rate']);
  627. $this->assertSame(['promoter', 'promoter'], array_column($result['data']['data'], 'promoter_account'));
  628. }
  629. public function test_summary_explicit_range_limit_remains_enforced(): void
  630. {
  631. $this->summaryHistory();
  632. $invalid = $this->summaryResponse(['start_date' => '2020-01-01', 'end_date' => '2026-10-01']);
  633. $this->assertSame(-3, $invalid['code']);
  634. $this->assertStringContainsString('366', $invalid['msg']);
  635. }
  636. private function memberHistory(): void
  637. {
  638. DB::connection()->getSchemaBuilder()->create('share_settings', function (Blueprint $t) {
  639. $t->id(); $t->decimal('valid_member_min_deposit', 20, 2);
  640. $t->decimal('tier_one_rate', 8, 4)->default(4);
  641. });
  642. DB::table('share_settings')->insert(['valid_member_min_deposit' => 20]);
  643. DB::connection()->getSchemaBuilder()->create('user_login', function (Blueprint $t) {
  644. $t->id(); $t->string('user_id'); $t->integer('status'); $t->string('platform');
  645. });
  646. DB::table('users')->where('id', 42)->update(['created_at' => '2020-01-01 00:00:00']);
  647. foreach ([
  648. [43, '1003', 'OTHER', '2020-01-01 23:59:59'],
  649. [44, '1004', 'PROMO', '2021-06-15 12:00:00'],
  650. [45, '1005', 'PROMO', date('Y-m-d') . ' 12:00:00'],
  651. [46, '1006', null, '2019-01-01 12:00:00'],
  652. [47, '1007', '', '2018-01-01 12:00:00'],
  653. ] as [$id, $memberId, $code, $createdAt]) {
  654. DB::table('users')->insert([
  655. 'id' => $id, 'member_id' => $memberId, 'account' => 'member' . $memberId,
  656. 'first_name' => '会员', 'user_code' => 'CODE' . $memberId,
  657. 'agent_user_code' => $code, 'created_at' => $createdAt,
  658. ]);
  659. }
  660. foreach ([
  661. ['1002', '充值', 100], ['1002', '提现', -10],
  662. ['1002', '投注', -20], ['1002', '优惠活动', 5], ['1003', '三方充值', 30],
  663. ] as [$memberId, $type, $amount]) {
  664. DB::table('balance_logs')->insert([
  665. 'member_id' => $memberId, 'change_type' => $type, 'amount' => $amount,
  666. 'before_balance' => 100, 'after_balance' => 100 + $amount,
  667. 'created_at' => date('Y-m-d H:i:s'),
  668. ]);
  669. }
  670. DB::table('user_login')->insert([
  671. ['user_id' => '1002', 'status' => 0, 'platform' => 'Android'],
  672. ['user_id' => '1002', 'status' => 1, 'platform' => 'H5'],
  673. ['user_id' => '1002', 'status' => 1, 'platform' => 'Android'],
  674. ['user_id' => '1003', 'status' => 1, 'platform' => 'Android'],
  675. ['user_id' => '1004', 'status' => 1, 'platform' => 'iOS'],
  676. ]);
  677. }
  678. private function membersResponse(array $params): array
  679. {
  680. $request = Request::create('/admin/shareEarning/members', 'GET', $params);
  681. return (new \App\Http\Middleware\TrimStrings())->handle($request, function ($request) {
  682. return (new \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull())->handle($request, function ($request) {
  683. $this->app->instance('request', $request);
  684. return (new ShareEarning())->memberList(new ShareEarningReportService());
  685. });
  686. })->getData(true);
  687. }
  688. /** @dataProvider clearedReportDates */
  689. public function test_members_without_dates_includes_historical_registration_days_without_backfill(array $dates): void
  690. {
  691. $this->memberHistory();
  692. $users = DB::table('users')->orderBy('id')->get()->toJson();
  693. $logs = DB::table('balance_logs')->orderBy('id')->get()->toJson();
  694. $result = $this->membersResponse($dates + ['page' => 1, 'limit' => 1]);
  695. $this->assertSame(0, $result['code']);
  696. $this->assertSame(3, $result['data']['total']);
  697. $this->assertCount(1, $result['data']['data']);
  698. $this->assertSame(date('Y-m-d'), $result['data']['data'][0]['date']);
  699. $last = $this->membersResponse($dates + ['page' => 3, 'limit' => 1]);
  700. $this->assertSame(3, $last['data']['total']);
  701. $row = $last['data']['data'][0];
  702. $this->assertSame('2020-01-01', $row['date']);
  703. $this->assertSame(2, $row['registered_members']);
  704. $this->assertSame(2, $row['promoter_count']);
  705. $this->assertSame(1, $row['h5_registered']);
  706. $this->assertSame(1, $row['android_registered']);
  707. $this->assertSame(0, $row['ios_registered']);
  708. $this->assertSame('130.0000', $row['deposit_total']);
  709. $this->assertSame('20.0000', $row['consume_total']);
  710. $this->assertSame('115.0000', $row['company_profit']);
  711. $this->assertSame($users, DB::table('users')->orderBy('id')->get()->toJson());
  712. $this->assertSame($logs, DB::table('balance_logs')->orderBy('id')->get()->toJson());
  713. $this->assertSame(0, ShareCommissionRecord::count());
  714. }
  715. public function test_members_explicit_dates_filter_registration_days_but_keep_lifetime_money_metrics(): void
  716. {
  717. $this->memberHistory();
  718. $result = $this->membersResponse(['start_date' => '2020-01-01', 'end_date' => '2020-01-01']);
  719. $this->assertSame(0, $result['code']);
  720. $this->assertSame(1, $result['data']['total']);
  721. $this->assertCount(1, $result['data']['data']);
  722. $row = $result['data']['data'][0];
  723. $this->assertSame('2020-01-01', $row['date']);
  724. $this->assertSame(2, $row['registered_members']);
  725. $this->assertSame('130.0000', $row['deposit_total']);
  726. $other = $this->membersResponse(['start_date' => '2021-06-15', 'end_date' => '2021-06-15']);
  727. $this->assertSame(0, $other['code']);
  728. $this->assertSame(1, $other['data']['total']);
  729. $this->assertSame(1, $other['data']['data'][0]['ios_registered']);
  730. $this->assertSame('0.0000', $other['data']['data'][0]['deposit_total']);
  731. }
  732. public function test_members_empty_days_and_explicit_range_limit(): void
  733. {
  734. $this->memberHistory();
  735. $empty = $this->membersResponse(['start_date' => '2019-01-01', 'end_date' => '2019-01-01']);
  736. $this->assertSame(0, $empty['code']);
  737. $this->assertSame(0, $empty['data']['total']);
  738. $this->assertSame([], $empty['data']['data']);
  739. $pastLastPage = $this->membersResponse(['page' => 4, 'limit' => 1]);
  740. $this->assertSame(3, $pastLastPage['data']['total']);
  741. $this->assertSame([], $pastLastPage['data']['data']);
  742. $invalid = $this->membersResponse(['start_date' => '2020-01-01', 'end_date' => '2026-10-01']);
  743. $this->assertSame(-3, $invalid['code']);
  744. $this->assertStringContainsString('366', $invalid['msg']);
  745. }
  746. private function promotersResponse(array $params): array
  747. {
  748. $request = Request::create('/admin/shareEarning/members/promoters', 'GET', $params);
  749. return (new \App\Http\Middleware\TrimStrings())->handle($request, function ($request) {
  750. return (new \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull())->handle($request, function ($request) {
  751. $this->app->instance('request', $request);
  752. return (new ShareEarning())->promoterDetails(new ShareEarningReportService());
  753. });
  754. })->getData(true);
  755. }
  756. public function test_promoter_details_preserves_historical_codes_when_no_current_promoter_matches(): void
  757. {
  758. $this->memberHistory();
  759. DB::table('users')->whereIn('id', [42, 43])->update(['created_at' => '2026-05-08 12:00:00']);
  760. DB::table('users')->where('id', 7)->update(['user_code' => 'CHANGED']);
  761. $before = DB::table('users')->orderBy('id')->get()->toJson();
  762. $days = $this->membersResponse(['start_date' => '2026-05-08', 'end_date' => '2026-05-08']);
  763. $result = $this->promotersResponse(['date' => '2026-05-08', 'page' => 1, 'limit' => 10, 'member_id' => '', 'account' => '']);
  764. $this->assertSame(0, $result['code']);
  765. $this->assertSame($days['data']['data'][0]['promoter_count'], $result['data']['total']);
  766. $this->assertCount(2, $result['data']['data']);
  767. $rows = array_column($result['data']['data'], null, 'promoter_code');
  768. $this->assertSame('100.0000', $rows['PROMO']['deposit_total']);
  769. $this->assertSame('30.0000', $rows['OTHER']['deposit_total']);
  770. foreach ($rows as $row) {
  771. $this->assertSame('2026-05-08', $row['date']);
  772. $this->assertSame('missing', $row['promoter_status']);
  773. $this->assertSame('', $row['member_id']);
  774. $this->assertSame('', $row['account']);
  775. $this->assertSame('', $row['nickname']);
  776. $this->assertSame(1, $row['registered_count']);
  777. $this->assertSame('0.0000', $row['commission']);
  778. }
  779. $this->assertSame($before, DB::table('users')->orderBy('id')->get()->toJson());
  780. $this->assertSame(0, ShareCommissionRecord::count());
  781. }
  782. public function test_promoter_details_keeps_matched_identity_commission_and_missing_code_in_same_report(): void
  783. {
  784. $this->memberHistory();
  785. foreach ([['2020-01-01', 1, '2.5000'], ['2020-01-01', 0, '100.0000'], ['2021-06-15', 1, '50.0000']] as $i => [$day, $status, $amount]) {
  786. ShareCommissionRecord::create([
  787. 'stat_date' => $day, 'promoter_user_id' => 7, 'type' => 'commission', 'category' => 'recharge',
  788. 'base_amount' => '100.0000', 'rate' => '2.5000', 'amount' => $amount,
  789. 'source_type' => 'promoter_test', 'source_id' => (string)$i, 'status' => $status,
  790. ]);
  791. }
  792. $result = $this->promotersResponse(['date' => '2020-01-01']);
  793. $this->assertSame(0, $result['code']);
  794. $this->assertSame(2, $result['data']['total']);
  795. $rows = array_column($result['data']['data'], null, 'promoter_code');
  796. $this->assertSame('matched', $rows['PROMO']['promoter_status']);
  797. $this->assertSame('1001', $rows['PROMO']['member_id']);
  798. $this->assertSame('promoter', $rows['PROMO']['account']);
  799. $this->assertSame('推广人', $rows['PROMO']['nickname']);
  800. $this->assertSame('100.0000', $rows['PROMO']['deposit_total']);
  801. $this->assertSame(1, $rows['PROMO']['registered_count']);
  802. $this->assertSame('2.5000', $rows['PROMO']['commission']);
  803. $this->assertSame('0.0000', $rows['PROMO']['current_fee_rate']);
  804. $this->assertSame('missing', $rows['OTHER']['promoter_status']);
  805. $this->assertSame('30.0000', $rows['OTHER']['deposit_total']);
  806. }
  807. public function test_promoter_details_pagination_filters_and_empty_dates_still_apply(): void
  808. {
  809. $this->memberHistory();
  810. $first = $this->promotersResponse(['date' => '2020-01-01', 'page' => 1, 'limit' => 1]);
  811. $this->assertSame(0, $first['code']);
  812. $this->assertSame(2, $first['data']['total']);
  813. $this->assertCount(1, $first['data']['data']);
  814. $this->assertSame('PROMO', $first['data']['data'][0]['promoter_code']);
  815. $last = $this->promotersResponse(['date' => '2020-01-01', 'page' => 2, 'limit' => 1]);
  816. $this->assertSame(2, $last['data']['total']);
  817. $this->assertSame('OTHER', $last['data']['data'][0]['promoter_code']);
  818. foreach ([['member_id' => '1001'], ['account' => 'prom']] as $filter) {
  819. $result = $this->promotersResponse($filter + ['date' => '2020-01-01']);
  820. $this->assertSame(0, $result['code']);
  821. $this->assertSame(1, $result['data']['total']);
  822. $this->assertSame('PROMO', $result['data']['data'][0]['promoter_code']);
  823. }
  824. foreach ([['date' => '2019-01-01'], ['date' => '2020-01-01', 'page' => 3, 'limit' => 1],
  825. ['date' => '2020-01-01', 'member_id' => '1002'], ['date' => '2020-01-01', 'account' => 'OTHER']] as $params) {
  826. $result = $this->promotersResponse($params);
  827. $this->assertSame(0, $result['code']);
  828. $this->assertSame([], $result['data']['data']);
  829. }
  830. }
  831. public function test_promoter_details_does_not_assign_an_ambiguous_code_to_one_of_several_users(): void
  832. {
  833. $this->memberHistory();
  834. DB::table('users')->insert([
  835. 'id' => 99, 'member_id' => '1009', 'account' => 'duplicate',
  836. 'first_name' => '重复邀请码', 'user_code' => 'PROMO',
  837. ]);
  838. $result = $this->promotersResponse(['date' => '2020-01-01']);
  839. $this->assertSame(0, $result['code']);
  840. $this->assertSame(2, $result['data']['total']);
  841. $rows = array_column($result['data']['data'], null, 'promoter_code');
  842. $this->assertSame('ambiguous', $rows['PROMO']['promoter_status']);
  843. $this->assertSame('', $rows['PROMO']['member_id']);
  844. $this->assertSame('', $rows['PROMO']['account']);
  845. $this->assertSame('100.0000', $rows['PROMO']['deposit_total']);
  846. $this->assertSame(1, $rows['PROMO']['registered_count']);
  847. $this->assertSame('0.0000', $rows['PROMO']['commission']);
  848. }
  849. }