AgentReportService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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, platform: true) + ['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, bool $platform = false): 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. ->whereIn('change_type', [
  129. '人工充值', '订单补偿', '人工扣款', '注册赠送', '优惠活动', '即充即送',
  130. '充值返现', '老用户回归', '比比返', '笔笔返', '返水', '回水',
  131. ])
  132. ->selectRaw(<<<'SQL'
  133. 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,
  134. COALESCE(SUM(CASE WHEN change_type = '人工扣款' AND amount < 0 THEN ABS(amount) ELSE 0 END), 0) AS manual_debit,
  135. 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,
  136. COALESCE(SUM(CASE WHEN change_type IN ('比比返','笔笔返','返水','回水') AND amount > 0 THEN amount ELSE 0 END), 0) AS rebate_amount
  137. SQL)->first();
  138. $bet = $this->betSummary($members, $memberIds, $start, $end, $platform);
  139. $companyProfit = $this->companyProfit(
  140. (string) $depositAmount,
  141. (string) $withdrawAmount,
  142. (string) ($funds->bonus_amount ?? 0),
  143. (string) ($funds->rebate_amount ?? 0)
  144. );
  145. $commissionAmount = $commissionAgentIds === [] ? 0 : AgentRebateRecord::query()
  146. ->whereIn('agent_id', $commissionAgentIds)
  147. ->whereBetween('settlement_date', [$start->toDateString(), $end->toDateString()])
  148. ->where('profit_status', AgentRebateRecord::STATUS_CREDITED)
  149. ->sum('profit_commission');
  150. return [
  151. 'agent_count' => $agentCount,
  152. 'member_count' => $memberCount,
  153. 'member_balance' => $this->decimal($memberBalance),
  154. 'deposit_amount' => $this->decimal($depositAmount),
  155. 'withdraw_amount' => $this->decimal($withdrawAmount),
  156. 'manual_credit' => $this->decimal($funds->manual_credit ?? 0),
  157. 'manual_debit' => $this->decimal($funds->manual_debit ?? 0),
  158. 'bonus_amount' => $this->decimal($funds->bonus_amount ?? 0),
  159. 'rebate_amount' => $this->decimal($funds->rebate_amount ?? 0),
  160. 'bet_count' => $bet['bet_count'],
  161. 'bet_amount' => $bet['bet_amount'],
  162. 'valid_bet_amount' => $bet['valid_bet_amount'],
  163. 'win_loss' => $bet['win_loss'],
  164. 'commission_amount' => $this->decimal($commissionAmount),
  165. 'company_profit' => $companyProfit,
  166. ];
  167. }
  168. public function refreshDaily(string $date): int
  169. {
  170. $day = Carbon::parse($date)->toDateString();
  171. $count = 0;
  172. Agent::query()->orderBy('id')->chunkById(100, function ($agents) use ($day, &$count) {
  173. foreach ($agents as $agent) {
  174. $summary = $this->summaryForAgentIds([(int) $agent->id], $day, $day);
  175. AgentDailyStat::query()->updateOrCreate(
  176. ['stat_date' => $day, 'agent_id' => $agent->id],
  177. [
  178. 'direct_agents' => 0,
  179. 'direct_members' => $summary['member_count'],
  180. 'member_balance' => $summary['member_balance'],
  181. 'deposit_amount' => $summary['deposit_amount'],
  182. 'withdraw_amount' => $summary['withdraw_amount'],
  183. 'manual_credit' => $summary['manual_credit'],
  184. 'manual_debit' => $summary['manual_debit'],
  185. 'bonus_amount' => $summary['bonus_amount'],
  186. 'rebate_amount' => $summary['rebate_amount'],
  187. 'bet_amount' => $summary['bet_amount'],
  188. 'valid_bet_amount' => $summary['valid_bet_amount'],
  189. 'bet_count' => $summary['bet_count'],
  190. 'win_loss' => $summary['win_loss'],
  191. 'commission_amount' => $summary['commission_amount'],
  192. 'company_profit' => $summary['company_profit'],
  193. ]
  194. );
  195. $count++;
  196. }
  197. });
  198. return $count;
  199. }
  200. public function reportRows(?Agent $scope, array $params): array
  201. {
  202. $page = max(1, (int) ($params['page'] ?? 1));
  203. // 报表每行需要聚合整棵代理树;上线批量聚合前先限制单页,避免一次请求放大到上千条 SQL。
  204. $limit = min(20, max(1, (int) ($params['limit'] ?? 10)));
  205. $query = Agent::query();
  206. if ($scope) {
  207. $ids = $this->visibleAgentIds($scope);
  208. $query->whereIn('id', $ids);
  209. } else {
  210. // 总后台代理报表:不列出测试代理
  211. \App\Support\StatsScope::excludeTestAgents($query, 'id');
  212. }
  213. if (!empty($params['username'])) {
  214. $query->where('username', 'like', '%' . $params['username'] . '%');
  215. }
  216. $total = (clone $query)->count();
  217. $startDate = (string) ($params['start_date'] ?? now()->toDateString());
  218. $endDate = (string) ($params['end_date'] ?? $startDate);
  219. $list = $query->orderBy('id')->forPage($page, $limit)->get()->map(function (Agent $agent) use ($startDate, $endDate) {
  220. $row = $this->summaryForTree($agent, $startDate, $endDate);
  221. return array_merge([
  222. 'id' => (int) $agent->id,
  223. 'username' => $agent->username,
  224. 'real_name' => $agent->real_name,
  225. 'type' => (int) $agent->type,
  226. 'type_text' => $agent->type_text,
  227. 'balance' => (string) $agent->balance,
  228. 'frozen_balance' => (string) $agent->frozen_balance,
  229. ], $row);
  230. })->all();
  231. return compact('total', 'page', 'limit', 'list');
  232. }
  233. private function betSummary($members, $memberIds, Carbon $start, Carbon $end, bool $platform): array
  234. {
  235. $total = ['bet_count' => 0, 'bet_amount' => '0.0000', 'valid_bet_amount' => '0.0000', 'win_loss' => '0.0000'];
  236. $sources = [];
  237. if (Schema::hasTable('bets')) {
  238. $orders = DB::table('bets')->where('status', 2)->whereBetween('created_at', [$start, $end]);
  239. $sources[] = $this->scopedBetTotals($orders, 'member_id', clone $memberIds,
  240. 'COUNT(*) bet_count, SUM(amount) bet_amount, SUM(amount) valid_bet_amount, SUM(profit - amount) win_loss', $platform);
  241. }
  242. foreach (['sport_game_order', 'jisu_game_order'] as $table) {
  243. if (!Schema::hasTable($table)) {
  244. continue;
  245. }
  246. $orders = DB::table($table)->whereIn('status', [1, 2])->whereBetween('created_at', [$start, $end]);
  247. $sources[] = $this->scopedBetTotals($orders, 'member_id', clone $memberIds,
  248. 'COUNT(*) bet_count, SUM(amount) bet_amount, SUM(amount) valid_bet_amount, SUM(CASE WHEN status = 1 THEN -amount ELSE profit_and_loss END) win_loss', $platform);
  249. }
  250. if (Schema::hasTable('lhc_order')) {
  251. $amountExpression = Schema::hasColumn('lhc_order', 'total_amount') ? 'COALESCE(total_amount, amount)' : 'amount';
  252. $winLossExpression = '(COALESCE(win_amount, 0) - ' . $amountExpression . ')';
  253. $orders = DB::table('lhc_order')->whereIn('lottery_status', [1, 2])->whereBetween('created_at', [$start->timestamp, $end->timestamp]);
  254. $sources[] = $this->scopedBetTotals($orders, 'member_id', clone $memberIds,
  255. "COUNT(*) bet_count, SUM({$amountExpression}) bet_amount, SUM({$amountExpression}) valid_bet_amount, SUM({$winLossExpression}) win_loss", $platform);
  256. }
  257. if (Schema::hasTable('third_game_orders')) {
  258. $orders = DB::table('third_game_orders')->where('status', 1)->whereBetween('last_update_time', [$start, $end]);
  259. $sources[] = $this->scopedBetTotals($orders, 'user_id', (clone $members)->select('id'),
  260. 'COUNT(*) bet_count, SUM(bet_amount) bet_amount, SUM(valid_amount) valid_bet_amount, SUM(settled_amount) win_loss', $platform);
  261. }
  262. foreach ($sources as $row) {
  263. $total['bet_count'] += (int) ($row->bet_count ?? 0);
  264. foreach (['bet_amount', 'valid_bet_amount', 'win_loss'] as $field) {
  265. $total[$field] = bcadd($total[$field], (string) ($row->{$field} ?? 0), 4);
  266. }
  267. }
  268. return $total;
  269. }
  270. private function scopedBetTotals($orders, string $identity, $eligible, string $totals, bool $platform): object
  271. {
  272. if (!$platform) {
  273. return $orders->whereIn($identity, $eligible)->selectRaw($totals)->first();
  274. }
  275. // 全平台先汇总同一会员的注单,避免每笔注单都查询会员表。
  276. $byMember = $orders->whereNotNull($identity)->select($identity)->selectRaw($totals)->groupBy($identity);
  277. if ($identity === 'member_id' && $orders->getConnection()->getDriverName() === 'mysql') {
  278. // 旧注单表的字符排序规则可能不同,保留不同字节的会员号,仍按原规则匹配会员表。
  279. $byMember->groupByRaw('CAST(member_id AS BINARY)');
  280. }
  281. return DB::query()->fromSub($byMember, 'game_member_totals')->whereIn($identity, $eligible)
  282. ->selectRaw('SUM(bet_count) bet_count, SUM(bet_amount) bet_amount, SUM(valid_bet_amount) valid_bet_amount, SUM(win_loss) win_loss')->first();
  283. }
  284. private function emptySummary(): array
  285. {
  286. return [
  287. 'agent_count' => 0, 'member_count' => 0, 'member_balance' => '0.0000',
  288. 'deposit_amount' => '0.0000', 'withdraw_amount' => '0.0000',
  289. 'manual_credit' => '0.0000', 'manual_debit' => '0.0000',
  290. 'bonus_amount' => '0.0000', 'rebate_amount' => '0.0000',
  291. 'bet_count' => 0, 'bet_amount' => '0.0000', 'valid_bet_amount' => '0.0000',
  292. 'win_loss' => '0.0000', 'commission_amount' => '0.0000', 'company_profit' => '0.0000',
  293. ];
  294. }
  295. private function decimal($value): string
  296. {
  297. return bcadd((string) ($value ?? 0), '0', 4);
  298. }
  299. public function companyProfit(string $deposit, string $withdraw, string $bonus, string $rebate): string
  300. {
  301. return bcsub(bcsub($deposit, $withdraw, 4), bcadd($bonus, $rebate, 4), 4);
  302. }
  303. }