Files
syops/frontend/src/shared/components/GeneralFeedbackDialog.vue
T
HTEWJ\26070045 836ddea84d Merge branch 'dev' into picture-feedback
# Conflicts:
#	backend/app/models/__init__.py
#	backend/app/services/voucher_check/notification.py
#	docs/features/accounting-voucher-check/demand.md
#	frontend/src/features/admin/modules/reports/ReportsPage.vue
#	frontend/src/shared/components/GeneralFeedbackDialog.vue
2026-10-29 12:42:02 +08:00

395 lines
15 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script setup lang="ts">
/**
* shared/components/GeneralFeedbackDialog.vue
* 通用意见反馈提交弹窗(Element Plus 版)。
* 用途:收集反馈类型/模块/内容,并支持粘贴(Ctrl+V)或点击选择图片;图片先经文件资产接口
* 上传换取 asset_no,提交时仅携带上传成功(status==='ready')的 asset_no 列表。
* 依赖:element-plus(ElDialog/ElSegmented/ElSelect/ElInput/ElButton/ElMessage)、
* shared/api/client.requestJson(自动附鉴权头,失败抛 BusinessError)、
* shared/api/file-assets.api.uploadFileAsset、vue-i18n。
* 逻辑关系:由 WorkspaceModals(workspace 入口,source_page='workspace')与
* ChatViewOverlays(chat 入口,source_page='chat' 且附 chat_log_id)挂载;
* 打开/重开与语言切换时重置表单并清理图片预览;提交成功 emit('submitted') 后关闭,
* 成功提示由父组件处理。类型/模块提交的是当前语言的展示文案(后端按 ≤32 字符字符串存储)。
*/
import { computed, reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { Loader2, Plus, X } from 'lucide-vue-next';
import {
ElButton,
ElDialog,
ElInput,
ElMessage,
ElOption,
ElSegmented,
ElSelect,
} from 'element-plus';
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/shared/styles/element-theme.css';
import { BusinessError, requestJson } from '@/shared/api/client';
import { uploadFileAsset } from '@/shared/api/file-assets.api';
/** 反馈图片数量上限(含上传中与已就绪;超过上限整批拒绝,不静默截取前 N 张)。 */
const MAX_FEEDBACK_IMAGES = 5;
/** 单张图片大小上限(MB):客户端预校验,避免超大文件先上传再被后端拒绝。 */
const MAX_FEEDBACK_IMAGE_SIZE_MB = 10;
/** 允许的图片 MIME 类型(与后端校验一致:png/jpg/jpeg/webp)。 */
const FEEDBACK_IMAGE_ACCEPT = ['image/png', 'image/jpeg', 'image/webp'];
interface PendingImage {
assetNo: string | null; // 上传成功后的 FA 编号
status: 'uploading' | 'ready';
previewUrl: string; // URL.createObjectURL(file)
filename: string;
}
interface Props {
modelValue: boolean;
sourcePage?: string;
chatLogId?: number | null;
}
const props = withDefaults(defineProps<Props>(), {
sourcePage: 'unknown',
chatLogId: null,
});
const emit = defineEmits<{
(e: 'update:modelValue', value: boolean): void;
(e: 'submitted'): void;
}>();
const { t, locale } = useI18n({ useScope: 'global' });
const visible = computed({
get: () => props.modelValue,
set: (v: boolean) => emit('update:modelValue', v),
});
const typeOptions = computed(() => [
t('feedback.type.featureSuggestion'),
t('feedback.type.issueReport'),
t('feedback.type.experienceOptimization'),
]);
const moduleOptions = computed(() => [
t('feedback.module.knowledgeBase'),
t('feedback.module.general'),
t('feedback.module.workflow'),
t('feedback.module.accountPermission'),
]);
const selectedType = ref<string>(t('feedback.type.featureSuggestion'));
const selectedModule = ref<string>(t('feedback.module.knowledgeBase'));
const content = ref('');
const submitting = ref(false);
const error = ref('');
const images = ref<PendingImage[]>([]);
const hasUploadingImage = computed(() => images.value.some((i) => i.status === 'uploading'));
const canSubmit = computed(() => content.value.trim().length > 0 && !submitting.value && !hasUploadingImage.value);
/**
* 批量加入反馈图片(粘贴与文件选择共用入口)。
* [AI 触发时机] 无 —— 纯 UI 交互:由 onPaste / onFileChange 调用,AI 不得主动调用。
* 核心逻辑:
* [STEP 1] 类型过滤:MIME 不在 FEEDBACK_IMAGE_ACCEPT 内的整段提示 invalidType(该批跳过);
* [STEP 2] 数量上限:已入队(含上传中)+ 本批有效数量 > MAX_FEEDBACK_IMAGES 时整批拒绝并提示
* maxCount,在发起任何上传之前拦截(防图片没传完又超限);
* [STEP 3] 逐张校验大小:超过 MAX_FEEDBACK_IMAGE_SIZE_MB 的单张跳过并提示 maxSize;
* [STEP 4] 逐张入队 status='uploading' → uploadFileAsset 成功置 ready+assetNo;
* 失败则移除该项(同时释放预览 URL)并提示 uploadFailed。
* @param files - 待加入的图片 File 列表(调用方保证来自剪贴板或 input.files)
* @returns Promise,完成后图片状态已落定(ready 或已移除)
*/
async function addImages(files: File[]): Promise<void> {
if (files.length === 0) return;
// [STEP 1] 类型过滤:不合法的整段提示一次,避免逐张刷屏
const typeValidFiles = files.filter((f) => FEEDBACK_IMAGE_ACCEPT.includes(f.type));
if (typeValidFiles.length < files.length) {
ElMessage.error(t('feedback.upload.invalidType'));
}
if (typeValidFiles.length === 0) return;
// [STEP 2] 数量上限校验必须先于任何上传发起;计数包含上传中与已就绪的图片
if (images.value.length + typeValidFiles.length > MAX_FEEDBACK_IMAGES) {
ElMessage.error(t('feedback.upload.maxCount', { count: MAX_FEEDBACK_IMAGES }));
return;
}
for (const file of typeValidFiles) {
// [STEP 3] 单张大小超限:仅跳过该张,不影响同批其他图片
if (file.size > MAX_FEEDBACK_IMAGE_SIZE_MB * 1024 * 1024) {
ElMessage.error(t('feedback.upload.maxSize', { size: MAX_FEEDBACK_IMAGE_SIZE_MB }));
continue;
}
// [STEP 4] 入队即占位(缩略图立即可见,uploading 态加遮罩),上传成功后才计入提交。
// 必须用 reactive 包装后再入队:uploadFileAsset 的 await 之后对 item 的 assetNo/status 写入
// 若发生在原始对象上,不经过数组内代理、不触发依赖更新,hasUploadingImage 的 computed
// 缓存永不失效 → 遮罩不消失且 canSubmit 永久为 false(提交按钮永远禁用)。
const item = reactive<PendingImage>({
assetNo: null,
status: 'uploading',
previewUrl: URL.createObjectURL(file),
filename: file.name,
});
images.value.push(item);
try {
const asset = await uploadFileAsset(file);
item.assetNo = asset.asset_no;
item.status = 'ready';
} catch {
// 上传失败:从队列移除并释放预览,避免提交时引用不存在的资产
const idx = images.value.indexOf(item);
if (idx !== -1) {
URL.revokeObjectURL(item.previewUrl);
images.value.splice(idx, 1);
}
ElMessage.error(t('feedback.upload.uploadFailed'));
}
}
}
/**
* 移除单张反馈图片。
* [AI 触发时机] 无 —— 纯 UI 交互:点击缩略图右上角 × 时调用。
* 核心逻辑:先 revoke 预览 objectURL(防内存泄漏)再从队列 splice;若该项尚在上传中,
* 其上传结果会被丢弃(indexOf 找不到已移除项,不会写回)。
* @param index - 待移除项在 images 中的下标
*/
function removeImage(index: number): void {
const item = images.value[index];
if (!item) return;
URL.revokeObjectURL(item.previewUrl);
images.value.splice(index, 1);
}
/**
* 处理弹窗内容区粘贴事件:提取剪贴板中的图片文件加入队列。
* [AI 触发时机] 无 —— 纯 UI 交互:仅在图片入队时才 preventDefault;
* 纯文本粘贴(无图片文件)不拦截,保证 textarea 文本粘贴行为不受影响。
* 核心逻辑:clipboardData.items 中 kind==='file' 且 type 以 'image/' 开头的项同步 getAsFile()
* (必须在 await 之前同步取完,剪贴板数据在事件处理后失效);未取到任何文件则直接返回。
* @param e - ClipboardEvent
*/
function onPaste(e: ClipboardEvent): void {
const items = e.clipboardData?.items;
if (!items) return;
const files: File[] = [];
for (const item of Array.from(items)) {
if (item.kind === 'file' && item.type.startsWith('image/')) {
const file = item.getAsFile();
if (file) files.push(file);
}
}
if (files.length === 0) return; // 纯文本粘贴:不拦截,保留默认行为
e.preventDefault();
void addImages(files);
}
/**
* 处理隐藏 file input 的 change 事件。
* [AI 触发时机] 无 —— 纯 UI 交互:点击「添加图片」格子选择文件后触发。
* 核心逻辑:取 input.files 交给 addImages,随后立即清空 input.value,
* 保证再次选择同一文件也会触发 change。
* @param e - input change 事件
*/
function onFileChange(e: Event): void {
const input = e.target as HTMLInputElement;
const files = input.files ? Array.from(input.files) : [];
void addImages(files);
input.value = '';
}
/**
* 清理全部待提交图片:revoke 所有预览 objectURL 并清空队列(防弹窗反复开关导致内存泄漏)。
* [AI 触发时机] 无 —— 内部生命周期函数:由 resetForm(打开/语言切换)与弹窗关闭 watch 调用。
*/
function cleanupImages(): void {
images.value.forEach((item) => URL.revokeObjectURL(item.previewUrl));
images.value = [];
}
const closeDialog = () => {
emit('update:modelValue', false);
};
const resetForm = () => {
selectedType.value = t('feedback.type.featureSuggestion');
selectedModule.value = t('feedback.module.knowledgeBase');
content.value = '';
error.value = '';
submitting.value = false;
cleanupImages();
};
watch(
() => props.modelValue,
(visible) => {
if (visible) resetForm();
else cleanupImages();
},
);
watch(locale, () => {
if (props.modelValue) {
resetForm();
}
});
/**
* 提交反馈(经统一 HTTP 客户端,自动附鉴权头)。
* [AI 触发时机] 无 —— 纯 UI 交互:点击提交按钮时调用。
* 核心逻辑:payload 携带 feedback_type / feedback_module(当前语言展示文案)、content、
* source_page、image_asset_nos(仅 status==='ready' 的图、按添加顺序;可为空数组,
* 后端把缺失与空数组同等对待),chat 入口另附 chat_log_id;BusinessError 的 message
* 展示在内联错误行,成功路径 emit('submitted') 后关闭(成功提示由父组件处理)。
*/
const submitFeedback = async () => {
if (!canSubmit.value) {
error.value = t('feedback.msg.fillContent');
return;
}
submitting.value = true;
error.value = '';
try {
const payload: Record<string, unknown> = {
feedback_type: selectedType.value,
feedback_module: selectedModule.value,
content: content.value.trim(),
source_page: props.sourcePage,
image_asset_nos: images.value
.filter((i) => i.status === 'ready')
.map((i) => i.assetNo as string),
};
if (props.chatLogId !== null && props.chatLogId !== undefined) {
payload.chat_log_id = props.chatLogId;
}
await requestJson<void>('/api/user/feedback', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
emit('submitted');
closeDialog();
} catch (e) {
error.value = e instanceof BusinessError ? e.message : t('feedback.msg.submitFailed');
} finally {
submitting.value = false;
}
};
</script>
<template>
<ElDialog
v-model="visible"
:title="t('feedback.title')"
width="640px"
append-to-body
:close-on-click-modal="false"
>
<div class="space-y-5" @paste="onPaste">
<div class="space-y-1.5">
<div class="text-sm font-medium text-secondary">{{ t('feedback.labels.type') }}</div>
<ElSegmented v-model="selectedType" :options="typeOptions" />
</div>
<div class="space-y-1.5">
<div class="text-sm font-medium text-secondary">{{ t('feedback.labels.module') }}</div>
<ElSelect v-model="selectedModule" class="w-full">
<ElOption v-for="item in moduleOptions" :key="item" :label="item" :value="item" />
</ElSelect>
</div>
<div class="space-y-1.5">
<div class="text-sm font-medium text-secondary">
{{ t('feedback.labels.content') }}<span class="ml-0.5 text-red-500">*</span>
</div>
<ElInput
v-model="content"
type="textarea"
:rows="5"
:maxlength="2000"
show-word-limit
resize="none"
:placeholder="t('feedback.placeholder.content')"
/>
<div class="mt-1 flex flex-wrap items-center gap-2">
<div
v-for="(img, idx) in images"
:key="img.previewUrl"
class="relative h-12 w-12"
>
<div class="h-full w-full overflow-hidden rounded-md border border-gray-200 dark:border-gray-600">
<img
:src="img.previewUrl"
:alt="img.filename"
class="h-full w-full object-cover"
/>
</div>
<!-- uploading 遮罩:提交按钮在此期间禁用(hasUploadingImage) -->
<div
v-if="img.status === 'uploading'"
class="pointer-events-none absolute inset-0 flex items-center justify-center rounded-md bg-black/50"
>
<Loader2 class="h-4 w-4 animate-spin text-white" />
</div>
<ElButton
size="small"
circle
:aria-label="t('feedback.upload.remove')"
class="absolute -right-2 -top-2"
@click="removeImage(idx)"
>
<X class="h-3 w-3" />
</ElButton>
</div>
<!-- label 包裹隐藏 file input:点击格子即唤起文件选择,无需手写按钮 -->
<label
class="flex h-12 cursor-pointer items-center gap-1.5 rounded-md border border-dashed border-gray-300 px-3 text-sm text-muted transition-colors hover:border-brand-400 hover:text-brand-600 dark:border-gray-600 dark:hover:border-brand-500"
>
<Plus class="h-4 w-4" />
<span>{{ t('feedback.upload.addImage') }}</span>
<input
type="file"
class="hidden"
multiple
accept="image/png,image/jpeg,image/webp"
@change="onFileChange"
/>
</label>
</div>
<p class="mt-1 text-xs text-muted">{{ t('feedback.upload.pasteHint') }}</p>
<!-- 内联错误行(字数统计由 ElInput show-word-limit 在输入框内单一呈现) -->
<div v-if="error" class="mt-2 text-base text-red-600">{{ error }}</div>
</div>
</div>
<template #footer>
<ElButton :disabled="submitting" @click="closeDialog">
{{ t('feedback.cancel') }}
</ElButton>
<ElButton
type="primary"
:loading="submitting"
:disabled="!canSubmit"
@click="submitFeedback"
>
{{ submitting ? t('feedback.submitting') : t('feedback.submit') }}
</ElButton>
</template>
</ElDialog>
</template>