ReportingTest.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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 Carbon\Carbon;
  7. use Illuminate\Config\Repository;
  8. use Illuminate\Database\Capsule\Manager;
  9. use Illuminate\Database\Schema\Blueprint;
  10. use Illuminate\Events\Dispatcher;
  11. use Illuminate\Foundation\Application;
  12. use Illuminate\Http\JsonResponse;
  13. use Illuminate\Http\Request;
  14. use Illuminate\Routing\Router;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Support\Facades\Facade;
  17. use Illuminate\Support\Facades\Schema;
  18. use Illuminate\Translation\ArrayLoader;
  19. use Illuminate\Translation\Translator;
  20. use Illuminate\Validation\Factory;
  21. use Illuminate\Validation\ValidationException;
  22. use PHPUnit\Framework\TestCase;
  23. /** Real source adapters, financial reconciliation, filters and aggregation; isolated SQLite only. */
  24. class ReportingTest extends TestCase
  25. {
  26. private Application $app;
  27. private ReportSync $sync;
  28. private ReportReader $reader;
  29. private ReportAdmin $admin;
  30. protected function setUp(): void
  31. {
  32. Carbon::setTestNow(Carbon::parse('2026-10-26 16:00:00', 'Asia/Shanghai'));
  33. Facade::clearResolvedInstances(); $this->app = new Application(dirname(__DIR__, 2));
  34. $this->app->instance('config', new Repository(['app' => ['locale' => 'zh', 'timezone' => 'Asia/Shanghai'], 'third_game' => ['currency' => 'CNY']])); Facade::setFacadeApplication($this->app);
  35. $db = new Manager($this->app); $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'bot_']);
  36. $db->setEventDispatcher(new Dispatcher($this->app)); $db->setAsGlobal(); $db->bootEloquent(); $this->app->instance('db', $db->getDatabaseManager()); $this->app->bind('db.schema', fn () => $db->schema());
  37. $translator = new Translator(new ArrayLoader(), 'zh'); $this->app->instance('translator', $translator); $this->app->instance('validator', new Factory($translator, $this->app));
  38. $this->app['validator']->setPresenceVerifier(new \Illuminate\Validation\DatabasePresenceVerifier($db->getDatabaseManager()));
  39. $this->app->instance('log', new \Psr\Log\NullLogger()); $this->app->instance(\Illuminate\Contracts\Routing\ResponseFactory::class, new class {
  40. public function json($data, $status = 200, $headers = [], $options = 0) { return new JsonResponse($data, $status, $headers, $options); }
  41. });
  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. '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',
  49. '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',
  50. 'payment_orders' => 'id INTEGER PRIMARY KEY,member_id TEXT,type INTEGER,amount TEXT,fee TEXT,status INTEGER,created_at TEXT,updated_at TEXT',
  51. 'bets' => 'id INTEGER PRIMARY KEY,member_id TEXT,amount TEXT,profit TEXT,status INTEGER,created_at TEXT,updated_at TEXT',
  52. 'share_claims' => 'id INTEGER PRIMARY KEY,user_id INTEGER,status TEXT,credited_log_id INTEGER',
  53. 'share_ledger' => 'id INTEGER PRIMARY KEY,user_id INTEGER,amount TEXT,bet_date TEXT,category TEXT,created_at TEXT',
  54. 'agent_balance_logs' => 'id INTEGER PRIMARY KEY,agent_id INTEGER,type TEXT,amount TEXT,reference_type TEXT,reference_id INTEGER,created_at TEXT',
  55. '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',
  56. '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',
  57. ] as $name => $columns) DB::statement('CREATE TABLE bot_' . $name . ' (' . $columns . ')');
  58. (require dirname(__DIR__, 2) . '/database/migrations/2026_10_26_140000_create_reporting_tables.php')->up();
  59. DB::table('reporting_settings')->where('id', 1)->update(['activity_started_at' => '2026-10-25 00:00:00']);
  60. DB::table('agents')->insert([['id' => 10, 'username' => 'agent10'], ['id' => 20, 'username' => 'agent20']]);
  61. 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]) {
  62. 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']);
  63. 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']);
  64. }
  65. $this->sync = new ReportSync(); $this->reader = new ReportReader(); $this->admin = new ReportAdmin();
  66. $this->ready();
  67. }
  68. protected function tearDown(): void { Carbon::setTestNow(); DB::disconnect(); Facade::clearResolvedInstances(); parent::tearDown(); }
  69. private function ready(): void { DB::table('reporting_sync_state')->updateOrInsert(['source' => '__run__'], ['state' => '{"complete":true}', 'updated_at' => now()]); }
  70. private function context(string $source, int $id, int $user = 2, string $platform = 'H5', ?string $success = null): void
  71. {
  72. DB::table('reporting_contexts')->insert(['source' => $source, 'source_id' => (string) $id, 'user_id' => $user, 'agent_id' => $user === 2 ? 10 : null,
  73. 'inviter_id' => $user === 2 ? 1 : null, 'client_platform' => $platform, 'occurred_at' => '2026-10-26 09:00:00', 'succeeded_at' => $success]);
  74. }
  75. private function bet(int $id = 1, array $extra = []): void
  76. {
  77. 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']);
  78. $this->context('bets', $id, ($extra['member_id'] ?? '200') === '500' ? 5 : 2, 'H5', '2026-10-26 10:00:00'); $this->sync->publish('bets', $id);
  79. }
  80. private function deposit(int $id = 1, string $amount = '1000', string $member = '200'): int
  81. {
  82. 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']);
  83. $this->sync->publish('balance_logs', $id); return (int) DB::table('reporting_events')->where('source', 'balance_logs')->where('source_id', (string) $id)->value('id');
  84. }
  85. private function verify(int $id, string $amount = '1000', string $fee = '2'): void
  86. {
  87. $this->admin->reconcile(['event_id' => $id, 'actual_amount' => $amount, 'external_fee' => $fee, 'occurred_at' => '2026-10-26 10:00:00', 'currency' => 'CNY', 'evidence' => '到账凭据#' . $id]);
  88. }
  89. public function test_source_projection_is_idempotent_and_cross_day_metrics_use_actual_events(): void
  90. {
  91. $this->bet(1, ['created_at' => '2026-10-25 23:00:00']); $this->sync->publish('bets', 1);
  92. $this->assertSame(1, DB::table('reporting_orders')->count());
  93. $row = $this->reader->summary([])['summary'];
  94. $this->assertSame('0.0000000000', $row['bet_amount']); $this->assertSame('100.0000000000', $row['settled_bet_amount']);
  95. $this->assertSame('60.0000000000', $row['payout_amount']); $this->assertSame('40.0000000000', $row['game_gross_profit']);
  96. $this->assertSame('40.0000000000', $row['company_profit']);
  97. $yesterday = $this->reader->summary(['start_date' => '2026-10-25', 'end_date' => '2026-10-25'])['summary'];
  98. $this->assertSame('100.0000000000', $yesterday['bet_amount']); $this->assertSame('0.0000000000', $yesterday['payout_amount']);
  99. }
  100. public function test_missing_fees_and_success_time_never_produce_fabricated_net_values(): void
  101. {
  102. $event = $this->deposit(); $this->bet();
  103. $row = $this->reader->summary([])['summary']; $this->assertNull($row['net_cash_flow']); $this->assertNull($row['company_profit']);
  104. $this->assertSame(1, $row['quality']['unverified_fees']); $this->assertSame('1000.0000000000', $row['deposit_amount']);
  105. $this->verify($event); $row = $this->reader->summary([])['summary'];
  106. $this->assertSame('998.0000000000', $row['net_cash_flow']); $this->assertSame('38.0000000000', $row['company_profit']);
  107. $before = DB::table('balance_logs')->get()->toArray(); $this->verify($event, '1000', '3'); $this->sync->publish('balance_logs', 1);
  108. $this->assertSame(1, DB::table('reporting_reconciliations')->count()); $this->assertEquals($before, DB::table('balance_logs')->get()->toArray());
  109. $this->assertSame('997.0000000000', $this->reader->summary([])['summary']['net_cash_flow']);
  110. }
  111. public function test_chain_withdraw_uses_recipient_amount_and_customer_fee_is_not_an_expense(): void
  112. {
  113. 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']);
  114. $this->sync->publish('withdraws', 1); $row = $this->reader->summary([])['summary'];
  115. $this->assertSame(1, $row['quality']['missing_time']); $this->assertNull($row['net_cash_flow']);
  116. $event = (int) DB::table('reporting_events')->value('id'); $this->verify($event, '686', '1');
  117. $row = $this->reader->summary([])['summary'];
  118. $this->assertSame('686.0000000000', $row['withdraw_amount']); $this->assertSame('14.0000000000', $row['customer_fee_income']);
  119. $this->assertSame('1.0000000000', $row['withdraw_fee']); $this->assertSame('-687.0000000000', $row['net_cash_flow']);
  120. DB::table('withdraws')->where('id', 1)->update(['status' => 2]); $result = $this->sync->sync(true);
  121. $this->assertSame(1, $result['errors']); $this->assertNull($this->reader->summary([])['summary']['net_cash_flow']);
  122. $this->verify($event, '0', '1'); $this->sync->sync(true);
  123. $this->assertSame('0.0000000000', $this->reader->summary([])['summary']['withdraw_amount']);
  124. }
  125. public function test_real_member_agent_sharing_overlap_is_not_added_twice_and_details_are_direct(): void
  126. {
  127. $this->bet(); $event = $this->deposit(); $this->verify($event);
  128. foreach (['business', 'promotion', 'sharing'] as $type) {
  129. $row = $this->reader->summary(['report_type' => $type])['summary']; $this->assertSame('100.0000000000', $row['bet_amount']);
  130. $this->assertSame('1000.0000000000', $row['deposit_amount']);
  131. }
  132. $this->assertSame('2', $this->reader->details([])['data'][0]['group_id']);
  133. $this->assertSame('10', $this->reader->details(['report_type' => 'promotion'])['data'][0]['group_id']);
  134. $this->assertSame('1', $this->reader->details(['report_type' => 'sharing'])['data'][0]['group_id']);
  135. $category = $this->reader->summary([])['categories'][8]; $this->assertNull($category['deposit_amount']); $this->assertNull($category['company_profit']);
  136. $this->assertSame('100.0000000000', $category['bet_amount']);
  137. }
  138. public function test_valid_member_threshold_is_strict_and_independent_from_sharing(): void
  139. {
  140. $this->bet(); $id = $this->deposit(1, '20'); $this->verify($id, '20', '0');
  141. $this->assertSame(0, $this->reader->summary([])['summary']['valid_member_count']);
  142. $this->admin->settings(['valid_deposit_min' => '19.99']);
  143. $this->assertSame(1, $this->reader->summary([])['summary']['valid_member_count']);
  144. $this->assertSame(1, DB::table('operation_audits')->where('resource_type', 'reporting_settings')->count());
  145. }
  146. public function test_platform_settlement_filters_tg_virtual_exclusion_and_rank_pagination(): void
  147. {
  148. $this->bet(); $this->bet(2, ['member_id' => '500', 'amount' => '200']);
  149. $this->bet(3, ['status' => 1, 'profit' => '0']);
  150. 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);
  151. $this->assertSame(3, DB::table('reporting_orders')->count());
  152. $this->assertSame('0.0000000000', $this->reader->summary(['platform' => 'PC'])['summary']['bet_amount']);
  153. $this->assertSame('100.0000000000', $this->reader->summary(['settlement_status' => 'pending'])['summary']['bet_amount']);
  154. $this->assertNull($this->reader->summary(['settlement_status' => 'pending'])['summary']['company_profit']);
  155. $ranks = $this->reader->details(['metric' => 'bet_amount', 'page' => 2, 'limit' => 1], true);
  156. $this->assertSame(2, $ranks['total']); $this->assertSame(2, $ranks['data'][0]['rank']);
  157. }
  158. public function test_activity_intervals_merge_devices_split_idle_and_history_is_explicitly_missing(): void
  159. {
  160. 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]) {
  161. 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]);
  162. }
  163. $row = $this->reader->summary([])['summary'];
  164. $this->assertSame(2, $row['activity_minutes']); $this->assertSame(1, $row['active_member_count']); $this->assertSame(4, $row['member_count']);
  165. $this->assertSame('0.250000', $row['active_rate']);
  166. $old = $this->reader->summary(['start_date' => '2026-10-24', 'end_date' => '2026-10-26'])['summary'];
  167. $this->assertNull($old['activity_minutes']); $this->assertSame(2, $old['known_activity_minutes']);
  168. }
  169. public function test_full_sync_and_repeated_sync_do_not_change_source_data_or_double_count(): void
  170. {
  171. $this->bet(); $this->deposit(); $before = DB::table('balance_logs')->get()->toArray();
  172. $first = $this->sync->sync(true); $second = $this->sync->sync(true);
  173. $this->assertSame(0, $first['errors']); $this->assertSame(0, $second['errors']);
  174. $this->assertSame(1, DB::table('reporting_orders')->count()); $this->assertSame(1, DB::table('reporting_events')->count());
  175. $this->assertEquals($before, DB::table('balance_logs')->get()->toArray());
  176. }
  177. private function activityObservation(string $at, ?int $agent = 10, ?int $inviter = 1, string $session = 'a'): void
  178. {
  179. DB::table('reporting_activity')->insert(['user_id' => 2, 'agent_id' => $agent, 'inviter_id' => $inviter,
  180. 'client_platform' => 'H5', 'session_hash' => $session, 'observed_at' => $at]);
  181. }
  182. public function test_activity_snapshot_survives_agent_reassignment_in_summary_details_and_filters(): void
  183. {
  184. $this->activityObservation('2026-10-26 10:00:00'); $this->activityObservation('2026-10-26 10:02:00');
  185. $before = $this->reader->summary(['report_type' => 'promotion', 'agent_account' => 'agent10'])['summary'];
  186. DB::table('users')->where('id', 2)->update(['agent_id' => 20]);
  187. $after = $this->reader->summary(['report_type' => 'promotion', 'agent_account' => 'agent10'])['summary'];
  188. $this->assertSame(2, $before['activity_minutes']); $this->assertSame(2, $after['activity_minutes']);
  189. $this->assertSame(1, $after['active_member_count']); $this->assertFalse($after['activity_population_complete']); $this->assertNull($after['active_rate']);
  190. $other = $this->reader->summary(['report_type' => 'promotion', 'agent_account' => 'agent20'])['summary'];
  191. $this->assertSame(0, $other['activity_minutes']); $this->assertSame(0, $other['active_member_count']);
  192. $details = $this->reader->details(['report_type' => 'promotion']);
  193. $this->assertSame(1, $details['total']); $this->assertSame('10', $details['data'][0]['group_id']); $this->assertSame(2, $details['data'][0]['activity_minutes']);
  194. $byGroup = $this->reader->summary(['report_type' => 'promotion', 'group_id' => '10'])['summary'];
  195. $this->assertSame(2, $byGroup['activity_minutes']);
  196. $business = $this->reader->summary(['agent_account' => 'agent10'])['summary']; $this->assertSame(2, $business['activity_minutes']);
  197. $this->activityObservation('2026-10-26 11:00:00', 20); $this->activityObservation('2026-10-26 11:03:00', 20);
  198. $groups = collect($this->reader->details(['report_type' => 'promotion'])['data'])->keyBy('group_id');
  199. $this->assertSame(2, $groups[10]['activity_minutes']); $this->assertSame(3, $groups[20]['activity_minutes']);
  200. $this->assertSame('0.500000', $groups[20]['active_rate']);
  201. $all = $this->reader->summary([])['summary']; $this->assertSame(5, $all['activity_minutes']); $this->assertSame(1, $all['active_member_count']);
  202. $this->assertSame('0.250000', $all['active_rate']);
  203. }
  204. public function test_agent_transition_with_overlapping_devices_counts_each_second_only_once(): void
  205. {
  206. $this->activityObservation('2026-10-26 10:00:00', 10, 1, 'a');
  207. $this->activityObservation('2026-10-26 10:01:00', 20, 1, 'b');
  208. $this->activityObservation('2026-10-26 10:02:00', 20, 1, 'a');
  209. $this->activityObservation('2026-10-26 10:03:00', 20, 1, 'b');
  210. DB::table('users')->where('id', 2)->update(['agent_id' => 20]);
  211. $groups = collect($this->reader->details(['report_type' => 'promotion'])['data'])->keyBy('group_id');
  212. $this->assertSame(1, $groups[10]['activity_minutes']); $this->assertSame(2, $groups[20]['activity_minutes']);
  213. $all = $this->reader->summary([])['summary']; $this->assertSame(3, $all['activity_minutes']); $this->assertSame(1, $all['active_member_count']);
  214. $this->assertSame(1, $this->reader->summary(['report_type' => 'promotion', 'agent_account' => 'agent10'])['summary']['activity_minutes']);
  215. $this->assertSame(2, $this->reader->summary(['report_type' => 'promotion', 'agent_account' => 'agent20'])['summary']['activity_minutes']);
  216. }
  217. public function test_activity_uses_inviter_snapshot_and_does_not_inherit_current_null_attribution(): void
  218. {
  219. $this->activityObservation('2026-10-26 10:00:00'); $this->activityObservation('2026-10-26 10:04:00');
  220. DB::table('share_members')->where('user_id', 2)->update(['parent_user_id' => 3]);
  221. $groups = collect($this->reader->details(['report_type' => 'sharing'])['data'])->keyBy('group_id');
  222. $this->assertSame(4, $groups[1]['activity_minutes']); $this->assertArrayNotHasKey(3, $groups->all());
  223. $this->assertSame(4, $this->reader->summary(['report_type' => 'sharing', 'inviter_account' => 'member1'])['summary']['activity_minutes']);
  224. $this->assertSame(0, $this->reader->summary(['report_type' => 'sharing', 'inviter_account' => 'member3'])['summary']['activity_minutes']);
  225. DB::table('reporting_activity')->delete();
  226. $this->activityObservation('2026-10-26 11:00:00', null, null); $this->activityObservation('2026-10-26 11:02:00', null, null);
  227. $this->assertSame(2, $this->reader->summary([])['summary']['activity_minutes']);
  228. $this->assertSame(0, $this->reader->summary(['report_type' => 'promotion'])['summary']['activity_minutes']);
  229. $this->assertSame(0, $this->reader->summary(['report_type' => 'sharing'])['summary']['activity_minutes']);
  230. }
  231. public function test_activity_interval_crossing_query_start_keeps_the_starting_snapshot(): void
  232. {
  233. $this->activityObservation('2026-10-25 23:59:00', 10); $this->activityObservation('2026-10-26 00:01:00', 20);
  234. DB::table('users')->where('id', 2)->update(['agent_id' => 20]);
  235. $groups = collect($this->reader->details(['report_type' => 'promotion'])['data'])->keyBy('group_id');
  236. $this->assertSame(1, $groups[10]['activity_minutes']); $this->assertSame(0, $groups[20]['activity_minutes']);
  237. $this->assertSame(1, $this->reader->summary([])['summary']['activity_minutes']);
  238. }
  239. public function test_order_time_reconciliation_survives_reimport_and_does_not_settle_source(): void
  240. {
  241. 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']);
  242. $this->sync->publish('bets', 1); $this->assertNull($this->reader->summary([])['summary']['company_profit']);
  243. $id = (int) DB::table('reporting_orders')->value('id'); $before = (array) DB::table('bets')->first();
  244. $this->admin->reconcileOrder(['id' => $id, 'settled_at' => '2026-10-26 10:00:00', 'evidence' => '开奖结算日志']); $this->sync->publish('bets', 1);
  245. $this->assertSame('40.0000000000', $this->reader->summary([])['summary']['company_profit']);
  246. $this->assertSame($before, (array) DB::table('bets')->first());
  247. }
  248. public function test_new_routes_have_admin_auth_and_only_operators_can_write_reconciliations(): void
  249. {
  250. $router = new Router(new Dispatcher($this->app), $this->app); $this->app->instance('router', $router);
  251. $router->group(['prefix' => 'admin'], function () { require dirname(__DIR__, 2) . '/routes/admin.php'; });
  252. foreach (['options', 'leaderboard', 'fund-flow', 'summary', 'details', 'orders', 'settings', 'payment-reconciliation'] as $action) {
  253. $r = $router->getRoutes()->match(Request::create('/admin/reporting/' . $action));
  254. $this->assertContains('admin.jwt', $r->middleware()); $this->assertContains('check.button.uri', $r->middleware());
  255. }
  256. foreach (['settings', 'payment-reconciliation', 'order-reconciliation'] as $action) $this->assertContains('operations.admin', $router->getRoutes()->match(Request::create('/admin/reporting/' . $action, 'POST'))->middleware());
  257. }
  258. public function test_share_accrual_and_claim_are_separate_and_agent_cost_only_counts_actual_credit(): void
  259. {
  260. $this->bet();
  261. 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'],
  262. ['id' => 2, 'user_id' => 1, 'amount' => '-3', 'bet_date' => '2026-10-26', 'category' => 'self:lottery', 'created_at' => '2026-10-26 11:00:00']]);
  263. DB::table('share_claims')->insert(['id' => 1, 'user_id' => 1, 'status' => 'approved', 'credited_log_id' => 10]);
  264. DB::table('balance_logs')->insert(['id' => 10, 'member_id' => '100', 'amount' => '5', 'change_type' => '分享佣金领取', 'created_at' => '2026-10-26 11:00:00']);
  265. 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']);
  266. 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']);
  267. 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);
  268. $row = $this->reader->summary([])['summary'];
  269. $this->assertSame('17.0000000000', $row['share_accrual']); $this->assertSame('5.0000000000', $row['share_commission']);
  270. $this->assertSame('9.0000000000', $row['agent_accrual']); $this->assertSame('7.0000000000', $row['agent_commission']);
  271. $this->assertSame('28.0000000000', $row['company_profit']);
  272. $details = $this->reader->details([]); $this->assertSame('7.0000000000', $details['unallocated']['agent_commission']);
  273. $this->assertSame('5.0000000000', $this->reader->summary(['report_type' => 'sharing'])['summary']['share_commission']);
  274. }
  275. public function test_daily_total_is_for_all_pages_and_source_errors_are_visible_until_fixed(): void
  276. {
  277. $this->bet(1, ['created_at' => '2026-10-25 09:00:00']);
  278. $r = $this->reader->funds(['start_date' => '2026-10-25', 'end_date' => '2026-10-26', 'limit' => 1, 'page' => 2]);
  279. $this->assertSame(2, $r['total']); $this->assertSame('2026-10-25', $r['data'][0]['group_id']);
  280. $this->assertSame('100.0000000000', $r['summary']['settled_bet_amount']);
  281. DB::table('bets')->insert(['id' => 2, 'member_id' => 'missing', 'amount' => '10', 'status' => 1, 'created_at' => '2026-10-26 10:00:00']);
  282. $r = $this->sync->sync(true); $this->assertSame(1, $r['errors']);
  283. $this->assertNull($this->reader->summary([])['summary']['company_profit']); $this->assertSame(1, DB::table('reporting_errors')->count());
  284. DB::table('bets')->where('id', 2)->update(['member_id' => '200']); $this->sync->sync(true);
  285. $this->assertSame(0, DB::table('reporting_errors')->count()); $this->assertNotNull($this->reader->summary([])['summary']['company_profit']);
  286. }
  287. public function test_eloquent_context_observer_records_status_transition_once_and_tg_activity_is_deduplicated(): void
  288. {
  289. $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();
  290. $context = DB::table('reporting_contexts')->where('source', 'withdraws')->first(); $this->assertNotNull($context); $this->assertNull($context->succeeded_at);
  291. $withdraw->status = 1; $withdraw->save(); $this->assertSame('2026-10-26 16:00:00', DB::table('reporting_contexts')->where('source', 'withdraws')->value('succeeded_at'));
  292. Carbon::setTestNow(Carbon::parse('2026-10-26 16:10:00', 'Asia/Shanghai')); $withdraw->amount = '11'; $withdraw->save();
  293. $this->assertSame('2026-10-26 16:00:00', DB::table('reporting_contexts')->where('source', 'withdraws')->value('succeeded_at'));
  294. $request = Request::create('/api/onMessage', 'POST'); $this->app->instance('request', $request); $user = (object) ['id' => 5, 'agent_id' => null, 'from' => -1];
  295. \App\Services\Reporting\ReportActivity::telegram($user); \App\Services\Reporting\ReportActivity::telegram($user);
  296. $this->assertSame(1, DB::table('reporting_activity')->count()); $this->assertSame('unknown', DB::table('reporting_activity')->value('client_platform'));
  297. }
  298. public function test_current_game_adapters_cover_parent_children_third_party_and_partial_sports_refunds(): void
  299. {
  300. 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)');
  301. 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)');
  302. 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)');
  303. 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)');
  304. $betAt = Carbon::parse('2026-10-26 09:00:00', 'Asia/Shanghai')->timestamp; $settledAt = $betAt + 3600;
  305. 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]);
  306. 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]]);
  307. $this->context('lhc_order', 1, 2, 'PC', '2026-10-26 10:00:00'); $this->sync->publish('lhc_order', 1);
  308. 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]);
  309. $this->context('sport_order', 1, 2, 'APP'); $this->sync->publish('sport_order', 1);
  310. 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']);
  311. $this->sync->publish('third_game_orders', 1);
  312. $r = $this->reader->summary([])['summary'];
  313. $this->assertSame(3, $r['order_count']); $this->assertSame('150.0000000000', $r['bet_amount']);
  314. $this->assertSame('100.0000000000', $r['settled_bet_amount']); $this->assertSame('18.0000000000', $r['payout_amount']);
  315. $this->assertSame('50.0000000000', $r['refund_amount']); $this->assertSame('82.0000000000', $r['game_gross_profit']);
  316. $unknown = $this->reader->summary(['platform' => 'unknown'])['summary']; $this->assertSame('30.0000000000', $unknown['bet_amount']);
  317. $this->assertFalse(Schema::hasTable('share_bet_facts')); // Reports did not publish or create sharing facts.
  318. $this->assertSame(0, $this->sync->sync(true)['errors']);
  319. Carbon::setTestNow(Carbon::parse('2026-10-26 16:10:00', 'Asia/Shanghai'));
  320. DB::table('lhc_order_item')->where('id', 2)->update(['win_amount' => '68', 'updated_at' => now()->timestamp]);
  321. $this->assertSame(0, $this->sync->sync()['errors']);
  322. $this->assertSame('32.0000000000', $this->reader->summary([])['summary']['game_gross_profit']);
  323. $this->assertSame(4, DB::table('reporting_orders')->count());
  324. }
  325. public function test_audit_failure_rolls_back_reconciliation_and_foreign_currency_is_not_summed(): void
  326. {
  327. $event = $this->deposit();
  328. DB::statement("CREATE TRIGGER reject_reporting_audit BEFORE INSERT ON bot_operation_audits BEGIN SELECT RAISE(ABORT, 'audit failed'); END");
  329. try { $this->verify($event); $this->fail('Expected audit failure'); } catch (\Illuminate\Database\QueryException $e) { $this->assertStringContainsString('audit failed', $e->getMessage()); }
  330. $this->assertSame(0, DB::table('reporting_reconciliations')->count());
  331. $this->bet(); DB::table('reporting_orders')->update(['currency' => 'USDT']);
  332. $r = $this->reader->summary([])['summary']; $this->assertSame('0.0000000000', $r['bet_amount']); $this->assertSame(1, $r['quality']['foreign_currency']); $this->assertNull($r['company_profit']);
  333. }
  334. public function test_verified_attribution_is_a_reporting_snapshot_and_survives_later_imports(): void
  335. {
  336. $event = $this->deposit(); $this->bet();
  337. $this->admin->reconcile(['event_id' => $event, 'actual_amount' => '1000', 'external_fee' => '0', 'occurred_at' => '2026-10-26 10:00:00',
  338. 'currency' => 'CNY', 'evidence' => '核对原绑定及装置', 'agent_id' => 20, 'inviter_id' => 3, 'client_platform' => 'APP']);
  339. $this->sync->publish('balance_logs', 1);
  340. $e = DB::table('reporting_events')->where('id', $event)->first(); $this->assertSame(20, $e->agent_id); $this->assertSame('verified', $e->attribution_quality);
  341. $this->assertSame('APP', $e->client_platform); $this->assertSame(10, DB::table('users')->where('id', 2)->value('agent_id'));
  342. $id = (int) DB::table('reporting_orders')->value('id');
  343. $this->admin->reconcileOrder(['id' => $id, 'agent_id' => 20, 'evidence' => '原始推广凭据']); $this->sync->publish('bets', 1);
  344. $this->assertSame(20, DB::table('reporting_orders')->value('agent_id'));
  345. $this->assertSame('1000.0000000000', $this->reader->summary(['report_type' => 'promotion', 'agent_account' => 'agent20'])['summary']['deposit_amount']);
  346. $this->assertSame(1, $this->reader->events(['group_id' => '2', 'kind' => 'deposit'])['total']);
  347. $this->assertSame(0, $this->admin->quality([])['total']);
  348. $this->assertNotEmpty($this->admin->quality([])['sources']);
  349. }
  350. /** @dataProvider invalidQueries */
  351. public function test_invalid_filters_do_not_query_unbounded_dates(array $input): void { $this->expectException(ValidationException::class); $this->reader->summary($input); }
  352. public static function invalidQueries(): array { return [[['start_date' => '2026-02-30']], [['end_date' => '2026-10-27']], [['start_date' => '2020-01-01']], [['platform' => 'ios']], [['settlement_status' => 'paid']], [['limit' => 999]]]; }
  353. }