AgentReportService.php 13 KB

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