AgentReportService.php 13 KB

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