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.

108 lines
3.2 KiB

8 months ago
<?php
namespace App\Console\Commands;
use App\Models\Course;
use App\Models\CourseSign;
use App\Models\User;
use Illuminate\Console\Command;
class AutoSchoolmate extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'auto_schoolmate';
/**
* 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()
{
2 months ago
// 获取所有已开始且需要自动加入校友库的课程(只处理存在 start_date 的课程)
8 months ago
$today = date('Y-m-d');
3 months ago
$courses = Course::where('auto_schoolmate', 1)
2 months ago
->whereNotNull('start_date')
->where('start_date', '<=', $today)
3 months ago
->get();
2 months ago
if ($courses->isEmpty()) {
return $this->info('没有需要处理的课程');
}
$this->info("找到 {$courses->count()} 个需要处理的课程");
3 months ago
$totalUpdated = 0;
2 months ago
$totalSkipped = 0;
$processedUserIds = []; // 记录已处理的用户ID避免重复处理
8 months ago
foreach ($courses as $course) {
2 months ago
// 获取报名通过的学员,并排除已经是校友的用户
$courseSigns = CourseSign::where('course_id', $course->id)
->where('status', 1)
->whereHas('user', function ($query) {
// 排除已经是校友的用户is_schoolmate = 1
$query->whereRaw('COALESCE(is_schoolmate, 0) != 1');
})->get();
3 months ago
if ($courseSigns->isEmpty()) {
continue;
}
2 months ago
// 获取需要更新的用户ID并排除已经在本脚本中处理过的用户
$userIds = $courseSigns->pluck('user_id')
->unique()
->filter(function ($userId) use (&$processedUserIds) {
// 如果已经处理过,跳过
if (in_array($userId, $processedUserIds)) {
return false;
}
$processedUserIds[] = $userId;
return true;
})
->values()
->toArray();
if (empty($userIds)) {
continue;
}
// 批量更新:只更新还不是校友的学员;使用课程开课时间作为 schoolmate_time
$updated = User::batchUpdateToSchoolmate($userIds, $course->start_date);
3 months ago
$totalUpdated += $updated;
2 months ago
$skipped = count($userIds) - $updated;
$totalSkipped += $skipped;
if ($updated > 0) {
$this->info("课程【{$course->name}】: 更新 {$updated} 位学员,跳过 {$skipped} 位已处理学员");
}
8 months ago
}
3 months ago
2 months ago
return $this->info("更新完成,共处理 {$totalUpdated} 位学员,跳过 {$totalSkipped} 位已处理学员");
8 months ago
}
}