BaseImportJob.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace App\Jobs;
  3. use App\Models\ImportLog;
  4. use Illuminate\Bus\Queueable;
  5. use Illuminate\Contracts\Queue\ShouldQueue;
  6. use Illuminate\Foundation\Bus\Dispatchable;
  7. use Illuminate\Queue\InteractsWithQueue;
  8. use Illuminate\Queue\SerializesModels;
  9. use Illuminate\Support\Facades\Cache;
  10. use Illuminate\Support\Facades\Storage;
  11. use Throwable;
  12. abstract class BaseImportJob implements ShouldQueue
  13. {
  14. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  15. public int $tries = 1;
  16. public int $timeout = 600;
  17. public function __construct(
  18. protected string $filePath,
  19. protected string $importId,
  20. protected int $userId,
  21. ) {}
  22. public function handle(): void
  23. {
  24. Cache::put($this->importId, ['status' => 'processing'], now()->addDay());
  25. try {
  26. $stats = $this->runSync($this->filePath);
  27. ImportLog::create([
  28. 'type' => $this->getImportType(),
  29. 'user_id' => $this->userId,
  30. 'total' => $stats['total'] ?? 0,
  31. 'created' => $stats['created'] ?? 0,
  32. 'updated' => $stats['updated'] ?? 0,
  33. 'inactivated' => $stats['inactivated'] ?? 0,
  34. 'imported_at' => now(),
  35. ]);
  36. Cache::put($this->importId, [
  37. 'status' => 'completed',
  38. 'stats' => $stats,
  39. ], now()->addDay());
  40. } finally {
  41. $this->cleanupFile();
  42. }
  43. }
  44. public function failed(Throwable $e): void
  45. {
  46. Cache::put($this->importId, [
  47. 'status' => 'failed',
  48. 'message' => $e->getMessage(),
  49. ], now()->addDay());
  50. $this->cleanupFile();
  51. }
  52. abstract protected function runSync(string $filePath): array;
  53. abstract protected function getImportType(): string;
  54. private function cleanupFile(): void
  55. {
  56. Storage::delete($this->filePath);
  57. }
  58. }