UserExpireWarningJob.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use App\Http\Models\Config;
  5. use App\Http\Models\User;
  6. use App\Http\Models\EmailLog;
  7. use App\Mail\userExpireWarning;
  8. use Mail;
  9. use Log;
  10. class UserExpireWarningJob extends Command
  11. {
  12. protected $signature = 'command:userExpireWarningJob';
  13. protected $description = '自动发邮件提醒用户临近到期';
  14. protected static $config;
  15. public function __construct()
  16. {
  17. parent::__construct();
  18. $config = Config::query()->get();
  19. $data = [];
  20. foreach ($config as $vo) {
  21. $data[$vo->name] = $vo->value;
  22. }
  23. self::$config = $data;
  24. }
  25. public function handle()
  26. {
  27. if (self::$config['expire_warning']) {
  28. $userList = User::query()->where('transfer_enable', '>', 0)->whereIn('status', [0, 1])->where('enable', 1)->get();
  29. foreach ($userList as $user) {
  30. // 用户名不是邮箱的跳过
  31. if (false === filter_var($user->username, FILTER_VALIDATE_EMAIL)) {
  32. continue;
  33. }
  34. $lastCanUseDays = floor(round(strtotime($user->expire_time) - strtotime(date('Y-m-d H:i:s'))) / 3600 / 24);
  35. if ($lastCanUseDays > 0 && $lastCanUseDays <= self::$config['expire_days']) {
  36. $title = '账号过期提醒';
  37. $content = '账号还剩【' . $lastCanUseDays . '】天即将过期';
  38. try {
  39. Mail::to($user->username)->send(new userExpireWarning(self::$config['website_name'], $lastCanUseDays));
  40. $this->sendEmailLog($user->id, $title, $content);
  41. } catch (\Exception $e) {
  42. $this->sendEmailLog($user->id, $title, $content, 0, $e->getMessage());
  43. }
  44. }
  45. }
  46. }
  47. Log::info('定时任务:' . $this->description);
  48. }
  49. /**
  50. * 写入邮件发送日志
  51. * @param int $user_id 用户ID
  52. * @param string $title 投递类型(投递标题)
  53. * @param string $content 投递内容(简要概述)
  54. * @param int $status 投递状态
  55. * @param string $error 投递失败时记录的异常信息
  56. */
  57. private function sendEmailLog($user_id, $title, $content, $status = 1, $error = '')
  58. {
  59. $emailLogObj = new EmailLog();
  60. $emailLogObj->user_id = $user_id;
  61. $emailLogObj->title = $title;
  62. $emailLogObj->content = $content;
  63. $emailLogObj->status = $status;
  64. $emailLogObj->error = $error;
  65. $emailLogObj->created_at = date('Y-m-d H:i:s');
  66. $emailLogObj->save();
  67. }
  68. }