ShareCommissionRecordingTest.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. <?php
  2. namespace Tests\Integration;
  3. use App\Console\Commands\BackfillShareCommissions;
  4. use App\Http\Controllers\admin\ShareEarning;
  5. use App\Models\BalanceLog;
  6. use App\Models\ShareCommissionRecord;
  7. use App\Services\BalanceLogService;
  8. use App\Services\ShareCommissionRecorder;
  9. use App\Services\ShareEarningReportService;
  10. use Illuminate\Config\Repository;
  11. use Illuminate\Database\Capsule\Manager;
  12. use Illuminate\Database\Schema\Blueprint;
  13. use Illuminate\Foundation\Application;
  14. use Illuminate\Http\JsonResponse;
  15. use Illuminate\Http\Request;
  16. use Illuminate\Support\Facades\DB;
  17. use Illuminate\Support\Facades\Facade;
  18. use Illuminate\Translation\ArrayLoader;
  19. use Illuminate\Translation\Translator;
  20. use Illuminate\Validation\Factory;
  21. use PHPUnit\Framework\TestCase;
  22. use Symfony\Component\Console\Tester\CommandTester;
  23. /** Real ledger, report controller and command against an isolated in-memory database. */
  24. class ShareCommissionRecordingTest extends TestCase
  25. {
  26. private Application $app;
  27. protected function setUp(): void
  28. {
  29. Facade::clearResolvedInstances();
  30. $this->app = new Application(dirname(__DIR__, 2));
  31. $this->app->instance('config', new Repository(['app' => ['locale' => 'zh', 'timezone' => 'Asia/Shanghai']]));
  32. Facade::setFacadeApplication($this->app);
  33. $db = new Manager($this->app);
  34. $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'bot_']);
  35. $db->setAsGlobal();
  36. $db->bootEloquent();
  37. $this->app->instance('db', $db->getDatabaseManager());
  38. $translator = new Translator(new ArrayLoader(), 'zh');
  39. $this->app->instance('translator', $translator);
  40. $this->app->instance('validator', new Factory($translator, $this->app));
  41. $this->app->instance(\Illuminate\Contracts\Routing\ResponseFactory::class, new class {
  42. public function json($data, $status = 200, $headers = [], $options = 0) {
  43. return new JsonResponse($data, $status, $headers, $options);
  44. }
  45. });
  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->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('share_commission_records', function (Blueprint $t) {
  67. $t->id(); $t->date('stat_date'); $t->integer('promoter_user_id');
  68. $t->integer('invitee_user_id')->nullable(); $t->string('type'); $t->string('category');
  69. $t->decimal('base_amount', 20, 4); $t->decimal('rate', 8, 4);
  70. $t->decimal('amount', 20, 4); $t->string('source_type'); $t->string('source_id');
  71. $t->integer('status'); $t->timestamps();
  72. $t->unique(['source_type', 'source_id', 'type', 'promoter_user_id'], 'uniq_share_source');
  73. });
  74. $db->schema()->create('config', function (Blueprint $t) {
  75. $t->id(); $t->string('field'); $t->string('val'); $t->timestamps();
  76. });
  77. $db->schema()->create('level', function (Blueprint $t) {
  78. $t->id(); $t->integer('level'); $t->decimal('recharge', 20, 2); $t->timestamps();
  79. });
  80. $db->schema()->create('recharge_channel_group', function (Blueprint $t) {
  81. $t->id(); $t->text('activity_type')->nullable(); $t->softDeletes(); $t->timestamps();
  82. });
  83. $db->schema()->create('backflow', function (Blueprint $t) {
  84. $t->id(); $t->string('member_id'); $t->string('date');
  85. foreach (['recharge_amount', 'withdrawal_amount', 'backflow_ratio', 'amount'] as $field) {
  86. $t->decimal($field, 20, 2)->default(0);
  87. }
  88. $t->timestamps();
  89. });
  90. DB::table('config')->insert([
  91. ['field' => 'recharge_rate', 'val' => '2.5000'],
  92. ['field' => 'huishui_percentage', 'val' => '0'],
  93. ['field' => 'huishui_restriction', 'val' => '999999'],
  94. ]);
  95. DB::table('level')->insert(['level' => 0, 'recharge' => 0]);
  96. DB::table('recharge_channel_group')->insert(['id' => 1, 'activity_type' => '']);
  97. DB::table('backflow')->insert(['member_id' => '1002', 'date' => date('Y-m')]);
  98. DB::table('users')->insert([
  99. ['id' => 7, 'member_id' => '1001', 'account' => 'promoter', 'first_name' => '推广人', 'user_code' => 'PROMO', 'agent_user_code' => null],
  100. ['id' => 42, 'member_id' => '1002', 'account' => 'invitee', 'first_name' => '被邀请人', 'user_code' => 'CHILD', 'agent_user_code' => 'PROMO'],
  101. ]);
  102. DB::table('wallets')->insert([
  103. ['member_id' => '1001', 'available_balance' => '20.00'],
  104. ['member_id' => '1002', 'available_balance' => '100.00'],
  105. ]);
  106. $this->app->instance('request', Request::create('/admin/shareEarning/summary', 'GET', []));
  107. }
  108. protected function tearDown(): void
  109. {
  110. DB::disconnect();
  111. Facade::clearResolvedInstances();
  112. parent::tearDown();
  113. }
  114. public static function depositTypes(): array
  115. {
  116. return [['充值'], ['三方充值']];
  117. }
  118. /** @dataProvider depositTypes */
  119. public function test_existing_rebate_payment_registers_real_commission_and_is_visible_in_summary(string $type): void
  120. {
  121. BalanceLogService::addLog('1002', '100.00', '0.00', '100.00', $type, 88, '');
  122. $rebate = BalanceLog::where('change_type', '充值返现')->firstOrFail();
  123. $record = ShareCommissionRecord::firstOrFail();
  124. $this->assertSame(7, (int)$record->promoter_user_id);
  125. $this->assertSame(42, (int)$record->invitee_user_id);
  126. $this->assertSame('100.0000', $record->base_amount);
  127. $this->assertSame('2.5000', $record->rate);
  128. $this->assertSame('2.5000', $record->amount);
  129. $this->assertSame(ShareCommissionRecorder::SOURCE_TYPE, $record->source_type);
  130. $this->assertSame((string)$rebate->id, $record->source_id);
  131. $this->assertEquals('22.50', DB::table('wallets')->where('member_id', '1001')->value('available_balance'));
  132. $this->assertEquals('100.00', DB::table('wallets')->where('member_id', '1002')->value('available_balance'));
  133. $body = (new ShareEarning())->summary(new ShareEarningReportService())->getData(true);
  134. $this->assertSame(0, $body['code']);
  135. $this->assertSame(1, $body['data']['total']);
  136. $this->assertSame('promoter', $body['data']['data'][0]['promoter_account']);
  137. $this->assertSame('100.0000', $body['data']['data'][0]['deposit']);
  138. $this->assertSame('2.5000', $body['data']['summary']['total_commission']);
  139. }
  140. public function test_live_record_keeps_original_rate_and_base_precision(): void
  141. {
  142. BalanceLogService::addLog('1002', '100.1256789012', '0.00', '100.1256789012', '充值', 88, '');
  143. $record = ShareCommissionRecord::firstOrFail();
  144. $this->assertSame('100.1257', $record->base_amount);
  145. $this->assertSame('2.5000', $record->rate);
  146. $this->assertSame('2.5000', $record->amount);
  147. }
  148. public static function unrelatedDeposits(): array
  149. {
  150. return [['人工充值', 'PROMO', 1], ['优惠活动', 'PROMO', 1], ['充值', '', 1], ['充值', 'MISSING', 1], ['充值', 'PROMO', 2]];
  151. }
  152. /** @dataProvider unrelatedDeposits */
  153. public function test_recording_does_not_expand_the_existing_payment_rules(string $type, string $code, int $from): void
  154. {
  155. DB::table('users')->where('member_id', '1002')->update(['agent_user_code' => $code, 'from' => $from]);
  156. BalanceLogService::addLog('1002', '100.00', '0.00', '100.00', $type, 88, '');
  157. $this->assertSame(0, ShareCommissionRecord::count());
  158. $this->assertSame(0, BalanceLog::where('change_type', '充值返现')->count());
  159. $this->assertEquals('20.00', DB::table('wallets')->where('member_id', '1001')->value('available_balance'));
  160. }
  161. public function test_commission_insert_failure_rolls_back_the_rebate_wallet_and_ledger(): void
  162. {
  163. DB::statement("CREATE TRIGGER fail_share_insert BEFORE INSERT ON bot_share_commission_records
  164. BEGIN SELECT RAISE(ABORT, 'injected share failure'); END");
  165. try {
  166. BalanceLogService::addLog('1002', '100.00', '0.00', '100.00', '充值', 88, '');
  167. $this->fail('Commission failure must abort the rebate payment.');
  168. } catch (\Illuminate\Database\QueryException $e) {
  169. $this->assertStringContainsString('injected share failure', $e->getMessage());
  170. }
  171. $this->assertSame(0, DB::transactionLevel());
  172. $this->assertEquals('20.00', DB::table('wallets')->where('member_id', '1001')->value('available_balance'));
  173. $this->assertSame(0, BalanceLog::where('change_type', '充值返现')->count());
  174. $this->assertSame(0, ShareCommissionRecord::count());
  175. $this->assertSame(1, BalanceLog::where('change_type', '充值')->count());
  176. }
  177. public function test_live_record_respects_the_callers_transaction_rollback(): void
  178. {
  179. DB::beginTransaction();
  180. BalanceLogService::addLog('1002', '100.00', '0.00', '100.00', '三方充值', 88, '');
  181. $this->assertSame(1, DB::transactionLevel());
  182. $this->assertSame(1, ShareCommissionRecord::count());
  183. DB::rollBack();
  184. $this->assertEquals('20.00', DB::table('wallets')->where('member_id', '1001')->value('available_balance'));
  185. $this->assertSame(0, BalanceLog::count());
  186. $this->assertSame(0, ShareCommissionRecord::count());
  187. }
  188. private function historicalRebate(array $extra = []): BalanceLog
  189. {
  190. DB::table('wallets')->where('member_id', '1001')->update(['available_balance' => '22.50']);
  191. $log = new BalanceLog();
  192. $log->forceFill($extra + [
  193. 'member_id' => '1001', 'type' => 1, 'change_type' => '充值返现', 'related_id' => 88,
  194. 'amount' => '2.50', 'before_balance' => '20.00', 'after_balance' => '22.50',
  195. 'remark' => '被邀请人:1002充值金额为:100.00',
  196. 'created_at' => '2026-10-01 01:02:03', 'updated_at' => '2026-10-01 01:02:03',
  197. ])->save();
  198. return $log;
  199. }
  200. public function test_historical_registration_is_idempotent_and_never_credits_again(): void
  201. {
  202. $rebate = $this->historicalRebate();
  203. DB::table('config')->where('field', 'recharge_rate')->update(['val' => '99']);
  204. DB::table('users')->where('member_id', '1002')->update(['agent_user_code' => 'CHANGED']);
  205. $wallets = DB::table('wallets')->orderBy('id')->get()->toJson();
  206. $ledger = DB::table('balance_logs')->orderBy('id')->get()->toJson();
  207. $recorder = new ShareCommissionRecorder();
  208. $this->assertSame('pending', $recorder->preview($rebate)['status']);
  209. $this->assertSame(0, ShareCommissionRecord::count());
  210. $this->assertSame('created', $recorder->record($rebate)['status']);
  211. $this->assertSame('existing', $recorder->record($rebate)['status']);
  212. $this->assertSame(1, ShareCommissionRecord::count());
  213. $record = ShareCommissionRecord::firstOrFail();
  214. $this->assertSame('2026-10-01', $record->stat_date->format('Y-m-d'));
  215. $this->assertSame('2.5000', $record->rate);
  216. $this->assertSame('100.0000', $record->base_amount);
  217. $this->assertSame(42, (int)$record->invitee_user_id);
  218. $this->assertSame($wallets, DB::table('wallets')->orderBy('id')->get()->toJson());
  219. $this->assertSame($ledger, DB::table('balance_logs')->orderBy('id')->get()->toJson());
  220. }
  221. public function test_unknown_historical_details_keep_actual_payment_without_inventing_a_base(): void
  222. {
  223. $rebate = $this->historicalRebate(['remark' => '历史返现']);
  224. $result = (new ShareCommissionRecorder())->record($rebate);
  225. $this->assertSame('created', $result['status']);
  226. $this->assertTrue($result['incomplete_metadata']);
  227. $record = ShareCommissionRecord::firstOrFail();
  228. $this->assertNull($record->invitee_user_id);
  229. $this->assertSame('0.0000', $record->base_amount);
  230. $this->assertSame('0.0000', $record->rate);
  231. $this->assertSame('2.5000', $record->amount);
  232. }
  233. public function test_historical_balance_comparison_uses_delta_before_rounding(): void
  234. {
  235. $rebate = $this->historicalRebate(['before_balance' => '20.0000499999', 'after_balance' => '22.5000500001']);
  236. $result = (new ShareCommissionRecorder())->record($rebate);
  237. $this->assertSame('created', $result['status']);
  238. $this->assertSame('2.5000', ShareCommissionRecord::firstOrFail()->amount);
  239. }
  240. public function test_same_payout_source_is_not_duplicated_when_user_rows_are_replaced(): void
  241. {
  242. $rebate = $this->historicalRebate();
  243. $recorder = new ShareCommissionRecorder();
  244. $recorder->record($rebate);
  245. DB::table('users')->where('id', 7)->delete();
  246. DB::table('users')->insert(['id' => 9, 'member_id' => '1001', 'account' => 'reimported', 'first_name' => '重建账户', 'user_code' => 'PROMO']);
  247. $this->assertSame('existing', $recorder->record($rebate)['status']);
  248. $this->assertSame(1, ShareCommissionRecord::count());
  249. $this->assertSame(7, (int)ShareCommissionRecord::firstOrFail()->promoter_user_id);
  250. }
  251. public static function invalidHistoricalLogs(): array
  252. {
  253. return [
  254. [['amount' => '0.00', 'after_balance' => '20.00'], 'invalid_amount'],
  255. [['after_balance' => '20.00'], 'unbalanced_log'],
  256. [['member_id' => '9999'], 'missing_promoter'],
  257. [['type' => 2], 'not_recharge_rebate'],
  258. [['change_type' => '优惠活动'], 'not_recharge_rebate'],
  259. ];
  260. }
  261. /** @dataProvider invalidHistoricalLogs */
  262. public function test_invalid_historical_logs_are_reported_instead_of_booked(array $extra, string $reason): void
  263. {
  264. $rebate = $this->historicalRebate($extra);
  265. $result = (new ShareCommissionRecorder())->record($rebate);
  266. $this->assertSame('skipped', $result['status']);
  267. $this->assertSame($reason, $result['reason']);
  268. $this->assertSame(0, ShareCommissionRecord::count());
  269. }
  270. public function test_backfill_does_not_reactivate_a_manually_voided_record(): void
  271. {
  272. $rebate = $this->historicalRebate();
  273. $recorder = new ShareCommissionRecorder();
  274. $recorder->record($rebate);
  275. ShareCommissionRecord::query()->update(['status' => 0]);
  276. $this->assertSame('existing', $recorder->record($rebate)['status']);
  277. $this->assertSame(0, ShareCommissionRecord::firstOrFail()->status);
  278. }
  279. private function command(array $options): CommandTester
  280. {
  281. $command = new BackfillShareCommissions();
  282. $command->setLaravel($this->app);
  283. $tester = new CommandTester($command);
  284. $tester->execute($options);
  285. return $tester;
  286. }
  287. public function test_backfill_command_defaults_to_preview_and_write_is_repeatable(): void
  288. {
  289. $this->historicalRebate();
  290. $options = ['--start-date' => '2026-10-01', '--end-date' => '2026-10-02', '--chunk' => 1];
  291. $wallets = DB::table('wallets')->orderBy('id')->get()->toJson();
  292. $preview = $this->command($options);
  293. $this->assertSame(0, $preview->getStatusCode());
  294. $this->assertStringContainsString('只读预览', $preview->getDisplay());
  295. $this->assertSame(0, ShareCommissionRecord::count());
  296. $written = $this->command($options + ['--write' => true]);
  297. $this->assertSame(0, $written->getStatusCode(), $written->getDisplay());
  298. $this->assertSame(1, ShareCommissionRecord::count());
  299. $again = $this->command($options + ['--write' => true]);
  300. $this->assertSame(0, $again->getStatusCode());
  301. $this->assertSame(1, ShareCommissionRecord::count());
  302. $this->assertSame($wallets, DB::table('wallets')->orderBy('id')->get()->toJson());
  303. }
  304. public function test_backfill_command_rejects_invalid_ranges_without_writing(): void
  305. {
  306. $this->historicalRebate();
  307. $result = $this->command(['--start-date' => '2026-10-03', '--end-date' => '2026-10-01', '--write' => true]);
  308. $this->assertSame(1, $result->getStatusCode());
  309. $this->assertSame(0, ShareCommissionRecord::count());
  310. }
  311. }