UserExpireWarningJob.php 2.7 KB

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