Agent.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. <?php
  2. namespace App\Http\Controllers\admin;
  3. use App\Http\Controllers\AgentApiController;
  4. use App\Models\Agent\Agent as AgentModel;
  5. use App\Models\Agent\AgentCommission;
  6. use App\Models\Agent\AgentCommissionRule;
  7. use App\Models\Agent\AgentLoginLog;
  8. use App\Models\Agent\AgentWithdrawal;
  9. use App\Models\EgameItem;
  10. use App\Models\User;
  11. use App\Services\Agent\AgentCommissionService;
  12. use App\Services\Agent\AgentDomainService;
  13. use App\Services\Agent\AgentReportService;
  14. use App\Services\Agent\AgentService;
  15. use App\Services\Agent\AgentWalletService;
  16. use App\Services\Agent\AgentWithdrawalService;
  17. use Illuminate\Http\Request;
  18. use Illuminate\Validation\Rule;
  19. use Illuminate\Support\Facades\DB;
  20. use App\Rules\DecimalNumber;
  21. use App\Constants\Util;
  22. use App\Services\ThirdGameBalanceService;
  23. class Agent extends AgentApiController
  24. {
  25. public function index(Request $request, AgentDomainService $domains)
  26. {
  27. return $this->execute(function () use ($request, $domains) {
  28. $data = $request->validate([
  29. 'page' => ['nullable', 'integer', 'min:1'], 'limit' => ['nullable', 'integer', 'min:1', 'max:100'],
  30. 'username' => ['nullable', 'string', 'max:64'], 'real_name' => ['nullable', 'string', 'max:128'],
  31. 'parent_id' => ['nullable', 'integer'], 'status' => ['nullable', 'integer', 'in:0,1'],
  32. 'start_date' => ['nullable', 'date_format:Y-m-d'], 'end_date' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:start_date'],
  33. ]);
  34. $page = max(1, (int) ($data['page'] ?? 1));
  35. $limit = min(100, max(1, (int) ($data['limit'] ?? 20)));
  36. $query = AgentModel::query()->with(['parent:id,username', 'token:id,agent_id,expires_at,last_used_at'])->withCount(['children', 'members']);
  37. if (!empty($data['username'])) $query->where('username', 'like', '%' . $data['username'] . '%');
  38. if (!empty($data['real_name'])) $query->where('real_name', 'like', '%' . $data['real_name'] . '%');
  39. if (!empty($data['parent_id'])) $query->where('parent_id', $data['parent_id']);
  40. if (isset($data['status'])) $query->where('status', $data['status']);
  41. if (!empty($data['start_date'])) $query->where('created_at', '>=', $data['start_date'] . ' 00:00:00');
  42. if (!empty($data['end_date'])) $query->where('created_at', '<=', $data['end_date'] . ' 23:59:59');
  43. $total = (clone $query)->count();
  44. $list = $query->orderByDesc('id')->forPage($page, $limit)->get()->map(fn(AgentModel $agent) => $this->formatAgent($agent, $domains));
  45. return compact('total', 'page', 'limit', 'list');
  46. });
  47. }
  48. public function show(Request $request, AgentDomainService $domains)
  49. {
  50. return $this->execute(function () use ($request, $domains) {
  51. $data = $request->validate(['id' => ['required', 'integer', 'exists:agents,id']]);
  52. $agent = AgentModel::query()->with(['parent:id,username', 'token:id,agent_id,expires_at,last_used_at'])->withCount(['children', 'members'])->findOrFail($data['id']);
  53. return $this->formatAgent($agent, $domains);
  54. });
  55. }
  56. public function store(Request $request, AgentService $service)
  57. {
  58. return $this->execute(function () use ($request, $service) {
  59. $data = $request->validate($this->rules());
  60. return DB::transaction(function () use ($data, $service) {
  61. $agent = $service->create($data, (int) request()->user->id);
  62. if (bccomp((string) ($data['initial_balance'] ?? 0), '0', 4) > 0) {
  63. app(AgentWalletService::class)->adjust(
  64. (int) $agent->id,
  65. (string) $data['initial_balance'],
  66. 'credit',
  67. '新增代理初始额度',
  68. 'agent-initial:' . $agent->id,
  69. 'admin',
  70. (int) request()->user->id
  71. );
  72. $agent = $agent->fresh();
  73. }
  74. return $agent;
  75. });
  76. });
  77. }
  78. public function update(Request $request, AgentService $service)
  79. {
  80. return $this->execute(function () use ($request, $service) {
  81. $data = $request->validate(array_merge(['id' => ['required', 'integer', 'exists:agents,id']], $this->rules(true)));
  82. return $service->update(AgentModel::query()->findOrFail($data['id']), $data);
  83. });
  84. }
  85. public function domains(Request $request, AgentDomainService $service)
  86. {
  87. return $this->execute(function () use ($request, $service) {
  88. $data = $request->validate([
  89. 'id' => ['required', 'integer', 'exists:agents,id'],
  90. 'pc' => ['nullable', 'string', 'max:255'], 'h5' => ['nullable', 'string', 'max:255'],
  91. ]);
  92. return $service->save(AgentModel::query()->findOrFail($data['id']), $data);
  93. });
  94. }
  95. public function adjust(Request $request, AgentWalletService $wallets)
  96. {
  97. return $this->execute(function () use ($request, $wallets) {
  98. $data = $request->validate([
  99. 'agent_id' => ['required', 'integer', 'exists:agents,id'], 'type' => ['required', 'in:credit,debit'],
  100. 'amount' => ['required', 'numeric', 'min:0.0001', new DecimalNumber()], 'remark' => ['required', 'string', 'max:500'],
  101. 'request_id' => ['required', 'string', 'max:64'],
  102. ]);
  103. return $wallets->adjust(
  104. (int) $data['agent_id'], (string) $data['amount'], $data['type'], $data['remark'],
  105. 'admin:' . request()->user->id . ':' . $data['request_id'], 'admin', (int) request()->user->id
  106. );
  107. });
  108. }
  109. public function quota(Request $request, ThirdGameBalanceService $thirdGame)
  110. {
  111. return $this->execute(function () use ($request, $thirdGame) {
  112. $data = $request->validate([
  113. 'agent_id' => ['required', 'integer', 'exists:agents,id'],
  114. 'refresh' => ['nullable', 'boolean'],
  115. ]);
  116. $agent = AgentModel::query()->findOrFail($data['agent_id']);
  117. $provider = $thirdGame->agentBalances((int) $agent->id, $request->boolean('refresh'));
  118. if (empty($provider['ok'])) {
  119. throw new \RuntimeException((string) ($provider['msg'] ?? '三方平台余额查询失败'));
  120. }
  121. $balances = is_array($provider['balances'] ?? null) ? $provider['balances'] : [];
  122. $platforms = EgameItem::query()->where('item_type', EgameItem::TYPE_PLATFORM)->where('game_type', 0)
  123. ->where('status', EgameItem::STATUS_ENABLED)->orderByDesc('sort')->get(['plat_type', 'name', 'logo'])
  124. ->map(function (EgameItem $platform) use ($balances) {
  125. $key = strtolower((string) $platform->plat_type);
  126. $platform->logo = Util::ensureUrl($platform->logo);
  127. $platform->setAttribute('balance', $balances[$key] ?? '0.0000000000');
  128. $platform->setAttribute('account_opened', array_key_exists($key, $balances) ? 1 : 0);
  129. return $platform;
  130. });
  131. return [
  132. 'agent_id' => (int) $agent->id,
  133. 'player_id' => (string) $provider['player_id'],
  134. 'currency' => (string) $provider['currency'],
  135. 'balance' => (string) $agent->balance,
  136. 'frozen_balance' => (string) $agent->frozen_balance,
  137. 'quota_mode' => 'provider',
  138. 'provider_wallet_supported' => true,
  139. 'platforms' => $platforms,
  140. ];
  141. });
  142. }
  143. public function bindMember(Request $request)
  144. {
  145. return $this->execute(function () use ($request) {
  146. $data = $request->validate([
  147. 'user_id' => ['required', 'integer', 'exists:users,id'],
  148. 'agent_id' => ['nullable', 'integer', 'exists:agents,id'],
  149. ]);
  150. $user = User::query()->findOrFail($data['user_id']);
  151. $user->agent_id = $data['agent_id'] ?? null;
  152. $user->save();
  153. return ['user_id' => (int) $user->id, 'agent_id' => $user->agent_id === null ? null : (int) $user->agent_id];
  154. });
  155. }
  156. public function loginLogs(Request $request)
  157. {
  158. return $this->execute(function () use ($request) {
  159. $data = $request->validate([
  160. 'page' => ['nullable', 'integer', 'min:1'], 'limit' => ['nullable', 'integer', 'min:1', 'max:100'],
  161. 'agent_id' => ['nullable', 'integer'], 'username' => ['nullable', 'string', 'max:64'],
  162. 'ip' => ['nullable', 'string', 'max:64'], 'device' => ['nullable', 'in:mobile,pc'],
  163. 'start_date' => ['nullable', 'date_format:Y-m-d'], 'end_date' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:start_date'],
  164. ]);
  165. $query = AgentLoginLog::query();
  166. foreach (['agent_id', 'username', 'ip', 'device'] as $field) if (!empty($data[$field])) $query->where($field, $data[$field]);
  167. return $this->paginate($query, $data, 'login_at');
  168. });
  169. }
  170. public function withdrawals(Request $request)
  171. {
  172. return $this->execute(function () use ($request) {
  173. $data = $request->validate([
  174. 'page' => ['nullable', 'integer', 'min:1'], 'limit' => ['nullable', 'integer', 'min:1', 'max:100'],
  175. 'agent_id' => ['nullable', 'integer'], 'order_no' => ['nullable', 'string', 'max:40'],
  176. 'status' => ['nullable', 'in:pending,approved,rejected,paid'],
  177. 'start_date' => ['nullable', 'date_format:Y-m-d'], 'end_date' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:start_date'],
  178. ]);
  179. $query = AgentWithdrawal::query()->with('agent:id,username,real_name');
  180. foreach (['agent_id', 'order_no', 'status'] as $field) if (!empty($data[$field])) $query->where($field, $data[$field]);
  181. return $this->paginate($query, $data);
  182. });
  183. }
  184. public function auditWithdrawal(Request $request, AgentWithdrawalService $service)
  185. {
  186. return $this->execute(function () use ($request, $service) {
  187. $data = $request->validate([
  188. 'id' => ['required', 'integer', 'exists:agent_withdrawals,id'],
  189. 'action' => ['required', 'in:approve,reject,paid'], 'remark' => ['nullable', 'string', 'max:500'],
  190. ]);
  191. return $service->audit((int) $data['id'], $data['action'], (int) request()->user->id, (string) ($data['remark'] ?? ''));
  192. });
  193. }
  194. public function reports(Request $request, AgentReportService $reports)
  195. {
  196. return $this->execute(function () use ($request, $reports) {
  197. $data = $request->validate([
  198. 'page' => ['nullable', 'integer', 'min:1'], 'limit' => ['nullable', 'integer', 'min:1', 'max:20'],
  199. 'username' => ['nullable', 'string', 'max:64'], 'start_date' => ['required', 'date_format:Y-m-d'],
  200. 'end_date' => ['required', 'date_format:Y-m-d', 'after_or_equal:start_date'],
  201. ]);
  202. return $reports->reportRows(null, $data);
  203. });
  204. }
  205. public function commissionRules(Request $request)
  206. {
  207. return $this->execute(function () use ($request) {
  208. $data = $request->validate(['agent_id' => ['nullable', 'integer']]);
  209. return AgentCommissionRule::query()->with('agent:id,username')->when(!empty($data['agent_id']), fn($q) => $q->where('agent_id', $data['agent_id']))
  210. ->orderByDesc('effective_from')->get();
  211. });
  212. }
  213. public function saveFlowCommissionRule(Request $request, AgentCommissionService $commissions)
  214. {
  215. return $this->execute(function () use ($request, $commissions) {
  216. $data = $request->validate([
  217. 'agent_id' => ['required', 'integer', 'exists:agents,id'],
  218. 'flow_rate' => ['required', 'numeric', 'between:0,100', new DecimalNumber(3, 4)],
  219. 'effective_from' => ['required', 'date_format:Y-m-d', 'date_equals:' . now()->toDateString()],
  220. ]);
  221. return $commissions->saveFlowRate(AgentModel::query()->findOrFail($data['agent_id']), (string) $data['flow_rate'], $data['effective_from'], (int) request()->user->id);
  222. });
  223. }
  224. public function saveProfitCommissionRule(Request $request, AgentCommissionService $commissions)
  225. {
  226. return $this->execute(function () use ($request, $commissions) {
  227. $data = $request->validate([
  228. 'agent_id' => ['required', 'integer', 'exists:agents,id'],
  229. 'profit_rate' => ['required', 'numeric', 'between:0,100', new DecimalNumber(3, 4)],
  230. 'effective_from' => ['required', 'date_format:Y-m-d', 'date_equals:' . now()->toDateString()],
  231. ]);
  232. return $commissions->saveProfitRate(AgentModel::query()->findOrFail($data['agent_id']), (string) $data['profit_rate'], $data['effective_from'], (int) request()->user->id);
  233. });
  234. }
  235. public function commissions(Request $request)
  236. {
  237. return $this->execute(function () use ($request) {
  238. $data = $request->validate([
  239. 'page' => ['nullable', 'integer', 'min:1'], 'limit' => ['nullable', 'integer', 'min:1', 'max:100'],
  240. 'agent_id' => ['nullable', 'integer'], 'type' => ['nullable', 'in:flow,profit'], 'status' => ['nullable', 'in:pending,credited'],
  241. 'start_date' => ['nullable', 'date_format:Y-m-d'], 'end_date' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:start_date'],
  242. ]);
  243. $query = AgentCommission::query()->with('agent:id,username');
  244. foreach (['agent_id', 'type', 'status'] as $field) if (!empty($data[$field])) $query->where($field, $data[$field]);
  245. if (!empty($data['start_date'])) $query->where('settlement_date', '>=', $data['start_date']);
  246. if (!empty($data['end_date'])) $query->where('settlement_date', '<=', $data['end_date']);
  247. return $this->paginate($query, $data, 'settlement_date', false);
  248. });
  249. }
  250. private function rules(bool $update = false): array
  251. {
  252. return [
  253. 'username' => $update
  254. ? ['sometimes', 'string', 'min:4', 'max:64', 'alpha_dash', Rule::unique('agents', 'username')->ignore((int) request()->input('id'))]
  255. : ['required', 'string', 'min:4', 'max:64', 'alpha_dash', 'unique:agents,username'],
  256. 'password' => [$update ? 'nullable' : 'required', 'string', 'min:6', 'max:100'],
  257. 'withdraw_password' => ['nullable', 'string', 'min:6', 'max:100'], 'real_name' => ['nullable', 'string', 'max:128'],
  258. 'parent_id' => ['nullable', 'integer', 'exists:agents,id'], 'deposit_fee_rate' => ['nullable', 'numeric', 'between:0,100', new DecimalNumber(3, 4)],
  259. 'withdraw_fee_rate' => ['nullable', 'numeric', 'between:0,100', new DecimalNumber(3, 4)],
  260. 'flow_commission_rate' => $update ? ['prohibited'] : ['nullable', 'numeric', 'between:0,100', new DecimalNumber(3, 4)],
  261. 'profit_commission_rate' => $update ? ['prohibited'] : ['nullable', 'numeric', 'between:0,100', new DecimalNumber(3, 4)],
  262. 'status' => ['nullable', 'integer', 'in:0,1'],
  263. 'initial_balance' => $update ? ['prohibited'] : ['nullable', 'numeric', 'min:0', new DecimalNumber()],
  264. ];
  265. }
  266. private function paginate($query, array $data, string $orderBy = 'id', bool $filterCreatedAt = true): array
  267. {
  268. $page = max(1, (int) ($data['page'] ?? 1));
  269. $limit = min(100, max(1, (int) ($data['limit'] ?? 20)));
  270. if ($filterCreatedAt && !empty($data['start_date'])) $query->where('created_at', '>=', $data['start_date'] . ' 00:00:00');
  271. if ($filterCreatedAt && !empty($data['end_date'])) $query->where('created_at', '<=', $data['end_date'] . ' 23:59:59');
  272. $total = (clone $query)->count();
  273. $list = $query->orderByDesc($orderBy)->orderByDesc('id')->forPage($page, $limit)->get();
  274. return compact('total', 'page', 'limit', 'list');
  275. }
  276. private function formatAgent(AgentModel $agent, AgentDomainService $domains): array
  277. {
  278. $token = $agent->token;
  279. $online = $token
  280. && $token->expires_at->isFuture()
  281. && $token->last_used_at
  282. && $token->last_used_at->gte(now()->subMinutes(config('agent.online_minutes', 5)));
  283. $data = $agent->toArray();
  284. unset($data['token']);
  285. return array_merge($data, $domains->format($agent), [
  286. 'login_status' => $online ? 1 : 0,
  287. 'login_status_text' => $online ? '在线' : '离线',
  288. 'last_active_at' => $token?->last_used_at?->toDateTimeString(),
  289. ]);
  290. }
  291. }