SharingSettlementTest.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. <?php
  2. namespace Tests\Integration;
  3. use App\Services\Sharing\ShareDefaults;
  4. use App\Services\Sharing\ShareRelations;
  5. use App\Services\Sharing\ShareSettlementService;
  6. use Carbon\Carbon;
  7. use Illuminate\Config\Repository;
  8. use Illuminate\Database\Capsule\Manager;
  9. use Illuminate\Database\Schema\Blueprint;
  10. use Illuminate\Foundation\Application;
  11. use Illuminate\Support\Facades\DB;
  12. use Illuminate\Support\Facades\Facade;
  13. use PHPUnit\Framework\TestCase;
  14. class SharingSettlementTest extends TestCase
  15. {
  16. private ShareSettlementService $service;
  17. private ShareRelations $relations;
  18. protected function setUp(): void
  19. {
  20. Facade::clearResolvedInstances();
  21. Carbon::setTestNow(Carbon::parse('2026-10-25 12:00:00','Asia/Shanghai'));
  22. $app=new Application(dirname(__DIR__,2));
  23. $app->instance('config',new Repository(['app'=>['timezone'=>'Asia/Shanghai'],'third_game'=>['currency'=>'CNY']]));
  24. Facade::setFacadeApplication($app);
  25. $db=new Manager($app); $db->addConnection(['driver'=>'sqlite','database'=>':memory:','prefix'=>'bot_']);
  26. $db->setAsGlobal(); $db->bootEloquent(); $app->instance('db',$db->getDatabaseManager()); $app->bind('db.schema',fn()=>$db->schema());
  27. $db->schema()->create('users',function(Blueprint $t){
  28. $t->id(); $t->string('member_id'); $t->string('user_code'); $t->string('agent_user_code')->nullable(); $t->integer('from')->default(1); $t->timestamps();
  29. $t->string('user_id')->nullable(); $t->string('first_name')->nullable(); $t->string('username')->nullable(); $t->string('language')->nullable();
  30. });
  31. $db->schema()->create('share_settings',function(Blueprint $t){
  32. $t->id(); $t->boolean('enabled')->default(1); $t->boolean('benefit_enabled')->default(0); $t->string('share_domain')->default('https://pc.example');
  33. $t->decimal('valid_member_min_deposit',24,10)->default(20); $t->timestamps();
  34. });
  35. $db->schema()->create('balance_logs',function(Blueprint $t){
  36. $t->id(); $t->string('member_id'); $t->integer('type')->default(1); $t->string('change_type'); $t->decimal('amount',24,10); $t->timestamps();
  37. });
  38. $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);});
  39. (require dirname(__DIR__,2).'/database/migrations/2026_10_24_120000_create_member_sharing_system.php')->up();
  40. 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]) {
  41. 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']);
  42. DB::table('balance_logs')->insert(['member_id'=>'M'.$id,'change_type'=>'充值','amount'=>20,'created_at'=>'2026-10-20 00:00:00']);
  43. DB::table('wallets')->insert(['member_id'=>'M'.$id]);
  44. }
  45. DB::table('share_settings')->insert(['activation_date'=>'2026-10-24','enabled'=>1,'benefit_enabled'=>1,'valid_member_min_effective_bet'=>100,'indirect_bonus_rate'=>30]);
  46. DB::table('share_policies')->insert(['effective_date'=>'2026-10-24','enabled'=>1,'benefit_enabled'=>1,
  47. 'valid_member_min_deposit'=>20,'valid_member_min_effective_bet'=>100,'indirect_bonus_rate'=>30,'rules'=>json_encode(ShareDefaults::rules())]);
  48. $this->relations=new ShareRelations(); $this->relations->initialize(true); $this->service=new ShareSettlementService();
  49. }
  50. protected function tearDown(): void
  51. {
  52. Carbon::setTestNow(); DB::disconnect(); Facade::clearResolvedInstances(); parent::tearDown();
  53. }
  54. private function fact(int $user,string $amount,string $date='2026-10-24',array $extra=[]): int
  55. {
  56. return DB::table('share_bet_facts')->insertGetId($extra+['source'=>'fixture','source_id'=>uniqid('',true),'user_id'=>$user,'member_id'=>'M'.$user,
  57. 'category'=>'third:2','bet_at'=>$date.' 12:00:00','bet_date'=>$date,'settled_at'=>'2026-10-25 10:00:00',
  58. 'bet_amount'=>$amount,'net_profit'=>'-'.$amount,'effective_amount'=>$amount,'settled'=>1,'voided'=>0,'currency'=>'CNY','source_version'=>str_repeat('a',64)]);
  59. }
  60. 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); }
  61. public function test_nine_categories_have_the_exact_twelve_tiers_and_both_qualifiers_are_required(): void
  62. {
  63. $this->assertCount(9,ShareDefaults::rules());
  64. $rules=ShareDefaults::rules()['third:2']; $this->assertCount(12,$rules);
  65. $this->assertSame('0.25',ShareSettlementService::rate($rules,1,'1000000'));
  66. $this->assertSame('0',ShareSettlementService::rate($rules,0,'99.99'));
  67. $this->assertSame('0.10',ShareSettlementService::rate($rules,0,'100'));
  68. $this->assertSame('0.70',ShareSettlementService::rate($rules,5,'1700000'));
  69. }
  70. public function test_receiver_own_rate_controls_unlimited_indirect_bonus_and_retries_are_idempotent(): void
  71. {
  72. $this->fact(2,'200'); $this->fact(3,'20000');
  73. $projection=$this->service->projection('2026-10-24');
  74. $a=$projection['rows'][1]['third:2']; $b=$projection['rows'][2]['third:2'];
  75. $this->assertEquals(0.1,$a['rate']); $this->assertEquals(0.2,$b['rate']);
  76. $this->assertSame('6.0000000000',$a['indirect_commission']);
  77. $this->assertSame('40.0000000000',$b['direct_commission']);
  78. $before=DB::table('wallets')->get()->toJson();
  79. $first=$this->service->settle('2026-10-24');
  80. $this->assertSame(2,$first['receivers']); $this->assertSame('6.2000000000',$this->amount(1));
  81. $this->assertSame('40.0000000000',$this->amount(2));
  82. $entries=DB::table('share_ledger')->count();
  83. $this->assertSame(0,$this->service->settle('2026-10-24')['changed']);
  84. $this->assertSame($entries,DB::table('share_ledger')->count());
  85. $this->assertSame($before,DB::table('wallets')->get()->toJson());
  86. }
  87. public function test_infinite_depth_is_flat_not_repeatedly_discounted(): void
  88. {
  89. $this->fact(2,'200'); $this->fact(3,'20000'); $this->fact(4,'1000');
  90. $row=$this->service->projection('2026-10-24')['rows'][1]['third:2'];
  91. $this->assertSame('21000.0000000000',$row['indirect_performance']);
  92. $this->assertSame('6.3000000000',$row['indirect_commission']);
  93. $this->assertSame(3,DB::table('share_tree')->where('ancestor_user_id',1)->where('descendant_user_id',4)->value('depth'));
  94. }
  95. public function test_qualification_excludes_performance_and_later_deposits_do_not_requalify_previous_days(): void
  96. {
  97. $this->fact(2,'200'); $this->fact(3,'20000');
  98. DB::table('balance_logs')->where('member_id','M3')->update(['created_at'=>'2026-10-25 00:01:00']);
  99. $projection=$this->service->projection('2026-10-24');
  100. $this->assertArrayNotHasKey(2,$projection['rows']);
  101. $this->assertSame('0',$projection['rows'][1]['third:2']['indirect_performance']);
  102. $this->assertSame(1,$projection['rows'][1]['third:2']['valid_direct_members']);
  103. $this->fact(2,'10','2026-10-25'); $this->fact(3,'20000','2026-10-25');
  104. $this->assertArrayHasKey(2,$this->service->projection('2026-10-25')['rows']);
  105. }
  106. public function test_all_game_cumulative_qualification_but_category_tiers_stay_independent(): void
  107. {
  108. $this->fact(2,'50'); $this->fact(2,'60','2026-10-23',['category'=>'self:sport']);
  109. $this->fact(5,'20000','2026-10-24',['category'=>'self:lottery']);
  110. $rows=$this->service->projection('2026-10-24')['rows'][1];
  111. $this->assertSame('50.0000000000',$rows['third:2']['direct_performance']);
  112. $this->assertSame('0',$rows['third:2']['rate']);
  113. $this->assertSame('0.20',$rows['self:lottery']['rate']);
  114. $this->assertSame(2,$rows['self:lottery']['valid_direct_members']);
  115. }
  116. public function test_late_result_reconciles_original_day_and_later_cumulative_qualifications(): void
  117. {
  118. $this->fact(2,'200'); $this->fact(3,'99');
  119. $this->service->settle('2026-10-24'); $this->assertSame('0.2000000000',$this->amount(1));
  120. $this->fact(3,'1','2026-10-23');
  121. DB::table('share_system_state')->insert(['key'=>'facts_dirty_dates','value'=>'["2026-10-23"]']);
  122. $result=$this->service->reconcile();
  123. $this->assertSame(1,$result['dates']); $this->assertSame('0.2297000000',$this->amount(1));
  124. $this->assertSame('[]',DB::table('share_system_state')->where('key','facts_dirty_dates')->value('value'));
  125. }
  126. public function test_paid_reversal_offsets_future_earnings_without_touching_main_wallet_or_reserved_claim(): void
  127. {
  128. $this->fact(2,'200'); $c=$this->fact(3,'20000'); $this->service->settle('2026-10-24');
  129. DB::table('share_accounts')->where('user_id',1)->update(['paid_amount'=>'6.2']);
  130. $wallet=DB::table('wallets')->get()->toJson();
  131. DB::table('share_bet_facts')->where('id',$c)->update(['voided'=>1,'effective_amount'=>0,'source_version'=>'canceled']);
  132. $this->service->settle('2026-10-24');
  133. $this->assertSame('0.2000000000',$this->amount(1)); $this->assertSame('6.2000000000',$this->amount(1,'paid_amount'));
  134. $this->assertSame('0.0000000000',$this->amount(2));
  135. Carbon::setTestNow(Carbon::parse('2026-10-26 12:00:00','Asia/Shanghai'));
  136. $this->fact(2,'10000','2026-10-25'); $this->service->settle('2026-10-25');
  137. $this->assertSame('10.2000000000',$this->amount(1));
  138. $this->assertSame('4.0000000000',bcsub($this->amount(1),$this->amount(1,'paid_amount'),10));
  139. $this->assertSame($wallet,DB::table('wallets')->get()->toJson());
  140. }
  141. public function test_policy_snapshot_is_used_for_replay_and_preview_is_read_only(): void
  142. {
  143. $fact=$this->fact(2,'200'); $this->service->settle('2026-10-24');
  144. $rules=ShareDefaults::rules(); $rules['third:2']=[['min_valid_members'=>0,'min_performance'=>'0','rate'=>'99']];
  145. DB::table('share_policies')->insert(['effective_date'=>'2026-10-25','enabled'=>1,'benefit_enabled'=>1,'valid_member_min_deposit'=>20,
  146. 'valid_member_min_effective_bet'=>100,'indirect_bonus_rate'=>30,'rules'=>json_encode($rules)]);
  147. DB::table('share_bet_facts')->where('id',$fact)->update(['effective_amount'=>'300']);
  148. $before=DB::table('share_accounts')->get()->toJson();
  149. $this->assertSame('0.1000000000',$this->service->settle('2026-10-24',false)['delta']);
  150. $this->assertSame($before,DB::table('share_accounts')->get()->toJson());
  151. $this->service->settle('2026-10-24'); $this->assertSame('0.3000000000',$this->amount(1));
  152. }
  153. public function test_grades_use_incremental_thresholds_and_never_downgrade_on_correction(): void
  154. {
  155. DB::table('share_levels')->insert([['level'=>2,'name'=>'二级','incremental_commission'=>100],['level'=>3,'name'=>'三级','incremental_commission'=>300]]);
  156. $fact=$this->fact(2,'50000'); $this->service->settle('2026-10-24');
  157. $this->assertSame(2,DB::table('share_members')->where('user_id',1)->value('level'));
  158. DB::table('share_bet_facts')->where('id',$fact)->update(['effective_amount'=>160000]);
  159. $this->service->settle('2026-10-24');
  160. $this->assertSame('400.0000000000',$this->amount(1));
  161. $this->assertSame(3,DB::table('share_members')->where('user_id',1)->value('level'));
  162. DB::table('share_bet_facts')->where('id',$fact)->update(['effective_amount'=>200]); $this->service->settle('2026-10-24');
  163. $this->assertSame(3,DB::table('share_members')->where('user_id',1)->value('level'));
  164. }
  165. public function test_later_first_binding_keeps_subtree_but_does_not_give_old_bets_to_new_ancestor(): void
  166. {
  167. $this->fact(2,'200'); $this->fact(3,'20000');
  168. $this->relations->bind(1,6,'A');
  169. $this->assertSame(3,DB::table('share_tree')->where('ancestor_user_id',6)->where('descendant_user_id',3)->value('depth'));
  170. $this->assertArrayNotHasKey(6,$this->service->projection('2026-10-24')['rows']);
  171. $this->expectException(\RuntimeException::class); $this->relations->bind(6,3,'X');
  172. }
  173. public function test_invalid_legacy_codes_and_cycles_are_isolated_without_guessing_or_mutating_users(): void
  174. {
  175. foreach ([[8,'P','Q'],[9,'Q','P'],[10,'R','MISSING'],[11,'DUP',null],[12,'DUP',null],[13,'CHILD','DUP']] as [$id,$code,$parent]) {
  176. 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']);
  177. }
  178. $users=DB::table('users')->get()->toJson();
  179. $preview=$this->relations->initialize(); $this->assertSame(6,$preview['created']);
  180. $this->assertSame(7,DB::table('share_members')->count());
  181. $this->relations->initialize(true);
  182. $this->assertSame('cycle',DB::table('share_members')->where('user_id',8)->value('binding_status'));
  183. $this->assertNull(DB::table('share_members')->where('user_id',9)->value('parent_user_id'));
  184. $this->assertSame('missing',DB::table('share_members')->where('user_id',10)->value('binding_status'));
  185. $this->assertSame('ambiguous',DB::table('share_members')->where('user_id',13)->value('binding_status'));
  186. $this->assertSame($users,DB::table('users')->get()->toJson());
  187. $this->assertSame(0,$this->relations->initialize(true)['created']);
  188. }
  189. public function test_fault_rolls_back_every_ledger_account_and_period_write(): void
  190. {
  191. $this->fact(2,'200');
  192. DB::statement("CREATE TRIGGER reject_share_ledger BEFORE INSERT ON bot_share_ledger BEGIN SELECT RAISE(ABORT,'injected failure'); END");
  193. try { $this->service->settle('2026-10-24'); $this->fail('ledger failure expected'); } catch (\Illuminate\Database\QueryException $e) { $this->assertStringContainsString('injected failure',$e->getMessage()); }
  194. $this->assertSame('0.0000000000',$this->amount(1)); $this->assertSame(0,DB::table('share_settlements')->count());
  195. $this->assertSame(0,DB::table('share_ledger')->count()); $this->assertSame(0,DB::transactionLevel());
  196. DB::statement('DROP TRIGGER reject_share_ledger');
  197. $this->service->settle('2026-10-24'); $this->assertSame('0.2000000000',$this->amount(1));
  198. }
  199. public function test_today_never_becomes_claimable_and_foreign_currency_is_not_combined(): void
  200. {
  201. $this->fact(2,'200'); $this->fact(3,'20000','2026-10-24',['currency'=>'USD']);
  202. $this->assertSame('0',$this->service->projection('2026-10-24')['rows'][1]['third:2']['indirect_performance']);
  203. $this->expectException(\InvalidArgumentException::class); $this->service->settle('2026-10-25');
  204. }
  205. public function test_open_day_stays_queued_and_a_missed_midnight_run_is_automatically_recovered(): void
  206. {
  207. Carbon::setTestNow(Carbon::parse('2026-10-24 12:00:00','Asia/Shanghai'));
  208. $this->fact(2,'200');
  209. DB::table('share_system_state')->insert(['key'=>'facts_dirty_dates','value'=>'["2026-10-24"]']);
  210. $this->assertSame(0,$this->service->reconcile()['dates']);
  211. $this->assertSame(['2026-10-24'],json_decode(DB::table('share_system_state')->where('key','facts_dirty_dates')->value('value'),true));
  212. Carbon::setTestNow(Carbon::parse('2026-10-26 12:00:00','Asia/Shanghai'));
  213. $this->service->settle('2026-10-25');
  214. $this->assertSame(1,$this->service->reconcile()['dates']);
  215. $this->assertSame('0.2000000000',$this->amount(1));
  216. }
  217. public function test_real_members_without_an_invitation_code_receive_one_once_without_rebinding(): void
  218. {
  219. 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']);
  220. $this->assertSame(1,$this->relations->initialize()['invitation_codes_assigned']);
  221. $this->assertSame('',DB::table('users')->where('id',8)->value('user_code'));
  222. $this->relations->initialize(true);
  223. $code=DB::table('users')->where('id',8)->value('user_code');
  224. $this->assertNotSame('',$code); $this->assertNotSame('0',$code);
  225. $this->assertSame($code,DB::table('share_members')->where('user_id',8)->value('invitation_code'));
  226. $this->assertNull(DB::table('share_members')->where('user_id',8)->value('parent_user_id'));
  227. $this->relations->initialize(true);
  228. $this->assertSame($code,DB::table('users')->where('id',8)->value('user_code'));
  229. }
  230. public function test_entry_visibility_does_not_control_monetary_policy_and_pre_activation_bets_never_pay(): void
  231. {
  232. $this->fact(2,'200');
  233. DB::table('share_policies')->where('effective_date','2026-10-24')->update(['enabled'=>0]);
  234. $this->service->settle('2026-10-24');
  235. $this->assertSame('0.2000000000',$this->amount(1));
  236. $this->assertSame([],$this->service->projection('2026-10-23')['rows']);
  237. $this->assertSame(0,$this->service->settle('2026-10-23')['changed']);
  238. }
  239. public function test_new_telegram_member_after_initialization_gets_a_root_and_account_without_reinitializing_others(): void
  240. {
  241. if (!function_exists('removeZero')) require_once dirname(__DIR__,2).'/app/Helpers/helpers.php';
  242. DB::table('wallets')->insert(['member_id'=>'M99']);
  243. $user=\App\Services\PublicService::index('M99','telegram-new','新会员');
  244. $id=(int)$user->id;
  245. $this->assertSame(-1,(int)$user->from);
  246. $this->assertSame('root',DB::table('share_members')->where('user_id',$id)->value('binding_status'));
  247. $this->assertSame((string)$user->user_code,DB::table('share_members')->where('user_id',$id)->value('invitation_code'));
  248. $this->assertSame(0,DB::table('share_tree')->where('ancestor_user_id',$id)->where('descendant_user_id',$id)->value('depth'));
  249. $this->assertSame('0.0000000000',$this->amount($id));
  250. $this->assertSame(8,DB::table('share_members')->count());
  251. }
  252. }