AgentReportService.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. <?php
  2. namespace App\Services\Agent;
  3. use App\Models\Agent\Agent;
  4. use App\Models\Agent\AgentDailyStat;
  5. use App\Models\Agent\AgentDailyGameStat;
  6. use App\Models\Agent\AgentRebateRecord;
  7. use App\Models\User;
  8. use Carbon\Carbon;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\Schema;
  11. use App\Services\PaymentOrderService;
  12. class AgentReportService
  13. {
  14. public function visibleAgentIds(Agent $root, bool $includeSelf = true): array
  15. {
  16. return Agent::query()
  17. ->when($includeSelf, function ($query) use ($root) {
  18. $query->where(function ($query) use ($root) {
  19. $query->whereKey($root->id)
  20. ->orWhere('path', 'like', rtrim((string) $root->path, '/') . '/%');
  21. });
  22. }, fn($query) => $query
  23. ->where('id', '<>', $root->id)
  24. ->where('path', 'like', rtrim((string) $root->path, '/') . '/%'))
  25. ->pluck('id')->map(fn($id) => (int) $id)->all();
  26. }
  27. public function summaryForTree(Agent $root, string $startDate, string $endDate): array
  28. {
  29. $ids = $this->visibleAgentIds($root);
  30. $summary = $this->summaryForAgentIds($ids, $startDate, $endDate);
  31. $summary['agent_count'] = max(0, count($ids) - 1);
  32. return $summary;
  33. }
  34. public function summaryForAgentIds(array $agentIds, string $startDate, string $endDate): array
  35. {
  36. if ($agentIds === []) {
  37. return $this->emptySummary();
  38. }
  39. return $this->aggregate(
  40. User::query()->whereIn('agent_id', $agentIds),
  41. count($agentIds),
  42. $agentIds,
  43. $startDate,
  44. $endDate
  45. );
  46. }
  47. public function summaryForMemberIds(array $memberIds, string $startDate, string $endDate): array
  48. {
  49. if ($memberIds === []) {
  50. return $this->emptySummary();
  51. }
  52. return $this->aggregate(User::query()->whereIn('member_id', $memberIds), 0, [], $startDate, $endDate);
  53. }
  54. private function aggregate($members, int $agentCount, array $commissionAgentIds, string $startDate, string $endDate): array
  55. {
  56. $start = Carbon::parse($startDate)->startOfDay();
  57. $end = Carbon::parse($endDate)->endOfDay();
  58. if ($start->gt($end)) {
  59. throw new \InvalidArgumentException('开始日期不能大于结束日期');
  60. }
  61. if ($start->diffInDays($end) > 366) {
  62. throw new \InvalidArgumentException('单次报表查询不能超过366天');
  63. }
  64. $memberCount = (clone $members)->count();
  65. $memberIds = (clone $members)->select('member_id');
  66. $memberBalance = DB::table('wallets')->whereIn('member_id', clone $memberIds)->sum('available_balance');
  67. $depositAmount = DB::table('recharges')->whereIn('member_id', clone $memberIds)
  68. ->where('status', 1)->whereBetween('created_at', [$start, $end])->sum('amount');
  69. $withdrawAmount = DB::table('withdraws')->whereIn('member_id', clone $memberIds)
  70. ->where('status', 1)->whereBetween('created_at', [$start, $end])->sum('amount');
  71. if (Schema::hasTable('payment_orders')) {
  72. $depositAmount = bcadd((string) $depositAmount, (string) DB::table('payment_orders')
  73. ->whereIn('member_id', clone $memberIds)
  74. ->where('status', PaymentOrderService::STATUS_SUCCESS)
  75. ->where('type', PaymentOrderService::TYPE_PAY)
  76. ->whereBetween('created_at', [$start, $end])->sum('amount'), 4);
  77. $withdrawAmount = bcadd((string) $withdrawAmount, (string) DB::table('payment_orders')
  78. ->whereIn('member_id', clone $memberIds)
  79. ->where('status', PaymentOrderService::STATUS_SUCCESS)
  80. ->whereIn('type', [PaymentOrderService::TYPE_PAYOUT, PaymentOrderService::TYPE_SELF_PAYOUT])
  81. ->whereBetween('created_at', [$start, $end])->sum('amount'), 4);
  82. }
  83. $funds = DB::table('balance_logs')->whereIn('member_id', clone $memberIds)
  84. ->whereBetween('created_at', [$start, $end])
  85. ->selectRaw(<<<'SQL'
  86. COALESCE(SUM(CASE WHEN change_type = '人工充值' AND related_id IS NULL AND amount > 0 THEN amount ELSE 0 END), 0) AS manual_credit,
  87. COALESCE(SUM(CASE WHEN change_type = '人工扣款' AND amount < 0 THEN ABS(amount) ELSE 0 END), 0) AS manual_debit,
  88. COALESCE(SUM(CASE WHEN (change_type IN ('注册赠送','优惠活动','即充即送','充值返现','老用户回归') OR (change_type = '人工充值' AND related_id = 0)) AND amount > 0 THEN amount ELSE 0 END), 0) AS bonus_amount,
  89. COALESCE(SUM(CASE WHEN change_type IN ('比比返','笔笔返','返水','回水') AND amount > 0 THEN amount ELSE 0 END), 0) AS rebate_amount
  90. SQL)->first();
  91. $bet = $this->betSummary($memberIds, $start, $end);
  92. $companyProfit = $this->companyProfit(
  93. (string) $depositAmount,
  94. (string) $withdrawAmount,
  95. (string) ($funds->bonus_amount ?? 0),
  96. (string) ($funds->rebate_amount ?? 0)
  97. );
  98. $commissionAmount = $commissionAgentIds === [] ? 0 : AgentRebateRecord::query()
  99. ->whereIn('agent_id', $commissionAgentIds)
  100. ->whereBetween('settlement_date', [$start->toDateString(), $end->toDateString()])
  101. ->selectRaw("COALESCE(SUM(CASE WHEN flow_status='credited' THEN flow_commission ELSE 0 END + CASE WHEN profit_status='credited' THEN profit_commission ELSE 0 END),0) total")
  102. ->value('total');
  103. return [
  104. 'agent_count' => $agentCount,
  105. 'member_count' => $memberCount,
  106. 'member_balance' => $this->decimal($memberBalance),
  107. 'deposit_amount' => $this->decimal($depositAmount),
  108. 'withdraw_amount' => $this->decimal($withdrawAmount),
  109. 'manual_credit' => $this->decimal($funds->manual_credit ?? 0),
  110. 'manual_debit' => $this->decimal($funds->manual_debit ?? 0),
  111. 'bonus_amount' => $this->decimal($funds->bonus_amount ?? 0),
  112. 'rebate_amount' => $this->decimal($funds->rebate_amount ?? 0),
  113. 'bet_count' => $bet['bet_count'],
  114. 'bet_amount' => $bet['bet_amount'],
  115. 'valid_bet_amount' => $bet['valid_bet_amount'],
  116. 'win_loss' => $bet['win_loss'],
  117. 'commission_amount' => $this->decimal($commissionAmount),
  118. 'company_profit' => $companyProfit,
  119. ];
  120. }
  121. public function refreshDaily(string $date): int
  122. {
  123. $day = Carbon::parse($date)->toDateString();
  124. $this->refreshDailyGameStats($day);
  125. $count = 0;
  126. Agent::query()->orderBy('id')->chunkById(100, function ($agents) use ($day, &$count) {
  127. foreach ($agents as $agent) {
  128. $summary = $this->summaryForAgentIds([(int) $agent->id], $day, $day);
  129. AgentDailyStat::query()->updateOrCreate(
  130. ['stat_date' => $day, 'agent_id' => $agent->id],
  131. [
  132. 'direct_agents' => Agent::query()->where('parent_id', $agent->id)->count(),
  133. 'direct_members' => $summary['member_count'],
  134. 'member_balance' => $summary['member_balance'],
  135. 'deposit_amount' => $summary['deposit_amount'],
  136. 'withdraw_amount' => $summary['withdraw_amount'],
  137. 'manual_credit' => $summary['manual_credit'],
  138. 'manual_debit' => $summary['manual_debit'],
  139. 'bonus_amount' => $summary['bonus_amount'],
  140. 'rebate_amount' => $summary['rebate_amount'],
  141. 'bet_amount' => $summary['bet_amount'],
  142. 'valid_bet_amount' => $summary['valid_bet_amount'],
  143. 'bet_count' => $summary['bet_count'],
  144. 'win_loss' => $summary['win_loss'],
  145. 'commission_amount' => $summary['commission_amount'],
  146. 'company_profit' => $summary['company_profit'],
  147. ]
  148. );
  149. $count++;
  150. }
  151. });
  152. return $count;
  153. }
  154. public function refreshDailyGameStats(string $date): int
  155. {
  156. $day = Carbon::parse($date)->toDateString();
  157. $start = Carbon::parse($day)->startOfDay();
  158. $end = Carbon::parse($day)->endOfDay();
  159. $queries = [];
  160. if (Schema::hasTable('third_game_orders')) {
  161. $queries[] = DB::table('third_game_orders as o')->join('users as u', 'u.id', '=', 'o.user_id')
  162. ->whereNotNull('u.agent_id')->where('o.status', 1)->whereBetween('o.last_update_time', [$start, $end])
  163. ->selectRaw('u.agent_id, LOWER(o.platform) platform, o.game_type, COUNT(*) bet_count, COALESCE(SUM(o.bet_amount),0) bet_amount, COALESCE(SUM(o.valid_amount),0) valid_bet_amount, COALESCE(SUM(o.settled_amount),0) win_loss')
  164. ->groupBy('u.agent_id', 'o.platform', 'o.game_type');
  165. }
  166. if (Schema::hasTable('bets')) {
  167. $queries[] = DB::table('bets as o')->join('users as u', 'u.member_id', '=', 'o.member_id')
  168. ->whereNotNull('u.agent_id')->where('o.status', 2)->whereBetween('o.created_at', [$start, $end])
  169. ->selectRaw("u.agent_id, 'pc28' platform, 3 game_type, COUNT(*) bet_count, COALESCE(SUM(o.amount),0) bet_amount, COALESCE(SUM(o.amount),0) valid_bet_amount, COALESCE(SUM(o.profit-o.amount),0) win_loss")
  170. ->groupBy('u.agent_id');
  171. }
  172. foreach ([['sport_game_order', 'sport', 4], ['jisu_game_order', 'jisu', 3]] as [$table, $platform, $gameType]) {
  173. if (!Schema::hasTable($table)) continue;
  174. $queries[] = DB::table("{$table} as o")->join('users as u', 'u.member_id', '=', 'o.member_id')
  175. ->whereNotNull('u.agent_id')->whereIn('o.status', [1, 2])->whereBetween('o.created_at', [$start, $end])
  176. ->selectRaw("u.agent_id, '{$platform}' platform, {$gameType} game_type, COUNT(*) bet_count, COALESCE(SUM(o.amount),0) bet_amount, COALESCE(SUM(o.amount),0) valid_bet_amount, COALESCE(SUM(CASE WHEN o.status=1 THEN -o.amount ELSE o.profit_and_loss END),0) win_loss")
  177. ->groupBy('u.agent_id');
  178. }
  179. if (Schema::hasTable('lhc_order')) {
  180. $amount = Schema::hasColumn('lhc_order', 'total_amount') ? 'COALESCE(o.total_amount,o.amount)' : 'o.amount';
  181. $queries[] = DB::table('lhc_order as o')->join('users as u', 'u.member_id', '=', 'o.member_id')
  182. ->whereNotNull('u.agent_id')->whereIn('o.lottery_status', [1, 2])
  183. ->whereBetween('o.created_at', [$start->timestamp, $end->timestamp])
  184. ->selectRaw("u.agent_id, 'lhc' platform, 3 game_type, COUNT(*) bet_count, COALESCE(SUM({$amount}),0) bet_amount, COALESCE(SUM({$amount}),0) valid_bet_amount, COALESCE(SUM(COALESCE(o.win_amount,0)-{$amount}),0) win_loss")
  185. ->groupBy('u.agent_id');
  186. }
  187. $rows = collect();
  188. if ($queries !== []) {
  189. $union = array_shift($queries);
  190. foreach ($queries as $query) $union->unionAll($query);
  191. $rows = DB::query()->fromSub($union, 'game_stats')
  192. ->selectRaw('agent_id, platform, game_type, SUM(bet_count) bet_count, SUM(bet_amount) bet_amount, SUM(valid_bet_amount) valid_bet_amount, SUM(win_loss) win_loss')
  193. ->groupBy('agent_id', 'platform', 'game_type')->get();
  194. }
  195. DB::transaction(function () use ($day, $rows) {
  196. AgentDailyGameStat::query()->where('stat_date', $day)->delete();
  197. $now = now();
  198. foreach ($rows->chunk(500) as $chunk) {
  199. AgentDailyGameStat::query()->insert($chunk->map(fn($row) => [
  200. 'stat_date' => $day, 'agent_id' => (int) $row->agent_id,
  201. 'platform' => (string) $row->platform, 'game_type' => (int) $row->game_type,
  202. 'bet_count' => (int) $row->bet_count, 'bet_amount' => (string) $row->bet_amount,
  203. 'valid_bet_amount' => (string) $row->valid_bet_amount, 'win_loss' => (string) $row->win_loss,
  204. 'created_at' => $now, 'updated_at' => $now,
  205. ])->all());
  206. }
  207. });
  208. return $rows->count();
  209. }
  210. public function reportRows(?Agent $scope, array $params): array
  211. {
  212. $page = max(1, (int) ($params['page'] ?? 1));
  213. // 报表每行需要聚合整棵代理树;上线批量聚合前先限制单页,避免一次请求放大到上千条 SQL。
  214. $limit = min(20, max(1, (int) ($params['limit'] ?? 10)));
  215. $query = Agent::query()->with('parent:id,username');
  216. if ($scope) {
  217. $ids = $this->visibleAgentIds($scope);
  218. $query->whereIn('id', $ids);
  219. }
  220. if (!empty($params['username'])) {
  221. $query->where('username', 'like', '%' . $params['username'] . '%');
  222. }
  223. $total = (clone $query)->count();
  224. $startDate = (string) ($params['start_date'] ?? now()->toDateString());
  225. $endDate = (string) ($params['end_date'] ?? $startDate);
  226. $list = $query->orderBy('id')->forPage($page, $limit)->get()->map(function (Agent $agent) use ($startDate, $endDate) {
  227. $row = $this->summaryForTree($agent, $startDate, $endDate);
  228. return array_merge([
  229. 'id' => (int) $agent->id,
  230. 'username' => $agent->username,
  231. 'real_name' => $agent->real_name,
  232. 'parent_username' => $agent->parent?->username,
  233. 'balance' => (string) $agent->balance,
  234. 'frozen_balance' => (string) $agent->frozen_balance,
  235. ], $row);
  236. })->all();
  237. return compact('total', 'page', 'limit', 'list');
  238. }
  239. private function betSummary($memberIds, Carbon $start, Carbon $end): array
  240. {
  241. $total = ['bet_count' => 0, 'bet_amount' => '0.0000', 'valid_bet_amount' => '0.0000', 'win_loss' => '0.0000'];
  242. $sources = [];
  243. if (Schema::hasTable('bets')) {
  244. $sources[] = DB::table('bets')->whereIn('member_id', clone $memberIds)->where('status', 2)
  245. ->whereBetween('created_at', [$start, $end])
  246. ->selectRaw('COUNT(*) bet_count, COALESCE(SUM(amount),0) bet_amount, COALESCE(SUM(amount),0) valid_bet_amount, COALESCE(SUM(profit - amount),0) win_loss')->first();
  247. }
  248. foreach (['sport_game_order', 'jisu_game_order'] as $table) {
  249. if (!Schema::hasTable($table)) {
  250. continue;
  251. }
  252. $sources[] = DB::table($table)->whereIn('member_id', clone $memberIds)->whereIn('status', [1, 2])
  253. ->whereBetween('created_at', [$start, $end])
  254. ->selectRaw('COUNT(*) bet_count, COALESCE(SUM(amount),0) bet_amount, COALESCE(SUM(amount),0) valid_bet_amount, COALESCE(SUM(CASE WHEN status = 1 THEN -amount ELSE profit_and_loss END),0) win_loss')->first();
  255. }
  256. if (Schema::hasTable('lhc_order')) {
  257. $amountExpression = Schema::hasColumn('lhc_order', 'total_amount') ? 'COALESCE(total_amount, amount)' : 'amount';
  258. $winLossExpression = '(COALESCE(win_amount, 0) - ' . $amountExpression . ')';
  259. $sources[] = DB::table('lhc_order')->whereIn('member_id', clone $memberIds)->whereIn('lottery_status', [1, 2])
  260. ->whereBetween('created_at', [$start->timestamp, $end->timestamp])
  261. ->selectRaw("COUNT(*) bet_count, COALESCE(SUM({$amountExpression}),0) bet_amount, COALESCE(SUM({$amountExpression}),0) valid_bet_amount, COALESCE(SUM({$winLossExpression}),0) win_loss")->first();
  262. }
  263. if (Schema::hasTable('third_game_orders')) {
  264. $sources[] = DB::table('third_game_orders')->whereIn('member_id', clone $memberIds)->where('status', 1)
  265. ->whereBetween('last_update_time', [$start, $end])
  266. ->selectRaw('COUNT(*) bet_count, COALESCE(SUM(bet_amount),0) bet_amount, COALESCE(SUM(valid_amount),0) valid_bet_amount, COALESCE(SUM(settled_amount),0) win_loss')->first();
  267. }
  268. foreach ($sources as $row) {
  269. $total['bet_count'] += (int) ($row->bet_count ?? 0);
  270. foreach (['bet_amount', 'valid_bet_amount', 'win_loss'] as $field) {
  271. $total[$field] = bcadd($total[$field], (string) ($row->{$field} ?? 0), 4);
  272. }
  273. }
  274. return $total;
  275. }
  276. private function emptySummary(): array
  277. {
  278. return [
  279. 'agent_count' => 0, 'member_count' => 0, 'member_balance' => '0.0000',
  280. 'deposit_amount' => '0.0000', 'withdraw_amount' => '0.0000',
  281. 'manual_credit' => '0.0000', 'manual_debit' => '0.0000',
  282. 'bonus_amount' => '0.0000', 'rebate_amount' => '0.0000',
  283. 'bet_count' => 0, 'bet_amount' => '0.0000', 'valid_bet_amount' => '0.0000',
  284. 'win_loss' => '0.0000', 'commission_amount' => '0.0000', 'company_profit' => '0.0000',
  285. ];
  286. }
  287. private function decimal($value): string
  288. {
  289. return bcadd((string) ($value ?? 0), '0', 4);
  290. }
  291. public function companyProfit(string $deposit, string $withdraw, string $bonus, string $rebate): string
  292. {
  293. return bcsub(bcsub($deposit, $withdraw, 4), bcadd($bonus, $rebate, 4), 4);
  294. }
  295. }