Files
KnowledgeBase/app/Filament/Actions/ImportSopTemplateAction.php
lizhuoran ebd1392580 feat(阶段四): 实现 SOP 模板导入导出功能
- 创建导出 Action(ExportSopTemplateAction)
- 创建导入 Action(ImportSopTemplateAction)
- 支持导出为 JSON 格式
- 支持从 JSON 文件导入
- 导入时验证文件格式和数据有效性
- 导入成功后跳转到编辑页面
- 文件大小限制 5MB
2026-03-09 13:24:37 +08:00

81 lines
2.3 KiB
PHP

<?php
namespace App\Filament\Actions;
use App\Services\SopTemplateService;
use Filament\Actions\Action;
use Filament\Forms;
use Filament\Notifications\Notification;
use Illuminate\Validation\ValidationException;
class ImportSopTemplateAction extends Action
{
public static function getDefaultName(): ?string
{
return 'import';
}
protected function setUp(): void
{
parent::setUp();
$this->label('导入模板');
$this->icon('heroicon-o-arrow-up-tray');
$this->color('success');
$this->modalHeading('导入 SOP 模板');
$this->modalDescription('从 JSON 文件导入 SOP 模板');
$this->modalSubmitActionLabel('导入');
$this->form([
Forms\Components\FileUpload::make('file')
->label('选择文件')
->acceptedFileTypes(['application/json'])
->required()
->maxSize(5120), // 5MB
]);
$this->action(function (array $data) {
try {
$filePath = storage_path('app/public/' . $data['file']);
$json = file_get_contents($filePath);
$service = app(SopTemplateService::class);
$template = $service->importFromJson($json);
// 删除临时文件
@unlink($filePath);
Notification::make()
->title('导入成功')
->body("SOP 模板「{$template->name}」已成功导入")
->success()
->send();
// 重定向到编辑页面
return redirect()->route('filament.admin.resources.sop-templates.edit', ['record' => $template]);
} catch (ValidationException $e) {
Notification::make()
->title('导入失败')
->body($e->getMessage())
->danger()
->send();
throw $e;
} catch (\Exception $e) {
Notification::make()
->title('导入失败')
->body('文件格式错误或数据无效')
->danger()
->send();
throw $e;
}
});
}
}