ImportSparePartsJob.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace App\Jobs\Import;
  3. use App\Models\Import;
  4. use App\Services\Import\ImportSparePartsService;
  5. use Illuminate\Bus\Queueable;
  6. use Illuminate\Contracts\Queue\ShouldQueue;
  7. use Illuminate\Foundation\Bus\Dispatchable;
  8. use Illuminate\Queue\InteractsWithQueue;
  9. use Illuminate\Queue\SerializesModels;
  10. use Illuminate\Support\Facades\Log;
  11. use Illuminate\Support\Facades\Storage;
  12. class ImportSparePartsJob implements ShouldQueue
  13. {
  14. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  15. public function __construct(
  16. private readonly string $filePath,
  17. private readonly int $userId,
  18. private readonly ?int $importId = null,
  19. ) {}
  20. public function handle(): void
  21. {
  22. Log::info("ImportSparePartsJob started", [
  23. 'file_path' => $this->filePath,
  24. 'user_id' => $this->userId,
  25. ]);
  26. $import = null;
  27. if ($this->importId) {
  28. $import = Import::find($this->importId);
  29. }
  30. try {
  31. $service = new ImportSparePartsService($this->filePath, $this->userId);
  32. $result = $service->handle();
  33. if ($import) {
  34. if ($result['success']) {
  35. $import->update([
  36. 'status' => Import::STATUS_COMPLETED,
  37. 'result' => implode("\n", $result['logs']),
  38. ]);
  39. } else {
  40. $import->update([
  41. 'status' => Import::STATUS_FAILED,
  42. 'result' => implode("\n", $result['logs']) . "\n\nОШИБКА: " . ($result['error'] ?? 'Неизвестная ошибка'),
  43. ]);
  44. }
  45. }
  46. Log::info("ImportSparePartsJob finished successfully");
  47. } catch (\Exception $e) {
  48. Log::error("ImportSparePartsJob failed: " . $e->getMessage(), [
  49. 'trace' => $e->getTraceAsString(),
  50. ]);
  51. if ($import) {
  52. $import->update([
  53. 'status' => Import::STATUS_FAILED,
  54. 'result' => "ОШИБКА: " . $e->getMessage() . "\n\n" . $e->getTraceAsString(),
  55. ]);
  56. }
  57. throw $e;
  58. } finally {
  59. // Удаляем временный файл
  60. if (file_exists($this->filePath)) {
  61. unlink($this->filePath);
  62. }
  63. }
  64. }
  65. }