KTV/app/Livewire/Admin/ArtistImportData.php

82 lines
2.1 KiB
PHP

<?php
namespace App\Livewire\Admin;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use WireUi\Traits\WireUiActions;
use Livewire\Component;
use Livewire\WithFileUploads;
use App\Jobs\ImportJob;
class ArtistImportData extends Component
{
use WithFileUploads, WireUiActions;
protected $listeners = ['openModal','closeModal'];
public bool $canCreate;
public bool $showModal = false;
public $file;
public string|null $tmpPath = null;
public function mount()
{
$this->canCreate = Auth::user()?->can('song-edit') ?? false;
}
public function openModal()
{
$this->showModal = true;
}
public function closeModal()
{
$this->deleteTmpFile(); // 關閉 modal 時刪除暫存檔案
$this->reset(['file', 'tmpPath']);
$this->showModal = false;
}
public function import()
{
// 檢查檔案是否有上傳
$this->validate([
'file' => 'required|file|mimes:csv,xlsx,xls'
]);
if ($this->canCreate) {
// 取得原始 tmp 路徑
$tmpPath = $this->file->getRealPath();
// 儲存檔案至 storage
$path = $this->file->storeAs('imports', uniqid() . '_' . $this->file->getClientOriginalName());
// 丟到 queue 執行
ImportJob::dispatch($path,'Artist');
$this->notification()->send([
'icon' => 'info',
'title' => $this->file->getClientOriginalName(),
'description' => '已排入背景匯入作業,請稍候查看結果',
]);
$this->deleteTmpFile(); // 匯入後也順便刪除 tmp 檔
$this->reset(['file', 'tmpPath']);
$this->showModal = false;
}
}
protected function deleteTmpFile()
{
if ($this->tmpPath && File::exists($this->tmpPath)) {
File::delete($this->tmpPath);
}
}
public function render()
{
return view('livewire.admin.artist-import-data');
}
}