BaseImportJob.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. 'on_leave' => $stats['on_leave'] ?? 0,
  35. 'imported_at' => now(),
  36. ]);
  37. Cache::put($this->importId, [
  38. 'status' => 'completed',
  39. 'stats' => $stats,
  40. ], now()->addDay());
  41. } finally {
  42. $this->cleanupFile();
  43. }
  44. }
  45. public function failed(Throwable $e): void
  46. {
  47. Cache::put($this->importId, [
  48. 'status' => 'failed',
  49. 'message' => $e->getMessage(),
  50. ], now()->addDay());
  51. $this->cleanupFile();
  52. }
  53. abstract protected function runSync(string $filePath): array;
  54. abstract protected function getImportType(): string;
  55. private function cleanupFile(): void
  56. {
  57. Storage::delete($this->filePath);
  58. }
  59. }