ReportingTest.php 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  1. <?php
  2. namespace Tests\Integration;
  3. use App\Services\Reporting\ReportAdmin;
  4. use App\Services\Reporting\ReportReader;
  5. use App\Services\Reporting\ReportSync;
  6. use App\Services\Sharing\ShareDefaults;
  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\Http\JsonResponse;
  14. use Illuminate\Http\Request;
  15. use Illuminate\Routing\Router;
  16. use Illuminate\Support\Facades\DB;
  17. use Illuminate\Support\Facades\Facade;
  18. use Illuminate\Support\Facades\Schema;
  19. use Illuminate\Translation\ArrayLoader;
  20. use Illuminate\Translation\Translator;
  21. use Illuminate\Validation\Factory;
  22. use Illuminate\Validation\ValidationException;
  23. use PHPUnit\Framework\Attributes\DataProvider;
  24. use PHPUnit\Framework\TestCase;
  25. /** Real source adapters, financial reconciliation, filters and aggregation; isolated SQLite only. */
  26. class ReportingTest extends TestCase
  27. {
  28. private Application $app;
  29. private ReportSync $sync;
  30. private ReportReader $reader;
  31. private ReportAdmin $admin;
  32. protected function setUp(): void
  33. {
  34. Carbon::setTestNow(Carbon::parse('2026-10-26 16:00:00', 'Asia/Shanghai'));
  35. Facade::clearResolvedInstances(); $this->app = new Application(dirname(__DIR__, 2));
  36. $this->app->instance('config', new Repository(['app' => ['locale' => 'zh', 'timezone' => 'Asia/Shanghai'], 'third_game' => ['currency' => 'CNY']])); Facade::setFacadeApplication($this->app);
  37. $db = new Manager($this->app); $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'bot_']);
  38. $db->setEventDispatcher(new Dispatcher($this->app)); $db->setAsGlobal(); $db->bootEloquent(); $this->app->instance('db', $db->getDatabaseManager()); $this->app->bind('db.schema', fn () => $db->schema());
  39. $translator = new Translator(new ArrayLoader(), 'zh'); $this->app->instance('translator', $translator); $this->app->instance('validator', new Factory($translator, $this->app));
  40. $this->app['validator']->setPresenceVerifier(new \Illuminate\Validation\DatabasePresenceVerifier($db->getDatabaseManager()));
  41. $this->app->instance('log', new \Psr\Log\NullLogger()); $this->app->instance(\Illuminate\Contracts\Routing\ResponseFactory::class, new \Tests\Support\JsonResponseFactory());
  42. Request::macro('validate', function ($rules) { return app('validator')->make($this->all(), $rules)->validate(); });
  43. $request = Request::create('/admin/reporting/summary'); $request->user = (object) ['id' => 1, 'username' => 'admin']; $this->app->instance('request', $request);
  44. foreach ([
  45. 'users' => 'id INTEGER PRIMARY KEY,member_id TEXT,user_id TEXT,username TEXT,first_name TEXT,agent_id INTEGER,"from" INTEGER,created_at TEXT',
  46. 'agents' => 'id INTEGER PRIMARY KEY,username TEXT',
  47. 'share_members' => 'user_id INTEGER PRIMARY KEY,parent_user_id INTEGER,bound_at TEXT',
  48. 'share_policies' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,effective_date TEXT,enabled INTEGER DEFAULT 0,benefit_enabled INTEGER DEFAULT 0,valid_member_min_deposit TEXT,valid_member_min_effective_bet TEXT,rules TEXT',
  49. 'share_system_state' => '"key" TEXT PRIMARY KEY,value TEXT',
  50. 'share_bet_facts' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,user_id INTEGER,member_id TEXT,category TEXT,bet_date TEXT,effective_amount TEXT,settled INTEGER DEFAULT 1,voided INTEGER DEFAULT 0,currency TEXT DEFAULT "CNY"',
  51. 'share_accounts' => 'user_id INTEGER PRIMARY KEY,earned_amount TEXT DEFAULT "0",paid_amount TEXT DEFAULT "0",reserved_amount TEXT DEFAULT "0"',
  52. 'share_settlements' => 'id INTEGER PRIMARY KEY,user_id INTEGER,bet_date TEXT,category TEXT,direct_commission TEXT,indirect_commission TEXT',
  53. 'balance_logs' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,member_id TEXT,amount TEXT,change_type TEXT,related_id INTEGER,type INTEGER DEFAULT 1,created_at TEXT,updated_at TEXT,before_balance TEXT,after_balance TEXT,remark TEXT',
  54. 'withdraws' => 'id INTEGER PRIMARY KEY,member_id TEXT,amount TEXT,to_account TEXT,service_charge TEXT,exchange_rate TEXT,status INTEGER,created_at TEXT,updated_at TEXT',
  55. 'payment_orders' => 'id INTEGER PRIMARY KEY,member_id TEXT,type INTEGER,amount TEXT,fee TEXT,status INTEGER,created_at TEXT,updated_at TEXT',
  56. 'bets' => 'id INTEGER PRIMARY KEY,member_id TEXT,amount TEXT,profit TEXT,status INTEGER,created_at TEXT,updated_at TEXT',
  57. 'share_claims' => 'id INTEGER PRIMARY KEY,user_id INTEGER,status TEXT,credited_log_id INTEGER',
  58. 'share_ledger' => 'id INTEGER PRIMARY KEY,user_id INTEGER,amount TEXT,bet_date TEXT,category TEXT,created_at TEXT',
  59. 'agent_balance_logs' => 'id INTEGER PRIMARY KEY,agent_id INTEGER,type TEXT,amount TEXT,reference_type TEXT,reference_id INTEGER,created_at TEXT',
  60. 'agent_rebate_records' => 'id INTEGER PRIMARY KEY,agent_id INTEGER,platform TEXT,game_type INTEGER,settlement_date TEXT,flow_commission TEXT,profit_commission TEXT,flow_status TEXT,profit_status TEXT,created_at TEXT,updated_at TEXT',
  61. 'operation_audits' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,resource_type TEXT,resource_id INTEGER,action TEXT,changes TEXT,operator_id INTEGER,operator_name TEXT,created_at TEXT DEFAULT CURRENT_TIMESTAMP',
  62. ] as $name => $columns) DB::statement('CREATE TABLE bot_' . $name . ' (' . $columns . ')');
  63. (require dirname(__DIR__, 2) . '/database/migrations/2026_10_26_140000_create_reporting_tables.php')->up();
  64. DB::table('reporting_settings')->where('id', 1)->update(['activity_started_at' => '2026-10-25 00:00:00']);
  65. DB::table('share_policies')->insert(['effective_date' => '2026-10-01', 'valid_member_min_deposit' => '20', 'valid_member_min_effective_bet' => '100', 'rules' => json_encode(ShareDefaults::rules())]);
  66. DB::table('share_system_state')->insert(['key' => 'initialized_at', 'value' => '2026-10-01 00:00:00']);
  67. DB::table('agents')->insert([['id' => 10, 'username' => 'agent10'], ['id' => 20, 'username' => 'agent20']]);
  68. foreach ([[1, '100', null, 1], [2, '200', 10, 1], [3, '300', 20, 1], [4, '400', 10, 2], [5, '500', null, -1]] as [$id, $member, $agent, $from]) {
  69. DB::table('users')->insert(['id' => $id, 'member_id' => $member, 'user_id' => 'u' . $member, 'username' => 'member' . $id, 'first_name' => '昵称' . $id, 'agent_id' => $agent, 'from' => $from, 'created_at' => '2026-10-01 00:00:00']);
  70. DB::table('share_members')->insert(['user_id' => $id, 'parent_user_id' => in_array($id, [2, 3]) ? 1 : null, 'bound_at' => '2026-10-01 00:00:00']);
  71. }
  72. $this->sync = new ReportSync(); $this->reader = new ReportReader(); $this->admin = new ReportAdmin();
  73. $this->ready();
  74. }
  75. protected function tearDown(): void { Carbon::setTestNow(); DB::disconnect(); Facade::clearResolvedInstances(); parent::tearDown(); }
  76. private function today(array $filters = []): array { return $filters + ['start_date' => now('Asia/Shanghai')->toDateString(), 'end_date' => now('Asia/Shanghai')->toDateString()]; }
  77. private function ready(): void { DB::table('reporting_sync_state')->updateOrInsert(['source' => '__run__'], ['state' => '{"complete":true}', 'updated_at' => now()]); }
  78. private function context(string $source, int $id, int $user = 2, string $platform = 'H5', ?string $success = null): void
  79. {
  80. DB::table('reporting_contexts')->insert(['source' => $source, 'source_id' => (string) $id, 'user_id' => $user, 'agent_id' => $user === 2 ? 10 : null,
  81. 'inviter_id' => $user === 2 ? 1 : null, 'client_platform' => $platform, 'occurred_at' => '2026-10-26 09:00:00', 'succeeded_at' => $success]);
  82. }
  83. private function bet(int $id = 1, array $extra = []): void
  84. {
  85. DB::table('bets')->insert($extra + ['id' => $id, 'member_id' => '200', 'amount' => '100', 'profit' => '60', 'status' => 2, 'created_at' => '2026-10-26 09:00:00', 'updated_at' => '2026-10-26 10:00:00']);
  86. $this->context('bets', $id, ($extra['member_id'] ?? '200') === '500' ? 5 : 2, 'H5', '2026-10-26 10:00:00'); $this->sync->publish('bets', $id);
  87. }
  88. private function deposit(int $id = 1, string $amount = '1000', string $member = '200'): int
  89. {
  90. DB::table('balance_logs')->insert(['id' => $id, 'member_id' => $member, 'amount' => $amount, 'change_type' => '充值', 'created_at' => '2026-10-26 09:00:00', 'updated_at' => '2026-10-26 09:00:00']);
  91. $this->sync->publish('balance_logs', $id); return (int) DB::table('reporting_events')->where('source', 'balance_logs')->where('source_id', (string) $id)->value('id');
  92. }
  93. private function verify(int $id, string $amount = '1000', string $fee = '2'): void
  94. {
  95. $this->admin->reconcile(['event_id' => $id, 'actual_amount' => $amount, 'external_fee' => $fee, 'occurred_at' => '2026-10-26 10:00:00', 'currency' => 'CNY', 'evidence' => '到账凭据#' . $id]);
  96. }
  97. private function qualificationFact(string $amount = '100', string $date = '2026-10-26', int $user = 2, array $extra = []): int
  98. {
  99. return DB::table('share_bet_facts')->insertGetId($extra + ['user_id' => $user, 'member_id' => (string) ($user * 100),
  100. 'category' => 'third:2', 'bet_date' => $date, 'effective_amount' => $amount]);
  101. }
  102. public function test_source_projection_is_idempotent_and_cross_day_metrics_use_actual_events(): void
  103. {
  104. $this->bet(1, ['created_at' => '2026-10-25 23:00:00']); $this->sync->publish('bets', 1);
  105. $this->assertSame(1, DB::table('reporting_orders')->count());
  106. $row = $this->reader->summary($this->today())['summary'];
  107. $this->assertSame('0.0000000000', $row['bet_amount']); $this->assertSame('100.0000000000', $row['settled_bet_amount']);
  108. $this->assertSame('60.0000000000', $row['payout_amount']); $this->assertSame('40.0000000000', $row['game_gross_profit']);
  109. $this->assertSame('40.0000000000', $row['company_profit']);
  110. $yesterday = $this->reader->summary(['start_date' => '2026-10-25', 'end_date' => '2026-10-25'])['summary'];
  111. $this->assertSame('100.0000000000', $yesterday['bet_amount']); $this->assertSame('0.0000000000', $yesterday['payout_amount']);
  112. }
  113. private function f1LotteryWithoutCompletionContext(): void
  114. {
  115. DB::statement('CREATE TABLE bot_lhc_order (id INTEGER PRIMARY KEY,member_id TEXT,ordernum TEXT,amount TEXT,total_amount TEXT,win_amount TEXT,type INTEGER,lottery_status INTEGER,is_faker INTEGER DEFAULT 0,created_at INTEGER,updated_at INTEGER)');
  116. DB::statement('CREATE TABLE bot_lhc_order_item (id INTEGER PRIMARY KEY,member_id TEXT,ordernum TEXT,lottery_status INTEGER,win_amount TEXT,updated_at INTEGER)');
  117. $betAt = Carbon::parse('2026-10-26 09:00:00', 'Asia/Shanghai')->timestamp;
  118. DB::table('lhc_order')->insert(['id' => 1, 'member_id' => '200', 'ordernum' => 'F1-live', 'amount' => '50', 'total_amount' => '100',
  119. 'win_amount' => '190', 'type' => 6, 'lottery_status' => 2, 'created_at' => $betAt, 'updated_at' => $betAt + 3600]);
  120. DB::table('lhc_order_item')->insert([
  121. ['id' => 1, 'member_id' => '200', 'ordernum' => 'F1-live', 'lottery_status' => 2, 'win_amount' => '190', 'updated_at' => $betAt + 3600],
  122. ['id' => 2, 'member_id' => '200', 'ordernum' => 'F1-live', 'lottery_status' => 1, 'win_amount' => '0', 'updated_at' => $betAt + 3600],
  123. ]);
  124. $this->context('lhc_order', 1);
  125. }
  126. private function f1PayoutReceipt(array $extra = []): void
  127. {
  128. DB::table('balance_logs')->insert($extra + ['member_id' => '200', 'type' => 1, 'related_id' => 1, 'amount' => '190',
  129. 'before_balance' => '100', 'after_balance' => '290', 'change_type' => '极速28中奖', 'created_at' => '2026-10-26 10:00:00']);
  130. }
  131. public function test_f1_wallet_receipt_restores_funds_business_category_and_sharing_settlement_totals(): void
  132. {
  133. $this->f1LotteryWithoutCompletionContext(); $this->f1PayoutReceipt();
  134. $before = DB::table('lhc_order')->get()->toJson();
  135. $this->sync->publish('lhc_order', 1); $this->sync->publish('lhc_order', 1);
  136. $funds = $this->reader->funds($this->today());
  137. $business = $this->reader->summary($this->today());
  138. $category = collect($business['categories'])->keyBy('group_id')['self:lottery'];
  139. $sharing = $this->reader->summary($this->today(['report_type' => 'sharing']));
  140. foreach ([$funds['summary'], $funds['data'][0], $business['summary'], $category, $sharing['summary']] as $row) {
  141. $this->assertSame('100.0000000000', $row['bet_amount']);
  142. $this->assertSame('100.0000000000', $row['settled_bet_amount']);
  143. $this->assertSame('190.0000000000', $row['payout_amount']);
  144. $this->assertSame('-90.0000000000', $row['game_gross_profit']);
  145. }
  146. $this->assertSame('F1彩票', $category['label']);
  147. $groups = $this->reader->details($this->today(['report_type' => 'sharing']))['data'];
  148. $this->assertSame('1', $groups[0]['group_id']);
  149. $this->assertSame('190.0000000000', $groups[0]['payout_amount']);
  150. $this->assertSame(2, DB::table('reporting_orders')->count());
  151. $this->assertSame('2026-10-26 10:00:00', DB::table('reporting_orders')->value('settled_at'));
  152. $this->assertSame($before, DB::table('lhc_order')->get()->toJson());
  153. }
  154. public function test_bulk_settlement_capture_preserves_event_attribution_and_records_actual_transition_once(): void
  155. {
  156. $this->f1LotteryWithoutCompletionContext();
  157. $this->sync->publish('lhc_order', 1);
  158. $this->assertSame('0.0000000000', $this->reader->funds($this->today())['summary']['payout_amount']);
  159. $before = DB::table('lhc_order')->get()->toJson();
  160. DB::table('users')->where('id', 2)->update(['agent_id' => 20]);
  161. \App\Services\Reporting\ReportContext::lotterySettled(1);
  162. Carbon::setTestNow(Carbon::parse('2026-10-26 16:10:00', 'Asia/Shanghai'));
  163. \App\Services\Reporting\ReportContext::lotterySettled(1);
  164. $context = DB::table('reporting_contexts')->where('source', 'lhc_order')->first();
  165. $this->assertSame('2026-10-26 16:00:00', $context->succeeded_at);
  166. $this->assertSame(10, (int) $context->agent_id); $this->assertSame(1, (int) $context->inviter_id);
  167. $this->assertSame('H5', $context->client_platform);
  168. $this->sync->publish('lhc_order', 1);
  169. $row = $this->reader->funds($this->today())['summary'];
  170. $this->assertSame('100.0000000000', $row['settled_bet_amount']);
  171. $this->assertSame('190.0000000000', $row['payout_amount']);
  172. $this->assertSame('-90.0000000000', $row['game_gross_profit']);
  173. $this->assertSame($before, DB::table('lhc_order')->get()->toJson());
  174. }
  175. public static function invalidF1Receipts(): array
  176. {
  177. return [
  178. [['related_id' => 999]], [['member_id' => '100']], [['type' => 2]],
  179. [['amount' => '191', 'after_balance' => '291']], [['after_balance' => '999']],
  180. [['created_at' => '2026-10-25 10:00:00']], [['change_type' => '充值']],
  181. ];
  182. }
  183. #[DataProvider('invalidF1Receipts')]
  184. public function test_unrelated_or_unbalanced_receipts_do_not_fabricate_lottery_settlement_time(array $receipt): void
  185. {
  186. $this->f1LotteryWithoutCompletionContext(); $this->f1PayoutReceipt($receipt);
  187. $this->sync->publish('lhc_order', 1);
  188. $this->assertNull(DB::table('reporting_orders')->value('settled_at'));
  189. $row = $this->reader->funds($this->today())['summary'];
  190. $this->assertSame('100.0000000000', $row['bet_amount']);
  191. $this->assertSame('0.0000000000', $row['payout_amount']);
  192. $this->assertGreaterThan(0, $row['quality']['missing_time']);
  193. }
  194. public function test_verified_lottery_time_takes_priority_over_payout_receipt_time(): void
  195. {
  196. $this->f1LotteryWithoutCompletionContext(); $this->f1PayoutReceipt();
  197. DB::table('reporting_contexts')->where('source', 'lhc_order')->update(['settlement_verified' => 1, 'succeeded_at' => '2026-10-26 11:30:00']);
  198. $this->sync->publish('lhc_order', 1);
  199. $this->assertSame('2026-10-26 11:30:00', DB::table('reporting_orders')->value('settled_at'));
  200. }
  201. public function test_bulk_lottery_loss_is_counted_as_settled_gross_profit_without_a_prize_receipt(): void
  202. {
  203. $this->f1LotteryWithoutCompletionContext();
  204. DB::table('lhc_order')->where('id', 1)->update(['lottery_status' => 1, 'win_amount' => '0']);
  205. DB::table('lhc_order_item')->update(['lottery_status' => 1, 'win_amount' => '0']);
  206. \App\Services\Reporting\ReportContext::lotterySettled(1);
  207. $this->sync->publish('lhc_order', 1);
  208. $row = $this->reader->funds($this->today())['summary'];
  209. $this->assertSame('100.0000000000', $row['settled_bet_amount']);
  210. $this->assertSame('0.0000000000', $row['payout_amount']);
  211. $this->assertSame('100.0000000000', $row['game_gross_profit']);
  212. }
  213. public function test_missing_fees_and_success_time_never_produce_fabricated_net_values(): void
  214. {
  215. $event = $this->deposit(); $this->bet();
  216. $row = $this->reader->summary($this->today())['summary']; $this->assertNull($row['net_cash_flow']); $this->assertNull($row['company_profit']);
  217. $this->assertSame(1, $row['quality']['unverified_fees']); $this->assertSame('1000.0000000000', $row['deposit_amount']);
  218. $this->verify($event); $row = $this->reader->summary($this->today())['summary'];
  219. $this->assertSame('998.0000000000', $row['net_cash_flow']); $this->assertSame('38.0000000000', $row['company_profit']);
  220. $before = DB::table('balance_logs')->get()->toArray(); $this->verify($event, '1000', '3'); $this->sync->publish('balance_logs', 1);
  221. $this->assertSame(1, DB::table('reporting_reconciliations')->count()); $this->assertEquals($before, DB::table('balance_logs')->get()->toArray());
  222. $this->assertSame('997.0000000000', $this->reader->summary($this->today())['summary']['net_cash_flow']);
  223. }
  224. public function test_chain_withdraw_uses_recipient_amount_and_customer_fee_is_not_an_expense(): void
  225. {
  226. DB::table('withdraws')->insert(['id' => 1, 'member_id' => '200', 'amount' => '100', 'to_account' => '98', 'service_charge' => '2', 'exchange_rate' => '7', 'status' => 1, 'created_at' => '2026-10-25 08:00:00', 'updated_at' => '2026-10-26 10:00:00']);
  227. $this->sync->publish('withdraws', 1); $row = $this->reader->summary($this->today())['summary'];
  228. $this->assertSame(1, $row['quality']['missing_time']); $this->assertNull($row['net_cash_flow']);
  229. $event = (int) DB::table('reporting_events')->value('id'); $this->verify($event, '686', '1');
  230. $row = $this->reader->summary($this->today())['summary'];
  231. $this->assertSame('686.0000000000', $row['withdraw_amount']); $this->assertSame('14.0000000000', $row['customer_fee_income']);
  232. $this->assertSame('1.0000000000', $row['withdraw_fee']); $this->assertSame('-687.0000000000', $row['net_cash_flow']);
  233. DB::table('withdraws')->where('id', 1)->update(['status' => 2]); $result = $this->sync->sync(true);
  234. $this->assertSame(1, $result['errors']); $this->assertNull($this->reader->summary($this->today())['summary']['net_cash_flow']);
  235. $this->verify($event, '0', '1'); $this->sync->sync(true);
  236. $this->assertSame('0.0000000000', $this->reader->summary($this->today())['summary']['withdraw_amount']);
  237. }
  238. public function test_real_member_agent_sharing_overlap_is_not_added_twice_and_details_are_direct(): void
  239. {
  240. $this->bet(); $event = $this->deposit(); $this->verify($event);
  241. foreach (['business', 'promotion', 'sharing'] as $type) {
  242. $row = $this->reader->summary(['report_type' => $type])['summary']; $this->assertSame('100.0000000000', $row['bet_amount']);
  243. $this->assertSame('1000.0000000000', $row['deposit_amount']);
  244. }
  245. $this->assertSame('2', $this->reader->details($this->today())['data'][0]['group_id']);
  246. $this->assertSame('10', $this->reader->details(['report_type' => 'promotion'])['data'][0]['group_id']);
  247. $this->assertSame('1', $this->reader->details(['report_type' => 'sharing'])['data'][0]['group_id']);
  248. $category = $this->reader->summary($this->today())['categories'][8]; $this->assertNull($category['deposit_amount']); $this->assertNull($category['company_profit']);
  249. $this->assertSame('100.0000000000', $category['bet_amount']);
  250. }
  251. public function test_valid_members_use_both_sharing_thresholds_inclusively(): void
  252. {
  253. $this->bet(); $this->deposit(1, '19.99'); $fact = $this->qualificationFact('100');
  254. $this->assertSame(0, $this->reader->summary($this->today())['summary']['valid_member_count']);
  255. DB::table('balance_logs')->where('id', 1)->update(['amount' => '20']);
  256. DB::table('share_bet_facts')->where('id', $fact)->update(['effective_amount' => '99.99']);
  257. $this->assertSame(0, $this->reader->summary($this->today())['summary']['valid_member_count']);
  258. DB::table('share_bet_facts')->where('id', $fact)->update(['effective_amount' => '100']);
  259. $report = $this->reader->summary($this->today());
  260. $this->assertSame(1, $report['summary']['valid_member_count']);
  261. $this->assertSame('20.0000000000', $report['valid_deposit_min']);
  262. $this->assertSame('100.0000000000', $report['valid_effective_bet_min']);
  263. $this->assertSame(['id' => 1, 'effective_date' => '2026-10-01', 'min_deposit' => '20.0000000000',
  264. 'min_effective_bet' => '100.0000000000', 'date' => '2026-10-26', 'available' => true, 'unavailable_reasons' => []], $report['valid_member_policy']);
  265. // Presentation switches and the retired report-only value do not change qualification.
  266. DB::table('reporting_settings')->where('id', 1)->update(['valid_deposit_min' => '9999']);
  267. DB::table('share_policies')->update(['enabled' => 0, 'benefit_enabled' => 0]);
  268. $this->assertSame(1, $this->reader->summary($this->today())['summary']['valid_member_count']);
  269. }
  270. public function test_qualification_is_cumulative_before_start_and_independent_of_report_filters_and_payment_verification(): void
  271. {
  272. $this->bet(); $this->bet(2, ['member_id' => '500']);
  273. DB::table('balance_logs')->insert([
  274. ['member_id' => '200', 'type' => 1, 'amount' => '8', 'change_type' => '充值', 'created_at' => '2026-10-01 10:00:00'],
  275. ['member_id' => '200', 'type' => 1, 'amount' => '12', 'change_type' => '三方充值', 'created_at' => '2026-10-25 10:00:00'],
  276. ]);
  277. $this->qualificationFact('50', '2026-10-01'); $this->qualificationFact('50', '2026-10-25', 2, ['category' => 'self:sport']);
  278. // Report events and their manual reconciliation are not the sharing deposit source.
  279. $event = $this->deposit(10, '1'); $this->verify($event, '0', '0');
  280. $input = ['platform' => 'H5', 'category' => 'self:lottery', 'settlement_status' => 'settled'];
  281. $report = $this->reader->summary($input);
  282. $this->assertSame(1, $report['summary']['valid_member_count']);
  283. $this->assertSame(1, collect($report['categories'])->keyBy('group_id')['self:lottery']['valid_member_count']);
  284. $this->assertSame(1, $this->reader->details($input + ['member_account' => 'member2'])['data'][0]['valid_member_count']);
  285. $this->assertSame(1, $this->reader->details($input + ['report_type' => 'promotion', 'agent_account' => 'agent10'])['data'][0]['valid_member_count']);
  286. $this->assertSame(1, $this->reader->details($input + ['report_type' => 'sharing', 'inviter_account' => 'member1'])['data'][0]['valid_member_count']);
  287. $this->assertSame(0, $this->reader->summary(['platform' => 'PC'])['summary']['valid_member_count']);
  288. }
  289. public function test_qualification_excludes_future_non_deposit_and_ineligible_facts(): void
  290. {
  291. $this->bet();
  292. foreach ([[1, '充值', '19', '2026-10-26 23:59:59'], [1, '充值', '1000', '2026-10-27 00:00:00'],
  293. [2, '充值', '1000', '2026-10-25 10:00:00'], [1, '人工加款', '1000', '2026-10-25 10:00:00'],
  294. [1, '充值', '-1000', '2026-10-25 10:00:00']] as [$type, $kind, $amount, $at]) {
  295. DB::table('balance_logs')->insert(['member_id' => '200', 'type' => $type, 'change_type' => $kind, 'amount' => $amount, 'created_at' => $at]);
  296. }
  297. $fact = $this->qualificationFact('99');
  298. $this->qualificationFact('1000', '2026-10-27');
  299. $this->qualificationFact('1000', '2026-10-25', 2, ['settled' => 0]);
  300. $this->qualificationFact('1000', '2026-10-25', 2, ['voided' => 1]);
  301. $this->qualificationFact('1000', '2026-10-25', 2, ['currency' => 'USDT']);
  302. $this->assertSame(0, $this->reader->summary($this->today())['summary']['valid_member_count']);
  303. DB::table('balance_logs')->insert(['member_id' => '200', 'type' => 1, 'change_type' => '三方充值', 'amount' => '1', 'created_at' => '2026-10-26 23:59:59']);
  304. $this->assertSame(0, $this->reader->summary($this->today())['summary']['valid_member_count']);
  305. DB::table('share_bet_facts')->where('id', $fact)->update(['effective_amount' => '100']);
  306. $this->assertSame(1, $this->reader->summary($this->today())['summary']['valid_member_count']);
  307. }
  308. public function test_pending_sharing_policy_never_applies_before_its_effective_date(): void
  309. {
  310. $this->bet(); $this->deposit(1, '20'); $this->qualificationFact();
  311. DB::table('share_policies')->insert(['effective_date' => '2026-10-27', 'valid_member_min_deposit' => '200', 'valid_member_min_effective_bet' => '1000', 'rules' => '{}']);
  312. $report = $this->reader->summary($this->today());
  313. $this->assertSame(1, $report['summary']['valid_member_count']); $this->assertSame(1, $report['valid_member_policy']['id']);
  314. $this->assertSame('20.0000000000', $this->admin->settings()['valid_deposit_min']);
  315. Carbon::setTestNow(Carbon::parse('2026-10-27 16:00:00', 'Asia/Shanghai'));
  316. $report = $this->reader->summary(['start_date' => '2026-10-26', 'end_date' => '2026-10-27']);
  317. $this->assertSame(0, $report['summary']['valid_member_count']); $this->assertSame(2, $report['valid_member_policy']['id']);
  318. $historical = $this->reader->summary(['start_date' => '2026-10-26', 'end_date' => '2026-10-26']);
  319. $this->assertSame(1, $historical['summary']['valid_member_count']); $this->assertSame(1, $historical['valid_member_policy']['id']);
  320. }
  321. public function test_zero_sharing_thresholds_are_preserved_and_candidate_population_is_unchanged(): void
  322. {
  323. $this->bet(1, ['status' => 1, 'profit' => '0']);
  324. DB::table('share_policies')->update(['valid_member_min_deposit' => '0', 'valid_member_min_effective_bet' => '0']);
  325. $report = $this->reader->summary($this->today());
  326. $this->assertSame(1, $report['summary']['valid_member_count']); $this->assertSame(4, $report['summary']['member_count']);
  327. $this->assertSame('0.0000000000', $report['valid_deposit_min']); $this->assertSame('0.0000000000', $report['valid_effective_bet_min']);
  328. $this->assertSame(0, $this->reader->summary(['settlement_status' => 'settled'])['summary']['valid_member_count']);
  329. }
  330. public function test_missing_policy_threshold_and_sharing_data_produce_null_not_an_independent_default(): void
  331. {
  332. $this->bet(); $this->deposit(); $this->qualificationFact();
  333. DB::table('share_policies')->update(['valid_member_min_effective_bet' => null]);
  334. $report = $this->reader->summary($this->today());
  335. $this->assertNull($report['summary']['valid_member_count']); $this->assertNull($report['valid_effective_bet_min']);
  336. $this->assertFalse($report['valid_member_policy']['available']);
  337. $this->assertContains('incomplete_qualification_policy', $report['valid_member_policy']['unavailable_reasons']);
  338. DB::table('share_policies')->delete();
  339. $report = $this->reader->summary($this->today());
  340. $this->assertNull($report['summary']['valid_member_count']); $this->assertNull($report['valid_deposit_min']);
  341. $this->assertContains('no_effective_policy', $report['valid_member_policy']['unavailable_reasons']);
  342. DB::table('share_policies')->insert(['effective_date' => '2026-10-01', 'valid_member_min_deposit' => '20', 'valid_member_min_effective_bet' => '100', 'rules' => '{}']);
  343. DB::table('share_system_state')->delete();
  344. $report = $this->reader->summary($this->today());
  345. $this->assertNull($report['summary']['valid_member_count']);
  346. $this->assertContains('relations_not_initialized', $report['valid_member_policy']['unavailable_reasons']);
  347. DB::table('share_system_state')->insert(['key' => 'initialized_at', 'value' => '2026-10-01']);
  348. Schema::drop('share_bet_facts');
  349. $report = $this->reader->summary($this->today());
  350. $this->assertNull($report['summary']['valid_member_count']);
  351. $this->assertContains('missing_table:share_bet_facts', $report['valid_member_policy']['unavailable_reasons']);
  352. }
  353. public function test_report_qualification_reads_do_not_settle_or_write_and_old_settings_post_is_rejected(): void
  354. {
  355. $this->bet(); $this->deposit(1, '20'); $this->qualificationFact();
  356. $tables = ['reporting_settings', 'reporting_orders', 'reporting_events', 'share_policies', 'share_system_state', 'share_bet_facts',
  357. 'balance_logs', 'share_accounts', 'share_settlements', 'share_ledger', 'share_claims', 'operation_audits'];
  358. $before = []; foreach ($tables as $table) $before[$table] = DB::table($table)->get()->toJson();
  359. for ($i = 0; $i < 2; ++$i) {
  360. $this->assertSame(1, $this->reader->summary($this->today())['summary']['valid_member_count']);
  361. $this->assertSame(1, $this->reader->details($this->today())['data'][0]['valid_member_count']);
  362. $settings = $this->admin->settings();
  363. $this->assertSame('20.0000000000', $settings['valid_deposit_min']);
  364. $this->assertSame('100.0000000000', $settings['valid_effective_bet_min']);
  365. $this->assertSame('2026-10-25 00:00:00', $settings['activity_started_at']);
  366. }
  367. try { $this->admin->settings(['valid_deposit_min' => '19.99']); $this->fail('Expected read-only settings rejection'); }
  368. catch (ValidationException $e) { $this->assertStringContainsString('/admin/shareEarning/settings/save', $e->validator->errors()->first()); }
  369. foreach ($tables as $table) $this->assertSame($before[$table], DB::table($table)->get()->toJson(), $table . ' must remain unchanged');
  370. }
  371. public function test_platform_settlement_filters_tg_virtual_exclusion_and_rank_pagination(): void
  372. {
  373. $this->bet(); $this->bet(2, ['member_id' => '500', 'amount' => '200']);
  374. $this->bet(3, ['status' => 1, 'profit' => '0']);
  375. DB::table('bets')->insert(['id' => 4, 'member_id' => '400', 'amount' => '99999', 'profit' => '0', 'status' => 1, 'created_at' => '2026-10-26 09:00:00']); $this->sync->publish('bets', 4);
  376. $this->assertSame(3, DB::table('reporting_orders')->count());
  377. $this->assertSame('0.0000000000', $this->reader->summary(['platform' => 'PC'])['summary']['bet_amount']);
  378. $this->assertSame('100.0000000000', $this->reader->summary(['settlement_status' => 'pending'])['summary']['bet_amount']);
  379. $this->assertNull($this->reader->summary(['settlement_status' => 'pending'])['summary']['company_profit']);
  380. $ranks = $this->reader->details(['metric' => 'bet_amount', 'page' => 2, 'limit' => 1], true);
  381. $this->assertSame(2, $ranks['total']); $this->assertSame(2, $ranks['data'][0]['rank']);
  382. }
  383. public function test_activity_intervals_merge_devices_split_idle_and_history_is_explicitly_missing(): void
  384. {
  385. foreach ([['a', '10:00:00'], ['b', '10:00:00'], ['a', '10:01:00'], ['b', '10:01:00'], ['a', '10:20:00'], ['a', '10:21:00']] as [$session, $at]) {
  386. DB::table('reporting_activity')->insert(['user_id' => 2, 'agent_id' => 10, 'inviter_id' => 1, 'client_platform' => 'H5', 'session_hash' => $session, 'observed_at' => '2026-10-26 ' . $at]);
  387. }
  388. $row = $this->reader->summary($this->today())['summary'];
  389. $this->assertSame(2, $row['activity_minutes']); $this->assertSame(1, $row['active_member_count']); $this->assertSame(4, $row['member_count']);
  390. $this->assertSame('0.250000', $row['active_rate']);
  391. $old = $this->reader->summary(['start_date' => '2026-10-24', 'end_date' => '2026-10-26'])['summary'];
  392. $this->assertNull($old['activity_minutes']); $this->assertSame(2, $old['known_activity_minutes']);
  393. }
  394. public function test_full_sync_and_repeated_sync_do_not_change_source_data_or_double_count(): void
  395. {
  396. $this->bet(); $this->deposit(); $before = DB::table('balance_logs')->get()->toArray();
  397. $first = $this->sync->sync(true); $second = $this->sync->sync(true);
  398. $this->assertSame(0, $first['errors']); $this->assertSame(0, $second['errors']);
  399. $this->assertSame(1, DB::table('reporting_orders')->count()); $this->assertSame(1, DB::table('reporting_events')->count());
  400. $this->assertEquals($before, DB::table('balance_logs')->get()->toArray());
  401. }
  402. public function test_lottery_parent_is_published_once_across_child_chunks_and_parent_scan(): void
  403. {
  404. $this->f1LotteryWithoutCompletionContext();
  405. for ($id = 3; $id <= 230; ++$id) DB::table('lhc_order_item')->insert([
  406. 'id' => $id, 'member_id' => '200', 'ordernum' => 'F1-live', 'lottery_status' => 1, 'win_amount' => '0', 'updated_at' => now()->timestamp,
  407. ]);
  408. DB::table('lhc_order')->where('id', 1)->update(['total_amount' => '11500']);
  409. $result = $this->sync->sync();
  410. $this->assertSame(0, $result['errors']);
  411. $this->assertSame(1, $result['published']);
  412. $this->assertSame(230, DB::table('reporting_orders')->count());
  413. Carbon::setTestNow(now('Asia/Shanghai')->addMinutes(10));
  414. DB::table('lhc_order_item')->where('id', 230)->update(['win_amount' => '68', 'lottery_status' => 2, 'updated_at' => now()->timestamp]);
  415. $this->assertSame(1, $this->sync->sync()['published']);
  416. $this->assertSame('68', (string) DB::table('reporting_orders')->where('source_id', '230')->value('payout_amount'));
  417. }
  418. public function test_source_cursor_advances_past_errors_and_failed_rows_retry_without_replaying_good_history(): void
  419. {
  420. foreach (range(1, 4) as $id) DB::table('bets')->insert(['id' => $id, 'member_id' => $id === 4 ? 'missing' : '200',
  421. 'amount' => '100', 'profit' => '60', 'status' => 2, 'created_at' => '2026-10-01 09:00:00', 'updated_at' => '2026-10-01 10:00:00']);
  422. $this->assertSame(1, $this->sync->sync()['errors']);
  423. $cursor = json_decode(DB::table('reporting_sync_state')->where('source', 'bets')->value('state'), true);
  424. $this->assertSame(4, $cursor['last_id']);
  425. Carbon::setTestNow(now('Asia/Shanghai')->addHour());
  426. DB::table('bets')->insert(['id' => 5, 'member_id' => '200', 'amount' => '100', 'profit' => '60', 'status' => 2,
  427. 'created_at' => '2026-10-01 09:00:00', 'updated_at' => '2026-10-01 10:00:00']);
  428. $result = $this->sync->sync();
  429. $this->assertSame(2, $result['scanned']);
  430. $this->assertSame(1, $result['errors']);
  431. $this->assertSame('errors', $result['sources']['bets']);
  432. $this->assertSame(4, DB::table('reporting_orders')->count());
  433. DB::table('bets')->where('id', 4)->update(['member_id' => '200']);
  434. Carbon::setTestNow(now('Asia/Shanghai')->addMinute());
  435. $result = $this->sync->sync();
  436. $this->assertSame(1, $result['scanned']);
  437. $this->assertSame(0, $result['errors']);
  438. $this->assertSame(5, DB::table('reporting_orders')->count());
  439. $this->assertSame(0, DB::table('reporting_errors')->count());
  440. }
  441. public function test_missing_timestamps_use_bounded_rotating_checks_and_still_apply_old_corrections(): void
  442. {
  443. DB::statement('CREATE TABLE bot_jisu_game_order (id INTEGER PRIMARY KEY,member_id TEXT,amount TEXT,win_amount TEXT,status INTEGER,created_at TEXT)');
  444. foreach (range(1, 405) as $id) {
  445. DB::table('bets')->insert(['id' => $id, 'member_id' => '200', 'amount' => '100', 'profit' => '60', 'status' => 2,
  446. 'created_at' => '2026-10-01 09:00:00', 'updated_at' => null]);
  447. DB::table('jisu_game_order')->insert(['id' => $id, 'member_id' => '200', 'amount' => '100', 'win_amount' => '60', 'status' => 2, 'created_at' => '2026-10-01 09:00:00']);
  448. }
  449. $this->assertSame(810, $this->sync->sync()['scanned']);
  450. DB::table('bets')->where('id', 405)->update(['profit' => '25']);
  451. DB::table('jisu_game_order')->where('id', 405)->update(['win_amount' => '35']);
  452. foreach ([400, 400, 10, 400] as $expected) {
  453. Carbon::setTestNow(now('Asia/Shanghai')->addMinute());
  454. $result = $this->sync->sync();
  455. $this->assertSame($expected, $result['scanned']);
  456. $this->assertSame(0, $result['errors']);
  457. }
  458. $this->assertSame('25', (string) DB::table('reporting_orders')->where('source', 'bets')->where('source_id', '405')->value('payout_amount'));
  459. $this->assertSame('35', (string) DB::table('reporting_orders')->where('source', 'jisu_game_order')->where('source_id', '405')->value('payout_amount'));
  460. }
  461. public function test_missing_source_errors_do_not_starve_later_retries_and_keep_run_incomplete(): void
  462. {
  463. DB::table('bets')->insert(['id' => 205, 'member_id' => '200', 'amount' => '100', 'profit' => '60', 'status' => 2,
  464. 'created_at' => '2026-10-01 09:00:00', 'updated_at' => '2026-10-01 10:00:00']);
  465. DB::table('reporting_sync_state')->insert(['source' => 'bets', 'state' => json_encode(['last_id' => 205, 'checked_at' => now()->toDateTimeString()]), 'updated_at' => now()]);
  466. foreach (range(1, 205) as $id) DB::table('reporting_errors')->insert(['source' => 'bets', 'source_id' => (string) $id,
  467. 'reason' => 'previous error', 'created_at' => '2026-10-01 10:00:00', 'updated_at' => '2026-10-01 10:00:00']);
  468. $first = $this->sync->sync();
  469. $this->assertSame(0, $first['published']);
  470. $this->assertSame(205, $first['errors']);
  471. Carbon::setTestNow(now('Asia/Shanghai')->addMinute());
  472. $second = $this->sync->sync();
  473. $this->assertSame(1, $second['published']);
  474. $this->assertSame(204, $second['errors']);
  475. $this->assertSame('errors', $second['sources']['bets']);
  476. $state = json_decode(DB::table('reporting_sync_state')->where('source', '__run__')->value('state'), true);
  477. $this->assertFalse($state['complete']);
  478. $this->assertSame(1, DB::table('reporting_orders')->count());
  479. }
  480. public function test_unchanged_projections_keep_timestamps_and_skip_updates(): void
  481. {
  482. $this->bet(); $this->deposit();
  483. $beforeOrders = DB::table('reporting_orders')->get()->toArray();
  484. $beforeEvents = DB::table('reporting_events')->get()->toArray();
  485. Carbon::setTestNow(now('Asia/Shanghai')->addMinutes(10));
  486. DB::table('bets')->where('id', 1)->update(['amount' => '100.0000000000']);
  487. DB::enableQueryLog(); DB::flushQueryLog();
  488. try {
  489. $this->assertSame(0, $this->sync->sync(true)['errors']);
  490. $updates = array_filter(DB::getQueryLog(), fn ($q) => preg_match('/^update "bot_reporting_(orders|events)"/', $q['query']));
  491. $this->assertSame([], array_values($updates));
  492. } finally { DB::disableQueryLog(); DB::flushQueryLog(); }
  493. $this->assertEquals($beforeOrders, DB::table('reporting_orders')->get()->toArray());
  494. $this->assertEquals($beforeEvents, DB::table('reporting_events')->get()->toArray());
  495. }
  496. public function test_sync_index_migration_is_repeatable_and_preserves_existing_indexes_and_data(): void
  497. {
  498. $this->bet();
  499. Schema::table('bets', fn (Blueprint $t) => $t->index(['updated_at', 'id'], 'existing_bets_update_index'));
  500. $migration = require dirname(__DIR__, 2) . '/database/migrations/2026_11_03_130000_add_sync_performance_indexes.php';
  501. $migration->up(); $migration->up();
  502. $plan = DB::select('EXPLAIN QUERY PLAN DELETE FROM bot_reporting_orders WHERE parent_source = ? AND parent_id = ?', ['lhc_order', '1']);
  503. $this->assertStringContainsString('reporting_orders_parent_lookup', json_encode($plan));
  504. $this->assertTrue(Schema::hasIndex('reporting_errors', 'reporting_errors_retry_lookup'));
  505. $migration->down();
  506. $this->assertTrue(Schema::hasIndex('bets', 'existing_bets_update_index'));
  507. $this->assertFalse(Schema::hasIndex('reporting_orders', 'reporting_orders_parent_lookup'));
  508. $this->assertSame(1, DB::table('reporting_orders')->count());
  509. }
  510. public function test_command_lock_skips_overlap_and_releases_after_failure(): void
  511. {
  512. $lock = new \App\Support\SyncCommandLock();
  513. $name = 'test:' . bin2hex(random_bytes(8));
  514. $this->assertSame(7, $lock->run($name, function () use ($lock, $name) {
  515. $this->assertNull($lock->run($name, function () { $this->fail('Overlapping synchronization ran'); }));
  516. $this->assertSame(8, $lock->run($name . ':other', fn () => 8));
  517. return 7;
  518. }));
  519. try { $lock->run($name, fn () => throw new \RuntimeException('expected failure')); }
  520. catch (\RuntimeException $e) { $this->assertSame('expected failure', $e->getMessage()); }
  521. $this->assertSame(9, $lock->run($name, fn () => 9));
  522. }
  523. private function activityObservation(string $at, ?int $agent = 10, ?int $inviter = 1, string $session = 'a'): void
  524. {
  525. DB::table('reporting_activity')->insert(['user_id' => 2, 'agent_id' => $agent, 'inviter_id' => $inviter,
  526. 'client_platform' => 'H5', 'session_hash' => $session, 'observed_at' => $at]);
  527. }
  528. public function test_activity_snapshot_survives_agent_reassignment_in_summary_details_and_filters(): void
  529. {
  530. $this->activityObservation('2026-10-26 10:00:00'); $this->activityObservation('2026-10-26 10:02:00');
  531. $before = $this->reader->summary($this->today(['report_type' => 'promotion', 'agent_account' => 'agent10']))['summary'];
  532. DB::table('users')->where('id', 2)->update(['agent_id' => 20]);
  533. $after = $this->reader->summary($this->today(['report_type' => 'promotion', 'agent_account' => 'agent10']))['summary'];
  534. $this->assertSame(2, $before['activity_minutes']); $this->assertSame(2, $after['activity_minutes']);
  535. $this->assertSame(1, $after['active_member_count']); $this->assertFalse($after['activity_population_complete']); $this->assertNull($after['active_rate']);
  536. $other = $this->reader->summary($this->today(['report_type' => 'promotion', 'agent_account' => 'agent20']))['summary'];
  537. $this->assertSame(0, $other['activity_minutes']); $this->assertSame(0, $other['active_member_count']);
  538. $details = $this->reader->details($this->today(['report_type' => 'promotion']));
  539. $this->assertSame(1, $details['total']); $this->assertSame('10', $details['data'][0]['group_id']); $this->assertSame(2, $details['data'][0]['activity_minutes']);
  540. $byGroup = $this->reader->summary($this->today(['report_type' => 'promotion', 'group_id' => '10']))['summary'];
  541. $this->assertSame(2, $byGroup['activity_minutes']);
  542. $business = $this->reader->summary($this->today(['agent_account' => 'agent10']))['summary']; $this->assertSame(2, $business['activity_minutes']);
  543. $this->activityObservation('2026-10-26 11:00:00', 20); $this->activityObservation('2026-10-26 11:03:00', 20);
  544. $groups = collect($this->reader->details($this->today(['report_type' => 'promotion']))['data'])->keyBy('group_id');
  545. $this->assertSame(2, $groups[10]['activity_minutes']); $this->assertSame(3, $groups[20]['activity_minutes']);
  546. $this->assertSame('0.500000', $groups[20]['active_rate']);
  547. $all = $this->reader->summary($this->today())['summary']; $this->assertSame(5, $all['activity_minutes']); $this->assertSame(1, $all['active_member_count']);
  548. $this->assertSame('0.250000', $all['active_rate']);
  549. }
  550. public function test_agent_transition_with_overlapping_devices_counts_each_second_only_once(): void
  551. {
  552. $this->activityObservation('2026-10-26 10:00:00', 10, 1, 'a');
  553. $this->activityObservation('2026-10-26 10:01:00', 20, 1, 'b');
  554. $this->activityObservation('2026-10-26 10:02:00', 20, 1, 'a');
  555. $this->activityObservation('2026-10-26 10:03:00', 20, 1, 'b');
  556. DB::table('users')->where('id', 2)->update(['agent_id' => 20]);
  557. $groups = collect($this->reader->details($this->today(['report_type' => 'promotion']))['data'])->keyBy('group_id');
  558. $this->assertSame(1, $groups[10]['activity_minutes']); $this->assertSame(2, $groups[20]['activity_minutes']);
  559. $all = $this->reader->summary($this->today())['summary']; $this->assertSame(3, $all['activity_minutes']); $this->assertSame(1, $all['active_member_count']);
  560. $this->assertSame(1, $this->reader->summary($this->today(['report_type' => 'promotion', 'agent_account' => 'agent10']))['summary']['activity_minutes']);
  561. $this->assertSame(2, $this->reader->summary($this->today(['report_type' => 'promotion', 'agent_account' => 'agent20']))['summary']['activity_minutes']);
  562. }
  563. public function test_activity_uses_inviter_snapshot_and_does_not_inherit_current_null_attribution(): void
  564. {
  565. $this->activityObservation('2026-10-26 10:00:00'); $this->activityObservation('2026-10-26 10:04:00');
  566. DB::table('share_members')->where('user_id', 2)->update(['parent_user_id' => 3]);
  567. $groups = collect($this->reader->details($this->today(['report_type' => 'sharing']))['data'])->keyBy('group_id');
  568. $this->assertSame(4, $groups[1]['activity_minutes']); $this->assertArrayNotHasKey(3, $groups->all());
  569. $this->assertSame(4, $this->reader->summary($this->today(['report_type' => 'sharing', 'inviter_account' => 'member1']))['summary']['activity_minutes']);
  570. $this->assertSame(0, $this->reader->summary($this->today(['report_type' => 'sharing', 'inviter_account' => 'member3']))['summary']['activity_minutes']);
  571. DB::table('reporting_activity')->delete();
  572. $this->activityObservation('2026-10-26 11:00:00', null, null); $this->activityObservation('2026-10-26 11:02:00', null, null);
  573. $this->assertSame(2, $this->reader->summary($this->today())['summary']['activity_minutes']);
  574. $this->assertSame(0, $this->reader->summary($this->today(['report_type' => 'promotion']))['summary']['activity_minutes']);
  575. $this->assertSame(0, $this->reader->summary($this->today(['report_type' => 'sharing']))['summary']['activity_minutes']);
  576. }
  577. public function test_activity_interval_crossing_query_start_keeps_the_starting_snapshot(): void
  578. {
  579. $this->activityObservation('2026-10-25 23:59:00', 10); $this->activityObservation('2026-10-26 00:01:00', 20);
  580. DB::table('users')->where('id', 2)->update(['agent_id' => 20]);
  581. $groups = collect($this->reader->details($this->today(['report_type' => 'promotion']))['data'])->keyBy('group_id');
  582. $this->assertSame(1, $groups[10]['activity_minutes']); $this->assertSame(0, $groups[20]['activity_minutes']);
  583. $this->assertSame(1, $this->reader->summary($this->today())['summary']['activity_minutes']);
  584. }
  585. public function test_order_time_reconciliation_survives_reimport_and_does_not_settle_source(): void
  586. {
  587. DB::table('bets')->insert(['id' => 1, 'member_id' => '200', 'amount' => '100', 'profit' => '60', 'status' => 2, 'created_at' => '2026-10-25 09:00:00', 'updated_at' => '2026-10-26 10:00:00']);
  588. $this->sync->publish('bets', 1); $this->assertNull($this->reader->summary($this->today())['summary']['company_profit']);
  589. $id = (int) DB::table('reporting_orders')->value('id'); $before = (array) DB::table('bets')->first();
  590. $this->admin->reconcileOrder(['id' => $id, 'settled_at' => '2026-10-26 10:00:00', 'evidence' => '开奖结算日志']); $this->sync->publish('bets', 1);
  591. $this->assertSame('40.0000000000', $this->reader->summary($this->today())['summary']['company_profit']);
  592. $this->assertSame($before, (array) DB::table('bets')->first());
  593. }
  594. public function test_new_routes_have_admin_auth_and_only_operators_can_write_reconciliations(): void
  595. {
  596. $router = new Router(new Dispatcher($this->app), $this->app); $this->app->instance('router', $router);
  597. $router->group(['prefix' => 'admin'], function () { require dirname(__DIR__, 2) . '/routes/admin.php'; });
  598. foreach (['options', 'leaderboard', 'fund-flow', 'summary', 'details', 'orders', 'settings', 'payment-reconciliation'] as $action) {
  599. $r = $router->getRoutes()->match(Request::create('/admin/reporting/' . $action));
  600. $this->assertContains('admin.jwt', $r->middleware()); $this->assertContains('check.button.uri', $r->middleware());
  601. }
  602. foreach (['settings', 'payment-reconciliation', 'order-reconciliation'] as $action) $this->assertContains('operations.admin', $router->getRoutes()->match(Request::create('/admin/reporting/' . $action, 'POST'))->middleware());
  603. }
  604. public function test_share_accrual_and_claim_are_separate_and_agent_cost_only_counts_actual_credit(): void
  605. {
  606. $this->bet();
  607. DB::table('share_ledger')->insert([['id' => 1, 'user_id' => 1, 'amount' => '20', 'bet_date' => '2026-10-26', 'category' => 'self:lottery', 'created_at' => '2026-10-26 10:00:00'],
  608. ['id' => 2, 'user_id' => 1, 'amount' => '-3', 'bet_date' => '2026-10-26', 'category' => 'self:lottery', 'created_at' => '2026-10-26 11:00:00']]);
  609. DB::table('share_claims')->insert(['id' => 1, 'user_id' => 1, 'status' => 'approved', 'credited_log_id' => 10]);
  610. DB::table('balance_logs')->insert(['id' => 10, 'member_id' => '100', 'amount' => '5', 'change_type' => '分享佣金领取', 'created_at' => '2026-10-26 11:00:00']);
  611. DB::table('agent_rebate_records')->insert(['id' => 1, 'agent_id' => 10, 'platform' => 'pc28', 'game_type' => 3, 'settlement_date' => '2026-10-26', 'flow_commission' => '7', 'profit_commission' => '2', 'flow_status' => 'credited', 'profit_status' => 'pending', 'created_at' => '2026-10-26 10:00:00']);
  612. DB::table('agent_balance_logs')->insert(['id' => 1, 'agent_id' => 10, 'type' => 'commission', 'amount' => '7', 'reference_type' => 'agent_rebate_record', 'reference_id' => 1, 'created_at' => '2026-10-26 11:00:00']);
  613. foreach ([['share_ledger', 1], ['share_ledger', 2], ['balance_logs', 10], ['agent_rebate_records', 1], ['agent_balance_logs', 1]] as [$source, $id]) $this->sync->publish($source, $id);
  614. $row = $this->reader->summary($this->today())['summary'];
  615. $this->assertSame('17.0000000000', $row['share_accrual']); $this->assertSame('5.0000000000', $row['share_commission']);
  616. $this->assertSame('9.0000000000', $row['agent_accrual']); $this->assertSame('7.0000000000', $row['agent_commission']);
  617. $this->assertSame('28.0000000000', $row['company_profit']);
  618. foreach ([false, true] as $ranking) {
  619. $details = $this->reader->details($this->today(), $ranking);
  620. // Agent-only costs belong to the separate metadata bucket, not a synthetic member row.
  621. $this->assertSame('7.0000000000', $details['unallocated']['agent_commission']);
  622. $this->assertSame('9.0000000000', $details['unallocated']['agent_accrual']);
  623. $this->assertNotContains('unallocated', array_column($details['data'], 'group_id'));
  624. $this->assertSame(2, $details['total']);
  625. }
  626. $this->assertSame('7.0000000000', $this->reader->summary($this->today())['summary']['agent_commission']);
  627. $this->assertSame('28.0000000000', $this->reader->summary($this->today())['summary']['company_profit']);
  628. $this->assertSame('5.0000000000', $this->reader->summary(['report_type' => 'sharing'])['summary']['share_commission']);
  629. }
  630. public function test_daily_total_is_for_all_pages_and_source_errors_are_visible_until_fixed(): void
  631. {
  632. $this->bet(1, ['created_at' => '2026-10-25 09:00:00']);
  633. $r = $this->reader->funds(['start_date' => '2026-10-25', 'end_date' => '2026-10-26', 'limit' => 1, 'page' => 2]);
  634. $this->assertSame(2, $r['total']); $this->assertSame('2026-10-25', $r['data'][0]['group_id']);
  635. $this->assertSame('100.0000000000', $r['summary']['settled_bet_amount']);
  636. DB::table('bets')->insert(['id' => 2, 'member_id' => 'missing', 'amount' => '10', 'status' => 1, 'created_at' => '2026-10-26 10:00:00']);
  637. $r = $this->sync->sync(true); $this->assertSame(1, $r['errors']);
  638. $this->assertNull($this->reader->summary($this->today())['summary']['company_profit']); $this->assertSame(1, DB::table('reporting_errors')->count());
  639. DB::table('bets')->where('id', 2)->update(['member_id' => '200']); $this->sync->sync(true);
  640. $this->assertSame(0, DB::table('reporting_errors')->count()); $this->assertNotNull($this->reader->summary($this->today())['summary']['company_profit']);
  641. }
  642. public function test_eloquent_context_observer_records_status_transition_once_and_tg_activity_is_deduplicated(): void
  643. {
  644. $withdraw = new \App\Models\Withdraw(); $withdraw->forceFill(['id' => 1, 'member_id' => '200', 'amount' => '10', 'to_account' => '9', 'service_charge' => '1', 'exchange_rate' => '7', 'status' => 0]); $withdraw->save();
  645. $context = DB::table('reporting_contexts')->where('source', 'withdraws')->first(); $this->assertNotNull($context); $this->assertNull($context->succeeded_at);
  646. $withdraw->status = 1; $withdraw->save(); $this->assertSame('2026-10-26 16:00:00', DB::table('reporting_contexts')->where('source', 'withdraws')->value('succeeded_at'));
  647. Carbon::setTestNow(Carbon::parse('2026-10-26 16:10:00', 'Asia/Shanghai')); $withdraw->amount = '11'; $withdraw->save();
  648. $this->assertSame('2026-10-26 16:00:00', DB::table('reporting_contexts')->where('source', 'withdraws')->value('succeeded_at'));
  649. $request = Request::create('/api/onMessage', 'POST'); $this->app->instance('request', $request); $user = (object) ['id' => 5, 'agent_id' => null, 'from' => -1];
  650. \App\Services\Reporting\ReportActivity::telegram($user); \App\Services\Reporting\ReportActivity::telegram($user);
  651. $this->assertSame(1, DB::table('reporting_activity')->count()); $this->assertSame('unknown', DB::table('reporting_activity')->value('client_platform'));
  652. }
  653. public function test_current_game_adapters_cover_parent_children_third_party_and_partial_sports_refunds(): void
  654. {
  655. DB::statement('CREATE TABLE bot_lhc_order (id INTEGER PRIMARY KEY,member_id TEXT,ordernum TEXT,amount TEXT,total_amount TEXT,type INTEGER,lottery_status INTEGER,is_faker INTEGER,created_at INTEGER,updated_at INTEGER)');
  656. DB::statement('CREATE TABLE bot_lhc_order_item (id INTEGER PRIMARY KEY,member_id TEXT,ordernum TEXT,lottery_status INTEGER,win_amount TEXT,updated_at INTEGER)');
  657. DB::statement('CREATE TABLE bot_sport_order (id INTEGER PRIMARY KEY,user_id TEXT,amount TEXT,win_amount TEXT,return_amount TEXT,status INTEGER,pay_status INTEGER,settlement_status INTEGER,return_status INTEGER,create_time INTEGER,update_time INTEGER,settlement_time INTEGER)');
  658. DB::statement('CREATE TABLE bot_third_game_orders (id INTEGER PRIMARY KEY,order_key TEXT,member_id TEXT,user_id INTEGER,platform TEXT DEFAULT "pg",player_id TEXT DEFAULT "u2",game_type INTEGER,bet_amount TEXT,settled_amount TEXT,status INTEGER,currency TEXT,bet_time TEXT,last_update_time TEXT,created_at TEXT,updated_at TEXT)');
  659. $betAt = Carbon::parse('2026-10-26 09:00:00', 'Asia/Shanghai')->timestamp; $settledAt = $betAt + 3600;
  660. DB::table('lhc_order')->insert(['id' => 1, 'member_id' => '200', 'ordernum' => 'L1', 'amount' => '10', 'total_amount' => '20', 'type' => 6, 'lottery_status' => 2, 'is_faker' => 0, 'created_at' => $betAt, 'updated_at' => $settledAt]);
  661. DB::table('lhc_order_item')->insert([['id' => 1, 'member_id' => '200', 'ordernum' => 'L1', 'lottery_status' => 1, 'win_amount' => '0', 'updated_at' => $settledAt], ['id' => 2, 'member_id' => '200', 'ordernum' => 'L1', 'lottery_status' => 2, 'win_amount' => '18', 'updated_at' => $settledAt]]);
  662. $this->context('lhc_order', 1, 2, 'PC', '2026-10-26 10:00:00'); $this->sync->publish('lhc_order', 1);
  663. DB::table('sport_order')->insert(['id' => 1, 'user_id' => '200', 'amount' => '100', 'win_amount' => '0', 'return_amount' => '50', 'status' => 1, 'pay_status' => 1, 'settlement_status' => 1, 'return_status' => 1, 'create_time' => $betAt, 'update_time' => $settledAt, 'settlement_time' => $settledAt]);
  664. $this->context('sport_order', 1, 2, 'APP'); $this->sync->publish('sport_order', 1);
  665. DB::table('third_game_orders')->insert(['id' => 1, 'order_key' => str_repeat('a', 64), 'member_id' => '200', 'user_id' => 2, 'game_type' => 4, 'bet_amount' => '30', 'settled_amount' => '-30', 'status' => 1, 'currency' => 'CNY', 'bet_time' => '2026-10-26 09:00:00', 'last_update_time' => '2026-10-26 10:00:00', 'created_at' => '2026-10-26 09:00:00', 'updated_at' => '2026-10-26 10:00:00']);
  666. $this->sync->publish('third_game_orders', 1);
  667. $r = $this->reader->summary($this->today())['summary'];
  668. $this->assertSame(3, $r['order_count']); $this->assertSame('150.0000000000', $r['bet_amount']);
  669. $this->assertSame('100.0000000000', $r['settled_bet_amount']); $this->assertSame('18.0000000000', $r['payout_amount']);
  670. $this->assertSame('50.0000000000', $r['refund_amount']); $this->assertSame('82.0000000000', $r['game_gross_profit']);
  671. $unknown = $this->reader->summary(['platform' => 'unknown'])['summary']; $this->assertSame('30.0000000000', $unknown['bet_amount']);
  672. $this->assertSame(0, DB::table('share_bet_facts')->count()); // Reports did not publish sharing facts.
  673. $this->assertSame(0, $this->sync->sync(true)['errors']);
  674. Carbon::setTestNow(Carbon::parse('2026-10-26 16:10:00', 'Asia/Shanghai'));
  675. DB::table('lhc_order_item')->where('id', 2)->update(['win_amount' => '68', 'updated_at' => now()->timestamp]);
  676. $this->assertSame(0, $this->sync->sync()['errors']);
  677. $this->assertSame('32.0000000000', $this->reader->summary($this->today())['summary']['game_gross_profit']);
  678. $this->assertSame(4, DB::table('reporting_orders')->count());
  679. }
  680. public static function thirdPartyReportCases(): array
  681. {
  682. $cases = [];
  683. foreach (range(1, 7) as $type) foreach ([
  684. 'win' => [1, '80', '100', '180', '0', '-80'],
  685. 'loss' => [1, '-100', '100', '0', '0', '100'],
  686. 'push' => [1, '0', '100', '100', '0', '0'],
  687. 'pending' => [0, '0', '0', '0', '0', '0'],
  688. 'void' => [2, '0', '0', '0', '100', '0'],
  689. 'cancelled' => [3, '0', '0', '0', '100', '0'],
  690. ] as $name => $values) $cases[$type . '-' . $name] = [$type, ...$values];
  691. return $cases;
  692. }
  693. private function commissionOrders(): void
  694. {
  695. DB::statement('CREATE TABLE bot_third_game_orders (id INTEGER PRIMARY KEY,order_key TEXT,member_id TEXT,user_id INTEGER,
  696. platform TEXT,player_id TEXT,game_type INTEGER,game_name TEXT,bet_amount TEXT,valid_amount TEXT,settled_amount TEXT,
  697. status INTEGER,currency TEXT,bet_time TEXT,last_update_time TEXT,created_at TEXT,updated_at TEXT)');
  698. $this->app->instance(\App\Services\ThirdGameCommissionService::class, new class extends \App\Services\ThirdGameCommissionService {
  699. public function rates(): array { return ['date' => '2026-10-26', 'fetched_at' => '2026-10-26 08:00:00',
  700. 'available' => true, 'ratios' => ['pg' => '0.09', 'ag' => '0.20', 'free' => '0']]; }
  701. });
  702. }
  703. private function commissionOrder(int $id, array $extra = []): void
  704. {
  705. $user = $extra['user_id'] ?? 2;
  706. DB::table('third_game_orders')->insert($extra + ['id' => $id, 'order_key' => hash('sha256', 'commission-' . $id),
  707. 'member_id' => (string) ($user * 100), 'user_id' => $user, 'platform' => 'pg', 'player_id' => 'u' . $user,
  708. 'game_type' => 2, 'game_name' => 'game-' . $id, 'bet_amount' => '100', 'valid_amount' => '95',
  709. 'settled_amount' => '-100', 'status' => 1, 'currency' => 'CNY', 'bet_time' => '2026-10-25 23:00:00',
  710. 'last_update_time' => '2026-10-26 10:00:00', 'created_at' => '2026-10-25 23:00:00', 'updated_at' => '2026-10-26 10:00:00']);
  711. $this->sync->publish('third_game_orders', $id);
  712. }
  713. public function test_platform_commissions_sum_multiple_games_by_category_and_respect_all_three_report_scopes(): void
  714. {
  715. $this->commissionOrders();
  716. $this->commissionOrder(1);
  717. $this->commissionOrder(2, ['settled_amount' => '40']);
  718. $this->commissionOrder(3, ['platform' => 'AG', 'game_type' => 1, 'settled_amount' => '-50']);
  719. $this->commissionOrder(4, ['platform' => 'ag', 'user_id' => 3, 'settled_amount' => '-20']);
  720. $this->commissionOrder(5, ['user_id' => 1, 'settled_amount' => '-10']);
  721. $this->bet();
  722. $business = $this->reader->summary($this->today());
  723. $this->assertSame('20.3000000000', $business['summary']['third_game_commission']);
  724. $this->assertSame('159.7000000000', $business['summary']['company_profit']);
  725. $categories = collect($business['categories'])->keyBy('group_id');
  726. $this->assertSame('10.3000000000', $categories['third:2']['third_game_commission']);
  727. $this->assertSame('10.0000000000', $categories['third:1']['third_game_commission']);
  728. $this->assertSame('0.0000000000', $categories['self:lottery']['third_game_commission']);
  729. foreach (['promotion', 'sharing'] as $type) {
  730. $report = $this->reader->summary($this->today(['report_type' => $type]));
  731. $this->assertSame('19.4000000000', $report['summary']['third_game_commission']);
  732. $this->assertSame(9, count($report['categories']));
  733. }
  734. $this->assertSame('15.4000000000', $this->reader->details($this->today(['report_type' => 'promotion', 'group_id' => '10']))['data'][0]['third_game_commission']);
  735. $funds = $this->reader->funds(['start_date' => '2026-10-25', 'end_date' => '2026-10-26', 'limit' => 1]);
  736. $this->assertSame('20.3000000000', $funds['summary']['third_game_commission']);
  737. $this->assertSame('20.3000000000', $funds['data'][0]['third_game_commission']);
  738. $this->assertSame('0.0000000000', $this->reader->funds(['start_date' => '2026-10-25', 'end_date' => '2026-10-26', 'limit' => 1, 'page' => 2])['data'][0]['third_game_commission']);
  739. $finance = \App\Services\FundsSummaryService::summary('2026-10-26', '2026-10-26');
  740. $expense = collect($finance['expense'])->keyBy('key');
  741. $this->assertSame('20.30', $expense['third_game_commission']['amount']);
  742. $this->assertSame(3, $expense['third_game_commission']['people']);
  743. $this->assertSame('20.30', $finance['expense_total']);
  744. $this->assertSame('0.00', $expense['third_party_fee']['amount']);
  745. }
  746. public function test_missing_platform_rates_are_unknown_zero_rates_are_valid_and_cash_flow_is_preserved(): void
  747. {
  748. $this->commissionOrders();
  749. $this->commissionOrder(1, ['platform' => 'free']);
  750. $this->assertSame('0.0000000000', $this->reader->summary($this->today())['summary']['third_game_commission']);
  751. $this->commissionOrder(2, ['platform' => 'missing']);
  752. $this->commissionOrder(3);
  753. $report = $this->reader->summary($this->today());
  754. $row = $report['summary'];
  755. $this->assertNull($row['third_game_commission']);
  756. $this->assertSame('9.0000000000', $row['known_third_game_commission']);
  757. $this->assertNull($row['company_profit']);
  758. $this->assertSame('0.0000000000', $row['net_cash_flow']);
  759. $this->assertSame(1, $row['quality']['missing_platform_ratio']);
  760. $finance = \App\Services\FundsSummaryService::summary();
  761. $this->assertNull(collect($finance['expense'])->keyBy('key')['third_game_commission']['amount']);
  762. $this->assertNull($finance['expense_total']);
  763. $this->assertSame('9.00', $finance['known_expense_total']);
  764. $this->assertSame('9.0000000000', $finance['third_game_commission_meta']['known_amount']);
  765. }
  766. public function test_commission_excludes_pending_void_virtual_and_foreign_orders_and_uses_settlement_date(): void
  767. {
  768. $this->commissionOrders();
  769. $this->commissionOrder(1);
  770. $this->commissionOrder(2, ['status' => 0]);
  771. $this->commissionOrder(3, ['status' => 2]);
  772. $this->commissionOrder(4, ['status' => 3]);
  773. $this->commissionOrder(5, ['user_id' => 4]);
  774. $this->commissionOrder(6, ['last_update_time' => '2026-10-25 23:30:00']);
  775. $this->assertSame('9.0000000000', $this->reader->summary($this->today())['summary']['third_game_commission']);
  776. $finance = \App\Services\FundsSummaryService::summary('2026-10-26', '2026-10-26');
  777. $this->assertSame('9.00', $finance['expense_total']);
  778. $this->commissionOrder(7, ['currency' => 'USD']);
  779. $finance = \App\Services\FundsSummaryService::summary('2026-10-26', '2026-10-26');
  780. $this->assertNull($finance['expense_total']);
  781. $this->assertSame(1, $finance['third_game_commission_meta']['quality']['foreign_currency']);
  782. $this->assertSame('9.0000000000', $finance['third_game_commission_meta']['known_amount']);
  783. }
  784. public function test_all_report_types_and_finance_share_one_daily_supplier_request(): void
  785. {
  786. $this->commissionOrders(); $this->commissionOrder(1);
  787. $this->app->instance(\App\Services\ThirdGameCommissionService::class, new \App\Services\ThirdGameCommissionService());
  788. $this->app->instance('cache', new \Illuminate\Cache\Repository(new \Illuminate\Cache\ArrayStore()));
  789. $this->app->instance(\Illuminate\Http\Client\Factory::class, new \Illuminate\Http\Client\Factory());
  790. config(['third_game.api_url' => 'https://supplier.test', 'third_game.sn' => 'test', 'third_game.key' => 'test']);
  791. \Illuminate\Support\Facades\Http::preventStrayRequests();
  792. \Illuminate\Support\Facades\Http::fake(['https://supplier.test/api/server/quota' => \Illuminate\Support\Facades\Http::response([
  793. 'code' => 10000, 'data' => ['ratios' => [['platfrom' => 'pg', 'ratio' => 0.09]]],
  794. ])]);
  795. foreach (['business', 'promotion', 'sharing'] as $type) {
  796. $report = $this->reader->summary($this->today(['report_type' => $type]));
  797. $this->assertSame('9.0000000000', $report['summary']['third_game_commission']);
  798. }
  799. $this->assertSame('9.0000000000', $this->reader->funds($this->today())['summary']['third_game_commission']);
  800. $this->assertSame('9.00', \App\Services\FundsSummaryService::summary()['expense_total']);
  801. \Illuminate\Support\Facades\Http::assertSentCount(1);
  802. }
  803. public function test_finance_commission_keeps_large_decimal_precision_and_reports_missing_source_data(): void
  804. {
  805. $this->commissionOrders();
  806. $this->commissionOrder(1, ['bet_amount' => '99999999999999.1234567891', 'settled_amount' => '-99999999999999.1234567891']);
  807. $this->assertSame('8999999999999.92', \App\Services\FundsSummaryService::summary()['expense_total']);
  808. DB::table('third_game_orders')->where('id', 1)->update(['settled_amount' => null]);
  809. $finance = \App\Services\FundsSummaryService::summary();
  810. $this->assertNull($finance['expense_total']);
  811. $this->assertSame(1, $finance['third_game_commission_meta']['quality']['missing_amount']);
  812. DB::table('third_game_orders')->where('id', 1)->update(['settled_amount' => '-100', 'last_update_time' => null]);
  813. $finance = \App\Services\FundsSummaryService::summary('2026-10-26', '2026-10-26');
  814. $this->assertNull($finance['expense_total']);
  815. $this->assertSame(1, $finance['third_game_commission_meta']['quality']['missing_time']);
  816. }
  817. #[DataProvider('thirdPartyReportCases')]
  818. public function test_third_party_categories_use_provider_settlement_time_and_preserve_net_payout_math(int $type, int $status, string $net, string $stake, string $payout, string $refund, string $gross): void
  819. {
  820. DB::statement('CREATE TABLE bot_third_game_orders (id INTEGER PRIMARY KEY,order_key TEXT,member_id TEXT,user_id INTEGER,platform TEXT DEFAULT "pg",player_id TEXT DEFAULT "u2",game_type INTEGER,bet_amount TEXT,settled_amount TEXT,status INTEGER,currency TEXT,bet_time TEXT,last_update_time TEXT,created_at TEXT,updated_at TEXT)');
  821. DB::table('third_game_orders')->insert(['id' => 1, 'order_key' => str_repeat('b', 64), 'member_id' => '200', 'user_id' => 2, 'game_type' => $type,
  822. 'bet_amount' => '100', 'settled_amount' => $net, 'status' => $status, 'currency' => 'CNY', 'bet_time' => '2026-10-25 23:00:00',
  823. 'last_update_time' => '2026-10-26 10:00:00', 'created_at' => '2026-10-26 12:00:00', 'updated_at' => '2026-10-26 13:00:00']);
  824. $this->sync->publish('third_game_orders', 1); $this->sync->publish('third_game_orders', 1);
  825. $day = $this->reader->funds($this->today())['summary'];
  826. $report = $this->reader->summary($this->today());
  827. $category = collect($report['categories'])->keyBy('group_id')['third:' . $type];
  828. foreach ([$day, $category, $this->reader->summary($this->today(['report_type' => 'sharing']))['summary']] as $row) {
  829. $this->assertSame('0.0000000000', $row['bet_amount']);
  830. $this->assertSame(bcadd($stake, '0', 10), $row['settled_bet_amount']);
  831. $this->assertSame(bcadd($payout, '0', 10), $row['payout_amount']);
  832. $this->assertSame(bcadd($refund, '0', 10), $row['refund_amount']);
  833. $this->assertSame(bcadd($gross, '0', 10), $row['game_gross_profit']);
  834. }
  835. $previous = $this->reader->summary(['start_date' => '2026-10-25', 'end_date' => '2026-10-25'])['summary'];
  836. $this->assertSame('100.0000000000', $previous['bet_amount']);
  837. $this->assertSame('0.0000000000', $previous['payout_amount']);
  838. $this->assertSame(1, DB::table('reporting_orders')->count());
  839. $this->assertSame($status === 0 ? null : '2026-10-26 10:00:00', DB::table('reporting_orders')->value('settled_at'));
  840. }
  841. public static function sportsReportCases(): array
  842. {
  843. return [
  844. 'win' => [1, 1, 0, '180', '0', '100', '180', '0', '-80'],
  845. 'loss' => [1, 1, 0, '0', '0', '100', '0', '0', '100'],
  846. 'half-loss' => [1, 1, 1, '0', '50', '50', '0', '50', '50'],
  847. 'push' => [1, 1, 1, '0', '100', '0', '0', '100', '0'],
  848. 'awaiting-payout' => [1, 2, 0, '180', '0', '0', '0', '0', '0'],
  849. 'void' => [2, 0, 2, '0', '100', '0', '0', '100', '0'],
  850. ];
  851. }
  852. #[DataProvider('sportsReportCases')]
  853. public function test_f1_sports_uses_official_settlement_or_refund_time(int $status, int $settlement, int $returnStatus, string $win, string $returned, string $stake, string $payout, string $refund, string $gross): void
  854. {
  855. DB::statement('CREATE TABLE bot_sport_order (id INTEGER PRIMARY KEY,user_id TEXT,amount TEXT,win_amount TEXT,return_amount TEXT,status INTEGER,pay_status INTEGER,settlement_status INTEGER,return_status INTEGER,create_time INTEGER,update_time INTEGER,settlement_time INTEGER,return_operation_time INTEGER)');
  856. DB::table('sport_order')->insert(['id' => 1, 'user_id' => '200', 'amount' => '100', 'win_amount' => $win, 'return_amount' => $returned,
  857. 'status' => $status, 'pay_status' => 1, 'settlement_status' => $settlement, 'return_status' => $returnStatus,
  858. 'create_time' => Carbon::parse('2026-10-25 23:00:00', 'Asia/Shanghai')->timestamp,
  859. 'update_time' => Carbon::parse('2026-10-26 13:00:00', 'Asia/Shanghai')->timestamp,
  860. 'settlement_time' => $status === 2 ? null : Carbon::parse('2026-10-26 10:00:00', 'Asia/Shanghai')->timestamp,
  861. 'return_operation_time' => $status === 2 ? Carbon::parse('2026-10-26 11:00:00', 'Asia/Shanghai')->timestamp : null]);
  862. $this->sync->publish('sport_order', 1);
  863. $category = collect($this->reader->summary($this->today())['categories'])->keyBy('group_id')['self:sport'];
  864. foreach ([$category, $this->reader->funds($this->today())['summary']] as $row) {
  865. $this->assertSame(bcadd($stake, '0', 10), $row['settled_bet_amount']);
  866. $this->assertSame(bcadd($payout, '0', 10), $row['payout_amount']);
  867. $this->assertSame(bcadd($refund, '0', 10), $row['refund_amount']);
  868. $this->assertSame(bcadd($gross, '0', 10), $row['game_gross_profit']);
  869. }
  870. $this->assertSame($settlement === 2 ? null : ($status === 2 ? '2026-10-26 11:00:00' : '2026-10-26 10:00:00'), DB::table('reporting_orders')->value('settled_at'));
  871. }
  872. public function test_legacy_sport_game_job_captures_losses_as_well_as_wins_for_reporting(): void
  873. {
  874. DB::statement('CREATE TABLE bot_sport_game_order (id INTEGER PRIMARY KEY,member_id TEXT,gameplay_id INTEGER,amount TEXT,odds TEXT,status INTEGER,win_amount TEXT,profit_and_loss TEXT,created_at TEXT,updated_at TEXT)');
  875. DB::statement('CREATE TABLE bot_wallets (id INTEGER PRIMARY KEY,member_id TEXT,available_balance TEXT,frozen_balance TEXT,created_at TEXT,updated_at TEXT)');
  876. DB::table('wallets')->insert(['id' => 1, 'member_id' => '200', 'available_balance' => '100', 'frozen_balance' => '0']);
  877. DB::table('sport_game_order')->insert([
  878. ['id' => 1, 'member_id' => '200', 'gameplay_id' => 1, 'amount' => '100', 'odds' => '1.8', 'status' => 0, 'created_at' => '2026-10-26 09:00:00'],
  879. ['id' => 2, 'member_id' => '200', 'gameplay_id' => 2, 'amount' => '50', 'odds' => '1.8', 'status' => 0, 'created_at' => '2026-10-26 09:00:00'],
  880. ]);
  881. $this->context('sport_game_order', 1); $this->context('sport_game_order', 2);
  882. (new \App\Jobs\SportGameOrderJob(1))->handle();
  883. $this->sync->publish('sport_game_order', 1); $this->sync->publish('sport_game_order', 2);
  884. $row = $this->reader->funds($this->today())['summary'];
  885. $this->assertSame('150.0000000000', $row['settled_bet_amount']);
  886. $this->assertSame('180.0000000000', $row['payout_amount']);
  887. $this->assertSame('-30.0000000000', $row['game_gross_profit']);
  888. $this->assertSame('280.00', bcadd((string) DB::table('wallets')->where('id', 1)->value('available_balance'), '0', 2));
  889. $this->assertSame(0, DB::transactionLevel());
  890. }
  891. public function test_audit_failure_rolls_back_reconciliation_and_foreign_currency_is_not_summed(): void
  892. {
  893. $event = $this->deposit();
  894. DB::statement("CREATE TRIGGER reject_reporting_audit BEFORE INSERT ON bot_operation_audits BEGIN SELECT RAISE(ABORT, 'audit failed'); END");
  895. try { $this->verify($event); $this->fail('Expected audit failure'); } catch (\Illuminate\Database\QueryException $e) { $this->assertStringContainsString('audit failed', $e->getMessage()); }
  896. $this->assertSame(0, DB::table('reporting_reconciliations')->count());
  897. $this->bet(); DB::table('reporting_orders')->update(['currency' => 'USDT']);
  898. $r = $this->reader->summary($this->today())['summary']; $this->assertSame('0.0000000000', $r['bet_amount']); $this->assertSame(1, $r['quality']['foreign_currency']); $this->assertNull($r['company_profit']);
  899. }
  900. public function test_verified_attribution_is_a_reporting_snapshot_and_survives_later_imports(): void
  901. {
  902. $event = $this->deposit(); $this->bet();
  903. $this->admin->reconcile(['event_id' => $event, 'actual_amount' => '1000', 'external_fee' => '0', 'occurred_at' => '2026-10-26 10:00:00',
  904. 'currency' => 'CNY', 'evidence' => '核对原绑定及装置', 'agent_id' => 20, 'inviter_id' => 3, 'client_platform' => 'APP']);
  905. $this->sync->publish('balance_logs', 1);
  906. $e = DB::table('reporting_events')->where('id', $event)->first(); $this->assertSame(20, $e->agent_id); $this->assertSame('verified', $e->attribution_quality);
  907. $this->assertSame('APP', $e->client_platform); $this->assertSame(10, DB::table('users')->where('id', 2)->value('agent_id'));
  908. $id = (int) DB::table('reporting_orders')->value('id');
  909. $this->admin->reconcileOrder(['id' => $id, 'agent_id' => 20, 'evidence' => '原始推广凭据']); $this->sync->publish('bets', 1);
  910. $this->assertSame(20, DB::table('reporting_orders')->value('agent_id'));
  911. $this->assertSame('1000.0000000000', $this->reader->summary(['report_type' => 'promotion', 'agent_account' => 'agent20'])['summary']['deposit_amount']);
  912. $this->assertSame(1, $this->reader->events(['group_id' => '2', 'kind' => 'deposit'])['total']);
  913. $this->assertSame(0, $this->admin->quality([])['total']);
  914. $this->assertNotEmpty($this->admin->quality([])['sources']);
  915. }
  916. private function historicalBet(int $id = 1, string $betAt = '2024-01-01 09:00:00', string $settledAt = '2024-01-02 10:00:00'): void
  917. {
  918. $this->bet($id, ['created_at' => $betAt, 'amount' => '40', 'profit' => '20']);
  919. DB::table('reporting_contexts')->where('source', 'bets')->where('source_id', (string) $id)->update(['succeeded_at' => $settledAt]);
  920. $this->sync->publish('bets', $id);
  921. }
  922. public function test_no_dates_default_to_all_history_and_dates_alone_select_a_period(): void
  923. {
  924. $this->historicalBet(); $this->bet(2);
  925. $default = $this->reader->summary([]);
  926. $this->assertSame(1, $default['filters']['all_time']); $this->assertSame('2024-01-01', $default['filters']['start_date']);
  927. $this->assertSame('2026-10-26', $default['filters']['end_date']);
  928. $this->assertSame('140.0000000000', $default['summary']['bet_amount']);
  929. $this->assertSame('80.0000000000', $default['summary']['payout_amount']);
  930. $blank = $this->reader->summary(['start_date' => '', 'end_date' => null]);
  931. $this->assertSame($default['filters'], $blank['filters']); $this->assertSame($default['summary'], $blank['summary']);
  932. $range = $this->reader->summary($this->today());
  933. $this->assertSame(0, $range['filters']['all_time']); $this->assertSame('2026-10-26', $range['filters']['start_date']);
  934. $this->assertSame('100.0000000000', $range['summary']['bet_amount']);
  935. $this->assertSame('2026-10-26', $default['valid_member_policy']['date']);
  936. $this->assertSame($default['summary'], $this->reader->summary(['all_time' => 0])['summary']);
  937. $this->assertSame($range['summary'], $this->reader->summary($this->today(['all_time' => 1]))['summary']);
  938. $bounded = $this->reader->params(['start_date' => now('Asia/Shanghai')->subDays(365)->toDateString()]);
  939. $this->assertSame(now('Asia/Shanghai')->subDays(365)->toDateString(), $bounded['start_date']);
  940. $this->assertSame(366, $this->admin->options()['max_days']);
  941. }
  942. public function test_all_time_funds_paginate_actual_days_and_keep_the_complete_summary(): void
  943. {
  944. $this->historicalBet(); $this->bet(2); $event = $this->deposit(); $this->verify($event);
  945. $first = $this->reader->funds(['limit' => 1]);
  946. $days = (int) Carbon::parse('2024-01-01')->diffInDays(Carbon::parse('2026-10-27'));
  947. $this->assertSame($days, $first['total']); $this->assertCount(1, $first['data']); $this->assertSame('2026-10-26', $first['data'][0]['date']);
  948. $this->assertSame('140.0000000000', $first['summary']['bet_amount']); $this->assertSame('80.0000000000', $first['summary']['payout_amount']);
  949. $this->assertSame('100.0000000000', $first['data'][0]['bet_amount']); $this->assertSame('60.0000000000', $first['data'][0]['payout_amount']);
  950. $this->assertSame('998.0000000000', $first['summary']['net_cash_flow']);
  951. $settled = $this->reader->funds(['limit' => 1, 'page' => $days - 1]);
  952. $this->assertSame($first['summary'], $settled['summary']); $this->assertSame('2024-01-02', $settled['data'][0]['date']);
  953. $this->assertSame('0.0000000000', $settled['data'][0]['bet_amount']); $this->assertSame('20.0000000000', $settled['data'][0]['payout_amount']);
  954. $bet = $this->reader->funds(['limit' => 1, 'page' => $days]);
  955. $this->assertSame('2024-01-01', $bet['data'][0]['date']); $this->assertSame('40.0000000000', $bet['data'][0]['bet_amount']);
  956. $this->assertSame('0.0000000000', $bet['data'][0]['payout_amount']);
  957. $outside = $this->reader->funds(['limit' => 1, 'page' => $days + 1]);
  958. $this->assertSame([], $outside['data']); $this->assertSame($first['summary'], $outside['summary']); $this->assertSame($days, $outside['total']);
  959. $bounded = $this->reader->funds(['start_date' => '2026-10-25', 'limit' => 1, 'page' => 2]);
  960. $this->assertSame(2, $bounded['total']); $this->assertSame('2026-10-25', $bounded['data'][0]['date']);
  961. $this->assertSame('100.0000000000', $bounded['summary']['bet_amount']);
  962. }
  963. public function test_all_time_uses_the_effective_reconciliation_date_and_amount(): void
  964. {
  965. $event = $this->deposit();
  966. DB::table('balance_logs')->where('id', 1)->update(['created_at' => '2019-01-01 09:00:00']); $this->sync->publish('balance_logs', 1);
  967. $this->admin->reconcile(['event_id' => $event, 'actual_amount' => '500', 'external_fee' => '3', 'occurred_at' => '2022-02-03 10:00:00',
  968. 'currency' => 'CNY', 'evidence' => '历史到账凭据']);
  969. $all = $this->reader->summary([]);
  970. $this->assertSame('2022-02-03', $all['filters']['start_date']); $this->assertSame('500.0000000000', $all['summary']['deposit_amount']);
  971. $this->assertSame('497.0000000000', $all['summary']['net_cash_flow']);
  972. $this->assertSame('0.0000000000', $this->reader->summary($this->today())['summary']['deposit_amount']);
  973. $funds = $this->reader->funds(['limit' => 1,
  974. 'page' => (int) Carbon::parse('2022-02-03')->diffInDays(Carbon::parse('2026-10-26')) + 1]);
  975. $this->assertSame('2022-02-03', $funds['data'][0]['date']); $this->assertSame('500.0000000000', $funds['data'][0]['deposit_amount']);
  976. $events = $this->reader->events([]);
  977. $this->assertSame(1, $events['total']); $this->assertSame('2022-02-03 10:00:00', $events['data'][0]['verified_at']);
  978. $this->assertSame($all['filters']['start_date'], $events['filters']['start_date']); $this->assertSame(1, $events['filters']['all_time']);
  979. }
  980. public function test_all_time_does_not_substitute_the_application_date_for_unknown_payment_time(): void
  981. {
  982. DB::table('withdraws')->insert(['id' => 1, 'member_id' => '200', 'amount' => '100', 'to_account' => '98', 'service_charge' => '2',
  983. 'exchange_rate' => '7', 'status' => 1, 'created_at' => '2001-01-01 08:00:00']);
  984. $this->sync->publish('withdraws', 1);
  985. $all = $this->reader->summary([]);
  986. $this->assertSame('2026-10-01', $all['filters']['start_date']); $this->assertSame(1, $all['summary']['quality']['missing_time']);
  987. $this->assertSame('0.0000000000', $all['summary']['withdraw_amount']); $this->assertNull($all['summary']['net_cash_flow']);
  988. $funds = $this->reader->funds(['limit' => 100]);
  989. $this->assertSame(26, $funds['total']); $this->assertCount(26, $funds['data']);
  990. foreach ($funds['data'] as $day) {
  991. $this->assertSame('0.0000000000', $day['withdraw_amount']); $this->assertSame(1, $day['quality']['missing_time']); $this->assertNull($day['net_cash_flow']);
  992. }
  993. $events = $this->reader->events([]);
  994. $this->assertSame(1, $events['total']); $this->assertNull($events['data'][0]['occurred_at']);
  995. $this->assertSame('2001-01-01 08:00:00', $events['data'][0]['candidate_at']);
  996. }
  997. public function test_all_time_first_day_uses_real_members_and_activity_and_empty_data_falls_back_to_today(): void
  998. {
  999. DB::table('users')->update(['created_at' => '2026-10-26 00:00:00']);
  1000. DB::table('users')->where('from', 2)->update(['created_at' => '1999-01-01 00:00:00']);
  1001. $this->assertSame('2026-10-26', $this->reader->params([])['start_date']);
  1002. DB::table('users')->where('id', 2)->update(['created_at' => '2023-01-01 00:00:00']);
  1003. $this->assertSame('2023-01-01', $this->reader->params([])['start_date']);
  1004. $this->activityObservation('2022-01-01 10:00:00'); $this->activityObservation('2022-01-01 10:02:00');
  1005. $all = $this->reader->summary([]);
  1006. $this->assertSame('2022-01-01', $all['filters']['start_date']); $this->assertSame(2, $all['summary']['known_activity_minutes']);
  1007. $this->assertNull($all['summary']['activity_minutes']);
  1008. DB::table('reporting_activity')->delete(); DB::table('users')->delete();
  1009. $empty = $this->reader->funds([]);
  1010. $this->assertSame('2026-10-26', $empty['filters']['start_date']); $this->assertSame(1, $empty['total']); $this->assertCount(1, $empty['data']);
  1011. $this->assertSame('0.0000000000', $empty['summary']['bet_amount']);
  1012. }
  1013. public function test_all_time_preserves_account_platform_settlement_and_ranking_filters(): void
  1014. {
  1015. $this->historicalBet(); $this->bet(2, ['member_id' => '500', 'amount' => '200']);
  1016. $this->bet(3, ['status' => 1, 'amount' => '30', 'profit' => '0']); $this->deposit();
  1017. foreach (['member_account' => 'member2', 'agent_account' => 'agent10', 'inviter_account' => 'member1'] as $filter => $value) {
  1018. $this->assertSame('70.0000000000', $this->reader->summary([$filter => $value])['summary']['bet_amount']);
  1019. }
  1020. $this->assertSame('40.0000000000', $this->reader->summary(['member_account' => 'member2', 'settlement_status' => 'settled'])['summary']['bet_amount']);
  1021. $this->assertSame('0.0000000000', $this->reader->summary(['platform' => 'APP'])['summary']['bet_amount']);
  1022. $this->assertSame('0.0000000000', $this->reader->summary(['category' => 'self:sport'])['summary']['bet_amount']);
  1023. $ranks = $this->reader->details(['metric' => 'bet_amount', 'page' => 2, 'limit' => 1], true);
  1024. $this->assertSame(2, $ranks['total']); $this->assertSame('2', $ranks['data'][0]['group_id']); $this->assertSame(2, $ranks['data'][0]['rank']);
  1025. $orders = $this->reader->orders(['member_account' => 'member2', 'page' => 2, 'limit' => 1]);
  1026. $this->assertSame(2, $orders['total']); $this->assertSame('2024-01-01 09:00:00', $orders['data'][0]['bet_at']);
  1027. $this->assertSame(1, $orders['filters']['all_time']); $this->assertSame('2024-01-01', $orders['filters']['start_date']);
  1028. $this->assertSame(0, $this->reader->events(['member_account' => 'member5'])['total']);
  1029. $this->assertSame(1, $this->reader->events(['member_account' => 'member2', 'kind' => 'deposit'])['total']);
  1030. }
  1031. #[DataProvider('invalidQueries')]
  1032. public function test_invalid_filters_do_not_query_unbounded_dates(array $input): void { $this->expectException(ValidationException::class); $this->reader->summary($input); }
  1033. public static function invalidQueries(): array { return [[['start_date' => '2026-02-30']], [['end_date' => '2026-10-27']], [['start_date' => '2020-01-01']],
  1034. [['platform' => 'ios']], [['settlement_status' => 'paid']], [['limit' => 999]], [['start_date' => []]], [['end_date' => []]],
  1035. [['start_date' => '2026-10-26', 'end_date' => '2026-10-25']], [['end_date' => '2026-02-30']],
  1036. [['start_date' => '2025-01-01', 'end_date' => '2026-10-26']], [['start_date' => 'not-a-date', 'end_date' => '2026-10-26']]]; }
  1037. }