SharingBetFactsTest.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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. });
  38. Schema::create('lhc_order_item', function (Blueprint $t) {
  39. $t->id(); $t->string('member_id'); $t->string('ordernum'); $t->integer('lottery_status');
  40. $t->decimal('win_amount', 24, 10)->nullable(); $t->decimal('profit_and_loss', 24, 10)->nullable(); $t->bigInteger('updated_at');
  41. });
  42. Schema::create('sport_game_order', function (Blueprint $t) {
  43. $t->id(); $t->string('member_id'); $t->integer('status'); $t->decimal('amount', 24, 10); $t->decimal('win_amount', 24, 10)->default(0); $t->timestamps();
  44. });
  45. Schema::create('sport_order', function (Blueprint $t) {
  46. $t->id(); $t->string('user_id'); $t->integer('status'); $t->integer('pay_status'); $t->integer('return_status')->default(0);
  47. $t->integer('settlement_status'); $t->decimal('amount', 24, 10); $t->decimal('win_amount', 24, 10)->default(0);
  48. $t->decimal('return_amount', 24, 10)->default(0); $t->bigInteger('create_time'); $t->bigInteger('update_time');
  49. $t->bigInteger('settlement_time'); $t->bigInteger('return_operation_time')->nullable();
  50. });
  51. Schema::create('third_game_orders', function (Blueprint $t) {
  52. $t->id(); $t->string('order_key'); $t->unsignedBigInteger('user_id')->nullable(); $t->string('member_id');
  53. $t->integer('game_type'); $t->integer('status'); $t->decimal('bet_amount', 24, 10)->nullable(); $t->decimal('settled_amount', 24, 10)->nullable();
  54. $t->string('currency'); $t->dateTime('bet_time'); $t->dateTime('last_update_time');
  55. });
  56. Schema::create('balance_logs', function (Blueprint $t) {
  57. $t->id(); $t->string('member_id'); $t->unsignedBigInteger('related_id'); $t->string('change_type'); $t->decimal('amount', 24, 10);
  58. });
  59. Schema::create('share_bet_facts', function (Blueprint $t) {
  60. $t->id(); $t->string('source'); $t->string('source_id'); $t->unsignedBigInteger('user_id'); $t->string('member_id');
  61. $t->string('category'); $t->dateTime('bet_at'); $t->date('bet_date'); $t->dateTime('settled_at')->nullable();
  62. foreach (['bet_amount', 'net_profit', 'effective_amount'] as $col) $t->decimal($col, 24, 10);
  63. $t->boolean('settled'); $t->boolean('voided'); $t->string('currency'); $t->string('source_version'); $t->timestamps(); $t->unique(['source', 'source_id']);
  64. });
  65. Schema::create('share_system_state', function (Blueprint $t) { $t->string('key')->primary(); $t->text('value'); $t->timestamps(); });
  66. DB::table('share_system_state')->insert(['key' => 'relations_lock', 'value' => '1']);
  67. Schema::create('rebates', function (Blueprint $t) {
  68. $t->id(); $t->string('member_id'); $t->date('date'); $t->decimal('betting_amount', 24, 2);
  69. $t->decimal('effective_betting_amount', 24, 2); $t->decimal('profit', 24, 2)->default(0); $t->integer('status'); $t->timestamps();
  70. });
  71. }
  72. protected function tearDown(): void
  73. {
  74. DB::disconnect(); Facade::clearResolvedInstances(); Facade::setFacadeApplication(null); Carbon::setTestNow();
  75. parent::tearDown();
  76. }
  77. private function lottery(int $status = 2): void
  78. {
  79. $time = Carbon::parse('2026-10-24 00:10:00', 'Asia/Shanghai')->timestamp;
  80. DB::table('lhc_order')->insert(['id' => 10, 'member_id' => '10001', 'ordernum' => 'current-lottery', 'type' => 5,
  81. 'lottery_status' => $status, 'amount' => 100, 'total_amount' => 200, 'created_at' => $time, 'updated_at' => $time + 3600]);
  82. DB::table('lhc_order_item')->insert([
  83. ['id' => 101, 'member_id' => '10001', 'ordernum' => 'current-lottery', 'lottery_status' => 2, 'win_amount' => 150, 'profit_and_loss' => 50, 'updated_at' => $time + 3600],
  84. ['id' => 102, 'member_id' => '10001', 'ordernum' => 'current-lottery', 'lottery_status' => 1, 'win_amount' => 0, 'profit_and_loss' => -100, 'updated_at' => $time + 3600],
  85. ]);
  86. }
  87. public function test_preview_then_sync_uses_child_bets_and_repeated_sync_is_idempotent(): void
  88. {
  89. $this->lottery();
  90. $sync = new BetFactSynchronizer();
  91. $this->assertSame(2, $sync->sync()['created']);
  92. $this->assertSame(0, DB::table('share_bet_facts')->count());
  93. $this->assertSame(2, $sync->sync(null, null, true)['created']);
  94. $this->assertEquals(150, DB::table('share_bet_facts')->sum('effective_amount'));
  95. $this->assertSame('2026-10-24', DB::table('share_bet_facts')->first()->bet_date);
  96. $this->assertSame(['2026-10-24'], json_decode(DB::table('share_system_state')->where('key', 'facts_dirty_dates')->value('value'), true));
  97. $again = $sync->sync(null, null, true);
  98. $this->assertSame(0, $again['created']); $this->assertSame(0, $again['updated']);
  99. $this->assertSame(2, DB::table('share_bet_facts')->count());
  100. }
  101. public function test_refunded_orders_mark_previous_facts_void_and_preserve_unfinished_facts(): void
  102. {
  103. $this->lottery();
  104. $sync = new BetFactSynchronizer(); $sync->sync(null, null, true);
  105. // Failed draw legacy refund is stored with loss status; its positive refund log is authoritative.
  106. DB::table('lhc_order')->where('id', 10)->update(['lottery_status' => 1, 'updated_at' => Carbon::now()->timestamp]);
  107. DB::table('balance_logs')->insert(['member_id' => '10001', 'related_id' => 10, 'change_type' => '投注退分', 'amount' => 200]);
  108. $this->assertSame(2, $sync->sync(null, null, true)['updated']);
  109. $this->assertEquals(0, DB::table('share_bet_facts')->sum('effective_amount'));
  110. $this->assertSame(2, DB::table('share_bet_facts')->where('voided', 1)->count());
  111. DB::table('sport_game_order')->insert(['member_id' => '10001', 'status' => 0, 'amount' => 100, 'created_at' => '2026-10-24 10:00:00']);
  112. $sync->sync(null, null, true);
  113. $pending = DB::table('share_bet_facts')->where('source', 'sport_game_order')->first();
  114. $this->assertEquals(0, $pending->effective_amount); $this->assertEquals(0, $pending->settled);
  115. }
  116. public function test_football_partial_returns_third_net_profit_and_demo_exclusion(): void
  117. {
  118. $time = Carbon::parse('2026-10-24 01:00:00', 'Asia/Shanghai')->timestamp;
  119. DB::table('sport_order')->insert(['user_id' => '10001', 'status' => 1, 'pay_status' => 1, 'settlement_status' => 1,
  120. 'amount' => 100, 'win_amount' => 0, 'return_amount' => 50, 'create_time' => $time, 'update_time' => $time + 3600, 'settlement_time' => $time + 3600]);
  121. foreach ([1 => '10001', 2 => '20002'] as $id => $member) {
  122. DB::table('third_game_orders')->insert(['user_id' => $id, 'member_id' => $member, 'order_key' => hash('sha256', (string) $id),
  123. 'game_type' => 4, 'status' => 1, 'bet_amount' => 100, 'settled_amount' => 80, 'currency' => 'CNY',
  124. 'bet_time' => '2026-10-24 01:00:00', 'last_update_time' => '2026-10-24 02:00:00']);
  125. }
  126. $result = (new BetFactSynchronizer())->sync(null, null, true);
  127. $this->assertSame([], $result['errors']); $this->assertSame(2, $result['created']);
  128. $this->assertEquals(50, DB::table('share_bet_facts')->where('source', 'sport_order')->value('effective_amount'));
  129. $this->assertEquals(80, DB::table('share_bet_facts')->where('source', 'third_game_orders')->value('effective_amount'));
  130. $this->assertSame(0, DB::table('share_bet_facts')->where('user_id', 2)->count());
  131. DB::table('third_game_orders')->where('user_id', 1)->update(['status' => 3, 'game_type' => 0, 'bet_amount' => null,
  132. 'settled_amount' => null, 'last_update_time' => '2026-10-24 12:00:00']);
  133. $sync = (new BetFactSynchronizer())->sync(null, null, true);
  134. $this->assertSame([], $sync['errors']); $this->assertSame(1, $sync['updated']);
  135. $cancelled = DB::table('share_bet_facts')->where('source', 'third_game_orders')->first();
  136. $this->assertEquals(0, $cancelled->effective_amount); $this->assertEquals(1, $cancelled->voided);
  137. $this->assertSame('third:4', $cancelled->category);
  138. }
  139. public function test_history_recalculation_is_preview_by_default_and_never_changes_paid_or_ambiguous_dates(): void
  140. {
  141. $this->lottery();
  142. DB::table('rebates')->insert([
  143. ['id' => 1, 'member_id' => '10001', 'date' => '2026-10-23', 'betting_amount' => 200, 'effective_betting_amount' => 200, 'status' => 0],
  144. ['id' => 2, 'member_id' => '10001', 'date' => '2026-10-24', 'betting_amount' => 200, 'effective_betting_amount' => 200, 'status' => 0],
  145. ['id' => 3, 'member_id' => '10001', 'date' => '2026-10-22', 'betting_amount' => 200, 'effective_betting_amount' => 200, 'status' => 1],
  146. ]);
  147. $command = new RecalculateShareRebates(); $sync = new BetFactSynchronizer();
  148. $preview = $command->recalculate($sync);
  149. $this->assertSame(1, $preview['changed']); $this->assertSame(1, $preview['skipped']); $this->assertSame(1, $preview['paid_untouched']);
  150. $this->assertEquals(200, DB::table('rebates')->where('id', 1)->value('effective_betting_amount'));
  151. $written = $command->recalculate($sync, true); $this->assertSame(1, $written['changed']);
  152. $this->assertEquals(150, DB::table('rebates')->where('id', 1)->value('effective_betting_amount'));
  153. $this->assertEquals(200, DB::table('rebates')->where('id', 2)->value('effective_betting_amount'));
  154. $this->assertEquals(200, DB::table('rebates')->where('id', 3)->value('effective_betting_amount'));
  155. }
  156. public function test_live_rebate_uses_betting_date_and_does_not_modify_paid_effective_basis(): void
  157. {
  158. DB::table('rebates')->insert(['id' => 1, 'member_id' => '10001', 'date' => '2026-10-23',
  159. 'betting_amount' => 100, 'effective_betting_amount' => 0, 'profit' => 0, 'status' => 0]);
  160. $row = Rebate::updateProfit(['member_id' => '10001', 'date' => '2026-10-23', 'profit' => 50]);
  161. $this->assertSame(1, $row->id); RebateService::updateEffectiveBettingAmount($row, '50.00');
  162. $this->assertEquals(50, DB::table('rebates')->value('effective_betting_amount'));
  163. DB::table('rebates')->where('id', 1)->update(['status' => 1]);
  164. RebateService::updateEffectiveBettingAmount($row, '100.00');
  165. $this->assertEquals(50, DB::table('rebates')->value('effective_betting_amount'));
  166. }
  167. public function test_legacy_injected_bets_are_never_a_source_and_partial_refund_is_flagged_for_review(): void
  168. {
  169. Schema::create('bets', function (Blueprint $t) { $t->id(); $t->integer('status'); $t->decimal('amount', 24, 10); });
  170. DB::table('bets')->insert(['status' => 2, 'amount' => 100000]);
  171. $this->lottery();
  172. DB::table('balance_logs')->insert(['member_id' => '10001', 'related_id' => 10, 'change_type' => '投注退分', 'amount' => 100]);
  173. $result = (new BetFactSynchronizer())->sync(null, null, true);
  174. $this->assertSame(1, $result['scanned']); $this->assertSame(1, count($result['errors']));
  175. $this->assertStringContainsString('refund requires review', $result['errors'][0]['reason']);
  176. $this->assertSame(0, DB::table('share_bet_facts')->count());
  177. $this->assertNull(DB::table('share_system_state')->where('key', 'facts_cursor:lhc_order')->value('value'));
  178. }
  179. public function test_incremental_cursor_includes_new_orders_with_old_dates_and_retries_updated_sources(): void
  180. {
  181. $sync = new BetFactSynchronizer(); $sync->sync(null, null, true);
  182. DB::table('sport_game_order')->insert(['id' => 20, 'member_id' => '10001', 'status' => 2, 'amount' => 100,
  183. 'win_amount' => 150, 'created_at' => '2026-10-01 10:00:00', 'updated_at' => '2026-10-01 11:00:00']);
  184. $this->assertSame(1, $sync->sync(null, null, true)['created']);
  185. DB::table('sport_game_order')->where('id', 20)->update(['status' => 3, 'updated_at' => '2026-10-24 12:00:00']);
  186. $this->assertSame(1, $sync->sync(null, null, true)['updated']);
  187. $this->assertEquals(0, DB::table('share_bet_facts')->value('effective_amount'));
  188. $this->assertSame(['2026-10-01'], json_decode(DB::table('share_system_state')->where('key', 'facts_dirty_dates')->value('value'), true));
  189. }
  190. public function test_second_child_failure_rolls_back_all_facts_dirty_dates_and_source_cursor(): void
  191. {
  192. $this->lottery();
  193. 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");
  194. $result = (new BetFactSynchronizer())->sync(null, null, true);
  195. $this->assertSame(1, count($result['errors'])); $this->assertSame(0, $result['created']);
  196. $this->assertSame(0, DB::table('share_bet_facts')->count());
  197. $this->assertNull(DB::table('share_system_state')->where('key', 'facts_dirty_dates')->value('value'));
  198. $this->assertNull(DB::table('share_system_state')->where('key', 'facts_cursor:lhc_order')->value('value'));
  199. $this->assertSame(0, DB::transactionLevel());
  200. }
  201. public function test_write_reloads_source_after_chunk_read_and_preview_never_creates_the_guard(): void
  202. {
  203. $this->lottery();
  204. DB::table('share_system_state')->where('key', 'relations_lock')->delete();
  205. $preview = (new BetFactSynchronizer())->sync();
  206. $this->assertSame(2, $preview['created']); $this->assertSame(0, DB::table('share_system_state')->count());
  207. DB::table('share_system_state')->insert(['key' => 'relations_lock', 'value' => '1']);
  208. $changed = false;
  209. DB::listen(function ($event) use (&$changed) {
  210. if (!$changed && str_contains($event->sql, 'from "bot_lhc_order" order by "id"')) {
  211. $changed = true;
  212. DB::table('lhc_order')->where('id', 10)->update(['lottery_status' => 4, 'updated_at' => Carbon::now()->timestamp]);
  213. }
  214. });
  215. $result = (new BetFactSynchronizer())->sync(null, null, true);
  216. $this->assertTrue($changed); $this->assertSame([], $result['errors']); $this->assertSame(2, $result['created']);
  217. $this->assertEquals(0, DB::table('share_bet_facts')->sum('effective_amount'));
  218. $this->assertSame(2, DB::table('share_bet_facts')->where('voided', 1)->count());
  219. }
  220. public function test_untrusted_source_quarantines_only_identifiable_old_facts_and_repair_restores_them(): void
  221. {
  222. $this->lottery();
  223. DB::table('sport_game_order')->insert(['member_id' => '10001', 'status' => 2, 'amount' => 100, 'win_amount' => 180,
  224. 'created_at' => '2026-10-24 10:00:00', 'updated_at' => '2026-10-24 11:00:00']);
  225. $sync = new BetFactSynchronizer(); $sync->sync(null, null, true);
  226. $original = DB::table('share_bet_facts')->where('source', 'lhc_order_item')->orderBy('source_id')->get();
  227. $cursor = DB::table('share_system_state')->where('key', 'facts_cursor:lhc_order')->value('value');
  228. DB::table('share_system_state')->where('key', 'facts_dirty_dates')->update(['value' => '[]']);
  229. DB::table('lhc_order')->where('id', 10)->update(['updated_at' => Carbon::now()->timestamp]);
  230. DB::table('balance_logs')->insert(['member_id' => '10001', 'related_id' => 10, 'change_type' => '投注退分', 'amount' => 100]);
  231. $bad = $sync->sync(null, null, true);
  232. $this->assertSame(1, count($bad['errors'])); $this->assertSame(2, $bad['errors'][0]['isolated_facts']);
  233. $this->assertSame(2, $bad['updated']);
  234. $this->assertEquals(0, DB::table('share_bet_facts')->where('source', 'lhc_order_item')->sum('effective_amount'));
  235. $this->assertSame(2, DB::table('share_bet_facts')->where('source', 'lhc_order_item')->where('settled', 0)->where('voided', 0)->count());
  236. $this->assertEquals(80, DB::table('share_bet_facts')->where('source', 'sport_game_order')->value('effective_amount'));
  237. $quarantined = DB::table('share_bet_facts')->where('source', 'lhc_order_item')->orderBy('source_id')->get();
  238. foreach ($original as $i => $old) {
  239. $this->assertEquals($old->bet_amount, $quarantined[$i]->bet_amount);
  240. $this->assertEquals($old->net_profit, $quarantined[$i]->net_profit);
  241. $this->assertNotSame($old->source_version, $quarantined[$i]->source_version);
  242. }
  243. $this->assertSame($cursor, DB::table('share_system_state')->where('key', 'facts_cursor:lhc_order')->value('value'));
  244. $this->assertSame(['2026-10-24'], json_decode(DB::table('share_system_state')->where('key', 'facts_dirty_dates')->value('value'), true));
  245. DB::table('balance_logs')->where('change_type', '投注退分')->delete();
  246. $fixed = $sync->sync(null, null, true);
  247. $this->assertSame([], $fixed['errors']); $this->assertSame(2, $fixed['updated']);
  248. $this->assertEquals(150, DB::table('share_bet_facts')->where('source', 'lhc_order_item')->sum('effective_amount'));
  249. $this->assertSame(2, DB::table('share_bet_facts')->where('source', 'lhc_order_item')->where('settled', 1)->count());
  250. }
  251. }