| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248 |
- <?php
- namespace App\Services\Agent;
- use App\Models\Agent\Agent;
- use App\Models\Agent\AgentDailyStat;
- use App\Models\User;
- use Carbon\Carbon;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Schema;
- use App\Services\PaymentOrderService;
- class AgentReportService
- {
- public function visibleAgentIds(Agent $root, bool $includeSelf = true): array
- {
- return Agent::query()
- ->when($includeSelf, function ($query) use ($root) {
- $query->where(function ($query) use ($root) {
- $query->whereKey($root->id)
- ->orWhere('path', 'like', rtrim((string) $root->path, '/') . '/%');
- });
- }, fn($query) => $query->where('path', 'like', rtrim((string) $root->path, '/') . '/%'))
- ->pluck('id')->map(fn($id) => (int) $id)->all();
- }
- public function summaryForTree(Agent $root, string $startDate, string $endDate): array
- {
- $ids = $this->visibleAgentIds($root);
- $summary = $this->summaryForAgentIds($ids, $startDate, $endDate);
- $summary['agent_count'] = max(0, count($ids) - 1);
- return $summary;
- }
- public function summaryForAgentIds(array $agentIds, string $startDate, string $endDate): array
- {
- if ($agentIds === []) {
- return $this->emptySummary();
- }
- return $this->aggregate(
- User::query()->whereIn('agent_id', $agentIds),
- count($agentIds),
- $agentIds,
- $startDate,
- $endDate
- );
- }
- public function summaryForMemberIds(array $memberIds, string $startDate, string $endDate): array
- {
- if ($memberIds === []) {
- return $this->emptySummary();
- }
- return $this->aggregate(User::query()->whereIn('member_id', $memberIds), 0, [], $startDate, $endDate);
- }
- private function aggregate($members, int $agentCount, array $commissionAgentIds, string $startDate, string $endDate): array
- {
- $start = Carbon::parse($startDate)->startOfDay();
- $end = Carbon::parse($endDate)->endOfDay();
- if ($start->gt($end)) {
- throw new \InvalidArgumentException('开始日期不能大于结束日期');
- }
- if ($start->diffInDays($end) > 366) {
- throw new \InvalidArgumentException('单次报表查询不能超过366天');
- }
- $memberCount = (clone $members)->count();
- $memberIds = (clone $members)->select('member_id');
- $memberBalance = DB::table('wallets')->whereIn('member_id', clone $memberIds)->sum('available_balance');
- $depositAmount = DB::table('recharges')->whereIn('member_id', clone $memberIds)
- ->where('status', 1)->whereBetween('created_at', [$start, $end])->sum('amount');
- $withdrawAmount = DB::table('withdraws')->whereIn('member_id', clone $memberIds)
- ->where('status', 1)->whereBetween('created_at', [$start, $end])->sum('amount');
- if (Schema::hasTable('payment_orders')) {
- $depositAmount = bcadd((string) $depositAmount, (string) DB::table('payment_orders')
- ->whereIn('member_id', clone $memberIds)
- ->where('status', PaymentOrderService::STATUS_SUCCESS)
- ->where('type', PaymentOrderService::TYPE_PAY)
- ->whereBetween('created_at', [$start, $end])->sum('amount'), 4);
- $withdrawAmount = bcadd((string) $withdrawAmount, (string) DB::table('payment_orders')
- ->whereIn('member_id', clone $memberIds)
- ->where('status', PaymentOrderService::STATUS_SUCCESS)
- ->whereIn('type', [PaymentOrderService::TYPE_PAYOUT, PaymentOrderService::TYPE_SELF_PAYOUT])
- ->whereBetween('created_at', [$start, $end])->sum('amount'), 4);
- }
- $funds = DB::table('balance_logs')->whereIn('member_id', clone $memberIds)
- ->whereBetween('created_at', [$start, $end])
- ->selectRaw(<<<'SQL'
- COALESCE(SUM(CASE WHEN change_type = '人工充值' AND related_id IS NULL AND amount > 0 THEN amount ELSE 0 END), 0) AS manual_credit,
- COALESCE(SUM(CASE WHEN change_type = '人工扣款' AND amount < 0 THEN ABS(amount) ELSE 0 END), 0) AS manual_debit,
- 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,
- COALESCE(SUM(CASE WHEN change_type IN ('比比返','笔笔返','返水','回水') AND amount > 0 THEN amount ELSE 0 END), 0) AS rebate_amount
- SQL)->first();
- $bet = $this->betSummary($memberIds, $start, $end);
- $companyProfit = $this->companyProfit(
- (string) $depositAmount,
- (string) $withdrawAmount,
- (string) ($funds->bonus_amount ?? 0),
- (string) ($funds->rebate_amount ?? 0)
- );
- $commissionAmount = $commissionAgentIds === [] ? 0 : DB::table('agent_commissions')
- ->whereIn('agent_id', $commissionAgentIds)->where('status', 'credited')
- ->whereBetween('settlement_date', [$start->toDateString(), $end->toDateString()])->sum('amount');
- return [
- 'agent_count' => $agentCount,
- 'member_count' => $memberCount,
- 'member_balance' => $this->decimal($memberBalance),
- 'deposit_amount' => $this->decimal($depositAmount),
- 'withdraw_amount' => $this->decimal($withdrawAmount),
- 'manual_credit' => $this->decimal($funds->manual_credit ?? 0),
- 'manual_debit' => $this->decimal($funds->manual_debit ?? 0),
- 'bonus_amount' => $this->decimal($funds->bonus_amount ?? 0),
- 'rebate_amount' => $this->decimal($funds->rebate_amount ?? 0),
- 'bet_count' => $bet['bet_count'],
- 'bet_amount' => $bet['bet_amount'],
- 'valid_bet_amount' => $bet['valid_bet_amount'],
- 'win_loss' => $bet['win_loss'],
- 'commission_amount' => $this->decimal($commissionAmount),
- 'company_profit' => $companyProfit,
- ];
- }
- public function refreshDaily(string $date): int
- {
- $day = Carbon::parse($date)->toDateString();
- $count = 0;
- Agent::query()->orderBy('id')->chunkById(100, function ($agents) use ($day, &$count) {
- foreach ($agents as $agent) {
- $summary = $this->summaryForAgentIds([(int) $agent->id], $day, $day);
- AgentDailyStat::query()->updateOrCreate(
- ['stat_date' => $day, 'agent_id' => $agent->id],
- [
- 'direct_agents' => Agent::query()->where('parent_id', $agent->id)->count(),
- 'direct_members' => $summary['member_count'],
- 'member_balance' => $summary['member_balance'],
- 'deposit_amount' => $summary['deposit_amount'],
- 'withdraw_amount' => $summary['withdraw_amount'],
- 'manual_credit' => $summary['manual_credit'],
- 'manual_debit' => $summary['manual_debit'],
- 'bonus_amount' => $summary['bonus_amount'],
- 'rebate_amount' => $summary['rebate_amount'],
- 'bet_amount' => $summary['bet_amount'],
- 'valid_bet_amount' => $summary['valid_bet_amount'],
- 'bet_count' => $summary['bet_count'],
- 'win_loss' => $summary['win_loss'],
- 'commission_amount' => $summary['commission_amount'],
- 'company_profit' => $summary['company_profit'],
- ]
- );
- $count++;
- }
- });
- return $count;
- }
- public function reportRows(?Agent $scope, array $params): array
- {
- $page = max(1, (int) ($params['page'] ?? 1));
- // 报表每行需要聚合整棵代理树;上线批量聚合前先限制单页,避免一次请求放大到上千条 SQL。
- $limit = min(20, max(1, (int) ($params['limit'] ?? 10)));
- $query = Agent::query()->with('parent:id,username');
- if ($scope) {
- $ids = $this->visibleAgentIds($scope);
- $query->whereIn('id', $ids);
- }
- if (!empty($params['username'])) {
- $query->where('username', 'like', '%' . $params['username'] . '%');
- }
- $total = (clone $query)->count();
- $startDate = (string) ($params['start_date'] ?? now()->toDateString());
- $endDate = (string) ($params['end_date'] ?? $startDate);
- $list = $query->orderBy('id')->forPage($page, $limit)->get()->map(function (Agent $agent) use ($startDate, $endDate) {
- $row = $this->summaryForTree($agent, $startDate, $endDate);
- return array_merge([
- 'id' => (int) $agent->id,
- 'username' => $agent->username,
- 'real_name' => $agent->real_name,
- 'parent_username' => $agent->parent?->username,
- 'balance' => (string) $agent->balance,
- 'frozen_balance' => (string) $agent->frozen_balance,
- ], $row);
- })->all();
- return compact('total', 'page', 'limit', 'list');
- }
- private function betSummary($memberIds, Carbon $start, Carbon $end): array
- {
- $total = ['bet_count' => 0, 'bet_amount' => '0.0000', 'valid_bet_amount' => '0.0000', 'win_loss' => '0.0000'];
- $sources = [];
- if (Schema::hasTable('bets')) {
- $sources[] = DB::table('bets')->whereIn('member_id', clone $memberIds)->where('status', 2)
- ->whereBetween('created_at', [$start, $end])
- ->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();
- }
- foreach (['sport_game_order', 'jisu_game_order'] as $table) {
- if (!Schema::hasTable($table)) {
- continue;
- }
- $sources[] = DB::table($table)->whereIn('member_id', clone $memberIds)->whereIn('status', [1, 2])
- ->whereBetween('created_at', [$start, $end])
- ->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();
- }
- if (Schema::hasTable('lhc_order')) {
- $amountExpression = Schema::hasColumn('lhc_order', 'total_amount') ? 'COALESCE(total_amount, amount)' : 'amount';
- $winLossExpression = '(COALESCE(win_amount, 0) - ' . $amountExpression . ')';
- $sources[] = DB::table('lhc_order')->whereIn('member_id', clone $memberIds)->whereIn('lottery_status', [1, 2])
- ->whereBetween('created_at', [$start->timestamp, $end->timestamp])
- ->selectRaw("COUNT(*) bet_count, COALESCE(SUM({$amountExpression}),0) bet_amount, COALESCE(SUM({$amountExpression}),0) valid_bet_amount, COALESCE(SUM({$winLossExpression}),0) win_loss")->first();
- }
- if (Schema::hasTable('third_game_orders')) {
- $sources[] = DB::table('third_game_orders')->whereIn('member_id', clone $memberIds)->where('status', 1)
- ->whereBetween('last_update_time', [$start, $end])
- ->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();
- }
- foreach ($sources as $row) {
- $total['bet_count'] += (int) ($row->bet_count ?? 0);
- foreach (['bet_amount', 'valid_bet_amount', 'win_loss'] as $field) {
- $total[$field] = bcadd($total[$field], (string) ($row->{$field} ?? 0), 4);
- }
- }
- return $total;
- }
- private function emptySummary(): array
- {
- return [
- 'agent_count' => 0, 'member_count' => 0, 'member_balance' => '0.0000',
- 'deposit_amount' => '0.0000', 'withdraw_amount' => '0.0000',
- 'manual_credit' => '0.0000', 'manual_debit' => '0.0000',
- 'bonus_amount' => '0.0000', 'rebate_amount' => '0.0000',
- 'bet_count' => 0, 'bet_amount' => '0.0000', 'valid_bet_amount' => '0.0000',
- 'win_loss' => '0.0000', 'commission_amount' => '0.0000', 'company_profit' => '0.0000',
- ];
- }
- private function decimal($value): string
- {
- return bcadd((string) ($value ?? 0), '0', 4);
- }
- public function companyProfit(string $deposit, string $withdraw, string $bonus, string $rebate): string
- {
- return bcsub(bcsub($deposit, $withdraw, 4), bcadd($bonus, $rebate, 4), 4);
- }
- }
|