UserTrafficAutoWarning.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Components\Helpers;
  4. use App\Mail\userTrafficWarning;
  5. use App\Models\User;
  6. use Illuminate\Console\Command;
  7. use Log;
  8. use Mail;
  9. class UserTrafficAutoWarning extends Command
  10. {
  11. protected $signature = 'userTrafficAutoWarning';
  12. protected $description = '用户流量超过警告阈值自动发邮件提醒';
  13. public function handle(): void
  14. {
  15. $jobStartTime = microtime(true);
  16. // 用户流量超过警告阈值自动发邮件提醒
  17. if (sysConfig('traffic_warning')) {
  18. $this->userTrafficWarning();
  19. }
  20. $jobEndTime = microtime(true);
  21. $jobUsedTime = round(($jobEndTime - $jobStartTime), 4);
  22. Log::info(
  23. '---【' . $this->description . '】完成---,耗时' . $jobUsedTime . '秒'
  24. );
  25. }
  26. // 用户流量超过警告阈值自动发邮件提醒
  27. private function userTrafficWarning(): void
  28. {
  29. $trafficWarningPercent = sysConfig('traffic_warning_percent');
  30. foreach (
  31. User::activeUser()->where('transfer_enable', '>', 0)->get() as $user
  32. ) {
  33. // 用户名不是邮箱的跳过
  34. if (false === filter_var($user->email, FILTER_VALIDATE_EMAIL)) {
  35. continue;
  36. }
  37. $usedPercent = round(
  38. ($user->d + $user->u) / $user->transfer_enable,
  39. 2
  40. ) * 100; // 已使用流量百分比
  41. if ($usedPercent >= $trafficWarningPercent) {
  42. $logId = Helpers::addNotificationLog(
  43. "流量提醒",
  44. '流量已使用:' . $usedPercent . '%,请保持关注。',
  45. 1,
  46. $user->email
  47. );
  48. Mail::to($user->email)->send(
  49. new userTrafficWarning($logId, $usedPercent)
  50. );
  51. }
  52. }
  53. }
  54. }