ImportYearDataJob.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace App\Jobs\Import;
  3. use App\Events\SendWebSocketMessageEvent;
  4. use App\Services\Import\ImportYearDataService;
  5. use Exception;
  6. use Illuminate\Contracts\Queue\ShouldQueue;
  7. use Illuminate\Foundation\Queue\Queueable;
  8. use Illuminate\Support\Facades\Log;
  9. class ImportYearDataJob implements ShouldQueue
  10. {
  11. use Queueable;
  12. /**
  13. * Количество попыток выполнения задания.
  14. */
  15. public int $tries = 1;
  16. /**
  17. * Таймаут выполнения задания (60 минут).
  18. */
  19. public int $timeout = 3600;
  20. public function __construct(
  21. private readonly string $archivePath,
  22. private readonly int $year,
  23. private readonly int $userId,
  24. private readonly bool $clearExisting = false,
  25. ) {}
  26. public function handle(): void
  27. {
  28. try {
  29. Log::info("ImportYearDataJob started for year {$this->year}", [
  30. 'archive' => $this->archivePath,
  31. 'clear_existing' => $this->clearExisting,
  32. ]);
  33. $service = new ImportYearDataService(
  34. $this->archivePath,
  35. $this->year,
  36. $this->userId,
  37. $this->clearExisting
  38. );
  39. $success = $service->handle();
  40. $logs = $service->getLogs();
  41. if ($success) {
  42. Log::info("ImportYearDataJob completed for year {$this->year}");
  43. event(new SendWebSocketMessageEvent(
  44. "Импорт данных за {$this->year} год завершён!",
  45. $this->userId,
  46. [
  47. 'success' => true,
  48. 'year' => $this->year,
  49. 'logs' => $logs,
  50. ]
  51. ));
  52. } else {
  53. Log::error("ImportYearDataJob failed for year {$this->year}");
  54. event(new SendWebSocketMessageEvent(
  55. "Ошибка импорта данных за {$this->year} год",
  56. $this->userId,
  57. [
  58. 'error' => 'Импорт завершился с ошибками',
  59. 'year' => $this->year,
  60. 'logs' => $logs,
  61. ]
  62. ));
  63. }
  64. } catch (Exception $e) {
  65. Log::error("ImportYearDataJob failed for year {$this->year}: " . $e->getMessage(), [
  66. 'trace' => $e->getTraceAsString()
  67. ]);
  68. event(new SendWebSocketMessageEvent(
  69. "Ошибка импорта данных за {$this->year} год: " . $e->getMessage(),
  70. $this->userId,
  71. [
  72. 'error' => $e->getMessage(),
  73. 'year' => $this->year,
  74. ]
  75. ));
  76. }
  77. }
  78. }