AgentReportService.php 13 KB

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