AgentController.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Facade\TableName;
  4. use App\Game\Services\OuroGameService;
  5. use App\Http\Controllers\Controller;
  6. use App\Http\helper\NumConfig;
  7. use App\Models\AccountsInfo;
  8. use App\Models\AgentDepositCommission;
  9. use App\Models\AgentLevel;
  10. use App\Models\AgentMaterial;
  11. use App\Models\AgentTask;
  12. use App\Models\AgentUserInfo;
  13. use App\Models\AgentUserRecord;
  14. use App\Models\AgentUserReward;
  15. use App\Models\AgentUserTaskCompletion;
  16. use App\Models\User;
  17. use App\Models\AgentWithdrawal;
  18. use Carbon\Carbon;
  19. use Illuminate\Http\Request;
  20. use Illuminate\Support\Facades\DB;
  21. use Illuminate\Support\Facades\Log;
  22. use Illuminate\Support\Facades\Validator;
  23. use Illuminate\Support\Str;
  24. class AgentController extends Controller
  25. {
  26. /**
  27. * 获取当前用户的代理信息
  28. */
  29. public function getInfo(Request $request)
  30. {
  31. $userId = $request->UserID;
  32. // 获取代理信息
  33. $agentInfo = AgentUserInfo::where('UserID', $userId)->first();
  34. if (!$agentInfo) {
  35. // 如果用户没有代理信息,创建一个新的
  36. $agentInfo = $this->createAgentInfo($userId);
  37. }
  38. // 获取用户的级别信息
  39. $levelInfo = AgentLevel::where('level', $agentInfo->level)->first();
  40. // $levelInfo = $agentInfo->agentLevel();
  41. // 获取下级用户数量
  42. $referralCount = AgentUserRecord::where('SpreaderID', $userId)
  43. ->where('is_valid', 1)
  44. ->count();
  45. $total_friends = AgentUserRecord::where('SpreaderID', $userId)
  46. ->count();
  47. //更新玩家
  48. if($total_friends!=$agentInfo->total_friends){
  49. $agentInfo->total_friends = $total_friends;
  50. $agentInfo->save();
  51. }
  52. //升级逻辑
  53. if($referralCount != $agentInfo->valid_referrals){
  54. // 更新有效邀请人数
  55. $agentInfo->valid_referrals = $referralCount;
  56. $agentInfo->save();
  57. // 检查并更新用户级别
  58. $this->updateUserLevel($userId);
  59. // 检查任务完成情况
  60. // $this->checkTaskCompletion($userId);
  61. }
  62. // 获取任务完成情况
  63. $completedTasks = AgentUserTaskCompletion::where('UserID', $userId)
  64. ->where('completed', 1)
  65. ->pluck('task_id')
  66. ->toArray();
  67. // 获取所有任务
  68. $allTasks = AgentTask::where('status', 1)
  69. ->orderBy('required_referrals')
  70. ->get();
  71. $tasks = [];
  72. foreach ($allTasks as $task) {
  73. $completed = in_array($task->id, $completedTasks);
  74. $canClaim = $agentInfo->valid_referrals >= $task->required_referrals && !$completed;
  75. $tasks[] = [
  76. 'id' => $task->id,
  77. 'taskid' => $task->taskid,
  78. 'title' => $task->task_title,
  79. 'required_referrals' => $task->required_referrals,
  80. 'reward_amount' => $task->reward_amount,
  81. 'completed' => $completed,
  82. 'progress' => min($referralCount, $task->required_referrals),
  83. 'total' => $task->required_referrals,
  84. 'can_claim' => $canClaim
  85. ];
  86. }
  87. // 获取今日和昨日佣金
  88. // $todayCommission = $agentInfo->today_commission;
  89. // $yesterdayCommission = $agentInfo->yesterday_commission;
  90. // $totalCommission = $agentInfo->total_commission;
  91. // 获取下一级别
  92. $nextLevel = null;
  93. if ($levelInfo->level < 6) { // 假设6是最高级别
  94. $nextLevel = AgentLevel::where('level', $levelInfo->level + 1)->first();
  95. }
  96. return apiReturnSuc([
  97. 'user_id' => $userId,
  98. 'referral_code' => $agentInfo->referral_code,
  99. 'referral_link' => env('SHARE_BASE_URL').'/'.$agentInfo->referral_code.'?ad='.rand(1,3),
  100. 'level' => [
  101. 'name' => $levelInfo->level_name,
  102. 'level' => $levelInfo->level,
  103. 'commission_rate' => $levelInfo->commission_rate . '%',
  104. ],
  105. 'next_level' => $nextLevel ? [
  106. 'name' => $nextLevel->level_name,
  107. 'level' => $nextLevel->level,
  108. 'required_referrals' => $nextLevel->required_referrals,
  109. 'commission_rate' => $nextLevel->commission_rate . '%',
  110. ] : null,
  111. 'statistics' => $agentInfo,
  112. 'tasks' => $tasks,
  113. 'progress' => [
  114. 'current' => $agentInfo->valid_referrals,
  115. 'next_target' => $nextLevel ? $nextLevel->required_referrals : null,
  116. ],
  117. 'share_materials'=>[
  118. 'text'=>AgentMaterial::where('type',2)->where('status',1)->value('content'),
  119. 'imgs'=>AgentMaterial::select('photo','title','content')->where('type',1)->where('status',1)->get(),
  120. ],
  121. 'withdraws'=>$this->getRecentWithdrawals()
  122. ]
  123. );
  124. }
  125. /**
  126. * 创建用户的代理信息
  127. */
  128. private function createAgentInfo($userId)
  129. {
  130. try {
  131. // 生成唯一邀请码
  132. $referralCode = $this->generateReferralCode($userId);
  133. // 创建代理信息
  134. $agentInfo = new AgentUserInfo();
  135. $agentInfo->UserID = $userId;
  136. $agentInfo->referral_code = $referralCode;
  137. $agentInfo->level = 1; // 默认级别为1
  138. $agentInfo->valid_referrals = 0;
  139. $agentInfo->total_commission = 0;
  140. $agentInfo->today_commission = 0;
  141. $agentInfo->yesterday_commission = 0;
  142. $agentInfo->save();
  143. return $agentInfo;
  144. }catch (\Exception $e){
  145. // 检查是否已存在代理信息
  146. return AgentUserInfo::where('UserID', $userId)->first();
  147. }
  148. }
  149. /**
  150. * 生成唯一的推广码
  151. */
  152. private function generateReferralCode($userId)
  153. {
  154. $baseCode = base_convert($userId, 10, 36); // 将用户ID转换为36进制
  155. $code = strtoupper(substr($baseCode, 0, 6)); // 截取前6位并转为大写
  156. // 确保唯一性
  157. while (AgentUserInfo::where('referral_code', $code)->exists()) {
  158. $random = Str::random(3);
  159. $code = strtoupper(substr($baseCode, 0, 3) . $random);
  160. }
  161. return $code;
  162. }
  163. /**
  164. * 获取用户的邀请记录
  165. */
  166. public function getReferrals(Request $request)
  167. {
  168. $userId = $request->UserID;
  169. $page = $request->input('page', 1);
  170. $perPage = $request->input('per_page', 20);
  171. // 获取所有下级用户
  172. $referrals = AgentUserRecord::where('SpreaderID', $userId)
  173. ->orderBy('created_at', 'desc')
  174. ->paginate($perPage, ['*'], 'page', $page);
  175. $items = [];
  176. foreach ($referrals as $referral) {
  177. $items[] = [
  178. 'user_id' => $referral->UserID,
  179. 'username' => AccountsInfo::find($referral->UserID)->NickName,
  180. 'register_time' => $referral->created_at,
  181. 'is_valid' => (bool)$referral->is_valid,
  182. 'valid_time' => $referral->valid_at,
  183. ];
  184. }
  185. return apiReturnSuc([
  186. 'total' => $referrals->total(),
  187. 'per_page' => $referrals->perPage(),
  188. 'current_page' => $referrals->currentPage(),
  189. 'last_page' => $referrals->lastPage(),
  190. 'items' => $items
  191. ]
  192. );
  193. }
  194. /**
  195. * 获取用户的佣金记录
  196. */
  197. public function getCommissions(Request $request)
  198. {
  199. $userId = $request->UserID;
  200. $page = $request->input('page', 1);
  201. $perPage = $request->input('per_page', 20);
  202. // 获取佣金记录
  203. $commissions = AgentDepositCommission::where('SpreaderID', $userId)
  204. ->orderBy('created_at', 'desc')
  205. ->paginate($perPage, ['*'], 'page', $page);
  206. $items = [];
  207. foreach ($commissions as $commission) {
  208. $items[] = [
  209. 'id' => $commission->id,
  210. 'user_id' => $commission->UserID,
  211. 'username' => AccountsInfo::find($commission->UserID)->NickName,
  212. 'order_sn' => $commission->order_sn,
  213. 'deposit_amount' => $commission->deposit_amount,
  214. 'commission_rate' => $commission->commission_rate . '%',
  215. 'commission_amount' => $commission->commission_amount,
  216. 'status' => $commission->status,
  217. 'created_at' => $commission->created_at,
  218. ];
  219. }
  220. return apiReturnSuc([
  221. 'total' => $commissions->total(),
  222. 'per_page' => $commissions->perPage(),
  223. 'current_page' => $commissions->currentPage(),
  224. 'last_page' => $commissions->lastPage(),
  225. 'items' => $items
  226. ]
  227. );
  228. }
  229. /**
  230. * 获取宣传素材
  231. */
  232. public function getMaterials(Request $request)
  233. {
  234. // 获取所有活跃的素材
  235. $materials = AgentMaterial::where('status', 1)
  236. ->where('type', 1)
  237. ->orderBy('sort_order')
  238. ->get();
  239. $items = [];
  240. foreach ($materials as $material) {
  241. $items[] = [
  242. 'photo' => $material->photo,
  243. 'title' => $material->title,
  244. 'content' => $material->content,
  245. ];
  246. }
  247. return apiReturnSuc($items);
  248. }
  249. /**
  250. * 获取用户的任务列表
  251. */
  252. public function getTasks(Request $request)
  253. {
  254. $userId = $request->UserID;
  255. // 获取代理信息
  256. $agentInfo = AgentUserInfo::where('UserID', $userId)->first();
  257. if (!$agentInfo) {
  258. return apiReturnFail('Agent information not found');
  259. }
  260. // 获取任务完成情况
  261. $completedTasks = AgentUserTaskCompletion::where('UserID', $userId)
  262. ->where('completed', 1)
  263. ->pluck('task_id')
  264. ->toArray();
  265. // 获取所有任务
  266. $allTasks = AgentTask::where('status', 1)
  267. ->orderBy('required_referrals')
  268. ->get();
  269. $tasks = [];
  270. foreach ($allTasks as $task) {
  271. $completed = in_array($task->id, $completedTasks);
  272. // 判断任务是否可领取:必须满足要求且未完成
  273. $canClaim = $agentInfo->valid_referrals >= $task->required_referrals && !$completed;
  274. $tasks[] = [
  275. 'id' => $task->id,
  276. 'taskid' => $task->taskid,
  277. 'title' => $task->task_title,
  278. 'required_referrals' => $task->required_referrals,
  279. 'reward_amount' => $task->reward_amount,
  280. 'completed' => $completed,
  281. 'progress' => min($agentInfo->valid_referrals, $task->required_referrals),
  282. 'total' => $task->required_referrals,
  283. 'can_claim' => $canClaim
  284. ];
  285. }
  286. return apiReturnSuc($tasks);
  287. }
  288. /**
  289. * 领取任务奖励
  290. */
  291. public function claimTaskReward(Request $request)
  292. {
  293. $userId = $request->UserID;
  294. $taskId = $request->input('task_id');
  295. // 验证任务ID
  296. $task = AgentTask::find($taskId);
  297. if (!$task || $task->status != 1) {
  298. return apiReturnFail('Invalid task');
  299. }
  300. // 获取代理信息
  301. $agentInfo = AgentUserInfo::where('UserID', $userId)->first();
  302. if (!$agentInfo) {
  303. return apiReturnFail('Agent information not found');
  304. }
  305. // 检查是否有足够的有效邀请人数
  306. if ($agentInfo->valid_referrals < $task->required_referrals) {
  307. return apiReturnFail('Not enough valid referrals');
  308. }
  309. // 检查任务是否已完成
  310. $taskCompletion = AgentUserTaskCompletion::where('UserID', $userId)
  311. ->where('task_id', $taskId)
  312. ->first();
  313. if ($taskCompletion && $taskCompletion->completed) {
  314. return apiReturnFail('Task already completed');
  315. }
  316. try {
  317. DB::beginTransaction();
  318. // 标记任务为已完成
  319. if (!$taskCompletion) {
  320. $taskCompletion = new AgentUserTaskCompletion();
  321. $taskCompletion->UserID = $userId;
  322. $taskCompletion->task_id = $taskId;
  323. $taskCompletion->taskid = $task->taskid;
  324. }
  325. $taskCompletion->completed = 1;
  326. $taskCompletion->completed_at = now();
  327. $taskCompletion->save();
  328. // 创建奖励记录
  329. $reward = new AgentUserReward();
  330. $reward->UserID = $userId;
  331. $reward->reward_type = 1; // 任务奖励
  332. $reward->source_id = $taskId;
  333. $reward->taskid = $task->taskid;
  334. $reward->amount = $task->reward_amount;
  335. $reward->remark = 'Completed invitation task reward: ' . $task->task_title;
  336. $reward->status = 1; // 已发放
  337. $reward->save();
  338. // 更新用户可提现余额
  339. $agentInfo->now_rewards += $task->reward_amount;
  340. $agentInfo->save();
  341. DB::commit();
  342. return apiReturnSuc([
  343. 'reward_amount' => $task->reward_amount,
  344. 'task_title' => $task->task_title
  345. ], '','Task reward claimed successfully');
  346. } catch (\Exception $e) {
  347. DB::rollBack();
  348. Log::error('Error claiming task reward: ' . $e->getMessage());
  349. return apiReturnFail('Failed to claim task reward');
  350. }
  351. }
  352. /**
  353. * 处理用户注册通过邀请码
  354. * 此方法需要在用户注册流程中调用
  355. */
  356. public function processReferral($newUserId, $referralCode)
  357. {
  358. // 查找邀请码对应的推广者
  359. $spreader = AgentUserInfo::where('referral_code', $referralCode)->first();
  360. if (!$spreader) {
  361. return false;
  362. }
  363. if($spreader->UserID==$newUserId)return false;
  364. // 创建邀请记录
  365. $referral = new AgentUserRecord();
  366. $referral->SpreaderID = $spreader->UserID;
  367. $referral->UserID = $newUserId;
  368. $referral->is_valid = 0; // 初始设为无效,需等待首次充值
  369. $referral->save();
  370. return $spreader;
  371. }
  372. /**
  373. * 处理用户充值后的佣金计算
  374. * 此方法需要在用户充值成功后调用
  375. */
  376. public function processDeposit($userId, $amount, $orderSn)
  377. {
  378. // 查找该用户的邀请记录
  379. $referral = AgentUserRecord::where('UserID', $userId)->first();
  380. if (!$referral) {
  381. return false; // 没有邀请关系
  382. }
  383. $spreaderId = $referral->SpreaderID;
  384. $isValid = $referral->is_valid;
  385. // 检查是否需要将邀请关系标记为有效(累计充值金额达到Rs200)
  386. if (!$isValid) {
  387. // 检查用户总充值金额
  388. $totalDeposit=DB::table('QPAccountsDB.dbo.YN_VIPAccount')->where('UserID', $userId)->value('Recharge') ?? 0;
  389. $totalDeposit += $amount; // 这里应加上用户历史充值
  390. if ($totalDeposit >= 200) {
  391. // 更新邀请记录为有效
  392. $referral->is_valid = 1;
  393. $referral->valid_at = now();
  394. $referral->save();
  395. // 更新邀请人的有效邀请数
  396. $spreaderInfo = AgentUserInfo::where('UserID', $spreaderId)->first();
  397. if ($spreaderInfo) {
  398. $spreaderInfo->valid_referrals += 1;
  399. $spreaderInfo->save();
  400. // 检查并更新邀请人的级别
  401. $this->updateUserLevel($spreaderId);
  402. // 检查任务完成情况
  403. // $this->checkTaskCompletion($spreaderId);
  404. }
  405. }
  406. }
  407. // 计算佣金
  408. $spreaderInfo = AgentUserInfo::where('UserID', $spreaderId)->first();
  409. if (!$spreaderInfo) {
  410. return false;
  411. }
  412. $levelInfo = AgentLevel::where('level', $spreaderInfo->level)->first();
  413. $commissionRate = $levelInfo ? $levelInfo->commission_rate : 0;
  414. $commissionAmount = $amount * ($commissionRate / 100);
  415. // 记录佣金
  416. $commission = new AgentDepositCommission();
  417. $commission->SpreaderID = $spreaderId;
  418. $commission->UserID = $userId;
  419. $commission->order_sn = $orderSn;
  420. $commission->deposit_amount = $amount;
  421. $commission->commission_rate = $commissionRate;
  422. $commission->commission_amount = $commissionAmount;
  423. $commission->status = 1; // 已发放
  424. $commission->save();
  425. // 更新用户佣金统计
  426. $spreaderInfo->total_commission += $commissionAmount;
  427. $spreaderInfo->today_commission += $commissionAmount;
  428. $spreaderInfo->now_rewards += $commissionAmount;
  429. $spreaderInfo->save();
  430. $agentInfo = AgentUserInfo::where('UserID', $spreaderId)->first();
  431. $agentInfo->now_rewards += $commissionAmount;
  432. $agentInfo->total_rewards += $commissionAmount;
  433. $agentInfo->save();
  434. return true;
  435. }
  436. /**
  437. * 更新用户的级别
  438. */
  439. private function updateUserLevel($userId)
  440. {
  441. // 获取用户当前有效邀请人数
  442. $agentInfo = AgentUserInfo::where('UserID', $userId)->first();
  443. if (!$agentInfo) {
  444. return false;
  445. }
  446. $validReferrals = $agentInfo->valid_referrals;
  447. // 找到对应的新级别
  448. $newLevel = AgentLevel::where('required_referrals', '<=', $validReferrals)
  449. ->orderByDesc('required_referrals')
  450. ->first();
  451. if ($newLevel && $newLevel->level != $agentInfo->level) {
  452. $agentInfo->level = $newLevel->level;
  453. $agentInfo->save();
  454. // 这里可以添加级别提升的通知逻辑
  455. return true;
  456. }
  457. return false;
  458. }
  459. /**
  460. * 检查用户任务完成情况
  461. */
  462. private function checkTaskCompletion($userId)
  463. {
  464. // 获取用户当前有效邀请人数
  465. $agentInfo = AgentUserInfo::where('UserID', $userId)->first();
  466. if (!$agentInfo) {
  467. return false;
  468. }
  469. $validReferrals = $agentInfo->valid_referrals;
  470. // 按照required_referrals升序获取所有任务,确保先处理要求少的任务
  471. $allTasks = AgentTask::where('status', 1)
  472. ->orderBy('required_referrals')
  473. ->get();
  474. // 获取用户已完成的任务ID
  475. $completedTaskIds = AgentUserTaskCompletion::where('UserID', $userId)
  476. ->where('completed', 1)
  477. ->pluck('task_id')
  478. ->toArray();
  479. // 检查每个任务是否应该完成
  480. foreach ($allTasks as $task) {
  481. // 如果有效邀请人数达到或超过任务要求
  482. if ($validReferrals >= $task->required_referrals) {
  483. // 检查该任务是否已经标记为完成
  484. if (!in_array($task->id, $completedTaskIds)) {
  485. // 创建或更新任务完成记录
  486. $completion = AgentUserTaskCompletion::firstOrNew([
  487. 'UserID' => $userId,
  488. 'task_id' => $task->id
  489. ]);
  490. $completion->taskid = $task->taskid;
  491. // $completion->completed = 1;
  492. // $completion->completed_at = now();
  493. // $completion->save();
  494. }
  495. }
  496. }
  497. return true;
  498. }
  499. /**
  500. * 每日重置佣金统计
  501. * 此方法应该通过计划任务每天调用一次
  502. */
  503. public function resetDailyCommission()
  504. {
  505. try {
  506. AgentUserInfo::query()->where('today_commission','<>',0)->orWhere('yesterday_commission','<>',0)->update([
  507. 'yesterday_commission' => DB::raw('today_commission'),
  508. 'today_commission' => 0
  509. ]);
  510. return apiReturnSuc([], 'Daily commission reset successfully');
  511. } catch (\Exception $e) {
  512. Log::error('Error resetting daily commission: ' . $e->getMessage());
  513. return apiReturnFail('Failed to reset daily commission');
  514. }
  515. }
  516. /**
  517. * 申请提现
  518. */
  519. public function requestWithdrawal(Request $request)
  520. {
  521. $userId = $request->UserID;
  522. $amount = floatval($request->input('amount'));
  523. // 验证提现金额
  524. if ($amount <= 0) {
  525. return apiReturnFail('Invalid withdrawal amount');
  526. }
  527. // 获取用户的代理信息
  528. $agentInfo = AgentUserInfo::where('UserID', $userId)->first();
  529. if (!$agentInfo) {
  530. return apiReturnFail('Agent information not found');
  531. }
  532. // 验证用户是否有足够的余额
  533. if ($agentInfo->now_rewards < $amount) {
  534. return apiReturnFail('Insufficient balance for withdrawal', ['balance' => $agentInfo->now_rewards]);
  535. }
  536. // 检查是否有未处理的提现请求
  537. $pendingWithdrawal = AgentWithdrawal::where('UserID', $userId)
  538. ->where('status', AgentWithdrawal::STATUS_PENDING)
  539. ->first();
  540. if ($pendingWithdrawal) {
  541. return apiReturnFail('You already have a pending withdrawal request');
  542. }
  543. //把钱存到用户账户里
  544. // 更新用户余额
  545. $agentInfo->now_rewards -= $amount;
  546. $agentInfo->save();
  547. OuroGameService::AddScore($userId,$amount*NumConfig::NUM_VALUE,OuroGameService::REASON_AgentWithDraw);
  548. OuroGameService::AddDrawBase($userId,$amount*NumConfig::NUM_VALUE,OuroGameService::REASON_AgentWithDraw);
  549. try {
  550. // 开始事务
  551. // DB::beginTransaction();
  552. // 生成订单号
  553. $orderSn = AgentWithdrawal::generateOrderSn();
  554. // 创建提现记录
  555. $withdrawal = new AgentWithdrawal();
  556. $withdrawal->UserID = $userId;
  557. $withdrawal->amount = $amount;
  558. $withdrawal->before_balance = $agentInfo->now_rewards+$amount;
  559. $withdrawal->after_balance = $agentInfo->now_rewards;
  560. $withdrawal->status = AgentWithdrawal::STATUS_COMPLETED;
  561. $withdrawal->order_sn = $orderSn;
  562. $withdrawal->save();
  563. // 更新用户余额
  564. // $agentInfo->now_rewards -= $amount;
  565. // $agentInfo->save();
  566. //
  567. // // 提交事务
  568. // DB::commit();
  569. //
  570. // return apiReturnSuc([
  571. // 'withdrawal_id' => $withdrawal->id,
  572. // 'order_sn' => $orderSn,
  573. // 'amount' => $amount,
  574. // 'status' => 'Completed',
  575. // 'current_balance' => $agentInfo->now_rewards
  576. // ], 'Withdrawal request submitted successfully');
  577. } catch (\Exception $e) {
  578. // 回滚事务
  579. // DB::rollBack();
  580. Log::error('Error processing withdrawal: ' . $e->getMessage());
  581. // return apiReturnFail('Failed to process withdrawal request');
  582. }
  583. return apiReturnSuc($agentInfo);
  584. }
  585. /**
  586. * 获取提现历史记录
  587. */
  588. public function getWithdrawalHistory(Request $request)
  589. {
  590. $userId = $request->UserID;
  591. $page = $request->input('page', 1);
  592. $perPage = $request->input('per_page', 20);
  593. // 获取用户的提现记录
  594. $withdrawals = AgentWithdrawal::where('UserID', $userId)
  595. ->orderBy('created_at', 'desc')
  596. ->paginate($perPage, ['*'], 'page', $page);
  597. $items = [];
  598. foreach ($withdrawals as $withdrawal) {
  599. $items[] = [
  600. 'id' => $withdrawal->id,
  601. 'order_sn' => $withdrawal->order_sn,
  602. 'amount' => $withdrawal->amount,
  603. 'status' => $withdrawal->status_text,
  604. 'status_code' => $withdrawal->status,
  605. 'remarks' => $withdrawal->remarks,
  606. 'created_at' => $withdrawal->created_at->format('Y-m-d H:i:s'),
  607. 'process_time' => $withdrawal->process_time ? $withdrawal->process_time->format('Y-m-d H:i:s') : null
  608. ];
  609. }
  610. return apiReturnSuc([
  611. 'total' => $withdrawals->total(),
  612. 'per_page' => $withdrawals->perPage(),
  613. 'current_page' => $withdrawals->currentPage(),
  614. 'last_page' => $withdrawals->lastPage(),
  615. 'items' => $items
  616. ]);
  617. }
  618. /**
  619. * 获取可提现金额
  620. */
  621. public function getWithdrawalBalance(Request $request)
  622. {
  623. $userId = $request->UserID;
  624. // 获取用户的代理信息
  625. $agentInfo = AgentUserInfo::where('UserID', $userId)->first();
  626. if (!$agentInfo) {
  627. return apiReturnFail('Agent information not found');
  628. }
  629. return apiReturnSuc([
  630. 'available_balance' => $agentInfo->now_rewards,
  631. 'total_withdrawn' => $agentInfo->withdraw_rewards,
  632. 'total_commission' => $agentInfo->total_commission,
  633. 'min_withdrawal' => 100, // 最小提现金额,可根据系统设置调整
  634. 'withdrawal_fee' => 4 // 提现手续费,可根据系统设置调整
  635. ]);
  636. }
  637. /**
  638. * 取消提现申请(仅处理中的可取消)
  639. */
  640. public function cancelWithdrawal(Request $request)
  641. {
  642. $userId = $request->UserID;
  643. $withdrawalId = $request->input('withdrawal_id');
  644. // 查找提现记录
  645. $withdrawal = AgentWithdrawal::where('id', $withdrawalId)
  646. ->where('UserID', $userId)
  647. ->where('status', AgentWithdrawal::STATUS_PENDING)
  648. ->first();
  649. if (!$withdrawal) {
  650. return apiReturnFail('Withdrawal request not found or cannot be cancelled');
  651. }
  652. try {
  653. // 开始事务
  654. DB::beginTransaction();
  655. // 获取用户的代理信息
  656. $agentInfo = AgentUserInfo::where('UserID', $userId)->first();
  657. if (!$agentInfo) {
  658. return apiReturnFail('Agent information not found');
  659. }
  660. // 更新提现状态
  661. $withdrawal->status = AgentWithdrawal::STATUS_REJECTED;
  662. $withdrawal->remarks = 'Cancelled by user';
  663. $withdrawal->process_time = now();
  664. $withdrawal->save();
  665. // 返还金额到用户余额
  666. $agentInfo->now_rewards += $withdrawal->amount;
  667. $agentInfo->save();
  668. // 提交事务
  669. DB::commit();
  670. return apiReturnSuc([
  671. 'withdrawal_id' => $withdrawal->id,
  672. 'current_balance' => $agentInfo->now_rewards
  673. ], 'Withdrawal cancelled successfully');
  674. } catch (\Exception $e) {
  675. // 回滚事务
  676. DB::rollBack();
  677. Log::error('Error cancelling withdrawal: ' . $e->getMessage());
  678. return apiReturnFail('Failed to cancel withdrawal request');
  679. }
  680. }
  681. /**
  682. * 管理员处理提现请求(仅限后台管理员使用)
  683. */
  684. public function processWithdrawal(Request $request)
  685. {
  686. // 这个方法通常在管理后台使用,此处仅提供参考实现
  687. $withdrawalId = $request->input('withdrawal_id');
  688. $action = $request->input('action'); // approve 或 reject
  689. $remarks = $request->input('remarks', '');
  690. $adminId = $request->input('admin_id');
  691. $adminName = $request->input('admin_name');
  692. // 查找提现记录
  693. $withdrawal = AgentWithdrawal::where('id', $withdrawalId)
  694. ->where('status', AgentWithdrawal::STATUS_PENDING)
  695. ->first();
  696. if (!$withdrawal) {
  697. return apiReturnFail('Withdrawal request not found or already processed');
  698. }
  699. try {
  700. // 开始事务
  701. DB::beginTransaction();
  702. // 获取用户的代理信息
  703. $agentInfo = AgentUserInfo::where('UserID', $withdrawal->UserID)->first();
  704. if (!$agentInfo) {
  705. return apiReturnFail('Agent information not found');
  706. }
  707. if ($action === 'approve') {
  708. // 审核通过
  709. $withdrawal->status = AgentWithdrawal::STATUS_COMPLETED;
  710. $withdrawal->remarks = $remarks ?: 'Approved';
  711. // 更新用户提现总额
  712. $agentInfo->withdraw_rewards += $withdrawal->amount;
  713. $agentInfo->save();
  714. } elseif ($action === 'reject') {
  715. // 拒绝提现
  716. $withdrawal->status = AgentWithdrawal::STATUS_REJECTED;
  717. $withdrawal->remarks = $remarks ?: 'Rejected';
  718. // 返还金额到用户余额
  719. $agentInfo->now_rewards += $withdrawal->amount;
  720. $agentInfo->save();
  721. } else {
  722. return apiReturnFail('Invalid action');
  723. }
  724. // 更新处理信息
  725. $withdrawal->admin_id = $adminId;
  726. $withdrawal->admin_name = $adminName;
  727. $withdrawal->process_time = now();
  728. $withdrawal->save();
  729. // 提交事务
  730. DB::commit();
  731. return apiReturnSuc([
  732. 'withdrawal_id' => $withdrawal->id,
  733. 'status' => $withdrawal->status_text,
  734. 'user_id' => $withdrawal->UserID,
  735. 'amount' => $withdrawal->amount
  736. ], 'Withdrawal processed successfully');
  737. } catch (\Exception $e) {
  738. // 回滚事务
  739. DB::rollBack();
  740. Log::error('Error processing withdrawal: ' . $e->getMessage());
  741. return apiReturnFail('Failed to process withdrawal request');
  742. }
  743. }
  744. /**
  745. * 获取近期提现成功记录(用于首页等公开展示)
  746. */
  747. public function getRecentWithdrawals()
  748. {
  749. $recents=DB::table('QPAccountsDB.dbo.OrderWithDraw')->orderByDesc('RecordID')->limit(50)->get();
  750. $result=[];
  751. // 限制返回记录数量
  752. foreach ($recents as $withdrawal){
  753. $nickname=$withdrawal->BankUserName;
  754. $length = mb_strlen($nickname);
  755. if ($length > 6) {
  756. $maskedNickname = mb_substr($nickname, 0, 3) . '***' . mb_substr($nickname, -2);
  757. } else {
  758. $maskedNickname = mb_substr($nickname, 0, 1) . '***' . mb_substr($nickname, -1);
  759. }
  760. $phone=$withdrawal->PhoneNumber;
  761. $phone = mb_substr($phone, 0, 3) . '***' . mb_substr($phone, -2);
  762. $result[] = [
  763. 'user' => $maskedNickname,
  764. 'phone'=>$phone,
  765. 'amount' => ($withdrawal->WithDraw+$withdrawal->ServiceFee)/NumConfig::NUM_VALUE,
  766. 'date' => $withdrawal->CreateDate
  767. ];
  768. }
  769. return $result;
  770. }
  771. }