AgentReportService.php 12 KB

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