AgentReportService.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. <?php
  2. namespace App\Services\Agent;
  3. use App\Models\Agent\Agent;
  4. use App\Models\Agent\AgentDailyStat;
  5. use App\Models\Agent\AgentRebateRecord;
  6. use App\Models\User;
  7. use App\Support\StatsScope;
  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. /** 二级代理已取消,代理只能看到自己。 */
  15. public function visibleAgentIds(Agent $root, bool $includeSelf = true): array
  16. {
  17. return $includeSelf ? [(int) $root->id] : [];
  18. }
  19. /**
  20. * 代理首页汇总(GET /agent/dashboard)。合营代理:自己名下的会员;入股代理(股东):全平台会员
  21. * (不含试玩账号 users.from=2,口径同总后台首页),没有合营分成,commission_amount 为 0。
  22. * scope 告诉前端统计范围:own / platform。代理报表(reportRows)仍按各自名下会员统计。
  23. */
  24. public function dashboard(Agent $agent, string $startDate, string $endDate): array
  25. {
  26. if ($agent->isEquity()) {
  27. // 全平台:排除试玩账号和测试会员(测试代理名下)
  28. $members = StatsScope::realUsers(User::query(), 'users');
  29. return $this->aggregate($members, 0, [], $startDate, $endDate) + ['scope' => 'platform'];
  30. }
  31. return $this->summaryForTree($agent, $startDate, $endDate) + ['scope' => 'own'];
  32. }
  33. public function dailyDeposits(Agent $agent, Carbon $start, Carbon $end): array
  34. {
  35. $members = $agent->isEquity()
  36. ? StatsScope::realUsers(User::query(), 'users')
  37. : User::query()->where('agent_id', $agent->id);
  38. $deposits = $this->depositSources($members->select('member_id'), $start, $end, Schema::hasTable('payment_orders'));
  39. $orders = array_shift($deposits)->select('member_id', 'created_at')
  40. ->selectRaw('amount * COALESCE(exchange_rate, 1) AS amount');
  41. foreach ($deposits as $source) {
  42. $orders->unionAll($source->select('member_id', 'created_at', 'amount'));
  43. }
  44. $date = 'DATE(' . DB::getQueryGrammar()->wrap('created_at') . ')';
  45. $daily = DB::query()->fromSub($orders, 'deposits')->groupByRaw($date)
  46. ->selectRaw("{$date} AS stat_date, COUNT(DISTINCT member_id) AS deposit_members, SUM(amount) AS deposit_amount")
  47. ->get()->keyBy('stat_date');
  48. $list = [];
  49. for ($day = $start->copy(); $day->lte($end); $day->addDay()) {
  50. $date = $day->toDateString();
  51. $row = $daily->get($date);
  52. $list[] = [
  53. 'date' => $date,
  54. 'deposit_members' => (int) ($row->deposit_members ?? 0),
  55. 'deposit_amount' => $this->decimal($row->deposit_amount ?? 0),
  56. ];
  57. }
  58. return $list;
  59. }
  60. private function depositSources($memberIds, Carbon $start, Carbon $end, bool $hasPaymentOrders): array
  61. {
  62. $endExclusive = $end->copy()->startOfDay()->addDay();
  63. $inRange = fn (string $table) => DB::table($table)->whereIn('member_id', clone $memberIds)
  64. ->where('created_at', '>=', $start)->where('created_at', '<', $endExclusive);
  65. $sources = [$inRange('recharges')->where('status', 1)];
  66. if ($hasPaymentOrders) {
  67. $sources[] = $inRange('payment_orders')->where('status', PaymentOrderService::STATUS_SUCCESS)
  68. ->whereIn('type', [PaymentOrderService::TYPE_PAY, PaymentOrderService::TYPE_SELF_PAY]);
  69. }
  70. return $sources;
  71. }
  72. public function summaryForTree(Agent $root, string $startDate, string $endDate): array
  73. {
  74. $ids = $this->visibleAgentIds($root);
  75. $summary = $this->summaryForAgentIds($ids, $startDate, $endDate);
  76. $summary['agent_count'] = max(0, count($ids) - 1);
  77. return $summary;
  78. }
  79. public function summaryForAgentIds(array $agentIds, string $startDate, string $endDate): array
  80. {
  81. if ($agentIds === []) {
  82. return $this->emptySummary();
  83. }
  84. return $this->aggregate(
  85. User::query()->whereIn('agent_id', $agentIds),
  86. count($agentIds),
  87. $agentIds,
  88. $startDate,
  89. $endDate
  90. );
  91. }
  92. public function summaryForMemberIds(array $memberIds, string $startDate, string $endDate): array
  93. {
  94. if ($memberIds === []) {
  95. return $this->emptySummary();
  96. }
  97. return $this->aggregate(User::query()->whereIn('member_id', $memberIds), 0, [], $startDate, $endDate);
  98. }
  99. private function aggregate($members, int $agentCount, array $commissionAgentIds, string $startDate, string $endDate): array
  100. {
  101. $start = Carbon::parse($startDate)->startOfDay();
  102. $end = Carbon::parse($endDate)->endOfDay();
  103. if ($start->gt($end)) {
  104. throw new \InvalidArgumentException('开始日期不能大于结束日期');
  105. }
  106. if ($start->diffInDays($end) > 366) {
  107. throw new \InvalidArgumentException('单次报表查询不能超过366天');
  108. }
  109. $memberCount = (clone $members)->count();
  110. $memberIds = (clone $members)->select('member_id');
  111. $memberBalance = DB::table('wallets')->whereIn('member_id', clone $memberIds)->sum('available_balance');
  112. $hasPaymentOrders = Schema::hasTable('payment_orders');
  113. $depositAmount = '0.0000';
  114. foreach ($this->depositSources($memberIds, $start, $end, $hasPaymentOrders) as $source) {
  115. $depositAmount = bcadd($depositAmount, (string) $source->sum('amount'), 4);
  116. }
  117. $withdrawAmount = DB::table('withdraws')->whereIn('member_id', clone $memberIds)
  118. ->where('status', 1)->whereBetween('created_at', [$start, $end])->sum('amount');
  119. if ($hasPaymentOrders) {
  120. $withdrawAmount = bcadd((string) $withdrawAmount, (string) DB::table('payment_orders')
  121. ->whereIn('member_id', clone $memberIds)
  122. ->where('status', PaymentOrderService::STATUS_SUCCESS)
  123. ->whereIn('type', [PaymentOrderService::TYPE_PAYOUT, PaymentOrderService::TYPE_SELF_PAYOUT])
  124. ->whereBetween('created_at', [$start, $end])->sum('amount'), 4);
  125. }
  126. $funds = DB::table('balance_logs')->whereIn('member_id', clone $memberIds)
  127. ->whereBetween('created_at', [$start, $end])
  128. ->selectRaw(<<<'SQL'
  129. COALESCE(SUM(CASE WHEN ((change_type = '人工充值' AND related_id IS NULL) OR change_type = '订单补偿') AND amount > 0 THEN amount ELSE 0 END), 0) AS manual_credit,
  130. COALESCE(SUM(CASE WHEN change_type = '人工扣款' AND amount < 0 THEN ABS(amount) ELSE 0 END), 0) AS manual_debit,
  131. 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,
  132. COALESCE(SUM(CASE WHEN change_type IN ('比比返','笔笔返','返水','回水') AND amount > 0 THEN amount ELSE 0 END), 0) AS rebate_amount
  133. SQL)->first();
  134. $bet = $this->betSummary($members, $memberIds, $start, $end);
  135. $companyProfit = $this->companyProfit(
  136. (string) $depositAmount,
  137. (string) $withdrawAmount,
  138. (string) ($funds->bonus_amount ?? 0),
  139. (string) ($funds->rebate_amount ?? 0)
  140. );
  141. $commissionAmount = $commissionAgentIds === [] ? 0 : AgentRebateRecord::query()
  142. ->whereIn('agent_id', $commissionAgentIds)
  143. ->whereBetween('settlement_date', [$start->toDateString(), $end->toDateString()])
  144. ->where('profit_status', AgentRebateRecord::STATUS_CREDITED)
  145. ->sum('profit_commission');
  146. return [
  147. 'agent_count' => $agentCount,
  148. 'member_count' => $memberCount,
  149. 'member_balance' => $this->decimal($memberBalance),
  150. 'deposit_amount' => $this->decimal($depositAmount),
  151. 'withdraw_amount' => $this->decimal($withdrawAmount),
  152. 'manual_credit' => $this->decimal($funds->manual_credit ?? 0),
  153. 'manual_debit' => $this->decimal($funds->manual_debit ?? 0),
  154. 'bonus_amount' => $this->decimal($funds->bonus_amount ?? 0),
  155. 'rebate_amount' => $this->decimal($funds->rebate_amount ?? 0),
  156. 'bet_count' => $bet['bet_count'],
  157. 'bet_amount' => $bet['bet_amount'],
  158. 'valid_bet_amount' => $bet['valid_bet_amount'],
  159. 'win_loss' => $bet['win_loss'],
  160. 'commission_amount' => $this->decimal($commissionAmount),
  161. 'company_profit' => $companyProfit,
  162. ];
  163. }
  164. public function refreshDaily(string $date): int
  165. {
  166. $day = Carbon::parse($date)->toDateString();
  167. $count = 0;
  168. Agent::query()->orderBy('id')->chunkById(100, function ($agents) use ($day, &$count) {
  169. foreach ($agents as $agent) {
  170. $summary = $this->summaryForAgentIds([(int) $agent->id], $day, $day);
  171. AgentDailyStat::query()->updateOrCreate(
  172. ['stat_date' => $day, 'agent_id' => $agent->id],
  173. [
  174. 'direct_agents' => 0,
  175. 'direct_members' => $summary['member_count'],
  176. 'member_balance' => $summary['member_balance'],
  177. 'deposit_amount' => $summary['deposit_amount'],
  178. 'withdraw_amount' => $summary['withdraw_amount'],
  179. 'manual_credit' => $summary['manual_credit'],
  180. 'manual_debit' => $summary['manual_debit'],
  181. 'bonus_amount' => $summary['bonus_amount'],
  182. 'rebate_amount' => $summary['rebate_amount'],
  183. 'bet_amount' => $summary['bet_amount'],
  184. 'valid_bet_amount' => $summary['valid_bet_amount'],
  185. 'bet_count' => $summary['bet_count'],
  186. 'win_loss' => $summary['win_loss'],
  187. 'commission_amount' => $summary['commission_amount'],
  188. 'company_profit' => $summary['company_profit'],
  189. ]
  190. );
  191. $count++;
  192. }
  193. });
  194. return $count;
  195. }
  196. public function reportRows(?Agent $scope, array $params): array
  197. {
  198. $page = max(1, (int) ($params['page'] ?? 1));
  199. // 报表每行需要聚合整棵代理树;上线批量聚合前先限制单页,避免一次请求放大到上千条 SQL。
  200. $limit = min(20, max(1, (int) ($params['limit'] ?? 10)));
  201. $query = Agent::query();
  202. if ($scope) {
  203. $ids = $this->visibleAgentIds($scope);
  204. $query->whereIn('id', $ids);
  205. } else {
  206. // 总后台代理报表:不列出测试代理
  207. \App\Support\StatsScope::excludeTestAgents($query, 'id');
  208. }
  209. if (!empty($params['username'])) {
  210. $query->where('username', 'like', '%' . $params['username'] . '%');
  211. }
  212. $total = (clone $query)->count();
  213. $startDate = (string) ($params['start_date'] ?? now()->toDateString());
  214. $endDate = (string) ($params['end_date'] ?? $startDate);
  215. $list = $query->orderBy('id')->forPage($page, $limit)->get()->map(function (Agent $agent) use ($startDate, $endDate) {
  216. $row = $this->summaryForTree($agent, $startDate, $endDate);
  217. return array_merge([
  218. 'id' => (int) $agent->id,
  219. 'username' => $agent->username,
  220. 'real_name' => $agent->real_name,
  221. 'type' => (int) $agent->type,
  222. 'type_text' => $agent->type_text,
  223. 'balance' => (string) $agent->balance,
  224. 'frozen_balance' => (string) $agent->frozen_balance,
  225. ], $row);
  226. })->all();
  227. return compact('total', 'page', 'limit', 'list');
  228. }
  229. private function betSummary($members, $memberIds, Carbon $start, Carbon $end): array
  230. {
  231. $total = ['bet_count' => 0, 'bet_amount' => '0.0000', 'valid_bet_amount' => '0.0000', 'win_loss' => '0.0000'];
  232. $sources = [];
  233. if (Schema::hasTable('bets')) {
  234. $sources[] = DB::table('bets')->whereIn('member_id', clone $memberIds)->where('status', 2)
  235. ->whereBetween('created_at', [$start, $end])
  236. ->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();
  237. }
  238. foreach (['sport_game_order', 'jisu_game_order'] as $table) {
  239. if (!Schema::hasTable($table)) {
  240. continue;
  241. }
  242. $sources[] = DB::table($table)->whereIn('member_id', clone $memberIds)->whereIn('status', [1, 2])
  243. ->whereBetween('created_at', [$start, $end])
  244. ->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();
  245. }
  246. if (Schema::hasTable('lhc_order')) {
  247. $amountExpression = Schema::hasColumn('lhc_order', 'total_amount') ? 'COALESCE(total_amount, amount)' : 'amount';
  248. $winLossExpression = '(COALESCE(win_amount, 0) - ' . $amountExpression . ')';
  249. $sources[] = DB::table('lhc_order')->whereIn('member_id', clone $memberIds)->whereIn('lottery_status', [1, 2])
  250. ->whereBetween('created_at', [$start->timestamp, $end->timestamp])
  251. ->selectRaw("COUNT(*) bet_count, COALESCE(SUM({$amountExpression}),0) bet_amount, COALESCE(SUM({$amountExpression}),0) valid_bet_amount, COALESCE(SUM({$winLossExpression}),0) win_loss")->first();
  252. }
  253. if (Schema::hasTable('third_game_orders')) {
  254. $sources[] = DB::table('third_game_orders')->whereIn('user_id', (clone $members)->select('id'))->where('status', 1)
  255. ->whereBetween('last_update_time', [$start, $end])
  256. ->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();
  257. }
  258. foreach ($sources as $row) {
  259. $total['bet_count'] += (int) ($row->bet_count ?? 0);
  260. foreach (['bet_amount', 'valid_bet_amount', 'win_loss'] as $field) {
  261. $total[$field] = bcadd($total[$field], (string) ($row->{$field} ?? 0), 4);
  262. }
  263. }
  264. return $total;
  265. }
  266. private function emptySummary(): array
  267. {
  268. return [
  269. 'agent_count' => 0, 'member_count' => 0, 'member_balance' => '0.0000',
  270. 'deposit_amount' => '0.0000', 'withdraw_amount' => '0.0000',
  271. 'manual_credit' => '0.0000', 'manual_debit' => '0.0000',
  272. 'bonus_amount' => '0.0000', 'rebate_amount' => '0.0000',
  273. 'bet_count' => 0, 'bet_amount' => '0.0000', 'valid_bet_amount' => '0.0000',
  274. 'win_loss' => '0.0000', 'commission_amount' => '0.0000', 'company_profit' => '0.0000',
  275. ];
  276. }
  277. private function decimal($value): string
  278. {
  279. return bcadd((string) ($value ?? 0), '0', 4);
  280. }
  281. public function companyProfit(string $deposit, string $withdraw, string $bonus, string $rebate): string
  282. {
  283. return bcsub(bcsub($deposit, $withdraw, 4), bcadd($bonus, $rebate, 4), 4);
  284. }
  285. }