UpdateActivityStatusCommand.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <?php
  2. namespace App\Module\Activity\Commands;
  3. use App\Module\Activity\Enums\ACTIVITY_STATUS;
  4. use App\Module\Activity\Events\ActivityStatusChangedEvent;
  5. use App\Module\Activity\Models\ActivityConfig;
  6. use Carbon\Carbon;
  7. use Illuminate\Console\Command;
  8. use Illuminate\Support\Facades\Log;
  9. /**
  10. * 更新活动状态命令
  11. */
  12. class UpdateActivityStatusCommand extends Command
  13. {
  14. /**
  15. * 命令名称
  16. *
  17. * @var string
  18. */
  19. protected $signature = 'activity:update-status {--force : 强制更新所有活动状态}';
  20. /**
  21. * 命令描述
  22. *
  23. * @var string
  24. */
  25. protected $description = '根据时间自动更新活动状态';
  26. /**
  27. * 执行命令
  28. *
  29. * @return int
  30. */
  31. public function handle()
  32. {
  33. $this->info('开始更新活动状态...');
  34. $now = Carbon::now();
  35. $updated = 0;
  36. $force = $this->option('force');
  37. // 更新未开始的活动
  38. $notStartedQuery = ActivityConfig::where('status', ACTIVITY_STATUS::NOT_STARTED);
  39. if (!$force) {
  40. $notStartedQuery->where('start_time', '<=', $now);
  41. }
  42. $notStartedActivities = $notStartedQuery->get();
  43. foreach ($notStartedActivities as $activity) {
  44. $oldStatus = $activity->status;
  45. if ($force || $activity->start_time <= $now) {
  46. $activity->status = ACTIVITY_STATUS::IN_PROGRESS;
  47. $activity->save();
  48. // 触发活动状态变更事件
  49. event(new ActivityStatusChangedEvent(
  50. $activity->id,
  51. $oldStatus,
  52. ACTIVITY_STATUS::IN_PROGRESS
  53. ));
  54. $this->info("活动 [{$activity->id}] {$activity->name} 状态已更新为进行中");
  55. $updated++;
  56. }
  57. }
  58. // 更新进行中的活动
  59. $inProgressQuery = ActivityConfig::where('status', ACTIVITY_STATUS::IN_PROGRESS);
  60. if (!$force) {
  61. $inProgressQuery->where('end_time', '<', $now);
  62. }
  63. $inProgressActivities = $inProgressQuery->get();
  64. foreach ($inProgressActivities as $activity) {
  65. $oldStatus = $activity->status;
  66. if ($force || $activity->end_time < $now) {
  67. $activity->status = ACTIVITY_STATUS::ENDED;
  68. $activity->save();
  69. // 触发活动状态变更事件
  70. event(new ActivityStatusChangedEvent(
  71. $activity->id,
  72. $oldStatus,
  73. ACTIVITY_STATUS::ENDED
  74. ));
  75. $this->info("活动 [{$activity->id}] {$activity->name} 状态已更新为已结束");
  76. $updated++;
  77. }
  78. }
  79. $this->info("活动状态更新完成,共更新 {$updated} 个活动");
  80. // 记录日志
  81. Log::info("活动状态更新完成", [
  82. 'updated_count' => $updated,
  83. 'force' => $force
  84. ]);
  85. return 0;
  86. }
  87. }