Agent.php 19 KB

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