SharingSettlementTest.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. <?php
  2. namespace Tests\Integration;
  3. use App\Console\Commands\SettleSharing;
  4. use App\Services\Sharing\ShareDefaults;
  5. use App\Services\Sharing\ShareRelations;
  6. use App\Services\Sharing\ShareSettlementService;
  7. use Carbon\Carbon;
  8. use Illuminate\Config\Repository;
  9. use Illuminate\Database\Capsule\Manager;
  10. use Illuminate\Database\Schema\Blueprint;
  11. use Illuminate\Foundation\Application;
  12. use Illuminate\Support\Facades\DB;
  13. use Illuminate\Support\Facades\Facade;
  14. use PHPUnit\Framework\TestCase;
  15. use Symfony\Component\Console\Tester\CommandTester;
  16. class SharingSettlementTest extends TestCase
  17. {
  18. private ShareSettlementService $service;
  19. private ShareRelations $relations;
  20. protected function setUp(): void
  21. {
  22. Facade::clearResolvedInstances();
  23. Carbon::setTestNow(Carbon::parse('2026-10-25 12:00:00','Asia/Shanghai'));
  24. $app=new Application(dirname(__DIR__,2));
  25. $app->instance('config',new Repository(['app'=>['timezone'=>'Asia/Shanghai'],'third_game'=>['currency'=>'CNY']]));
  26. Facade::setFacadeApplication($app);
  27. $db=new Manager($app); $db->addConnection(['driver'=>'sqlite','database'=>':memory:','prefix'=>'bot_']);
  28. $db->setAsGlobal(); $db->bootEloquent(); $app->instance('db',$db->getDatabaseManager()); $app->bind('db.schema',fn()=>$db->schema());
  29. $db->schema()->create('users',function(Blueprint $t){
  30. $t->id(); $t->string('member_id'); $t->string('user_code'); $t->string('agent_user_code')->nullable(); $t->integer('from')->default(1); $t->timestamps();
  31. $t->string('user_id')->nullable(); $t->string('first_name')->nullable(); $t->string('username')->nullable(); $t->string('language')->nullable();
  32. $t->integer('recharge_channel_group_id')->default(0);
  33. });
  34. $db->schema()->create('share_settings',function(Blueprint $t){
  35. $t->id(); $t->boolean('enabled')->default(1); $t->boolean('benefit_enabled')->default(0); $t->string('share_domain')->default('https://pc.example');
  36. $t->decimal('valid_member_min_deposit',24,10)->default(20); $t->timestamps();
  37. });
  38. $db->schema()->create('balance_logs',function(Blueprint $t){
  39. $t->id(); $t->string('member_id'); $t->integer('type')->default(1); $t->string('change_type'); $t->decimal('amount',24,10); $t->timestamps();
  40. });
  41. $db->schema()->create('wallets',function(Blueprint $t){$t->id();$t->string('member_id');$t->decimal('available_balance',24,10)->default(50);$t->decimal('frozen_balance',24,10)->default(0);});
  42. (require dirname(__DIR__,2).'/database/migrations/2026_10_24_120000_create_member_sharing_system.php')->up();
  43. foreach ([[1,'A',null],[2,'B','A'],[3,'C','B'],[4,'D','C'],[5,'E','A'],[6,'X',null],[7,'DEMO',null]] as [$id,$code,$parent]) {
  44. DB::table('users')->insert(['id'=>$id,'member_id'=>'M'.$id,'user_code'=>$code,'agent_user_code'=>$parent,'from'=>$id===7?2:1,'created_at'=>'2026-10-01 00:00:00']);
  45. DB::table('balance_logs')->insert(['member_id'=>'M'.$id,'change_type'=>'充值','amount'=>20,'created_at'=>'2026-10-20 00:00:00']);
  46. DB::table('wallets')->insert(['member_id'=>'M'.$id]);
  47. }
  48. DB::table('share_settings')->insert(['activation_date'=>'2026-10-24','enabled'=>1,'benefit_enabled'=>1,'valid_member_min_effective_bet'=>100]);
  49. DB::table('share_policies')->insert(['effective_date'=>'2026-10-24','enabled'=>1,'benefit_enabled'=>1,
  50. 'valid_member_min_deposit'=>20,'valid_member_min_effective_bet'=>100,'rules'=>json_encode(ShareDefaults::rules())]);
  51. $this->relations=new ShareRelations(); $this->relations->initialize(true); $this->service=new ShareSettlementService();
  52. }
  53. protected function tearDown(): void
  54. {
  55. Carbon::setTestNow(); DB::disconnect(); Facade::clearResolvedInstances(); parent::tearDown();
  56. }
  57. private function fact(int $user,string $amount,string $date='2026-10-24',array $extra=[]): int
  58. {
  59. return DB::table('share_bet_facts')->insertGetId($extra+['source'=>'fixture','source_id'=>uniqid('',true),'user_id'=>$user,'member_id'=>'M'.$user,
  60. 'category'=>'third:2','bet_at'=>$date.' 12:00:00','bet_date'=>$date,'settled_at'=>'2026-10-25 10:00:00',
  61. 'bet_amount'=>$amount,'net_profit'=>'-'.$amount,'effective_amount'=>$amount,'settled'=>1,'voided'=>0,'currency'=>'CNY','source_version'=>str_repeat('a',64)]);
  62. }
  63. private function amount(int $user,string $field='earned_amount'): string { return bcadd((string)DB::table('share_accounts')->where('user_id',$user)->value($field),'0',10); }
  64. public function test_nine_categories_have_the_exact_twelve_tiers_and_both_qualifiers_are_required(): void
  65. {
  66. $this->assertCount(9,ShareDefaults::rules());
  67. $rules=ShareDefaults::rules()['third:2']; $this->assertCount(12,$rules);
  68. $this->assertSame('0.25',ShareSettlementService::rate($rules,1,'1000000'));
  69. $this->assertSame('0',ShareSettlementService::rate($rules,0,'99.99'));
  70. $this->assertSame('0.10',ShareSettlementService::rate($rules,0,'100'));
  71. $this->assertSame('0.70',ShareSettlementService::rate($rules,5,'1700000'));
  72. }
  73. public function test_receiver_own_rate_is_compounded_by_depth_and_retries_are_idempotent(): void
  74. {
  75. $this->fact(2,'200'); $this->fact(3,'20000');
  76. $projection=$this->service->projection('2026-10-24');
  77. $a=$projection['rows'][1]['third:2']; $b=$projection['rows'][2]['third:2'];
  78. $this->assertEquals(0.1,$a['rate']); $this->assertEquals(0.2,$b['rate']);
  79. $this->assertSame('0.0200000000',$a['indirect_commission']);
  80. $this->assertSame('40.0000000000',$b['direct_commission']);
  81. $before=DB::table('wallets')->get()->toJson();
  82. $first=$this->service->settle('2026-10-24');
  83. $this->assertSame(2,$first['receivers']); $this->assertSame('0.2200000000',$this->amount(1));
  84. $this->assertSame('40.0000000000',$this->amount(2));
  85. $entries=DB::table('share_ledger')->count();
  86. $this->assertSame(0,$this->service->settle('2026-10-24')['changed']);
  87. $this->assertSame($entries,DB::table('share_ledger')->count());
  88. $this->assertSame($before,DB::table('wallets')->get()->toJson());
  89. }
  90. public function test_third_depth_adds_another_receiver_rate_factor(): void
  91. {
  92. $this->fact(2,'200'); $this->fact(3,'20000'); $this->fact(4,'1000');
  93. $row=$this->service->projection('2026-10-24')['rows'][1]['third:2'];
  94. $this->assertSame('21000.0000000000',$row['indirect_performance']);
  95. $this->assertSame('0.0200010000',$row['indirect_commission']);
  96. $this->assertSame(3,DB::table('share_tree')->where('ancestor_user_id',1)->where('descendant_user_id',4)->value('depth'));
  97. }
  98. public function test_ten_percent_compounds_through_four_levels_using_only_the_receiver_rate(): void
  99. {
  100. DB::table('users')->insert(['id'=>8,'member_id'=>'M8','user_code'=>'F','agent_user_code'=>'D','created_at'=>'2026-10-01 00:00:00']);
  101. DB::table('balance_logs')->insert(['member_id'=>'M8','change_type'=>'充值','amount'=>20,'created_at'=>'2026-10-20 00:00:00']);
  102. $this->relations->initialize(true);
  103. $rules=ShareDefaults::rules();
  104. $rules['third:2']=[
  105. ['min_valid_members'=>0,'min_performance'=>'0','rate'=>'10'],
  106. ['min_valid_members'=>0,'min_performance'=>'2000','rate'=>'20'],
  107. ];
  108. DB::table('share_policies')->where('effective_date','2026-10-24')->update(['rules'=>json_encode($rules)]);
  109. $this->fact(2,'1000'); $this->fact(3,'2000'); $this->fact(4,'1000'); $this->fact(8,'1000');
  110. $rows=$this->service->projection('2026-10-24')['rows'];
  111. $a=$rows[1]['third:2'];
  112. $this->assertSame('10',$a['rate']);
  113. $this->assertSame('20',$rows[2]['third:2']['rate']);
  114. $this->assertSame('100.0000000000',$a['direct_commission']);
  115. $this->assertSame('4000.0000000000',$a['indirect_performance']);
  116. // 2000*10%*10% + 1000*10%^3 + 1000*10%^4 = 20+1+0.1.
  117. $this->assertSame('21.1000000000',$a['indirect_commission']);
  118. $this->service->settle('2026-10-24');
  119. $this->assertSame('121.1000000000',$this->amount(1));
  120. $this->assertSame(0,$this->service->settle('2026-10-24')['changed']);
  121. }
  122. public function test_depth_buckets_keep_precision_until_the_final_aggregate(): void
  123. {
  124. $second=ShareSettlementService::depthCommission('0.000000006','10',2);
  125. $third=ShareSettlementService::depthCommission('0.00000006','10',3);
  126. $this->assertSame('0.000000000060000000000000000000',$second);
  127. $this->assertSame('0.000000000060000000000000000000',$third);
  128. $this->assertSame('0.0000000001',bcadd(bcadd($second,$third,30),'0',10));
  129. $this->assertSame('0.000000000000000000000000000000',ShareSettlementService::depthCommission('1000','0',99));
  130. $this->assertSame('1000.000000000000000000000000000000',ShareSettlementService::depthCommission('1000','100',999));
  131. $this->assertSame('0.000000000000000000000000000000',ShareSettlementService::depthCommission('1000','0.1',999));
  132. }
  133. public function test_formula_cutover_preserves_booked_history_and_changes_only_following_days(): void
  134. {
  135. $this->fact(2,'200'); $this->fact(3,'20000');
  136. DB::table('share_policies')->where('effective_date','2026-10-24')->update(['indirect_bonus_rate'=>30]);
  137. DB::table('share_system_state')->insert(['key'=>'commission_depth_rate_start','value'=>'2099-01-01']);
  138. $this->service->settle('2026-10-24');
  139. $this->assertSame('6.2000000000',$this->amount(1));
  140. DB::table('share_system_state')->where('key','commission_depth_rate_start')->delete();
  141. $before=DB::table('share_accounts')->get()->toJson();
  142. $ledger=DB::table('share_ledger')->get()->toJson();
  143. $wallets=DB::table('wallets')->get()->toJson();
  144. $migration=require dirname(__DIR__,2).'/database/migrations/2026_10_24_150000_use_depth_rates_for_member_sharing.php';
  145. $migration->up();
  146. $this->assertSame('2026-10-26',DB::table('share_system_state')->where('key','commission_depth_rate_start')->value('value'));
  147. $this->assertSame($before,DB::table('share_accounts')->get()->toJson());
  148. $this->assertSame($ledger,DB::table('share_ledger')->get()->toJson());
  149. $this->assertSame($wallets,DB::table('wallets')->get()->toJson());
  150. $this->assertSame(0,$this->service->settle('2026-10-24')['changed']);
  151. $this->fact(2,'200','2026-10-26'); $this->fact(3,'20000','2026-10-26');
  152. $this->assertSame('0.0200000000',$this->service->projection('2026-10-26')['rows'][1]['third:2']['indirect_commission']);
  153. Carbon::setTestNow(Carbon::parse('2026-10-27 12:00:00','Asia/Shanghai'));
  154. $migration->up();
  155. $this->assertSame('2026-10-26',DB::table('share_system_state')->where('key','commission_depth_rate_start')->value('value'));
  156. }
  157. public function test_fresh_installation_requires_no_legacy_bonus_or_waiting_day(): void
  158. {
  159. DB::table('share_settings')->update(['activation_date'=>null]);
  160. $migration=require dirname(__DIR__,2).'/database/migrations/2026_10_24_150000_use_depth_rates_for_member_sharing.php';
  161. $migration->up();
  162. $this->assertSame('1970-01-01',DB::table('share_system_state')->where('key','commission_depth_rate_start')->value('value'));
  163. $migration->down();
  164. $this->assertFalse(DB::table('share_system_state')->where('key','commission_depth_rate_start')->exists());
  165. }
  166. public function test_qualification_excludes_performance_and_later_deposits_do_not_requalify_previous_days(): void
  167. {
  168. $this->fact(2,'200'); $this->fact(3,'20000');
  169. DB::table('balance_logs')->where('member_id','M3')->update(['created_at'=>'2026-10-25 00:01:00']);
  170. $projection=$this->service->projection('2026-10-24');
  171. $this->assertArrayNotHasKey(2,$projection['rows']);
  172. $this->assertSame('0',$projection['rows'][1]['third:2']['indirect_performance']);
  173. $this->assertSame(1,$projection['rows'][1]['third:2']['valid_direct_members']);
  174. $this->fact(2,'10','2026-10-25'); $this->fact(3,'20000','2026-10-25');
  175. $this->assertArrayHasKey(2,$this->service->projection('2026-10-25')['rows']);
  176. }
  177. public function test_all_game_cumulative_qualification_but_category_tiers_stay_independent(): void
  178. {
  179. $this->fact(2,'50'); $this->fact(2,'60','2026-10-23',['category'=>'self:sport']);
  180. $this->fact(5,'20000','2026-10-24',['category'=>'self:lottery']);
  181. $rows=$this->service->projection('2026-10-24')['rows'][1];
  182. $this->assertSame('50.0000000000',$rows['third:2']['direct_performance']);
  183. $this->assertSame('0',$rows['third:2']['rate']);
  184. $this->assertSame('0.20',$rows['self:lottery']['rate']);
  185. $this->assertSame(2,$rows['self:lottery']['valid_direct_members']);
  186. }
  187. public function test_late_result_reconciles_original_day_and_later_cumulative_qualifications(): void
  188. {
  189. $this->fact(2,'200'); $this->fact(3,'99');
  190. $this->service->settle('2026-10-24'); $this->assertSame('0.2000000000',$this->amount(1));
  191. $this->fact(3,'1','2026-10-23');
  192. DB::table('share_system_state')->insert(['key'=>'facts_dirty_dates','value'=>'["2026-10-23"]']);
  193. $result=$this->service->reconcile();
  194. $this->assertSame(1,$result['dates']); $this->assertSame('0.2000990000',$this->amount(1));
  195. $this->assertSame('[]',DB::table('share_system_state')->where('key','facts_dirty_dates')->value('value'));
  196. }
  197. public function test_paid_reversal_offsets_future_earnings_without_touching_main_wallet_or_reserved_claim(): void
  198. {
  199. $this->fact(2,'200'); $c=$this->fact(3,'20000'); $this->service->settle('2026-10-24');
  200. DB::table('share_accounts')->where('user_id',1)->update(['paid_amount'=>'0.22']);
  201. $wallet=DB::table('wallets')->get()->toJson();
  202. DB::table('share_bet_facts')->where('id',$c)->update(['voided'=>1,'effective_amount'=>0,'source_version'=>'canceled']);
  203. $this->service->settle('2026-10-24');
  204. $this->assertSame('0.2000000000',$this->amount(1)); $this->assertSame('0.2200000000',$this->amount(1,'paid_amount'));
  205. $this->assertSame('0.0000000000',$this->amount(2));
  206. Carbon::setTestNow(Carbon::parse('2026-10-26 12:00:00','Asia/Shanghai'));
  207. $this->fact(2,'10000','2026-10-25'); $this->service->settle('2026-10-25');
  208. $this->assertSame('10.2000000000',$this->amount(1));
  209. $this->assertSame('9.9800000000',bcsub($this->amount(1),$this->amount(1,'paid_amount'),10));
  210. $this->assertSame($wallet,DB::table('wallets')->get()->toJson());
  211. }
  212. public function test_policy_snapshot_is_used_for_replay_and_preview_is_read_only(): void
  213. {
  214. $fact=$this->fact(2,'200'); $this->service->settle('2026-10-24');
  215. $rules=ShareDefaults::rules(); $rules['third:2']=[['min_valid_members'=>0,'min_performance'=>'0','rate'=>'99']];
  216. DB::table('share_policies')->insert(['effective_date'=>'2026-10-25','enabled'=>1,'benefit_enabled'=>1,'valid_member_min_deposit'=>20,
  217. 'valid_member_min_effective_bet'=>100,'rules'=>json_encode($rules)]);
  218. DB::table('share_bet_facts')->where('id',$fact)->update(['effective_amount'=>'300']);
  219. $before=DB::table('share_accounts')->get()->toJson();
  220. $this->assertSame('0.1000000000',$this->service->settle('2026-10-24',false)['delta']);
  221. $this->assertSame($before,DB::table('share_accounts')->get()->toJson());
  222. $this->service->settle('2026-10-24'); $this->assertSame('0.3000000000',$this->amount(1));
  223. }
  224. public function test_grades_use_incremental_thresholds_and_never_downgrade_on_correction(): void
  225. {
  226. DB::table('share_levels')->insert([['level'=>2,'name'=>'二级','incremental_commission'=>100],['level'=>3,'name'=>'三级','incremental_commission'=>300]]);
  227. $fact=$this->fact(2,'50000'); $this->service->settle('2026-10-24');
  228. $this->assertSame(2,DB::table('share_members')->where('user_id',1)->value('level'));
  229. DB::table('share_bet_facts')->where('id',$fact)->update(['effective_amount'=>160000]);
  230. $this->service->settle('2026-10-24');
  231. $this->assertSame('400.0000000000',$this->amount(1));
  232. $this->assertSame(3,DB::table('share_members')->where('user_id',1)->value('level'));
  233. DB::table('share_bet_facts')->where('id',$fact)->update(['effective_amount'=>200]); $this->service->settle('2026-10-24');
  234. $this->assertSame(3,DB::table('share_members')->where('user_id',1)->value('level'));
  235. }
  236. public function test_later_first_binding_keeps_subtree_but_does_not_give_old_bets_to_new_ancestor(): void
  237. {
  238. $this->fact(2,'200'); $this->fact(3,'20000');
  239. $this->relations->bind(1,6,'A');
  240. $this->assertSame(3,DB::table('share_tree')->where('ancestor_user_id',6)->where('descendant_user_id',3)->value('depth'));
  241. $this->assertArrayNotHasKey(6,$this->service->projection('2026-10-24')['rows']);
  242. $this->expectException(\RuntimeException::class); $this->relations->bind(6,3,'X');
  243. }
  244. public function test_invalid_legacy_codes_and_cycles_are_isolated_without_guessing_or_mutating_users(): void
  245. {
  246. foreach ([[8,'P','Q'],[9,'Q','P'],[10,'R','MISSING'],[11,'DUP',null],[12,'DUP',null],[13,'CHILD','DUP']] as [$id,$code,$parent]) {
  247. DB::table('users')->insert(['id'=>$id,'member_id'=>'M'.$id,'user_code'=>$code,'agent_user_code'=>$parent,'created_at'=>'2026-10-01 00:00:00']);
  248. }
  249. $users=DB::table('users')->get()->toJson();
  250. $preview=$this->relations->initialize(); $this->assertSame(6,$preview['created']);
  251. $this->assertSame(7,DB::table('share_members')->count());
  252. $this->relations->initialize(true);
  253. $this->assertSame('cycle',DB::table('share_members')->where('user_id',8)->value('binding_status'));
  254. $this->assertNull(DB::table('share_members')->where('user_id',9)->value('parent_user_id'));
  255. $this->assertSame('missing',DB::table('share_members')->where('user_id',10)->value('binding_status'));
  256. $this->assertSame('ambiguous',DB::table('share_members')->where('user_id',13)->value('binding_status'));
  257. $this->assertSame($users,DB::table('users')->get()->toJson());
  258. $this->assertSame(0,$this->relations->initialize(true)['created']);
  259. }
  260. public function test_fault_rolls_back_every_ledger_account_and_period_write(): void
  261. {
  262. $this->fact(2,'200');
  263. DB::statement("CREATE TRIGGER reject_share_ledger BEFORE INSERT ON bot_share_ledger BEGIN SELECT RAISE(ABORT,'injected failure'); END");
  264. try { $this->service->settle('2026-10-24'); $this->fail('ledger failure expected'); } catch (\Illuminate\Database\QueryException $e) { $this->assertStringContainsString('injected failure',$e->getMessage()); }
  265. $this->assertSame('0.0000000000',$this->amount(1)); $this->assertSame(0,DB::table('share_settlements')->count());
  266. $this->assertSame(0,DB::table('share_ledger')->count()); $this->assertSame(0,DB::transactionLevel());
  267. DB::statement('DROP TRIGGER reject_share_ledger');
  268. $this->service->settle('2026-10-24'); $this->assertSame('0.2000000000',$this->amount(1));
  269. }
  270. public function test_today_is_rejected_without_debug_opt_in_and_foreign_currency_is_not_combined(): void
  271. {
  272. $this->fact(2,'200'); $this->fact(3,'20000','2026-10-24',['currency'=>'USD']);
  273. $this->assertSame('0',$this->service->projection('2026-10-24')['rows'][1]['third:2']['indirect_performance']);
  274. $this->expectException(\InvalidArgumentException::class); $this->service->settle('2026-10-25');
  275. }
  276. private function command(array $options): CommandTester
  277. {
  278. $command = new SettleSharing();
  279. $command->setLaravel(app());
  280. $tester = new CommandTester($command);
  281. $tester->execute($options);
  282. return $tester;
  283. }
  284. public function test_debug_today_credits_once_revises_only_the_delta_and_closes_normally_after_midnight(): void
  285. {
  286. $this->service->settle('2026-10-24');
  287. $fact = $this->fact(2, '200', '2026-10-25');
  288. $wallets = DB::table('wallets')->get()->toJson();
  289. $first = $this->service->settle('2026-10-25', true, true);
  290. $this->assertTrue($first['written']);
  291. $this->assertSame('0.2000000000', $this->amount(1));
  292. $this->assertSame('2026-10-24', DB::table('share_system_state')->where('key', 'last_settlement_date')->value('value'));
  293. $this->assertContains('2026-10-25', json_decode(DB::table('share_system_state')->where('key', 'facts_dirty_dates')->value('value'), true));
  294. $entries = DB::table('share_ledger')->count();
  295. $this->assertSame(0, $this->service->settle('2026-10-25', true, true)['changed']);
  296. $this->assertSame($entries, DB::table('share_ledger')->count());
  297. DB::table('share_bet_facts')->where('id', $fact)->update(['effective_amount' => 400]);
  298. $this->assertSame('0.2000000000', $this->service->settle('2026-10-25', true, true)['delta']);
  299. $this->assertSame('0.4000000000', $this->amount(1));
  300. $this->assertSame(0, $this->service->reconcile()['dates']);
  301. Carbon::setTestNow(Carbon::parse('2026-10-26 00:01:00', 'Asia/Shanghai'));
  302. $entries = DB::table('share_ledger')->count();
  303. $this->assertSame(1, $this->service->reconcile()['dates']);
  304. $this->assertSame('2026-10-25', DB::table('share_system_state')->where('key', 'last_settlement_date')->value('value'));
  305. $this->assertSame($entries, DB::table('share_ledger')->count());
  306. $this->assertSame('0.4000000000', $this->amount(1));
  307. $this->assertSame($wallets, DB::table('wallets')->get()->toJson());
  308. }
  309. public function test_allow_today_flag_defaults_to_today_and_ordinary_command_still_defaults_to_yesterday(): void
  310. {
  311. $this->fact(2, '200'); $this->fact(2, '300', '2026-10-25');
  312. $normal = $this->command([]);
  313. $this->assertSame(0, $normal->getStatusCode());
  314. $this->assertSame('2026-10-24', json_decode($normal->getDisplay(), true)['date']);
  315. $this->assertSame('0.2000000000', $this->amount(1));
  316. $blocked = $this->command(['date' => '2026-10-25']);
  317. $this->assertSame(1, $blocked->getStatusCode());
  318. $this->assertStringContainsString('--allow-today', $blocked->getDisplay());
  319. $debug = $this->command(['--allow-today' => true]);
  320. $this->assertSame(0, $debug->getStatusCode());
  321. $this->assertSame('2026-10-25', json_decode($debug->getDisplay(), true)['date']);
  322. $this->assertSame('0.5000000000', $this->amount(1));
  323. $again = $this->command(['date' => '2026-10-25', '--allow-today' => true]);
  324. $this->assertSame(0, $again->getStatusCode());
  325. $this->assertSame(0, json_decode($again->getDisplay(), true)['changed']);
  326. $this->assertSame('2026-10-24', DB::table('share_system_state')->where('key', 'last_settlement_date')->value('value'));
  327. }
  328. public function test_debug_preview_today_is_read_only_including_levels_markers_and_reconciliation_queue(): void
  329. {
  330. $this->fact(2, '50000', '2026-10-25');
  331. DB::table('share_levels')->insert(['level' => 2, 'name' => '二级', 'incremental_commission' => 100]);
  332. $tables = ['share_accounts', 'share_settlements', 'share_ledger', 'share_members', 'share_system_state', 'wallets'];
  333. $before = [];
  334. foreach ($tables as $table) $before[$table] = DB::table($table)->get()->toJson();
  335. $preview = $this->command(['--allow-today' => true, '--preview' => true]);
  336. $this->assertSame(0, $preview->getStatusCode());
  337. $data = json_decode($preview->getDisplay(), true);
  338. $this->assertSame('2026-10-25', $data['date']);
  339. $this->assertFalse($data['written']);
  340. $this->assertGreaterThan(0, $data['changed']);
  341. foreach ($tables as $table) $this->assertSame($before[$table], DB::table($table)->get()->toJson(), $table);
  342. }
  343. /** @dataProvider forbiddenDebugOptions */
  344. public function test_future_dates_and_incompatible_debug_options_are_rejected_before_writing(array $options): void
  345. {
  346. $this->fact(2, '200', '2026-10-25');
  347. $before = DB::table('share_system_state')->get()->toJson();
  348. $command = $this->command($options);
  349. $this->assertSame(1, $command->getStatusCode());
  350. $this->assertSame(0, DB::table('share_ledger')->count());
  351. $this->assertSame(0, DB::table('share_settlements')->count());
  352. $this->assertSame('0.0000000000', $this->amount(1));
  353. $this->assertSame($before, DB::table('share_system_state')->get()->toJson());
  354. }
  355. public static function forbiddenDebugOptions(): array
  356. {
  357. return [
  358. 'future' => [['date' => '2026-10-26']],
  359. 'future with opt in' => [['date' => '2026-10-26', '--allow-today' => true]],
  360. 'future preview' => [['date' => '2026-10-26', '--allow-today' => true, '--preview' => true]],
  361. 'invalid calendar date' => [['date' => '2026-02-30', '--allow-today' => true]],
  362. 'reconcile' => [['--allow-today' => true, '--reconcile' => true]],
  363. 'reconcile and preview' => [['--allow-today' => true, '--reconcile' => true, '--preview' => true]],
  364. ];
  365. }
  366. public function test_debug_today_uses_beijing_date_even_when_utc_is_still_yesterday(): void
  367. {
  368. Carbon::setTestNow(Carbon::parse('2026-10-25 00:01:00', 'Asia/Shanghai'));
  369. $command = $this->command(['--allow-today' => true]);
  370. $this->assertSame(0, $command->getStatusCode());
  371. $this->assertSame('2026-10-25', json_decode($command->getDisplay(), true)['date']);
  372. $this->assertFalse(DB::table('share_system_state')->where('key', 'last_settlement_date')->exists());
  373. }
  374. public function test_open_day_stays_queued_and_a_missed_midnight_run_is_automatically_recovered(): void
  375. {
  376. Carbon::setTestNow(Carbon::parse('2026-10-24 12:00:00','Asia/Shanghai'));
  377. $this->fact(2,'200');
  378. DB::table('share_system_state')->insert(['key'=>'facts_dirty_dates','value'=>'["2026-10-24"]']);
  379. $this->assertSame(0,$this->service->reconcile()['dates']);
  380. $this->assertSame(['2026-10-24'],json_decode(DB::table('share_system_state')->where('key','facts_dirty_dates')->value('value'),true));
  381. Carbon::setTestNow(Carbon::parse('2026-10-26 12:00:00','Asia/Shanghai'));
  382. $this->service->settle('2026-10-25');
  383. $this->assertSame(1,$this->service->reconcile()['dates']);
  384. $this->assertSame('0.2000000000',$this->amount(1));
  385. }
  386. public function test_real_members_without_an_invitation_code_receive_one_once_without_rebinding(): void
  387. {
  388. DB::table('users')->insert(['id'=>8,'member_id'=>'M8','user_code'=>'','agent_user_code'=>null,'from'=>-1,'created_at'=>'2026-10-01 00:00:00']);
  389. $this->assertSame(1,$this->relations->initialize()['invitation_codes_assigned']);
  390. $this->assertSame('',DB::table('users')->where('id',8)->value('user_code'));
  391. $this->relations->initialize(true);
  392. $code=DB::table('users')->where('id',8)->value('user_code');
  393. $this->assertNotSame('',$code); $this->assertNotSame('0',$code);
  394. $this->assertSame($code,DB::table('share_members')->where('user_id',8)->value('invitation_code'));
  395. $this->assertNull(DB::table('share_members')->where('user_id',8)->value('parent_user_id'));
  396. $this->relations->initialize(true);
  397. $this->assertSame($code,DB::table('users')->where('id',8)->value('user_code'));
  398. }
  399. public function test_entry_visibility_does_not_control_monetary_policy_and_pre_activation_bets_never_pay(): void
  400. {
  401. $this->fact(2,'200');
  402. DB::table('share_policies')->where('effective_date','2026-10-24')->update(['enabled'=>0]);
  403. $this->service->settle('2026-10-24');
  404. $this->assertSame('0.2000000000',$this->amount(1));
  405. $this->assertSame([],$this->service->projection('2026-10-23')['rows']);
  406. $this->assertSame(0,$this->service->settle('2026-10-23')['changed']);
  407. }
  408. public function test_new_telegram_member_after_initialization_gets_a_root_and_account_without_reinitializing_others(): void
  409. {
  410. if (!function_exists('removeZero')) require_once dirname(__DIR__,2).'/app/Helpers/helpers.php';
  411. DB::table('wallets')->insert(['member_id'=>'M99']);
  412. $user=\App\Services\PublicService::index('M99','telegram-new','新会员');
  413. $id=(int)$user->id;
  414. $this->assertSame(-1,(int)$user->from);
  415. $this->assertSame(1,(int)$user->recharge_channel_group_id);
  416. $this->assertSame('root',DB::table('share_members')->where('user_id',$id)->value('binding_status'));
  417. $this->assertSame((string)$user->user_code,DB::table('share_members')->where('user_id',$id)->value('invitation_code'));
  418. $this->assertSame(0,DB::table('share_tree')->where('ancestor_user_id',$id)->where('descendant_user_id',$id)->value('depth'));
  419. $this->assertSame('0.0000000000',$this->amount($id));
  420. $this->assertSame(8,DB::table('share_members')->count());
  421. }
  422. }