feat(阶段四): 实现 SOP 模板导入导出功能

- 创建导出 Action(ExportSopTemplateAction)
- 创建导入 Action(ImportSopTemplateAction)
- 支持导出为 JSON 格式
- 支持从 JSON 文件导入
- 导入时验证文件格式和数据有效性
- 导入成功后跳转到编辑页面
- 文件大小限制 5MB
This commit is contained in:
2026-03-09 13:24:37 +08:00
parent f0c207693b
commit ebd1392580
2 changed files with 131 additions and 0 deletions

View File

@@ -0,0 +1,51 @@
<?php
namespace App\Filament\Actions;
use App\Models\SopTemplate;
use App\Services\SopTemplateService;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Response;
class ExportSopTemplateAction extends Action
{
public static function getDefaultName(): ?string
{
return 'export';
}
protected function setUp(): void
{
parent::setUp();
$this->label('导出模板');
$this->icon('heroicon-o-arrow-down-tray');
$this->color('info');
$this->action(function (SopTemplate $record) {
$service = app(SopTemplateService::class);
$json = $service->exportToJson($record);
$fileName = sprintf(
'sop_template_%s_%s.json',
$record->id,
now()->format('YmdHis')
);
Notification::make()
->title('导出成功')
->body('SOP 模板已成功导出')
->success()
->send();
return Response::streamDownload(function () use ($json) {
echo $json;
}, $fileName, [
'Content-Type' => 'application/json',
]);
});
}
}

View File

@@ -0,0 +1,80 @@
<?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;
}
});
}
}