| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- <?php
- namespace App\Module\Farm\Commands;
- use App\Module\Farm\Enums\GROWTH_STAGE;
- use App\Module\Farm\Logics\CropLogic;
- use App\Module\Farm\Models\FarmCrop;
- use Illuminate\Console\Command;
- use Illuminate\Support\Facades\Log;
- /**
- * 更新作物生长状态命令
- */
- class UpdateCropGrowthCommand extends Command
- {
- /**
- * 命令名称
- *
- * @var string
- */
- protected $signature = 'farm:update-crop-growth';
- /**
- * 命令描述
- *
- * @var string
- */
- protected $description = '更新作物生长状态';
- /**
- * 执行命令
- *
- * @return int
- */
- public function handle()
- {
- $this->info('开始更新作物生长状态...');
- try {
- // 获取需要更新生长阶段的作物
- /**
- * @var \Illuminate\Database\Eloquent\Collection $crops
- */
- $crops = FarmCrop::whereNotNull('stage_end_time')
- ->where('stage_end_time', '<=', now())
- ->where('growth_stage', '<', GROWTH_STAGE::WITHERED->value)
- ->get();
- $this->info("找到 {$crops->count()} 个需要更新的作物");
- $updatedCount = 0;
- foreach ($crops as $crop) {
- $userId = $crop->user_id;
- $oldStage = $crop->growth_stage;
- // 使用CropLogic的updateGrowthStage方法,确保所有逻辑都正确执行
- $cropLogic = new CropLogic();
- $updated = $cropLogic->updateGrowthStage($crop->id);
- if ($updated) {
- $updatedCount++;
- // 重新获取作物信息以显示更新后的状态
- $crop->refresh();
- // 获取阶段名称用于显示
- $oldStageName = GROWTH_STAGE::getName($oldStage->value);
- $newStageName = GROWTH_STAGE::getName($crop->growth_stage->value);
- $this->info("作物 ID: {$crop->id}, 用户 ID: {$userId}, 阶段: {$oldStageName} -> {$newStageName}");
- }
- }
- $this->info("成功更新 {$updatedCount} 个作物的生长状态");
- Log::info('作物生长状态更新成功', [
- 'total' => $crops->count(),
- 'updated' => $updatedCount
- ]);
- return 0;
- } catch (\Exception $e) {
- $this->error('作物生长状态更新失败: ' . $e->getMessage());
- Log::error('作物生长状态更新失败', [
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return 1;
- }
- }
- }
|