You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

115 lines
3.4 KiB

6 months ago
<?php
namespace App\Console\Commands;
3 weeks ago
use App\Models\Config;
6 months ago
use App\Models\User;
use App\Notifications\AuditNotify;
use App\Notifications\BirthdayNotify;
use App\Repositories\MeetRepository;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Notification;
class CheckBirthday extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'check_birthday';
/**
* The console command description.
*
* @var string
*/
protected $description = '检测今天哪些人生日';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
3 weeks ago
// 匹配今天生日格式YYYY-MM-DD 或 MM-DD
$today = date('m-d');
$users = User::where('is_schoolmate', 1)
->where(function ($query) use ($today) {
$query->where('birthday', 'like', '%-' . $today)
->orWhere('birthday', 'like', $today . '%');
})
->get();
$birthdayCount = $users->count();
// 发送通知给用户
6 months ago
foreach ($users as $user) {
Notification::send($user, new BirthdayNotify(['user_id' => $user->id]));
}
3 weeks ago
// 如果有生日用户,给管理员发送短信
if ($birthdayCount > 0) {
$adminMobiles = Config::getValueByKey('birthday_notice');
if ($adminMobiles) {
$smsSign = Config::getValueByKey('sms_sign') ?: '';
// 收集生日用户名字
$userNames = $users->pluck('username')->filter()->toArray();
// 构建短信内容(统一模板,显示所有名字)
$namesStr = implode('、', $userNames);
$content = "{$smsSign}今日有{$birthdayCount}位校友生日:{$namesStr},请及时关注。";
// 分割手机号(支持英文逗号分隔)
$mobileList = array_map('trim', explode(',', $adminMobiles));
$mobileList = array_filter($mobileList); // 过滤空值
$successCount = 0;
$failCount = 0;
foreach ($mobileList as $mobile) {
if (empty($mobile)) {
continue;
}
$result = ymSms($mobile, $content);
if ($result) {
$this->info("已向管理员 {$mobile} 发送生日提醒短信");
$successCount++;
} else {
$this->error("向管理员 {$mobile} 发送短信失败");
$failCount++;
}
}
if ($successCount > 0) {
$this->info("共向 {$successCount} 位管理员发送短信成功");
}
if ($failCount > 0) {
$this->error("共 {$failCount} 位管理员短信发送失败");
}
} else {
$this->warn("未配置 birthday_notice 管理员手机号,跳过短信发送");
}
} else {
$this->info("今日无校友生日");
}
return $this->info("检测完成,共发现 {$birthdayCount} 位校友生日");
6 months ago
}
}