UserService.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Order;
  4. use App\Models\Server;
  5. use App\Models\User;
  6. class UserService
  7. {
  8. public function isAvailable(User $user)
  9. {
  10. if (!$user->banned && $user->transfer_enable && ($user->expired_at > time() || $user->expired_at === NULL)) {
  11. return true;
  12. }
  13. return false;
  14. }
  15. public function getAvailableUsers()
  16. {
  17. return User::whereRaw('u + d < transfer_enable')
  18. ->where(function ($query) {
  19. $query->where('expired_at', '>=', time())
  20. ->orWhere('expired_at', NULL);
  21. })
  22. ->where('banned', 0)
  23. ->get();
  24. }
  25. public function getUnAvailbaleUsers()
  26. {
  27. return User::where(function ($query) {
  28. $query->where('expired_at', '<', time())
  29. ->orWhere('expired_at', 0);
  30. })
  31. ->where(function ($query) {
  32. $query->where('plan_id', NULL)
  33. ->orWhere('transfer_enable', 0);
  34. })
  35. ->get();
  36. }
  37. public function getUsersByIds($ids)
  38. {
  39. return User::whereIn('id', $ids)->get();
  40. }
  41. public function getAllUsers()
  42. {
  43. return User::all();
  44. }
  45. public function addBalance(int $userId, int $balance):bool
  46. {
  47. $user = User::find($userId);
  48. if (!$user) {
  49. return false;
  50. }
  51. $user->balance = $user->balance + $balance;
  52. if ($user->balance < 0) {
  53. return false;
  54. }
  55. if (!$user->save()) {
  56. return false;
  57. }
  58. return true;
  59. }
  60. public function isNotCompleteOrderByUserId(int $userId):bool
  61. {
  62. $order = Order::whereIn('status', [0, 1])
  63. ->where('user_id', $userId)
  64. ->first();
  65. if (!$order) {
  66. return false;
  67. }
  68. return true;
  69. }
  70. public function trafficFetch(int $u, int $d, int $userId, object $server, string $protocol):bool
  71. {
  72. $user = User::lockForUpdate()
  73. ->find($userId);
  74. if (!$user) {
  75. return true;
  76. }
  77. $user->t = time();
  78. $user->u = $user->u + $u;
  79. $user->d = $user->d + $d;
  80. if (!$user->save()) {
  81. return false;
  82. }
  83. $mailService = new MailService();
  84. $serverService = new ServerService();
  85. try {
  86. $mailService->remindTraffic($user);
  87. $serverService->log(
  88. $userId,
  89. $server->id,
  90. $u,
  91. $d,
  92. $server->rate,
  93. $protocol
  94. );
  95. } catch (\Exception $e) {
  96. }
  97. return true;
  98. }
  99. }