SharingBetFactsTest.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. <?php
  2. namespace Tests\Integration;
  3. use App\Console\Commands\RecalculateShareRebates;
  4. use App\Models\Rebate;
  5. use App\Services\RebateService;
  6. use App\Services\Sharing\BetFactSynchronizer;
  7. use Carbon\Carbon;
  8. use Illuminate\Config\Repository;
  9. use Illuminate\Database\Capsule\Manager;
  10. use Illuminate\Database\Schema\Blueprint;
  11. use Illuminate\Events\Dispatcher;
  12. use Illuminate\Foundation\Application;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Facade;
  15. use Illuminate\Support\Facades\Schema;
  16. use PHPUnit\Framework\TestCase;
  17. class SharingBetFactsTest extends TestCase
  18. {
  19. protected function setUp(): void
  20. {
  21. parent::setUp();
  22. Carbon::setTestNow(Carbon::parse('2026-10-24 12:00:00', 'Asia/Shanghai'));
  23. Facade::clearResolvedInstances();
  24. $app = new Application(dirname(__DIR__, 2));
  25. $app->instance('config', new Repository(['app' => ['timezone' => 'Asia/Shanghai']]));
  26. Facade::setFacadeApplication($app);
  27. $db = new Manager($app);
  28. $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'bot_']);
  29. $db->setEventDispatcher(new Dispatcher($app)); $db->setAsGlobal(); $db->bootEloquent();
  30. $app->instance('db', $db->getDatabaseManager());
  31. $app->bind('db.schema', fn () => $db->schema());
  32. Schema::create('users', function (Blueprint $t) { $t->id(); $t->string('member_id'); $t->integer('from')->default(1); });
  33. DB::table('users')->insert([['id' => 1, 'member_id' => '10001', 'from' => -1], ['id' => 2, 'member_id' => '20002', 'from' => 2]]);
  34. Schema::create('lhc_order', function (Blueprint $t) {
  35. $t->id(); $t->string('member_id'); $t->string('ordernum'); $t->integer('type'); $t->integer('lottery_status');
  36. $t->decimal('amount', 24, 10); $t->decimal('total_amount', 24, 10)->nullable(); $t->bigInteger('created_at'); $t->bigInteger('updated_at');
  37. $t->decimal('coupon_discount', 14, 2)->default(0);
  38. });
  39. Schema::create('lhc_order_item', function (Blueprint $t) {
  40. $t->id(); $t->string('member_id'); $t->string('ordernum'); $t->integer('lottery_status');
  41. $t->decimal('win_amount', 24, 10)->nullable(); $t->decimal('profit_and_loss', 24, 10)->nullable(); $t->bigInteger('updated_at');
  42. $t->decimal('coupon_discount', 14, 2)->default(0);
  43. });
  44. Schema::create('sport_game_order', function (Blueprint $t) {
  45. $t->id(); $t->string('member_id'); $t->integer('status'); $t->decimal('amount', 24, 10); $t->decimal('win_amount', 24, 10)->default(0); $t->timestamps();
  46. $t->decimal('coupon_discount', 14, 2)->default(0);
  47. });
  48. Schema::create('sport_order', function (Blueprint $t) {
  49. $t->id(); $t->string('user_id'); $t->integer('status'); $t->integer('pay_status'); $t->integer('return_status')->default(0);
  50. $t->integer('settlement_status'); $t->decimal('amount', 24, 10); $t->decimal('win_amount', 24, 10)->default(0);
  51. $t->decimal('return_amount', 24, 10)->default(0); $t->bigInteger('create_time'); $t->bigInteger('update_time');
  52. $t->bigInteger('settlement_time'); $t->bigInteger('return_operation_time')->nullable();
  53. });
  54. Schema::create('third_game_orders', function (Blueprint $t) {
  55. $t->id(); $t->string('order_key'); $t->unsignedBigInteger('user_id')->nullable(); $t->string('member_id');
  56. $t->integer('game_type'); $t->integer('status'); $t->decimal('bet_amount', 24, 10)->nullable(); $t->decimal('settled_amount', 24, 10)->nullable();
  57. $t->string('currency'); $t->dateTime('bet_time'); $t->dateTime('last_update_time');
  58. });
  59. Schema::create('balance_logs', function (Blueprint $t) {
  60. $t->id(); $t->string('member_id'); $t->unsignedBigInteger('related_id'); $t->string('change_type'); $t->decimal('amount', 24, 10);
  61. });
  62. Schema::create('share_bet_facts', function (Blueprint $t) {
  63. $t->id(); $t->string('source'); $t->string('source_id'); $t->unsignedBigInteger('user_id'); $t->string('member_id');
  64. $t->string('category'); $t->dateTime('bet_at'); $t->date('bet_date'); $t->dateTime('settled_at')->nullable();
  65. foreach (['bet_amount', 'net_profit', 'effective_amount'] as $col) $t->decimal($col, 24, 10);
  66. $t->boolean('settled'); $t->boolean('voided'); $t->string('currency'); $t->string('source_version'); $t->timestamps(); $t->unique(['source', 'source_id']);
  67. });
  68. Schema::create('share_system_state', function (Blueprint $t) { $t->string('key')->primary(); $t->text('value'); $t->timestamps(); });
  69. DB::table('share_system_state')->insert(['key' => 'relations_lock', 'value' => '1']);
  70. Schema::create('rebates', function (Blueprint $t) {
  71. $t->id(); $t->string('member_id'); $t->date('date'); $t->decimal('betting_amount', 24, 2);
  72. $t->decimal('effective_betting_amount', 24, 2); $t->decimal('profit', 24, 2)->default(0); $t->integer('status'); $t->timestamps();
  73. });
  74. }
  75. protected function tearDown(): void
  76. {
  77. DB::disconnect(); Facade::clearResolvedInstances(); Facade::setFacadeApplication(null); Carbon::setTestNow();
  78. parent::tearDown();
  79. }
  80. private function lottery(int $status = 2): void
  81. {
  82. $time = Carbon::parse('2026-10-24 00:10:00', 'Asia/Shanghai')->timestamp;
  83. DB::table('lhc_order')->insert(['id' => 10, 'member_id' => '10001', 'ordernum' => 'current-lottery', 'type' => 5,
  84. 'lottery_status' => $status, 'amount' => 100, 'total_amount' => 200, 'created_at' => $time, 'updated_at' => $time + 3600]);
  85. DB::table('lhc_order_item')->insert([
  86. ['id' => 101, 'member_id' => '10001', 'ordernum' => 'current-lottery', 'lottery_status' => 2, 'win_amount' => 150, 'profit_and_loss' => 50, 'updated_at' => $time + 3600],
  87. ['id' => 102, 'member_id' => '10001', 'ordernum' => 'current-lottery', 'lottery_status' => 1, 'win_amount' => 0, 'profit_and_loss' => -100, 'updated_at' => $time + 3600],
  88. ]);
  89. }
  90. public function test_preview_then_sync_uses_child_bets_and_repeated_sync_is_idempotent(): void
  91. {
  92. $this->lottery();
  93. $sync = new BetFactSynchronizer();
  94. $this->assertSame(2, $sync->sync()['created']);
  95. $this->assertSame(0, DB::table('share_bet_facts')->count());
  96. $this->assertSame(2, $sync->sync(null, null, true)['created']);
  97. $this->assertEquals(150, DB::table('share_bet_facts')->sum('effective_amount'));
  98. $this->assertSame('2026-10-24', DB::table('share_bet_facts')->first()->bet_date);
  99. $this->assertSame(['2026-10-24'], json_decode(DB::table('share_system_state')->where('key', 'facts_dirty_dates')->value('value'), true));
  100. $again = $sync->sync(null, null, true);
  101. $this->assertSame(0, $again['created']); $this->assertSame(0, $again['updated']);
  102. $this->assertSame(2, DB::table('share_bet_facts')->count());
  103. }
  104. public function test_coupon_orders_use_paid_stake_for_net_profit_and_effective_bet(): void
  105. {
  106. // 2 numbers x 100 with a 60 coupon split 30/30: paid 70 each, payouts still on the full 100.
  107. $this->lottery();
  108. DB::table('lhc_order')->where('id', 10)->update(['coupon_discount' => 60]);
  109. DB::table('lhc_order_item')->update(['coupon_discount' => 30]);
  110. DB::table('sport_game_order')->insert([
  111. ['id' => 1, 'member_id' => '10001', 'status' => 2, 'amount' => 100, 'win_amount' => 200, 'coupon_discount' => 50, 'created_at' => '2026-10-24 10:00:00', 'updated_at' => '2026-10-24 11:00:00'],
  112. ['id' => 2, 'member_id' => '10001', 'status' => 1, 'amount' => 100, 'win_amount' => 0, 'coupon_discount' => 50, 'created_at' => '2026-10-24 10:00:00', 'updated_at' => '2026-10-24 11:00:00'],
  113. ]);
  114. $result = (new BetFactSynchronizer())->sync(null, null, true);
  115. $this->assertSame([], $result['errors']);
  116. $fact = fn (string $source, string $id) => DB::table('share_bet_facts')->where('source', $source)->where('source_id', $id)->first();
  117. $won = $fact('lhc_order_item', '101'); $lost = $fact('lhc_order_item', '102');
  118. $this->assertEquals(70, $won->bet_amount); $this->assertEquals(80, $won->net_profit); $this->assertEquals(70, $won->effective_amount);
  119. $this->assertEquals(-70, $lost->net_profit); $this->assertEquals(70, $lost->effective_amount);
  120. $this->assertEquals(150, $fact('sport_game_order', '1')->net_profit); $this->assertEquals(50, $fact('sport_game_order', '1')->effective_amount);
  121. $this->assertEquals(-50, $fact('sport_game_order', '2')->net_profit); $this->assertEquals(50, $fact('sport_game_order', '2')->effective_amount);
  122. // A refund of the paid total (not the gross 200) is a consistent full refund.
  123. DB::table('lhc_order')->where('id', 10)->update(['lottery_status' => 1, 'updated_at' => Carbon::now()->timestamp]);
  124. DB::table('balance_logs')->insert(['member_id' => '10001', 'related_id' => 10, 'change_type' => '投注退分', 'amount' => 140]);
  125. $this->assertSame([], (new BetFactSynchronizer())->sync(null, null, true)['errors']);
  126. $this->assertSame(2, DB::table('share_bet_facts')->where('source', 'lhc_order_item')->where('voided', 1)->count());
  127. }
  128. public function test_refunded_orders_mark_previous_facts_void_and_preserve_unfinished_facts(): void
  129. {
  130. $this->lottery();
  131. $sync = new BetFactSynchronizer(); $sync->sync(null, null, true);
  132. // Failed draw legacy refund is stored with loss status; its positive refund log is authoritative.
  133. DB::table('lhc_order')->where('id', 10)->update(['lottery_status' => 1, 'updated_at' => Carbon::now()->timestamp]);
  134. DB::table('balance_logs')->insert(['member_id' => '10001', 'related_id' => 10, 'change_type' => '投注退分', 'amount' => 200]);
  135. $this->assertSame(2, $sync->sync(null, null, true)['updated']);
  136. $this->assertEquals(0, DB::table('share_bet_facts')->sum('effective_amount'));
  137. $this->assertSame(2, DB::table('share_bet_facts')->where('voided', 1)->count());
  138. DB::table('sport_game_order')->insert(['member_id' => '10001', 'status' => 0, 'amount' => 100, 'created_at' => '2026-10-24 10:00:00']);
  139. $sync->sync(null, null, true);
  140. $pending = DB::table('share_bet_facts')->where('source', 'sport_game_order')->first();
  141. $this->assertEquals(0, $pending->effective_amount); $this->assertEquals(0, $pending->settled);
  142. }
  143. public function test_football_partial_returns_third_net_profit_and_demo_exclusion(): void
  144. {
  145. $time = Carbon::parse('2026-10-24 01:00:00', 'Asia/Shanghai')->timestamp;
  146. DB::table('sport_order')->insert(['user_id' => '10001', 'status' => 1, 'pay_status' => 1, 'settlement_status' => 1,
  147. 'amount' => 100, 'win_amount' => 0, 'return_amount' => 50, 'create_time' => $time, 'update_time' => $time + 3600, 'settlement_time' => $time + 3600]);
  148. foreach ([1 => '10001', 2 => '20002'] as $id => $member) {
  149. DB::table('third_game_orders')->insert(['user_id' => $id, 'member_id' => $member, 'order_key' => hash('sha256', (string) $id),
  150. 'game_type' => 4, 'status' => 1, 'bet_amount' => 100, 'settled_amount' => 80, 'currency' => 'CNY',
  151. 'bet_time' => '2026-10-24 01:00:00', 'last_update_time' => '2026-10-24 02:00:00']);
  152. }
  153. $result = (new BetFactSynchronizer())->sync(null, null, true);
  154. $this->assertSame([], $result['errors']); $this->assertSame(2, $result['created']);
  155. $this->assertEquals(50, DB::table('share_bet_facts')->where('source', 'sport_order')->value('effective_amount'));
  156. $this->assertEquals(80, DB::table('share_bet_facts')->where('source', 'third_game_orders')->value('effective_amount'));
  157. $this->assertSame(0, DB::table('share_bet_facts')->where('user_id', 2)->count());
  158. DB::table('third_game_orders')->where('user_id', 1)->update(['status' => 3, 'game_type' => 0, 'bet_amount' => null,
  159. 'settled_amount' => null, 'last_update_time' => '2026-10-24 12:00:00']);
  160. $sync = (new BetFactSynchronizer())->sync(null, null, true);
  161. $this->assertSame([], $sync['errors']); $this->assertSame(1, $sync['updated']);
  162. $cancelled = DB::table('share_bet_facts')->where('source', 'third_game_orders')->first();
  163. $this->assertEquals(0, $cancelled->effective_amount); $this->assertEquals(1, $cancelled->voided);
  164. $this->assertSame('third:4', $cancelled->category);
  165. }
  166. public function test_history_recalculation_is_preview_by_default_and_never_changes_paid_or_ambiguous_dates(): void
  167. {
  168. $this->lottery();
  169. DB::table('rebates')->insert([
  170. ['id' => 1, 'member_id' => '10001', 'date' => '2026-10-23', 'betting_amount' => 200, 'effective_betting_amount' => 200, 'status' => 0],
  171. ['id' => 2, 'member_id' => '10001', 'date' => '2026-10-24', 'betting_amount' => 200, 'effective_betting_amount' => 200, 'status' => 0],
  172. ['id' => 3, 'member_id' => '10001', 'date' => '2026-10-22', 'betting_amount' => 200, 'effective_betting_amount' => 200, 'status' => 1],
  173. ]);
  174. $command = new RecalculateShareRebates(); $sync = new BetFactSynchronizer();
  175. $preview = $command->recalculate($sync);
  176. $this->assertSame(1, $preview['changed']); $this->assertSame(1, $preview['skipped']); $this->assertSame(1, $preview['paid_untouched']);
  177. $this->assertEquals(200, DB::table('rebates')->where('id', 1)->value('effective_betting_amount'));
  178. $written = $command->recalculate($sync, true); $this->assertSame(1, $written['changed']);
  179. $this->assertEquals(150, DB::table('rebates')->where('id', 1)->value('effective_betting_amount'));
  180. $this->assertEquals(200, DB::table('rebates')->where('id', 2)->value('effective_betting_amount'));
  181. $this->assertEquals(200, DB::table('rebates')->where('id', 3)->value('effective_betting_amount'));
  182. }
  183. public function test_live_rebate_uses_betting_date_and_does_not_modify_paid_effective_basis(): void
  184. {
  185. DB::table('rebates')->insert(['id' => 1, 'member_id' => '10001', 'date' => '2026-10-23',
  186. 'betting_amount' => 100, 'effective_betting_amount' => 0, 'profit' => 0, 'status' => 0]);
  187. $row = Rebate::updateProfit(['member_id' => '10001', 'date' => '2026-10-23', 'profit' => 50]);
  188. $this->assertSame(1, $row->id); RebateService::updateEffectiveBettingAmount($row, '50.00');
  189. $this->assertEquals(50, DB::table('rebates')->value('effective_betting_amount'));
  190. DB::table('rebates')->where('id', 1)->update(['status' => 1]);
  191. RebateService::updateEffectiveBettingAmount($row, '100.00');
  192. $this->assertEquals(50, DB::table('rebates')->value('effective_betting_amount'));
  193. }
  194. public function test_legacy_injected_bets_are_never_a_source_and_partial_refund_is_flagged_for_review(): void
  195. {
  196. Schema::create('bets', function (Blueprint $t) { $t->id(); $t->integer('status'); $t->decimal('amount', 24, 10); });
  197. DB::table('bets')->insert(['status' => 2, 'amount' => 100000]);
  198. $this->lottery();
  199. DB::table('balance_logs')->insert(['member_id' => '10001', 'related_id' => 10, 'change_type' => '投注退分', 'amount' => 100]);
  200. $result = (new BetFactSynchronizer())->sync(null, null, true);
  201. $this->assertSame(1, $result['scanned']); $this->assertSame(1, count($result['errors']));
  202. $this->assertStringContainsString('refund requires review', $result['errors'][0]['reason']);
  203. $this->assertSame(0, DB::table('share_bet_facts')->count());
  204. $this->assertNull(DB::table('share_system_state')->where('key', 'facts_cursor:lhc_order')->value('value'));
  205. }
  206. public function test_incremental_cursor_includes_new_orders_with_old_dates_and_retries_updated_sources(): void
  207. {
  208. $sync = new BetFactSynchronizer(); $sync->sync(null, null, true);
  209. DB::table('sport_game_order')->insert(['id' => 20, 'member_id' => '10001', 'status' => 2, 'amount' => 100,
  210. 'win_amount' => 150, 'created_at' => '2026-10-01 10:00:00', 'updated_at' => '2026-10-01 11:00:00']);
  211. $this->assertSame(1, $sync->sync(null, null, true)['created']);
  212. DB::table('sport_game_order')->where('id', 20)->update(['status' => 3, 'updated_at' => '2026-10-24 12:00:00']);
  213. $this->assertSame(1, $sync->sync(null, null, true)['updated']);
  214. $this->assertEquals(0, DB::table('share_bet_facts')->value('effective_amount'));
  215. $this->assertSame(['2026-10-01'], json_decode(DB::table('share_system_state')->where('key', 'facts_dirty_dates')->value('value'), true));
  216. }
  217. public function test_second_child_failure_rolls_back_all_facts_dirty_dates_and_source_cursor(): void
  218. {
  219. $this->lottery();
  220. DB::statement("CREATE TRIGGER reject_second_fact BEFORE INSERT ON bot_share_bet_facts WHEN NEW.source_id='102' BEGIN SELECT RAISE(ABORT,'second child failed'); END");
  221. $result = (new BetFactSynchronizer())->sync(null, null, true);
  222. $this->assertSame(1, count($result['errors'])); $this->assertSame(0, $result['created']);
  223. $this->assertSame(0, DB::table('share_bet_facts')->count());
  224. $this->assertNull(DB::table('share_system_state')->where('key', 'facts_dirty_dates')->value('value'));
  225. $this->assertNull(DB::table('share_system_state')->where('key', 'facts_cursor:lhc_order')->value('value'));
  226. $this->assertSame(0, DB::transactionLevel());
  227. }
  228. public function test_write_reloads_source_after_chunk_read_and_preview_never_creates_the_guard(): void
  229. {
  230. $this->lottery();
  231. DB::table('share_system_state')->where('key', 'relations_lock')->delete();
  232. $preview = (new BetFactSynchronizer())->sync();
  233. $this->assertSame(2, $preview['created']); $this->assertSame(0, DB::table('share_system_state')->count());
  234. DB::table('share_system_state')->insert(['key' => 'relations_lock', 'value' => '1']);
  235. $changed = false;
  236. DB::listen(function ($event) use (&$changed) {
  237. if (!$changed && preg_match('/from "bot_lhc_order" (where "id" is not null )?order by "id"/', $event->sql)) {
  238. $changed = true;
  239. DB::table('lhc_order')->where('id', 10)->update(['lottery_status' => 4, 'updated_at' => Carbon::now()->timestamp]);
  240. }
  241. });
  242. $result = (new BetFactSynchronizer())->sync(null, null, true);
  243. $this->assertTrue($changed); $this->assertSame([], $result['errors']); $this->assertSame(2, $result['created']);
  244. $this->assertEquals(0, DB::table('share_bet_facts')->sum('effective_amount'));
  245. $this->assertSame(2, DB::table('share_bet_facts')->where('voided', 1)->count());
  246. }
  247. public function test_untrusted_source_quarantines_only_identifiable_old_facts_and_repair_restores_them(): void
  248. {
  249. $this->lottery();
  250. DB::table('sport_game_order')->insert(['member_id' => '10001', 'status' => 2, 'amount' => 100, 'win_amount' => 180,
  251. 'created_at' => '2026-10-24 10:00:00', 'updated_at' => '2026-10-24 11:00:00']);
  252. $sync = new BetFactSynchronizer(); $sync->sync(null, null, true);
  253. $original = DB::table('share_bet_facts')->where('source', 'lhc_order_item')->orderBy('source_id')->get();
  254. $cursor = DB::table('share_system_state')->where('key', 'facts_cursor:lhc_order')->value('value');
  255. DB::table('share_system_state')->where('key', 'facts_dirty_dates')->update(['value' => '[]']);
  256. DB::table('lhc_order')->where('id', 10)->update(['updated_at' => Carbon::now()->timestamp]);
  257. DB::table('balance_logs')->insert(['member_id' => '10001', 'related_id' => 10, 'change_type' => '投注退分', 'amount' => 100]);
  258. $bad = $sync->sync(null, null, true);
  259. $this->assertSame(1, count($bad['errors'])); $this->assertSame(2, $bad['errors'][0]['isolated_facts']);
  260. $this->assertSame(2, $bad['updated']);
  261. $this->assertEquals(0, DB::table('share_bet_facts')->where('source', 'lhc_order_item')->sum('effective_amount'));
  262. $this->assertSame(2, DB::table('share_bet_facts')->where('source', 'lhc_order_item')->where('settled', 0)->where('voided', 0)->count());
  263. $this->assertEquals(80, DB::table('share_bet_facts')->where('source', 'sport_game_order')->value('effective_amount'));
  264. $quarantined = DB::table('share_bet_facts')->where('source', 'lhc_order_item')->orderBy('source_id')->get();
  265. foreach ($original as $i => $old) {
  266. $this->assertEquals($old->bet_amount, $quarantined[$i]->bet_amount);
  267. $this->assertEquals($old->net_profit, $quarantined[$i]->net_profit);
  268. $this->assertNotSame($old->source_version, $quarantined[$i]->source_version);
  269. }
  270. $this->assertSame($cursor, DB::table('share_system_state')->where('key', 'facts_cursor:lhc_order')->value('value'));
  271. $this->assertSame(['2026-10-24'], json_decode(DB::table('share_system_state')->where('key', 'facts_dirty_dates')->value('value'), true));
  272. DB::table('balance_logs')->where('change_type', '投注退分')->delete();
  273. $fixed = $sync->sync(null, null, true);
  274. $this->assertSame([], $fixed['errors']); $this->assertSame(2, $fixed['updated']);
  275. $this->assertEquals(150, DB::table('share_bet_facts')->where('source', 'lhc_order_item')->sum('effective_amount'));
  276. $this->assertSame(2, DB::table('share_bet_facts')->where('source', 'lhc_order_item')->where('settled', 1)->count());
  277. }
  278. }