| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- <?php
- namespace App\Console\Commands;
- use App\Jobs\Import\ImportYearDataJob;
- use App\Services\Import\ImportYearDataService;
- use Illuminate\Console\Command;
- class ImportYearData extends Command
- {
- protected $signature = 'app:import-year-data
- {file : Путь к ZIP-архиву с данными}
- {year : Год для импорта данных}
- {--clear : Очистить существующие данные за год перед импортом}
- {--queue : Выполнить в очереди}
- {--user= : ID пользователя для уведомлений (по умолчанию 1)}';
- protected $description = 'Импорт всех данных CRM за указанный год из ZIP-архива';
- public function handle(): int
- {
- $filePath = $this->argument('file');
- $year = (int) $this->argument('year');
- $clearExisting = $this->option('clear');
- $userId = (int) ($this->option('user') ?? 1);
- if ($year < 2020 || $year > 2100) {
- $this->error("Некорректный год: {$year}");
- return self::FAILURE;
- }
- // Проверяем существование файла
- if (!file_exists($filePath)) {
- // Проверяем в storage
- $storagePath = storage_path('app/public/' . $filePath);
- if (file_exists($storagePath)) {
- $filePath = $storagePath;
- } else {
- $this->error("Файл не найден: {$filePath}");
- return self::FAILURE;
- }
- }
- $this->info("Импорт данных за {$year} год из файла: {$filePath}");
- if ($clearExisting) {
- $this->warn('ВНИМАНИЕ: Существующие данные за этот год будут удалены!');
- if (!$this->confirm('Продолжить?')) {
- $this->info('Операция отменена.');
- return self::SUCCESS;
- }
- }
- if ($this->option('queue')) {
- ImportYearDataJob::dispatch($filePath, $year, $userId, $clearExisting);
- $this->info('Задание добавлено в очередь. Вы получите уведомление по завершении.');
- return self::SUCCESS;
- }
- $this->info('Начинаю импорт...');
- try {
- $service = new ImportYearDataService($filePath, $year, $userId, $clearExisting);
- $success = $service->handle();
- $logs = $service->getLogs();
- $this->newLine();
- $this->info('Лог импорта:');
- foreach ($logs as $log) {
- $method = match ($log['level']) {
- 'ERROR' => 'error',
- 'WARNING' => 'warn',
- default => 'line',
- };
- $this->$method("[{$log['level']}] {$log['message']}");
- }
- $this->newLine();
- if ($success) {
- $this->info('Импорт успешно завершён!');
- return self::SUCCESS;
- } else {
- $this->error('Импорт завершился с ошибками.');
- return self::FAILURE;
- }
- } catch (\Exception $e) {
- $this->error('Ошибка импорта: ' . $e->getMessage());
- return self::FAILURE;
- }
- }
- }
|