| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- <?php
- namespace App\Module\Activity\Commands;
- use App\Module\Activity\Enums\ACTIVITY_STATUS;
- use App\Module\Activity\Events\ActivityStatusChangedEvent;
- use App\Module\Activity\Models\ActivityConfig;
- use Carbon\Carbon;
- use Illuminate\Console\Command;
- use Illuminate\Support\Facades\Log;
- /**
- * 更新活动状态命令
- */
- class UpdateActivityStatusCommand extends Command
- {
- /**
- * 命令名称
- *
- * @var string
- */
- protected $signature = 'activity:update-status {--force : 强制更新所有活动状态}';
- /**
- * 命令描述
- *
- * @var string
- */
- protected $description = '根据时间自动更新活动状态';
- /**
- * 执行命令
- *
- * @return int
- */
- public function handle()
- {
- $this->info('开始更新活动状态...');
-
- $now = Carbon::now();
- $updated = 0;
- $force = $this->option('force');
-
- // 更新未开始的活动
- $notStartedQuery = ActivityConfig::where('status', ACTIVITY_STATUS::NOT_STARTED);
-
- if (!$force) {
- $notStartedQuery->where('start_time', '<=', $now);
- }
-
- $notStartedActivities = $notStartedQuery->get();
-
- foreach ($notStartedActivities as $activity) {
- $oldStatus = $activity->status;
-
- if ($force || $activity->start_time <= $now) {
- $activity->status = ACTIVITY_STATUS::IN_PROGRESS;
- $activity->save();
-
- // 触发活动状态变更事件
- event(new ActivityStatusChangedEvent(
- $activity->id,
- $oldStatus,
- ACTIVITY_STATUS::IN_PROGRESS
- ));
-
- $this->info("活动 [{$activity->id}] {$activity->name} 状态已更新为进行中");
- $updated++;
- }
- }
-
- // 更新进行中的活动
- $inProgressQuery = ActivityConfig::where('status', ACTIVITY_STATUS::IN_PROGRESS);
-
- if (!$force) {
- $inProgressQuery->where('end_time', '<', $now);
- }
-
- $inProgressActivities = $inProgressQuery->get();
-
- foreach ($inProgressActivities as $activity) {
- $oldStatus = $activity->status;
-
- if ($force || $activity->end_time < $now) {
- $activity->status = ACTIVITY_STATUS::ENDED;
- $activity->save();
-
- // 触发活动状态变更事件
- event(new ActivityStatusChangedEvent(
- $activity->id,
- $oldStatus,
- ACTIVITY_STATUS::ENDED
- ));
-
- $this->info("活动 [{$activity->id}] {$activity->name} 状态已更新为已结束");
- $updated++;
- }
- }
-
- $this->info("活动状态更新完成,共更新 {$updated} 个活动");
-
- // 记录日志
- Log::info("活动状态更新完成", [
- 'updated_count' => $updated,
- 'force' => $force
- ]);
-
- return 0;
- }
- }
|