ImportJob.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace App\Jobs\Import;
  3. use App\Events\SendWebSocketMessageEvent;
  4. use App\Models\Import;
  5. use App\Services\Import\ImportSparePartOrdersService;
  6. use App\Services\ImportCatalogService;
  7. use Illuminate\Support\Facades\Storage;
  8. use App\Services\ImportMafsService;
  9. use App\Services\ImportOrdersService;
  10. use App\Services\ImportReclamationsService;
  11. use Exception;
  12. use Illuminate\Contracts\Queue\ShouldQueue;
  13. use Illuminate\Foundation\Queue\Queueable;
  14. use Illuminate\Support\Facades\Log;
  15. class ImportJob implements ShouldQueue
  16. {
  17. use Queueable;
  18. /**
  19. * Create a new job instance.
  20. */
  21. public function __construct(
  22. private readonly Import $import,
  23. private readonly int $userId,
  24. )
  25. {}
  26. /**
  27. * Execute the job.
  28. */
  29. public function handle(): void
  30. {
  31. try {
  32. switch($this->import->type) {
  33. case 'orders':
  34. (new ImportOrdersService($this->import))->handle();
  35. break;
  36. case 'mafs':
  37. (new ImportMafsService($this->import))->handle();
  38. break;
  39. case 'reclamations':
  40. (new ImportReclamationsService($this->import))->handle();
  41. break;
  42. case 'catalog':
  43. (new ImportCatalogService($this->import, $this->import->year))->handle();
  44. break;
  45. case 'spare_part_orders':
  46. $this->handleSparePartOrdersImport();
  47. break;
  48. }
  49. Log::info('Import ' . $this->import->type. ' job done!');
  50. event(new SendWebSocketMessageEvent('Импорт завершён!', $this->userId, ['path' => $this->import->filename, 'type' => $this->import->type]));
  51. } catch (Exception $e) {
  52. Log::info('Import ' . $this->import->type. ' job failed! ERROR: ' . $e->getMessage());
  53. event(new SendWebSocketMessageEvent('Ошибка импорта! ' . $e->getMessage(), $this->userId, ['error' => $e->getMessage()]));
  54. }
  55. }
  56. private function handleSparePartOrdersImport(): void
  57. {
  58. $filePath = Storage::disk('upload')->path($this->import->filename);
  59. $service = new ImportSparePartOrdersService($filePath, $this->userId);
  60. $result = $service->handle();
  61. // Записываем логи в Import
  62. foreach ($service->getLogs() as $logLine) {
  63. $this->import->log($logLine);
  64. }
  65. $this->import->status = $result['success'] ? 'DONE' : 'ERROR';
  66. $this->import->save();
  67. }
  68. }