| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- <?php
- namespace App\Jobs;
- use App\Models\ImportLog;
- use Illuminate\Bus\Queueable;
- use Illuminate\Contracts\Queue\ShouldQueue;
- use Illuminate\Foundation\Bus\Dispatchable;
- use Illuminate\Queue\InteractsWithQueue;
- use Illuminate\Queue\SerializesModels;
- use Illuminate\Support\Facades\Cache;
- use Illuminate\Support\Facades\Storage;
- use Throwable;
- abstract class BaseImportJob implements ShouldQueue
- {
- use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
- public int $tries = 1;
- public int $timeout = 600;
- public function __construct(
- protected string $filePath,
- protected string $importId,
- protected int $userId,
- ) {}
- public function handle(): void
- {
- Cache::put($this->importId, ['status' => 'processing'], now()->addDay());
- try {
- $stats = $this->runSync($this->filePath);
- ImportLog::create([
- 'type' => $this->getImportType(),
- 'user_id' => $this->userId,
- 'total' => $stats['total'] ?? 0,
- 'created' => $stats['created'] ?? 0,
- 'updated' => $stats['updated'] ?? 0,
- 'inactivated' => $stats['inactivated'] ?? 0,
- 'on_leave' => $stats['on_leave'] ?? 0,
- 'imported_at' => now(),
- ]);
- Cache::put($this->importId, [
- 'status' => 'completed',
- 'stats' => $stats,
- ], now()->addDay());
- } finally {
- $this->cleanupFile();
- }
- }
- public function failed(Throwable $e): void
- {
- Cache::put($this->importId, [
- 'status' => 'failed',
- 'message' => $e->getMessage(),
- ], now()->addDay());
- $this->cleanupFile();
- }
- abstract protected function runSync(string $filePath): array;
- abstract protected function getImportType(): string;
- private function cleanupFile(): void
- {
- Storage::delete($this->filePath);
- }
- }
|