ReportingTest.php 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  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\TestCase;
  24. /** Real source adapters, financial reconciliation, filters and aggregation; isolated SQLite only. */
  25. class ReportingTest extends TestCase
  26. {
  27. private Application $app;
  28. private ReportSync $sync;
  29. private ReportReader $reader;
  30. private ReportAdmin $admin;
  31. protected function setUp(): void
  32. {
  33. Carbon::setTestNow(Carbon::parse('2026-10-26 16:00:00', 'Asia/Shanghai'));
  34. Facade::clearResolvedInstances(); $this->app = new Application(dirname(__DIR__, 2));
  35. $this->app->instance('config', new Repository(['app' => ['locale' => 'zh', 'timezone' => 'Asia/Shanghai'], 'third_game' => ['currency' => 'CNY']])); Facade::setFacadeApplication($this->app);
  36. $db = new Manager($this->app); $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'bot_']);
  37. $db->setEventDispatcher(new Dispatcher($this->app)); $db->setAsGlobal(); $db->bootEloquent(); $this->app->instance('db', $db->getDatabaseManager()); $this->app->bind('db.schema', fn () => $db->schema());
  38. $translator = new Translator(new ArrayLoader(), 'zh'); $this->app->instance('translator', $translator); $this->app->instance('validator', new Factory($translator, $this->app));
  39. $this->app['validator']->setPresenceVerifier(new \Illuminate\Validation\DatabasePresenceVerifier($db->getDatabaseManager()));
  40. $this->app->instance('log', new \Psr\Log\NullLogger()); $this->app->instance(\Illuminate\Contracts\Routing\ResponseFactory::class, new class {
  41. public function json($data, $status = 200, $headers = [], $options = 0) { return new JsonResponse($data, $status, $headers, $options); }
  42. });
  43. Request::macro('validate', function ($rules) { return app('validator')->make($this->all(), $rules)->validate(); });
  44. $request = Request::create('/admin/reporting/summary'); $request->user = (object) ['id' => 1, 'username' => 'admin']; $this->app->instance('request', $request);
  45. foreach ([
  46. 'users' => 'id INTEGER PRIMARY KEY,member_id TEXT,user_id TEXT,username TEXT,first_name TEXT,agent_id INTEGER,"from" INTEGER,created_at TEXT',
  47. 'agents' => 'id INTEGER PRIMARY KEY,username TEXT',
  48. 'share_members' => 'user_id INTEGER PRIMARY KEY,parent_user_id INTEGER,bound_at TEXT',
  49. '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',
  50. 'share_system_state' => '"key" TEXT PRIMARY KEY,value TEXT',
  51. '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"',
  52. 'share_accounts' => 'user_id INTEGER PRIMARY KEY,earned_amount TEXT DEFAULT "0",paid_amount TEXT DEFAULT "0",reserved_amount TEXT DEFAULT "0"',
  53. 'share_settlements' => 'id INTEGER PRIMARY KEY,user_id INTEGER,bet_date TEXT,category TEXT,direct_commission TEXT,indirect_commission TEXT',
  54. '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',
  55. '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',
  56. 'payment_orders' => 'id INTEGER PRIMARY KEY,member_id TEXT,type INTEGER,amount TEXT,fee TEXT,status INTEGER,created_at TEXT,updated_at TEXT',
  57. 'bets' => 'id INTEGER PRIMARY KEY,member_id TEXT,amount TEXT,profit TEXT,status INTEGER,created_at TEXT,updated_at TEXT',
  58. 'share_claims' => 'id INTEGER PRIMARY KEY,user_id INTEGER,status TEXT,credited_log_id INTEGER',
  59. 'share_ledger' => 'id INTEGER PRIMARY KEY,user_id INTEGER,amount TEXT,bet_date TEXT,category TEXT,created_at TEXT',
  60. 'agent_balance_logs' => 'id INTEGER PRIMARY KEY,agent_id INTEGER,type TEXT,amount TEXT,reference_type TEXT,reference_id INTEGER,created_at TEXT',
  61. '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',
  62. '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',
  63. ] as $name => $columns) DB::statement('CREATE TABLE bot_' . $name . ' (' . $columns . ')');
  64. (require dirname(__DIR__, 2) . '/database/migrations/2026_10_26_140000_create_reporting_tables.php')->up();
  65. DB::table('reporting_settings')->where('id', 1)->update(['activity_started_at' => '2026-10-25 00:00:00']);
  66. 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())]);
  67. DB::table('share_system_state')->insert(['key' => 'initialized_at', 'value' => '2026-10-01 00:00:00']);
  68. DB::table('agents')->insert([['id' => 10, 'username' => 'agent10'], ['id' => 20, 'username' => 'agent20']]);
  69. 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]) {
  70. 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']);
  71. 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']);
  72. }
  73. $this->sync = new ReportSync(); $this->reader = new ReportReader(); $this->admin = new ReportAdmin();
  74. $this->ready();
  75. }
  76. protected function tearDown(): void { Carbon::setTestNow(); DB::disconnect(); Facade::clearResolvedInstances(); parent::tearDown(); }
  77. private function today(array $filters = []): array { return $filters + ['start_date' => now('Asia/Shanghai')->toDateString(), 'end_date' => now('Asia/Shanghai')->toDateString()]; }
  78. private function ready(): void { DB::table('reporting_sync_state')->updateOrInsert(['source' => '__run__'], ['state' => '{"complete":true}', 'updated_at' => now()]); }
  79. private function context(string $source, int $id, int $user = 2, string $platform = 'H5', ?string $success = null): void
  80. {
  81. DB::table('reporting_contexts')->insert(['source' => $source, 'source_id' => (string) $id, 'user_id' => $user, 'agent_id' => $user === 2 ? 10 : null,
  82. 'inviter_id' => $user === 2 ? 1 : null, 'client_platform' => $platform, 'occurred_at' => '2026-10-26 09:00:00', 'succeeded_at' => $success]);
  83. }
  84. private function bet(int $id = 1, array $extra = []): void
  85. {
  86. 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']);
  87. $this->context('bets', $id, ($extra['member_id'] ?? '200') === '500' ? 5 : 2, 'H5', '2026-10-26 10:00:00'); $this->sync->publish('bets', $id);
  88. }
  89. private function deposit(int $id = 1, string $amount = '1000', string $member = '200'): int
  90. {
  91. 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']);
  92. $this->sync->publish('balance_logs', $id); return (int) DB::table('reporting_events')->where('source', 'balance_logs')->where('source_id', (string) $id)->value('id');
  93. }
  94. private function verify(int $id, string $amount = '1000', string $fee = '2'): void
  95. {
  96. $this->admin->reconcile(['event_id' => $id, 'actual_amount' => $amount, 'external_fee' => $fee, 'occurred_at' => '2026-10-26 10:00:00', 'currency' => 'CNY', 'evidence' => '到账凭据#' . $id]);
  97. }
  98. private function qualificationFact(string $amount = '100', string $date = '2026-10-26', int $user = 2, array $extra = []): int
  99. {
  100. return DB::table('share_bet_facts')->insertGetId($extra + ['user_id' => $user, 'member_id' => (string) ($user * 100),
  101. 'category' => 'third:2', 'bet_date' => $date, 'effective_amount' => $amount]);
  102. }
  103. public function test_source_projection_is_idempotent_and_cross_day_metrics_use_actual_events(): void
  104. {
  105. $this->bet(1, ['created_at' => '2026-10-25 23:00:00']); $this->sync->publish('bets', 1);
  106. $this->assertSame(1, DB::table('reporting_orders')->count());
  107. $row = $this->reader->summary($this->today())['summary'];
  108. $this->assertSame('0.0000000000', $row['bet_amount']); $this->assertSame('100.0000000000', $row['settled_bet_amount']);
  109. $this->assertSame('60.0000000000', $row['payout_amount']); $this->assertSame('40.0000000000', $row['game_gross_profit']);
  110. $this->assertSame('40.0000000000', $row['company_profit']);
  111. $yesterday = $this->reader->summary(['start_date' => '2026-10-25', 'end_date' => '2026-10-25'])['summary'];
  112. $this->assertSame('100.0000000000', $yesterday['bet_amount']); $this->assertSame('0.0000000000', $yesterday['payout_amount']);
  113. }
  114. private function f1LotteryWithoutCompletionContext(): void
  115. {
  116. 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)');
  117. 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)');
  118. $betAt = Carbon::parse('2026-10-26 09:00:00', 'Asia/Shanghai')->timestamp;
  119. DB::table('lhc_order')->insert(['id' => 1, 'member_id' => '200', 'ordernum' => 'F1-live', 'amount' => '50', 'total_amount' => '100',
  120. 'win_amount' => '190', 'type' => 6, 'lottery_status' => 2, 'created_at' => $betAt, 'updated_at' => $betAt + 3600]);
  121. DB::table('lhc_order_item')->insert([
  122. ['id' => 1, 'member_id' => '200', 'ordernum' => 'F1-live', 'lottery_status' => 2, 'win_amount' => '190', 'updated_at' => $betAt + 3600],
  123. ['id' => 2, 'member_id' => '200', 'ordernum' => 'F1-live', 'lottery_status' => 1, 'win_amount' => '0', 'updated_at' => $betAt + 3600],
  124. ]);
  125. $this->context('lhc_order', 1);
  126. }
  127. private function f1PayoutReceipt(array $extra = []): void
  128. {
  129. DB::table('balance_logs')->insert($extra + ['member_id' => '200', 'type' => 1, 'related_id' => 1, 'amount' => '190',
  130. 'before_balance' => '100', 'after_balance' => '290', 'change_type' => '极速28中奖', 'created_at' => '2026-10-26 10:00:00']);
  131. }
  132. public function test_f1_wallet_receipt_restores_funds_business_category_and_sharing_settlement_totals(): void
  133. {
  134. $this->f1LotteryWithoutCompletionContext(); $this->f1PayoutReceipt();
  135. $before = DB::table('lhc_order')->get()->toJson();
  136. $this->sync->publish('lhc_order', 1); $this->sync->publish('lhc_order', 1);
  137. $funds = $this->reader->funds($this->today());
  138. $business = $this->reader->summary($this->today());
  139. $category = collect($business['categories'])->keyBy('group_id')['self:lottery'];
  140. $sharing = $this->reader->summary($this->today(['report_type' => 'sharing']));
  141. foreach ([$funds['summary'], $funds['data'][0], $business['summary'], $category, $sharing['summary']] as $row) {
  142. $this->assertSame('100.0000000000', $row['bet_amount']);
  143. $this->assertSame('100.0000000000', $row['settled_bet_amount']);
  144. $this->assertSame('190.0000000000', $row['payout_amount']);
  145. $this->assertSame('-90.0000000000', $row['game_gross_profit']);
  146. }
  147. $this->assertSame('F1彩票', $category['label']);
  148. $groups = $this->reader->details($this->today(['report_type' => 'sharing']))['data'];
  149. $this->assertSame('1', $groups[0]['group_id']);
  150. $this->assertSame('190.0000000000', $groups[0]['payout_amount']);
  151. $this->assertSame(2, DB::table('reporting_orders')->count());
  152. $this->assertSame('2026-10-26 10:00:00', DB::table('reporting_orders')->value('settled_at'));
  153. $this->assertSame($before, DB::table('lhc_order')->get()->toJson());
  154. }
  155. public function test_bulk_settlement_capture_preserves_event_attribution_and_records_actual_transition_once(): void
  156. {
  157. $this->f1LotteryWithoutCompletionContext();
  158. $this->sync->publish('lhc_order', 1);
  159. $this->assertSame('0.0000000000', $this->reader->funds($this->today())['summary']['payout_amount']);
  160. $before = DB::table('lhc_order')->get()->toJson();
  161. DB::table('users')->where('id', 2)->update(['agent_id' => 20]);
  162. \App\Services\Reporting\ReportContext::lotterySettled(1);
  163. Carbon::setTestNow(Carbon::parse('2026-10-26 16:10:00', 'Asia/Shanghai'));
  164. \App\Services\Reporting\ReportContext::lotterySettled(1);
  165. $context = DB::table('reporting_contexts')->where('source', 'lhc_order')->first();
  166. $this->assertSame('2026-10-26 16:00:00', $context->succeeded_at);
  167. $this->assertSame(10, (int) $context->agent_id); $this->assertSame(1, (int) $context->inviter_id);
  168. $this->assertSame('H5', $context->client_platform);
  169. $this->sync->publish('lhc_order', 1);
  170. $row = $this->reader->funds($this->today())['summary'];
  171. $this->assertSame('100.0000000000', $row['settled_bet_amount']);
  172. $this->assertSame('190.0000000000', $row['payout_amount']);
  173. $this->assertSame('-90.0000000000', $row['game_gross_profit']);
  174. $this->assertSame($before, DB::table('lhc_order')->get()->toJson());
  175. }
  176. public static function invalidF1Receipts(): array
  177. {
  178. return [
  179. [['related_id' => 999]], [['member_id' => '100']], [['type' => 2]],
  180. [['amount' => '191', 'after_balance' => '291']], [['after_balance' => '999']],
  181. [['created_at' => '2026-10-25 10:00:00']], [['change_type' => '充值']],
  182. ];
  183. }
  184. /** @dataProvider invalidF1Receipts */
  185. public function test_unrelated_or_unbalanced_receipts_do_not_fabricate_lottery_settlement_time(array $receipt): void
  186. {
  187. $this->f1LotteryWithoutCompletionContext(); $this->f1PayoutReceipt($receipt);
  188. $this->sync->publish('lhc_order', 1);
  189. $this->assertNull(DB::table('reporting_orders')->value('settled_at'));
  190. $row = $this->reader->funds($this->today())['summary'];
  191. $this->assertSame('100.0000000000', $row['bet_amount']);
  192. $this->assertSame('0.0000000000', $row['payout_amount']);
  193. $this->assertGreaterThan(0, $row['quality']['missing_time']);
  194. }
  195. public function test_verified_lottery_time_takes_priority_over_payout_receipt_time(): void
  196. {
  197. $this->f1LotteryWithoutCompletionContext(); $this->f1PayoutReceipt();
  198. DB::table('reporting_contexts')->where('source', 'lhc_order')->update(['settlement_verified' => 1, 'succeeded_at' => '2026-10-26 11:30:00']);
  199. $this->sync->publish('lhc_order', 1);
  200. $this->assertSame('2026-10-26 11:30:00', DB::table('reporting_orders')->value('settled_at'));
  201. }
  202. public function test_bulk_lottery_loss_is_counted_as_settled_gross_profit_without_a_prize_receipt(): void
  203. {
  204. $this->f1LotteryWithoutCompletionContext();
  205. DB::table('lhc_order')->where('id', 1)->update(['lottery_status' => 1, 'win_amount' => '0']);
  206. DB::table('lhc_order_item')->update(['lottery_status' => 1, 'win_amount' => '0']);
  207. \App\Services\Reporting\ReportContext::lotterySettled(1);
  208. $this->sync->publish('lhc_order', 1);
  209. $row = $this->reader->funds($this->today())['summary'];
  210. $this->assertSame('100.0000000000', $row['settled_bet_amount']);
  211. $this->assertSame('0.0000000000', $row['payout_amount']);
  212. $this->assertSame('100.0000000000', $row['game_gross_profit']);
  213. }
  214. public function test_missing_fees_and_success_time_never_produce_fabricated_net_values(): void
  215. {
  216. $event = $this->deposit(); $this->bet();
  217. $row = $this->reader->summary($this->today())['summary']; $this->assertNull($row['net_cash_flow']); $this->assertNull($row['company_profit']);
  218. $this->assertSame(1, $row['quality']['unverified_fees']); $this->assertSame('1000.0000000000', $row['deposit_amount']);
  219. $this->verify($event); $row = $this->reader->summary($this->today())['summary'];
  220. $this->assertSame('998.0000000000', $row['net_cash_flow']); $this->assertSame('38.0000000000', $row['company_profit']);
  221. $before = DB::table('balance_logs')->get()->toArray(); $this->verify($event, '1000', '3'); $this->sync->publish('balance_logs', 1);
  222. $this->assertSame(1, DB::table('reporting_reconciliations')->count()); $this->assertEquals($before, DB::table('balance_logs')->get()->toArray());
  223. $this->assertSame('997.0000000000', $this->reader->summary($this->today())['summary']['net_cash_flow']);
  224. }
  225. public function test_chain_withdraw_uses_recipient_amount_and_customer_fee_is_not_an_expense(): void
  226. {
  227. 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']);
  228. $this->sync->publish('withdraws', 1); $row = $this->reader->summary($this->today())['summary'];
  229. $this->assertSame(1, $row['quality']['missing_time']); $this->assertNull($row['net_cash_flow']);
  230. $event = (int) DB::table('reporting_events')->value('id'); $this->verify($event, '686', '1');
  231. $row = $this->reader->summary($this->today())['summary'];
  232. $this->assertSame('686.0000000000', $row['withdraw_amount']); $this->assertSame('14.0000000000', $row['customer_fee_income']);
  233. $this->assertSame('1.0000000000', $row['withdraw_fee']); $this->assertSame('-687.0000000000', $row['net_cash_flow']);
  234. DB::table('withdraws')->where('id', 1)->update(['status' => 2]); $result = $this->sync->sync(true);
  235. $this->assertSame(1, $result['errors']); $this->assertNull($this->reader->summary($this->today())['summary']['net_cash_flow']);
  236. $this->verify($event, '0', '1'); $this->sync->sync(true);
  237. $this->assertSame('0.0000000000', $this->reader->summary($this->today())['summary']['withdraw_amount']);
  238. }
  239. public function test_real_member_agent_sharing_overlap_is_not_added_twice_and_details_are_direct(): void
  240. {
  241. $this->bet(); $event = $this->deposit(); $this->verify($event);
  242. foreach (['business', 'promotion', 'sharing'] as $type) {
  243. $row = $this->reader->summary(['report_type' => $type])['summary']; $this->assertSame('100.0000000000', $row['bet_amount']);
  244. $this->assertSame('1000.0000000000', $row['deposit_amount']);
  245. }
  246. $this->assertSame('2', $this->reader->details($this->today())['data'][0]['group_id']);
  247. $this->assertSame('10', $this->reader->details(['report_type' => 'promotion'])['data'][0]['group_id']);
  248. $this->assertSame('1', $this->reader->details(['report_type' => 'sharing'])['data'][0]['group_id']);
  249. $category = $this->reader->summary($this->today())['categories'][8]; $this->assertNull($category['deposit_amount']); $this->assertNull($category['company_profit']);
  250. $this->assertSame('100.0000000000', $category['bet_amount']);
  251. }
  252. public function test_valid_members_use_both_sharing_thresholds_inclusively(): void
  253. {
  254. $this->bet(); $this->deposit(1, '19.99'); $fact = $this->qualificationFact('100');
  255. $this->assertSame(0, $this->reader->summary($this->today())['summary']['valid_member_count']);
  256. DB::table('balance_logs')->where('id', 1)->update(['amount' => '20']);
  257. DB::table('share_bet_facts')->where('id', $fact)->update(['effective_amount' => '99.99']);
  258. $this->assertSame(0, $this->reader->summary($this->today())['summary']['valid_member_count']);
  259. DB::table('share_bet_facts')->where('id', $fact)->update(['effective_amount' => '100']);
  260. $report = $this->reader->summary($this->today());
  261. $this->assertSame(1, $report['summary']['valid_member_count']);
  262. $this->assertSame('20.0000000000', $report['valid_deposit_min']);
  263. $this->assertSame('100.0000000000', $report['valid_effective_bet_min']);
  264. $this->assertSame(['id' => 1, 'effective_date' => '2026-10-01', 'min_deposit' => '20.0000000000',
  265. 'min_effective_bet' => '100.0000000000', 'date' => '2026-10-26', 'available' => true, 'unavailable_reasons' => []], $report['valid_member_policy']);
  266. // Presentation switches and the retired report-only value do not change qualification.
  267. DB::table('reporting_settings')->where('id', 1)->update(['valid_deposit_min' => '9999']);
  268. DB::table('share_policies')->update(['enabled' => 0, 'benefit_enabled' => 0]);
  269. $this->assertSame(1, $this->reader->summary($this->today())['summary']['valid_member_count']);
  270. }
  271. public function test_qualification_is_cumulative_before_start_and_independent_of_report_filters_and_payment_verification(): void
  272. {
  273. $this->bet(); $this->bet(2, ['member_id' => '500']);
  274. DB::table('balance_logs')->insert([
  275. ['member_id' => '200', 'type' => 1, 'amount' => '8', 'change_type' => '充值', 'created_at' => '2026-10-01 10:00:00'],
  276. ['member_id' => '200', 'type' => 1, 'amount' => '12', 'change_type' => '三方充值', 'created_at' => '2026-10-25 10:00:00'],
  277. ]);
  278. $this->qualificationFact('50', '2026-10-01'); $this->qualificationFact('50', '2026-10-25', 2, ['category' => 'self:sport']);
  279. // Report events and their manual reconciliation are not the sharing deposit source.
  280. $event = $this->deposit(10, '1'); $this->verify($event, '0', '0');
  281. $input = ['platform' => 'H5', 'category' => 'self:lottery', 'settlement_status' => 'settled'];
  282. $report = $this->reader->summary($input);
  283. $this->assertSame(1, $report['summary']['valid_member_count']);
  284. $this->assertSame(1, collect($report['categories'])->keyBy('group_id')['self:lottery']['valid_member_count']);
  285. $this->assertSame(1, $this->reader->details($input + ['member_account' => 'member2'])['data'][0]['valid_member_count']);
  286. $this->assertSame(1, $this->reader->details($input + ['report_type' => 'promotion', 'agent_account' => 'agent10'])['data'][0]['valid_member_count']);
  287. $this->assertSame(1, $this->reader->details($input + ['report_type' => 'sharing', 'inviter_account' => 'member1'])['data'][0]['valid_member_count']);
  288. $this->assertSame(0, $this->reader->summary(['platform' => 'PC'])['summary']['valid_member_count']);
  289. }
  290. public function test_qualification_excludes_future_non_deposit_and_ineligible_facts(): void
  291. {
  292. $this->bet();
  293. foreach ([[1, '充值', '19', '2026-10-26 23:59:59'], [1, '充值', '1000', '2026-10-27 00:00:00'],
  294. [2, '充值', '1000', '2026-10-25 10:00:00'], [1, '人工加款', '1000', '2026-10-25 10:00:00'],
  295. [1, '充值', '-1000', '2026-10-25 10:00:00']] as [$type, $kind, $amount, $at]) {
  296. DB::table('balance_logs')->insert(['member_id' => '200', 'type' => $type, 'change_type' => $kind, 'amount' => $amount, 'created_at' => $at]);
  297. }
  298. $fact = $this->qualificationFact('99');
  299. $this->qualificationFact('1000', '2026-10-27');
  300. $this->qualificationFact('1000', '2026-10-25', 2, ['settled' => 0]);
  301. $this->qualificationFact('1000', '2026-10-25', 2, ['voided' => 1]);
  302. $this->qualificationFact('1000', '2026-10-25', 2, ['currency' => 'USDT']);
  303. $this->assertSame(0, $this->reader->summary($this->today())['summary']['valid_member_count']);
  304. DB::table('balance_logs')->insert(['member_id' => '200', 'type' => 1, 'change_type' => '三方充值', 'amount' => '1', 'created_at' => '2026-10-26 23:59:59']);
  305. $this->assertSame(0, $this->reader->summary($this->today())['summary']['valid_member_count']);
  306. DB::table('share_bet_facts')->where('id', $fact)->update(['effective_amount' => '100']);
  307. $this->assertSame(1, $this->reader->summary($this->today())['summary']['valid_member_count']);
  308. }
  309. public function test_pending_sharing_policy_never_applies_before_its_effective_date(): void
  310. {
  311. $this->bet(); $this->deposit(1, '20'); $this->qualificationFact();
  312. DB::table('share_policies')->insert(['effective_date' => '2026-10-27', 'valid_member_min_deposit' => '200', 'valid_member_min_effective_bet' => '1000', 'rules' => '{}']);
  313. $report = $this->reader->summary($this->today());
  314. $this->assertSame(1, $report['summary']['valid_member_count']); $this->assertSame(1, $report['valid_member_policy']['id']);
  315. $this->assertSame('20.0000000000', $this->admin->settings()['valid_deposit_min']);
  316. Carbon::setTestNow(Carbon::parse('2026-10-27 16:00:00', 'Asia/Shanghai'));
  317. $report = $this->reader->summary(['start_date' => '2026-10-26', 'end_date' => '2026-10-27']);
  318. $this->assertSame(0, $report['summary']['valid_member_count']); $this->assertSame(2, $report['valid_member_policy']['id']);
  319. $historical = $this->reader->summary(['start_date' => '2026-10-26', 'end_date' => '2026-10-26']);
  320. $this->assertSame(1, $historical['summary']['valid_member_count']); $this->assertSame(1, $historical['valid_member_policy']['id']);
  321. }
  322. public function test_zero_sharing_thresholds_are_preserved_and_candidate_population_is_unchanged(): void
  323. {
  324. $this->bet(1, ['status' => 1, 'profit' => '0']);
  325. DB::table('share_policies')->update(['valid_member_min_deposit' => '0', 'valid_member_min_effective_bet' => '0']);
  326. $report = $this->reader->summary($this->today());
  327. $this->assertSame(1, $report['summary']['valid_member_count']); $this->assertSame(4, $report['summary']['member_count']);
  328. $this->assertSame('0.0000000000', $report['valid_deposit_min']); $this->assertSame('0.0000000000', $report['valid_effective_bet_min']);
  329. $this->assertSame(0, $this->reader->summary(['settlement_status' => 'settled'])['summary']['valid_member_count']);
  330. }
  331. public function test_missing_policy_threshold_and_sharing_data_produce_null_not_an_independent_default(): void
  332. {
  333. $this->bet(); $this->deposit(); $this->qualificationFact();
  334. DB::table('share_policies')->update(['valid_member_min_effective_bet' => null]);
  335. $report = $this->reader->summary($this->today());
  336. $this->assertNull($report['summary']['valid_member_count']); $this->assertNull($report['valid_effective_bet_min']);
  337. $this->assertFalse($report['valid_member_policy']['available']);
  338. $this->assertContains('incomplete_qualification_policy', $report['valid_member_policy']['unavailable_reasons']);
  339. DB::table('share_policies')->delete();
  340. $report = $this->reader->summary($this->today());
  341. $this->assertNull($report['summary']['valid_member_count']); $this->assertNull($report['valid_deposit_min']);
  342. $this->assertContains('no_effective_policy', $report['valid_member_policy']['unavailable_reasons']);
  343. DB::table('share_policies')->insert(['effective_date' => '2026-10-01', 'valid_member_min_deposit' => '20', 'valid_member_min_effective_bet' => '100', 'rules' => '{}']);
  344. DB::table('share_system_state')->delete();
  345. $report = $this->reader->summary($this->today());
  346. $this->assertNull($report['summary']['valid_member_count']);
  347. $this->assertContains('relations_not_initialized', $report['valid_member_policy']['unavailable_reasons']);
  348. DB::table('share_system_state')->insert(['key' => 'initialized_at', 'value' => '2026-10-01']);
  349. Schema::drop('share_bet_facts');
  350. $report = $this->reader->summary($this->today());
  351. $this->assertNull($report['summary']['valid_member_count']);
  352. $this->assertContains('missing_table:share_bet_facts', $report['valid_member_policy']['unavailable_reasons']);
  353. }
  354. public function test_report_qualification_reads_do_not_settle_or_write_and_old_settings_post_is_rejected(): void
  355. {
  356. $this->bet(); $this->deposit(1, '20'); $this->qualificationFact();
  357. $tables = ['reporting_settings', 'reporting_orders', 'reporting_events', 'share_policies', 'share_system_state', 'share_bet_facts',
  358. 'balance_logs', 'share_accounts', 'share_settlements', 'share_ledger', 'share_claims', 'operation_audits'];
  359. $before = []; foreach ($tables as $table) $before[$table] = DB::table($table)->get()->toJson();
  360. for ($i = 0; $i < 2; ++$i) {
  361. $this->assertSame(1, $this->reader->summary($this->today())['summary']['valid_member_count']);
  362. $this->assertSame(1, $this->reader->details($this->today())['data'][0]['valid_member_count']);
  363. $settings = $this->admin->settings();
  364. $this->assertSame('20.0000000000', $settings['valid_deposit_min']);
  365. $this->assertSame('100.0000000000', $settings['valid_effective_bet_min']);
  366. $this->assertSame('2026-10-25 00:00:00', $settings['activity_started_at']);
  367. }
  368. try { $this->admin->settings(['valid_deposit_min' => '19.99']); $this->fail('Expected read-only settings rejection'); }
  369. catch (ValidationException $e) { $this->assertStringContainsString('/admin/shareEarning/settings/save', $e->validator->errors()->first()); }
  370. foreach ($tables as $table) $this->assertSame($before[$table], DB::table($table)->get()->toJson(), $table . ' must remain unchanged');
  371. }
  372. public function test_platform_settlement_filters_tg_virtual_exclusion_and_rank_pagination(): void
  373. {
  374. $this->bet(); $this->bet(2, ['member_id' => '500', 'amount' => '200']);
  375. $this->bet(3, ['status' => 1, 'profit' => '0']);
  376. 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);
  377. $this->assertSame(3, DB::table('reporting_orders')->count());
  378. $this->assertSame('0.0000000000', $this->reader->summary(['platform' => 'PC'])['summary']['bet_amount']);
  379. $this->assertSame('100.0000000000', $this->reader->summary(['settlement_status' => 'pending'])['summary']['bet_amount']);
  380. $this->assertNull($this->reader->summary(['settlement_status' => 'pending'])['summary']['company_profit']);
  381. $ranks = $this->reader->details(['metric' => 'bet_amount', 'page' => 2, 'limit' => 1], true);
  382. $this->assertSame(2, $ranks['total']); $this->assertSame(2, $ranks['data'][0]['rank']);
  383. }
  384. public function test_activity_intervals_merge_devices_split_idle_and_history_is_explicitly_missing(): void
  385. {
  386. 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]) {
  387. 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]);
  388. }
  389. $row = $this->reader->summary($this->today())['summary'];
  390. $this->assertSame(2, $row['activity_minutes']); $this->assertSame(1, $row['active_member_count']); $this->assertSame(4, $row['member_count']);
  391. $this->assertSame('0.250000', $row['active_rate']);
  392. $old = $this->reader->summary(['start_date' => '2026-10-24', 'end_date' => '2026-10-26'])['summary'];
  393. $this->assertNull($old['activity_minutes']); $this->assertSame(2, $old['known_activity_minutes']);
  394. }
  395. public function test_full_sync_and_repeated_sync_do_not_change_source_data_or_double_count(): void
  396. {
  397. $this->bet(); $this->deposit(); $before = DB::table('balance_logs')->get()->toArray();
  398. $first = $this->sync->sync(true); $second = $this->sync->sync(true);
  399. $this->assertSame(0, $first['errors']); $this->assertSame(0, $second['errors']);
  400. $this->assertSame(1, DB::table('reporting_orders')->count()); $this->assertSame(1, DB::table('reporting_events')->count());
  401. $this->assertEquals($before, DB::table('balance_logs')->get()->toArray());
  402. }
  403. private function activityObservation(string $at, ?int $agent = 10, ?int $inviter = 1, string $session = 'a'): void
  404. {
  405. DB::table('reporting_activity')->insert(['user_id' => 2, 'agent_id' => $agent, 'inviter_id' => $inviter,
  406. 'client_platform' => 'H5', 'session_hash' => $session, 'observed_at' => $at]);
  407. }
  408. public function test_activity_snapshot_survives_agent_reassignment_in_summary_details_and_filters(): void
  409. {
  410. $this->activityObservation('2026-10-26 10:00:00'); $this->activityObservation('2026-10-26 10:02:00');
  411. $before = $this->reader->summary($this->today(['report_type' => 'promotion', 'agent_account' => 'agent10']))['summary'];
  412. DB::table('users')->where('id', 2)->update(['agent_id' => 20]);
  413. $after = $this->reader->summary($this->today(['report_type' => 'promotion', 'agent_account' => 'agent10']))['summary'];
  414. $this->assertSame(2, $before['activity_minutes']); $this->assertSame(2, $after['activity_minutes']);
  415. $this->assertSame(1, $after['active_member_count']); $this->assertFalse($after['activity_population_complete']); $this->assertNull($after['active_rate']);
  416. $other = $this->reader->summary($this->today(['report_type' => 'promotion', 'agent_account' => 'agent20']))['summary'];
  417. $this->assertSame(0, $other['activity_minutes']); $this->assertSame(0, $other['active_member_count']);
  418. $details = $this->reader->details($this->today(['report_type' => 'promotion']));
  419. $this->assertSame(1, $details['total']); $this->assertSame('10', $details['data'][0]['group_id']); $this->assertSame(2, $details['data'][0]['activity_minutes']);
  420. $byGroup = $this->reader->summary($this->today(['report_type' => 'promotion', 'group_id' => '10']))['summary'];
  421. $this->assertSame(2, $byGroup['activity_minutes']);
  422. $business = $this->reader->summary($this->today(['agent_account' => 'agent10']))['summary']; $this->assertSame(2, $business['activity_minutes']);
  423. $this->activityObservation('2026-10-26 11:00:00', 20); $this->activityObservation('2026-10-26 11:03:00', 20);
  424. $groups = collect($this->reader->details($this->today(['report_type' => 'promotion']))['data'])->keyBy('group_id');
  425. $this->assertSame(2, $groups[10]['activity_minutes']); $this->assertSame(3, $groups[20]['activity_minutes']);
  426. $this->assertSame('0.500000', $groups[20]['active_rate']);
  427. $all = $this->reader->summary($this->today())['summary']; $this->assertSame(5, $all['activity_minutes']); $this->assertSame(1, $all['active_member_count']);
  428. $this->assertSame('0.250000', $all['active_rate']);
  429. }
  430. public function test_agent_transition_with_overlapping_devices_counts_each_second_only_once(): void
  431. {
  432. $this->activityObservation('2026-10-26 10:00:00', 10, 1, 'a');
  433. $this->activityObservation('2026-10-26 10:01:00', 20, 1, 'b');
  434. $this->activityObservation('2026-10-26 10:02:00', 20, 1, 'a');
  435. $this->activityObservation('2026-10-26 10:03:00', 20, 1, 'b');
  436. DB::table('users')->where('id', 2)->update(['agent_id' => 20]);
  437. $groups = collect($this->reader->details($this->today(['report_type' => 'promotion']))['data'])->keyBy('group_id');
  438. $this->assertSame(1, $groups[10]['activity_minutes']); $this->assertSame(2, $groups[20]['activity_minutes']);
  439. $all = $this->reader->summary($this->today())['summary']; $this->assertSame(3, $all['activity_minutes']); $this->assertSame(1, $all['active_member_count']);
  440. $this->assertSame(1, $this->reader->summary($this->today(['report_type' => 'promotion', 'agent_account' => 'agent10']))['summary']['activity_minutes']);
  441. $this->assertSame(2, $this->reader->summary($this->today(['report_type' => 'promotion', 'agent_account' => 'agent20']))['summary']['activity_minutes']);
  442. }
  443. public function test_activity_uses_inviter_snapshot_and_does_not_inherit_current_null_attribution(): void
  444. {
  445. $this->activityObservation('2026-10-26 10:00:00'); $this->activityObservation('2026-10-26 10:04:00');
  446. DB::table('share_members')->where('user_id', 2)->update(['parent_user_id' => 3]);
  447. $groups = collect($this->reader->details($this->today(['report_type' => 'sharing']))['data'])->keyBy('group_id');
  448. $this->assertSame(4, $groups[1]['activity_minutes']); $this->assertArrayNotHasKey(3, $groups->all());
  449. $this->assertSame(4, $this->reader->summary($this->today(['report_type' => 'sharing', 'inviter_account' => 'member1']))['summary']['activity_minutes']);
  450. $this->assertSame(0, $this->reader->summary($this->today(['report_type' => 'sharing', 'inviter_account' => 'member3']))['summary']['activity_minutes']);
  451. DB::table('reporting_activity')->delete();
  452. $this->activityObservation('2026-10-26 11:00:00', null, null); $this->activityObservation('2026-10-26 11:02:00', null, null);
  453. $this->assertSame(2, $this->reader->summary($this->today())['summary']['activity_minutes']);
  454. $this->assertSame(0, $this->reader->summary($this->today(['report_type' => 'promotion']))['summary']['activity_minutes']);
  455. $this->assertSame(0, $this->reader->summary($this->today(['report_type' => 'sharing']))['summary']['activity_minutes']);
  456. }
  457. public function test_activity_interval_crossing_query_start_keeps_the_starting_snapshot(): void
  458. {
  459. $this->activityObservation('2026-10-25 23:59:00', 10); $this->activityObservation('2026-10-26 00:01:00', 20);
  460. DB::table('users')->where('id', 2)->update(['agent_id' => 20]);
  461. $groups = collect($this->reader->details($this->today(['report_type' => 'promotion']))['data'])->keyBy('group_id');
  462. $this->assertSame(1, $groups[10]['activity_minutes']); $this->assertSame(0, $groups[20]['activity_minutes']);
  463. $this->assertSame(1, $this->reader->summary($this->today())['summary']['activity_minutes']);
  464. }
  465. public function test_order_time_reconciliation_survives_reimport_and_does_not_settle_source(): void
  466. {
  467. 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']);
  468. $this->sync->publish('bets', 1); $this->assertNull($this->reader->summary($this->today())['summary']['company_profit']);
  469. $id = (int) DB::table('reporting_orders')->value('id'); $before = (array) DB::table('bets')->first();
  470. $this->admin->reconcileOrder(['id' => $id, 'settled_at' => '2026-10-26 10:00:00', 'evidence' => '开奖结算日志']); $this->sync->publish('bets', 1);
  471. $this->assertSame('40.0000000000', $this->reader->summary($this->today())['summary']['company_profit']);
  472. $this->assertSame($before, (array) DB::table('bets')->first());
  473. }
  474. public function test_new_routes_have_admin_auth_and_only_operators_can_write_reconciliations(): void
  475. {
  476. $router = new Router(new Dispatcher($this->app), $this->app); $this->app->instance('router', $router);
  477. $router->group(['prefix' => 'admin'], function () { require dirname(__DIR__, 2) . '/routes/admin.php'; });
  478. foreach (['options', 'leaderboard', 'fund-flow', 'summary', 'details', 'orders', 'settings', 'payment-reconciliation'] as $action) {
  479. $r = $router->getRoutes()->match(Request::create('/admin/reporting/' . $action));
  480. $this->assertContains('admin.jwt', $r->middleware()); $this->assertContains('check.button.uri', $r->middleware());
  481. }
  482. foreach (['settings', 'payment-reconciliation', 'order-reconciliation'] as $action) $this->assertContains('operations.admin', $router->getRoutes()->match(Request::create('/admin/reporting/' . $action, 'POST'))->middleware());
  483. }
  484. public function test_share_accrual_and_claim_are_separate_and_agent_cost_only_counts_actual_credit(): void
  485. {
  486. $this->bet();
  487. 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'],
  488. ['id' => 2, 'user_id' => 1, 'amount' => '-3', 'bet_date' => '2026-10-26', 'category' => 'self:lottery', 'created_at' => '2026-10-26 11:00:00']]);
  489. DB::table('share_claims')->insert(['id' => 1, 'user_id' => 1, 'status' => 'approved', 'credited_log_id' => 10]);
  490. DB::table('balance_logs')->insert(['id' => 10, 'member_id' => '100', 'amount' => '5', 'change_type' => '分享佣金领取', 'created_at' => '2026-10-26 11:00:00']);
  491. 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']);
  492. 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']);
  493. 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);
  494. $row = $this->reader->summary($this->today())['summary'];
  495. $this->assertSame('17.0000000000', $row['share_accrual']); $this->assertSame('5.0000000000', $row['share_commission']);
  496. $this->assertSame('9.0000000000', $row['agent_accrual']); $this->assertSame('7.0000000000', $row['agent_commission']);
  497. $this->assertSame('28.0000000000', $row['company_profit']);
  498. foreach ([false, true] as $ranking) {
  499. $details = $this->reader->details($this->today(), $ranking);
  500. // Agent-only costs belong to the separate metadata bucket, not a synthetic member row.
  501. $this->assertSame('7.0000000000', $details['unallocated']['agent_commission']);
  502. $this->assertSame('9.0000000000', $details['unallocated']['agent_accrual']);
  503. $this->assertNotContains('unallocated', array_column($details['data'], 'group_id'));
  504. $this->assertSame(2, $details['total']);
  505. }
  506. $this->assertSame('7.0000000000', $this->reader->summary($this->today())['summary']['agent_commission']);
  507. $this->assertSame('28.0000000000', $this->reader->summary($this->today())['summary']['company_profit']);
  508. $this->assertSame('5.0000000000', $this->reader->summary(['report_type' => 'sharing'])['summary']['share_commission']);
  509. }
  510. public function test_daily_total_is_for_all_pages_and_source_errors_are_visible_until_fixed(): void
  511. {
  512. $this->bet(1, ['created_at' => '2026-10-25 09:00:00']);
  513. $r = $this->reader->funds(['start_date' => '2026-10-25', 'end_date' => '2026-10-26', 'limit' => 1, 'page' => 2]);
  514. $this->assertSame(2, $r['total']); $this->assertSame('2026-10-25', $r['data'][0]['group_id']);
  515. $this->assertSame('100.0000000000', $r['summary']['settled_bet_amount']);
  516. DB::table('bets')->insert(['id' => 2, 'member_id' => 'missing', 'amount' => '10', 'status' => 1, 'created_at' => '2026-10-26 10:00:00']);
  517. $r = $this->sync->sync(true); $this->assertSame(1, $r['errors']);
  518. $this->assertNull($this->reader->summary($this->today())['summary']['company_profit']); $this->assertSame(1, DB::table('reporting_errors')->count());
  519. DB::table('bets')->where('id', 2)->update(['member_id' => '200']); $this->sync->sync(true);
  520. $this->assertSame(0, DB::table('reporting_errors')->count()); $this->assertNotNull($this->reader->summary($this->today())['summary']['company_profit']);
  521. }
  522. public function test_eloquent_context_observer_records_status_transition_once_and_tg_activity_is_deduplicated(): void
  523. {
  524. $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();
  525. $context = DB::table('reporting_contexts')->where('source', 'withdraws')->first(); $this->assertNotNull($context); $this->assertNull($context->succeeded_at);
  526. $withdraw->status = 1; $withdraw->save(); $this->assertSame('2026-10-26 16:00:00', DB::table('reporting_contexts')->where('source', 'withdraws')->value('succeeded_at'));
  527. Carbon::setTestNow(Carbon::parse('2026-10-26 16:10:00', 'Asia/Shanghai')); $withdraw->amount = '11'; $withdraw->save();
  528. $this->assertSame('2026-10-26 16:00:00', DB::table('reporting_contexts')->where('source', 'withdraws')->value('succeeded_at'));
  529. $request = Request::create('/api/onMessage', 'POST'); $this->app->instance('request', $request); $user = (object) ['id' => 5, 'agent_id' => null, 'from' => -1];
  530. \App\Services\Reporting\ReportActivity::telegram($user); \App\Services\Reporting\ReportActivity::telegram($user);
  531. $this->assertSame(1, DB::table('reporting_activity')->count()); $this->assertSame('unknown', DB::table('reporting_activity')->value('client_platform'));
  532. }
  533. public function test_current_game_adapters_cover_parent_children_third_party_and_partial_sports_refunds(): void
  534. {
  535. 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)');
  536. 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)');
  537. 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)');
  538. DB::statement('CREATE TABLE bot_third_game_orders (id INTEGER PRIMARY KEY,order_key TEXT,member_id TEXT,user_id INTEGER,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)');
  539. $betAt = Carbon::parse('2026-10-26 09:00:00', 'Asia/Shanghai')->timestamp; $settledAt = $betAt + 3600;
  540. 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]);
  541. 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]]);
  542. $this->context('lhc_order', 1, 2, 'PC', '2026-10-26 10:00:00'); $this->sync->publish('lhc_order', 1);
  543. 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]);
  544. $this->context('sport_order', 1, 2, 'APP'); $this->sync->publish('sport_order', 1);
  545. 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']);
  546. $this->sync->publish('third_game_orders', 1);
  547. $r = $this->reader->summary($this->today())['summary'];
  548. $this->assertSame(3, $r['order_count']); $this->assertSame('150.0000000000', $r['bet_amount']);
  549. $this->assertSame('100.0000000000', $r['settled_bet_amount']); $this->assertSame('18.0000000000', $r['payout_amount']);
  550. $this->assertSame('50.0000000000', $r['refund_amount']); $this->assertSame('82.0000000000', $r['game_gross_profit']);
  551. $unknown = $this->reader->summary(['platform' => 'unknown'])['summary']; $this->assertSame('30.0000000000', $unknown['bet_amount']);
  552. $this->assertSame(0, DB::table('share_bet_facts')->count()); // Reports did not publish sharing facts.
  553. $this->assertSame(0, $this->sync->sync(true)['errors']);
  554. Carbon::setTestNow(Carbon::parse('2026-10-26 16:10:00', 'Asia/Shanghai'));
  555. DB::table('lhc_order_item')->where('id', 2)->update(['win_amount' => '68', 'updated_at' => now()->timestamp]);
  556. $this->assertSame(0, $this->sync->sync()['errors']);
  557. $this->assertSame('32.0000000000', $this->reader->summary($this->today())['summary']['game_gross_profit']);
  558. $this->assertSame(4, DB::table('reporting_orders')->count());
  559. }
  560. public function test_audit_failure_rolls_back_reconciliation_and_foreign_currency_is_not_summed(): void
  561. {
  562. $event = $this->deposit();
  563. DB::statement("CREATE TRIGGER reject_reporting_audit BEFORE INSERT ON bot_operation_audits BEGIN SELECT RAISE(ABORT, 'audit failed'); END");
  564. try { $this->verify($event); $this->fail('Expected audit failure'); } catch (\Illuminate\Database\QueryException $e) { $this->assertStringContainsString('audit failed', $e->getMessage()); }
  565. $this->assertSame(0, DB::table('reporting_reconciliations')->count());
  566. $this->bet(); DB::table('reporting_orders')->update(['currency' => 'USDT']);
  567. $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']);
  568. }
  569. public function test_verified_attribution_is_a_reporting_snapshot_and_survives_later_imports(): void
  570. {
  571. $event = $this->deposit(); $this->bet();
  572. $this->admin->reconcile(['event_id' => $event, 'actual_amount' => '1000', 'external_fee' => '0', 'occurred_at' => '2026-10-26 10:00:00',
  573. 'currency' => 'CNY', 'evidence' => '核对原绑定及装置', 'agent_id' => 20, 'inviter_id' => 3, 'client_platform' => 'APP']);
  574. $this->sync->publish('balance_logs', 1);
  575. $e = DB::table('reporting_events')->where('id', $event)->first(); $this->assertSame(20, $e->agent_id); $this->assertSame('verified', $e->attribution_quality);
  576. $this->assertSame('APP', $e->client_platform); $this->assertSame(10, DB::table('users')->where('id', 2)->value('agent_id'));
  577. $id = (int) DB::table('reporting_orders')->value('id');
  578. $this->admin->reconcileOrder(['id' => $id, 'agent_id' => 20, 'evidence' => '原始推广凭据']); $this->sync->publish('bets', 1);
  579. $this->assertSame(20, DB::table('reporting_orders')->value('agent_id'));
  580. $this->assertSame('1000.0000000000', $this->reader->summary(['report_type' => 'promotion', 'agent_account' => 'agent20'])['summary']['deposit_amount']);
  581. $this->assertSame(1, $this->reader->events(['group_id' => '2', 'kind' => 'deposit'])['total']);
  582. $this->assertSame(0, $this->admin->quality([])['total']);
  583. $this->assertNotEmpty($this->admin->quality([])['sources']);
  584. }
  585. private function historicalBet(int $id = 1, string $betAt = '2024-01-01 09:00:00', string $settledAt = '2024-01-02 10:00:00'): void
  586. {
  587. $this->bet($id, ['created_at' => $betAt, 'amount' => '40', 'profit' => '20']);
  588. DB::table('reporting_contexts')->where('source', 'bets')->where('source_id', (string) $id)->update(['succeeded_at' => $settledAt]);
  589. $this->sync->publish('bets', $id);
  590. }
  591. public function test_no_dates_default_to_all_history_and_dates_alone_select_a_period(): void
  592. {
  593. $this->historicalBet(); $this->bet(2);
  594. $default = $this->reader->summary([]);
  595. $this->assertSame(1, $default['filters']['all_time']); $this->assertSame('2024-01-01', $default['filters']['start_date']);
  596. $this->assertSame('2026-10-26', $default['filters']['end_date']);
  597. $this->assertSame('140.0000000000', $default['summary']['bet_amount']);
  598. $this->assertSame('80.0000000000', $default['summary']['payout_amount']);
  599. $blank = $this->reader->summary(['start_date' => '', 'end_date' => null]);
  600. $this->assertSame($default['filters'], $blank['filters']); $this->assertSame($default['summary'], $blank['summary']);
  601. $range = $this->reader->summary($this->today());
  602. $this->assertSame(0, $range['filters']['all_time']); $this->assertSame('2026-10-26', $range['filters']['start_date']);
  603. $this->assertSame('100.0000000000', $range['summary']['bet_amount']);
  604. $this->assertSame('2026-10-26', $default['valid_member_policy']['date']);
  605. $this->assertSame($default['summary'], $this->reader->summary(['all_time' => 0])['summary']);
  606. $this->assertSame($range['summary'], $this->reader->summary($this->today(['all_time' => 1]))['summary']);
  607. $bounded = $this->reader->params(['start_date' => now('Asia/Shanghai')->subDays(365)->toDateString()]);
  608. $this->assertSame(now('Asia/Shanghai')->subDays(365)->toDateString(), $bounded['start_date']);
  609. $this->assertSame(366, $this->admin->options()['max_days']);
  610. }
  611. public function test_all_time_funds_paginate_actual_days_and_keep_the_complete_summary(): void
  612. {
  613. $this->historicalBet(); $this->bet(2); $event = $this->deposit(); $this->verify($event);
  614. $first = $this->reader->funds(['limit' => 1]);
  615. $days = (int) Carbon::parse('2024-01-01')->diffInDays(Carbon::parse('2026-10-27'));
  616. $this->assertSame($days, $first['total']); $this->assertCount(1, $first['data']); $this->assertSame('2026-10-26', $first['data'][0]['date']);
  617. $this->assertSame('140.0000000000', $first['summary']['bet_amount']); $this->assertSame('80.0000000000', $first['summary']['payout_amount']);
  618. $this->assertSame('100.0000000000', $first['data'][0]['bet_amount']); $this->assertSame('60.0000000000', $first['data'][0]['payout_amount']);
  619. $this->assertSame('998.0000000000', $first['summary']['net_cash_flow']);
  620. $settled = $this->reader->funds(['limit' => 1, 'page' => $days - 1]);
  621. $this->assertSame($first['summary'], $settled['summary']); $this->assertSame('2024-01-02', $settled['data'][0]['date']);
  622. $this->assertSame('0.0000000000', $settled['data'][0]['bet_amount']); $this->assertSame('20.0000000000', $settled['data'][0]['payout_amount']);
  623. $bet = $this->reader->funds(['limit' => 1, 'page' => $days]);
  624. $this->assertSame('2024-01-01', $bet['data'][0]['date']); $this->assertSame('40.0000000000', $bet['data'][0]['bet_amount']);
  625. $this->assertSame('0.0000000000', $bet['data'][0]['payout_amount']);
  626. $outside = $this->reader->funds(['limit' => 1, 'page' => $days + 1]);
  627. $this->assertSame([], $outside['data']); $this->assertSame($first['summary'], $outside['summary']); $this->assertSame($days, $outside['total']);
  628. $bounded = $this->reader->funds(['start_date' => '2026-10-25', 'limit' => 1, 'page' => 2]);
  629. $this->assertSame(2, $bounded['total']); $this->assertSame('2026-10-25', $bounded['data'][0]['date']);
  630. $this->assertSame('100.0000000000', $bounded['summary']['bet_amount']);
  631. }
  632. public function test_all_time_uses_the_effective_reconciliation_date_and_amount(): void
  633. {
  634. $event = $this->deposit();
  635. DB::table('balance_logs')->where('id', 1)->update(['created_at' => '2019-01-01 09:00:00']); $this->sync->publish('balance_logs', 1);
  636. $this->admin->reconcile(['event_id' => $event, 'actual_amount' => '500', 'external_fee' => '3', 'occurred_at' => '2022-02-03 10:00:00',
  637. 'currency' => 'CNY', 'evidence' => '历史到账凭据']);
  638. $all = $this->reader->summary([]);
  639. $this->assertSame('2022-02-03', $all['filters']['start_date']); $this->assertSame('500.0000000000', $all['summary']['deposit_amount']);
  640. $this->assertSame('497.0000000000', $all['summary']['net_cash_flow']);
  641. $this->assertSame('0.0000000000', $this->reader->summary($this->today())['summary']['deposit_amount']);
  642. $funds = $this->reader->funds(['limit' => 1,
  643. 'page' => (int) Carbon::parse('2022-02-03')->diffInDays(Carbon::parse('2026-10-26')) + 1]);
  644. $this->assertSame('2022-02-03', $funds['data'][0]['date']); $this->assertSame('500.0000000000', $funds['data'][0]['deposit_amount']);
  645. $events = $this->reader->events([]);
  646. $this->assertSame(1, $events['total']); $this->assertSame('2022-02-03 10:00:00', $events['data'][0]['verified_at']);
  647. $this->assertSame($all['filters']['start_date'], $events['filters']['start_date']); $this->assertSame(1, $events['filters']['all_time']);
  648. }
  649. public function test_all_time_does_not_substitute_the_application_date_for_unknown_payment_time(): void
  650. {
  651. DB::table('withdraws')->insert(['id' => 1, 'member_id' => '200', 'amount' => '100', 'to_account' => '98', 'service_charge' => '2',
  652. 'exchange_rate' => '7', 'status' => 1, 'created_at' => '2001-01-01 08:00:00']);
  653. $this->sync->publish('withdraws', 1);
  654. $all = $this->reader->summary([]);
  655. $this->assertSame('2026-10-01', $all['filters']['start_date']); $this->assertSame(1, $all['summary']['quality']['missing_time']);
  656. $this->assertSame('0.0000000000', $all['summary']['withdraw_amount']); $this->assertNull($all['summary']['net_cash_flow']);
  657. $funds = $this->reader->funds(['limit' => 100]);
  658. $this->assertSame(26, $funds['total']); $this->assertCount(26, $funds['data']);
  659. foreach ($funds['data'] as $day) {
  660. $this->assertSame('0.0000000000', $day['withdraw_amount']); $this->assertSame(1, $day['quality']['missing_time']); $this->assertNull($day['net_cash_flow']);
  661. }
  662. $events = $this->reader->events([]);
  663. $this->assertSame(1, $events['total']); $this->assertNull($events['data'][0]['occurred_at']);
  664. $this->assertSame('2001-01-01 08:00:00', $events['data'][0]['candidate_at']);
  665. }
  666. public function test_all_time_first_day_uses_real_members_and_activity_and_empty_data_falls_back_to_today(): void
  667. {
  668. DB::table('users')->update(['created_at' => '2026-10-26 00:00:00']);
  669. DB::table('users')->where('from', 2)->update(['created_at' => '1999-01-01 00:00:00']);
  670. $this->assertSame('2026-10-26', $this->reader->params([])['start_date']);
  671. DB::table('users')->where('id', 2)->update(['created_at' => '2023-01-01 00:00:00']);
  672. $this->assertSame('2023-01-01', $this->reader->params([])['start_date']);
  673. $this->activityObservation('2022-01-01 10:00:00'); $this->activityObservation('2022-01-01 10:02:00');
  674. $all = $this->reader->summary([]);
  675. $this->assertSame('2022-01-01', $all['filters']['start_date']); $this->assertSame(2, $all['summary']['known_activity_minutes']);
  676. $this->assertNull($all['summary']['activity_minutes']);
  677. DB::table('reporting_activity')->delete(); DB::table('users')->delete();
  678. $empty = $this->reader->funds([]);
  679. $this->assertSame('2026-10-26', $empty['filters']['start_date']); $this->assertSame(1, $empty['total']); $this->assertCount(1, $empty['data']);
  680. $this->assertSame('0.0000000000', $empty['summary']['bet_amount']);
  681. }
  682. public function test_all_time_preserves_account_platform_settlement_and_ranking_filters(): void
  683. {
  684. $this->historicalBet(); $this->bet(2, ['member_id' => '500', 'amount' => '200']);
  685. $this->bet(3, ['status' => 1, 'amount' => '30', 'profit' => '0']); $this->deposit();
  686. foreach (['member_account' => 'member2', 'agent_account' => 'agent10', 'inviter_account' => 'member1'] as $filter => $value) {
  687. $this->assertSame('70.0000000000', $this->reader->summary([$filter => $value])['summary']['bet_amount']);
  688. }
  689. $this->assertSame('40.0000000000', $this->reader->summary(['member_account' => 'member2', 'settlement_status' => 'settled'])['summary']['bet_amount']);
  690. $this->assertSame('0.0000000000', $this->reader->summary(['platform' => 'APP'])['summary']['bet_amount']);
  691. $this->assertSame('0.0000000000', $this->reader->summary(['category' => 'self:sport'])['summary']['bet_amount']);
  692. $ranks = $this->reader->details(['metric' => 'bet_amount', 'page' => 2, 'limit' => 1], true);
  693. $this->assertSame(2, $ranks['total']); $this->assertSame('2', $ranks['data'][0]['group_id']); $this->assertSame(2, $ranks['data'][0]['rank']);
  694. $orders = $this->reader->orders(['member_account' => 'member2', 'page' => 2, 'limit' => 1]);
  695. $this->assertSame(2, $orders['total']); $this->assertSame('2024-01-01 09:00:00', $orders['data'][0]['bet_at']);
  696. $this->assertSame(1, $orders['filters']['all_time']); $this->assertSame('2024-01-01', $orders['filters']['start_date']);
  697. $this->assertSame(0, $this->reader->events(['member_account' => 'member5'])['total']);
  698. $this->assertSame(1, $this->reader->events(['member_account' => 'member2', 'kind' => 'deposit'])['total']);
  699. }
  700. /** @dataProvider invalidQueries */
  701. public function test_invalid_filters_do_not_query_unbounded_dates(array $input): void { $this->expectException(ValidationException::class); $this->reader->summary($input); }
  702. public static function invalidQueries(): array { return [[['start_date' => '2026-02-30']], [['end_date' => '2026-10-27']], [['start_date' => '2020-01-01']],
  703. [['platform' => 'ios']], [['settlement_status' => 'paid']], [['limit' => 999]], [['start_date' => []]], [['end_date' => []]],
  704. [['start_date' => '2026-10-26', 'end_date' => '2026-10-25']], [['end_date' => '2026-02-30']],
  705. [['start_date' => '2025-01-01', 'end_date' => '2026-10-26']], [['start_date' => 'not-a-date', 'end_date' => '2026-10-26']]]; }
  706. }