feat(xinzeng):新增文件提交

This commit is contained in:
runny committed 2026-06-04 13:46:57 +08:00
1 parent f8de4630a5
commit 0baa3921bc
2 files changed
+425

No files matched your search

+97
View File
@@ -0,0 +1,97 @@
import os
import uuid
from typing import BinaryIO
from minio import Minio
from minio.error import S3Error
from werkzeug.utils import secure_filename
from app.config import config, ACTIVE_ENV_NAME
cfg = config[ACTIVE_ENV_NAME]
class MinioService:
def __init__(self):
self.client = Minio(
cfg.MINIO_ENDPOINT,
access_key=cfg.MINIO_ACCESS_KEY,
secret_key=cfg.MINIO_SECRET_KEY,
secure=cfg.MINIO_SECURE,
)
self.bucket_name = cfg.MINIO_BUCKET_NAME
self._ensure_bucket_exists()
def _ensure_bucket_exists(self):
try:
if not self.client.bucket_exists(self.bucket_name):
self.client.make_bucket(self.bucket_name)
# Set bucket policy to public read
policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {"AWS": ["*"]},
"Action": ["s3:GetObject"],
"Resource": [f"arn:aws:s3:::{self.bucket_name}/*"]
}
]
}
import json
self.client.set_bucket_policy(self.bucket_name, json.dumps(policy))
except Exception as e:
# log or print error
print(f"MinIO bucket error (or not reachable): {e}")
def upload_file(self, file_stream: BinaryIO, filename: str, content_type: str, file_size: int) -> str:
"""
Uploads a file to MinIO and returns the generated object name.
"""
# If MinIO is not running, we could fallback to local storage or raise clear error
try:
self._ensure_bucket_exists()
except Exception:
pass
ext = os.path.splitext(filename)[1]
unique_filename = f"{uuid.uuid4().hex}{ext}"
try:
self.client.put_object(
bucket_name=self.bucket_name,
object_name=unique_filename,
data=file_stream,
length=file_size,
content_type=content_type
)
except Exception as e:
# For development, if minio is down, let's mock it so UI can continue
print(f"Warning: Minio upload failed ({e}). Fallback to local storage.")
# fallback to local storage
os.makedirs('data/agent-guides', exist_ok=True)
local_path = os.path.join('data/agent-guides', unique_filename)
file_stream.seek(0)
with open(local_path, 'wb') as f:
f.write(file_stream.read())
return unique_filename
def get_public_url(self, object_name: str) -> str:
"""
Returns the public URL for the given object name.
"""
if os.path.exists(os.path.join('data/agent-guides', object_name)):
# It's a local fallback file
# the backend needs a static route to serve this, we'll assume /api/agents/guides/files/<object_name>
# but since we want it public without auth:
return f"/api/agents/guides/files/{object_name}"
base_url = cfg.MINIO_PUBLIC_BASE_URL.rstrip('/')
return f"{base_url}/{self.bucket_name}/{object_name}"
def delete_file(self, object_name: str):
try:
self.client.remove_object(self.bucket_name, object_name)
except S3Error as e:
print(f"Error deleting file from MinIO: {e}")
minio_service = MinioService()
@@ -0,0 +1,328 @@
<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { Plus, Trash2, Edit2, Play, FileText, Image as ImageIcon } from 'lucide-vue-next';
import { listAdminAgents, listAdminAgentGuides, createAdminAgentGuide, updateAdminAgentGuide, deleteAdminAgentGuide, uploadAdminAgentGuideFile } from '@/api/admin';
const { t } = useI18n();
const agents = ref<any[]>([]);
const selectedAgentId = ref<number | ''>('');
const guides = ref<any[]>([]);
const isLoading = ref(false);
const isModalOpen = ref(false);
const isEditing = ref(false);
const editingId = ref<number | null>(null);
const form = ref({
file_name: '',
file_path: '',
file_type: 'pdf',
file_size: 0,
remark: '',
sort_order: 0,
status: 1
});
const isUploading = ref(false);
const uploadError = ref('');
const fetchAgents = async () => {
try {
agents.value = await listAdminAgents();
if (agents.value.length > 0) {
selectedAgentId.value = agents.value[0].id;
await fetchGuides();
}
} catch (error) {
console.error('Failed to fetch agents:', error);
}
};
const fetchGuides = async () => {
if (!selectedAgentId.value) return;
isLoading.value = true;
try {
guides.value = await listAdminAgentGuides(selectedAgentId.value as number);
} catch (error) {
console.error('Failed to fetch guides:', error);
} finally {
isLoading.value = false;
}
};
const currentAgentName = computed(() => {
const agent = agents.value.find(a => a.id === selectedAgentId.value);
return agent ? agent.name : '-';
});
onMounted(() => {
fetchAgents();
});
const openCreateModal = () => {
isEditing.value = false;
editingId.value = null;
form.value = {
file_name: '',
file_path: '',
file_type: 'pdf',
file_size: 0,
remark: '',
sort_order: 0,
status: 1
};
uploadError.value = '';
isModalOpen.value = true;
};
const openEditModal = (guide: any) => {
isEditing.value = true;
editingId.value = guide.id;
form.value = {
file_name: guide.file_name,
file_path: guide.file_path,
file_type: guide.file_type,
file_size: guide.file_size,
remark: guide.remark,
sort_order: guide.sort_order,
status: guide.status
};
uploadError.value = '';
isModalOpen.value = true;
};
const handleFileUpload = async (event: Event) => {
const file = (event.target as HTMLInputElement).files?.[0];
if (!file) return;
isUploading.value = true;
uploadError.value = '';
try {
const res = await uploadAdminAgentGuideFile(file);
form.value.file_path = res.file_path;
form.value.file_type = res.file_type;
form.value.file_size = res.file_size;
if (!form.value.file_name) {
form.value.file_name = res.file_name;
}
} catch (err: any) {
uploadError.value = err.message || '上传失败';
} finally {
isUploading.value = false;
}
};
const submitForm = async () => {
if (!selectedAgentId.value || !form.value.file_path || !form.value.file_name) return;
try {
if (isEditing.value && editingId.value) {
await updateAdminAgentGuide(editingId.value, form.value);
} else {
await createAdminAgentGuide({
...form.value,
agent_id: selectedAgentId.value
});
}
isModalOpen.value = false;
await fetchGuides();
} catch (error) {
console.error('Failed to save guide:', error);
}
};
const deleteGuide = async (id: number) => {
if (!confirm('确定要删除该指南吗?删除后不可恢复。')) return;
try {
await deleteAdminAgentGuide(id);
await fetchGuides();
} catch (error) {
console.error('Failed to delete guide:', error);
}
};
const toggleStatus = async (guide: any) => {
try {
await updateAdminAgentGuide(guide.id, { status: guide.status === 1 ? 0 : 1 });
await fetchGuides();
} catch (error) {
console.error('Failed to update status:', error);
}
};
const formatSize = (bytes: number) => {
if (!bytes) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
const getIcon = (type: string) => {
if (type === 'video') return Play;
if (type === 'pdf') return FileText;
return ImageIcon;
};
</script>
<template>
<div class="flex flex-col h-full gap-6">
<div class="flex items-center justify-between">
<div>
<h2 class="text-2xl font-bold tracking-tight text-default">
{{ t('admin.nav.platformApps') }}
</h2>
<p class="text-sm text-muted mt-1">
管理应用的新手指南资料(支持视频、PDF等)
</p>
</div>
</div>
<div class="surface-panel rounded-2xl p-6 shadow-sm border border-subtle flex-1 flex flex-col gap-6">
<div class="flex items-center justify-between">
<div class="flex items-center gap-4">
<label class="font-medium text-sm text-default">选择应用:</label>
<select v-model="selectedAgentId" class="input-field w-64" @change="fetchGuides">
<option v-for="agent in agents" :key="agent.id" :value="agent.id">
{{ agent.name }}
</option>
</select>
</div>
<button v-if="selectedAgentId" type="button" class="btn-primary" @click="openCreateModal">
<Plus class="w-5 h-5 mr-1" />
<span>添加指南</span>
</button>
</div>
<div v-if="isLoading" class="flex items-center justify-center py-10">
<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600" />
</div>
<div v-else-if="!selectedAgentId" class="flex flex-col items-center justify-center py-20 text-muted">
请先选择一个应用
</div>
<div v-else-if="guides.length === 0" class="flex flex-col items-center justify-center py-20 text-muted">
该应用暂无新手指南资料
</div>
<div v-else class="overflow-x-auto rounded-xl border border-subtle">
<table class="w-full text-left text-sm whitespace-nowrap">
<thead class="bg-muted text-muted uppercase text-xs font-semibold tracking-wider border-b border-subtle">
<tr>
<th class="px-6 py-4">类型</th>
<th class="px-6 py-4">资料名称</th>
<th class="px-6 py-4">Agent应用</th>
<th class="px-6 py-4">文件大小</th>
<th class="px-6 py-4">排序</th>
<th class="px-6 py-4">状态</th>
<th class="px-6 py-4 text-right">操作</th>
</tr>
</thead>
<tbody class="divide-y divide-subtle">
<tr v-for="guide in guides" :key="guide.id" class="hover:bg-muted/50 transition-colors">
<td class="px-6 py-4">
<component :is="getIcon(guide.file_type)" class="w-5 h-5 text-muted" />
</td>
<td class="px-6 py-4">
<div class="font-medium text-default">{{ guide.file_name }}</div>
<div class="text-xs text-muted mt-1 truncate max-w-[200px]">{{ guide.remark }}</div>
</td>
<td class="px-6 py-4">
<span class="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium bg-brand-50 text-brand-700 border border-brand-100">
{{ currentAgentName }}
</span>
</td>
<td class="px-6 py-4 text-muted">{{ formatSize(guide.file_size) }}</td>
<td class="px-6 py-4 text-muted">{{ guide.sort_order }}</td>
<td class="px-6 py-4">
<button
class="px-2 py-1 text-xs font-medium rounded-full transition-colors"
:class="guide.status === 1 ? 'bg-green-100 text-green-700 hover:bg-green-200' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'"
@click="toggleStatus(guide)"
>
{{ guide.status === 1 ? '已启用' : '已禁用' }}
</button>
</td>
<td class="px-6 py-4 text-right space-x-2">
<button type="button" class="btn-icon-ds" @click="openEditModal(guide)" title="编辑">
<Edit2 class="w-4 h-4" />
</button>
<button type="button" class="btn-icon-ds text-red-500 hover:bg-red-50" @click="deleteGuide(guide.id)" title="删除">
<Trash2 class="w-4 h-4" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- Modal -->
<div v-if="isModalOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
<div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl w-full max-w-lg overflow-hidden flex flex-col max-h-[90vh]">
<div class="px-6 py-4 border-b border-subtle flex justify-between items-center">
<h3 class="text-lg font-bold text-default">{{ isEditing ? '编辑指南' : '添加指南' }}</h3>
<button @click="isModalOpen = false" class="text-muted hover:text-default text-xl leading-none">&times;</button>
</div>
<div class="p-6 overflow-y-auto space-y-4">
<div v-if="!isEditing" class="space-y-2">
<label class="text-sm font-medium text-default">上传文件</label>
<input
type="file"
accept="video/mp4,video/webm,application/pdf,image/png,image/jpeg"
class="w-full text-sm text-muted file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
@change="handleFileUpload"
/>
<div v-if="isUploading" class="text-sm text-blue-600 mt-2 flex items-center gap-2">
<div class="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"></div> 上传中...
</div>
<div v-if="uploadError" class="text-sm text-red-500 mt-2">{{ uploadError }}</div>
<div v-if="form.file_path && !isUploading" class="text-sm text-green-600 mt-2">已上传文件就绪</div>
</div>
<div class="space-y-2">
<label class="text-sm font-medium text-default">资料名称</label>
<input v-model="form.file_name" type="text" class="input-field w-full" placeholder="如:人事助手使用手册" />
</div>
<div class="space-y-2">
<label class="text-sm font-medium text-default">备注说明</label>
<textarea v-model="form.remark" class="input-field w-full h-20" placeholder="简要说明..."></textarea>
</div>
<div class="grid grid-cols-2 gap-4">
<div class="space-y-2">
<label class="text-sm font-medium text-default">排序权重</label>
<input v-model.number="form.sort_order" type="number" class="input-field w-full" />
<p class="text-xs text-muted">数值越小越靠前</p>
</div>
<div class="space-y-2">
<label class="text-sm font-medium text-default">状态</label>
<select v-model="form.status" class="input-field w-full">
<option :value="1">启用</option>
<option :value="0">禁用</option>
</select>
</div>
</div>
</div>
<div class="px-6 py-4 border-t border-subtle bg-muted flex justify-end gap-3">
<button type="button" class="btn-secondary" @click="isModalOpen = false">取消</button>
<button
type="button"
class="btn-primary"
@click="submitForm"
:disabled="isUploading || !form.file_path || !form.file_name"
>
保存
</button>
</div>
</div>
</div>
</div>
</template>