Agent.php 16 KB

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