ShareCommissionRecordingTest.php 50 KB

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