ImportYearData.php 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Jobs\Import\ImportYearDataJob;
  4. use App\Services\Import\ImportYearDataService;
  5. use Illuminate\Console\Command;
  6. class ImportYearData extends Command
  7. {
  8. protected $signature = 'app:import-year-data
  9. {file : Путь к ZIP-архиву с данными}
  10. {year : Год для импорта данных}
  11. {--clear : Очистить существующие данные за год перед импортом}
  12. {--queue : Выполнить в очереди}
  13. {--user= : ID пользователя для уведомлений (по умолчанию 1)}';
  14. protected $description = 'Импорт всех данных CRM за указанный год из ZIP-архива';
  15. public function handle(): int
  16. {
  17. $filePath = $this->argument('file');
  18. $year = (int) $this->argument('year');
  19. $clearExisting = $this->option('clear');
  20. $userId = (int) ($this->option('user') ?? 1);
  21. if ($year < 2020 || $year > 2100) {
  22. $this->error("Некорректный год: {$year}");
  23. return self::FAILURE;
  24. }
  25. // Проверяем существование файла
  26. if (!file_exists($filePath)) {
  27. // Проверяем в storage
  28. $storagePath = storage_path('app/public/' . $filePath);
  29. if (file_exists($storagePath)) {
  30. $filePath = $storagePath;
  31. } else {
  32. $this->error("Файл не найден: {$filePath}");
  33. return self::FAILURE;
  34. }
  35. }
  36. $this->info("Импорт данных за {$year} год из файла: {$filePath}");
  37. if ($clearExisting) {
  38. $this->warn('ВНИМАНИЕ: Существующие данные за этот год будут удалены!');
  39. if (!$this->confirm('Продолжить?')) {
  40. $this->info('Операция отменена.');
  41. return self::SUCCESS;
  42. }
  43. }
  44. if ($this->option('queue')) {
  45. ImportYearDataJob::dispatch($filePath, $year, $userId, $clearExisting);
  46. $this->info('Задание добавлено в очередь. Вы получите уведомление по завершении.');
  47. return self::SUCCESS;
  48. }
  49. $this->info('Начинаю импорт...');
  50. try {
  51. $service = new ImportYearDataService($filePath, $year, $userId, $clearExisting);
  52. $success = $service->handle();
  53. $logs = $service->getLogs();
  54. $this->newLine();
  55. $this->info('Лог импорта:');
  56. foreach ($logs as $log) {
  57. $method = match ($log['level']) {
  58. 'ERROR' => 'error',
  59. 'WARNING' => 'warn',
  60. default => 'line',
  61. };
  62. $this->$method("[{$log['level']}] {$log['message']}");
  63. }
  64. $this->newLine();
  65. if ($success) {
  66. $this->info('Импорт успешно завершён!');
  67. return self::SUCCESS;
  68. } else {
  69. $this->error('Импорт завершился с ошибками.');
  70. return self::FAILURE;
  71. }
  72. } catch (\Exception $e) {
  73. $this->error('Ошибка импорта: ' . $e->getMessage());
  74. return self::FAILURE;
  75. }
  76. }
  77. }