Merge branch 'dev911' into test

This commit is contained in:
runny committed 2026-09-11 02:25:58 +08:00
commit e13838cbb8
71 files changed
+4706 -177

No files matched your search

+34 -1
View File
@@ -18,7 +18,15 @@ import type {
UsageReport,
UsageRangeKey,
} from '../types/report.types';
import type { TrainingConfig, TrainingConfigPayload, TrainingResourceCandidates } from '../types/training-config.types';
import type {
LeanTrainingWeeklyTask,
LeanTrainingWeeklyTaskPayload,
LeanTrainingDashboard,
LeanTrainingPushLog,
TrainingConfig,
TrainingConfigPayload,
TrainingResourceCandidates,
} from '../types/training-config.types';
const auth = () => ({ headers: getAuthHeaders() });
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
@@ -454,6 +462,31 @@ export const deleteAdminTrainingConfig = (id: number) =>
...auth(),
});
export const createOrUpdateAdminLeanTrainingWeeklyTask = (payload: LeanTrainingWeeklyTaskPayload) =>
requestJson<LeanTrainingWeeklyTask>('/api/admin/lean-training/weekly-tasks', {
method: 'POST',
...jsonAuth(),
body: JSON.stringify(payload),
});
export const getAdminLeanTrainingDashboard = () =>
requestJson<LeanTrainingDashboard>('/api/admin/lean-training/dashboard', auth());
/** 按 ID 读取指定周任务详情:发布/补推后刷新所选周任务上下文(dashboard 永远返回最新周,会跳走所选历史周)。 */
export const getAdminLeanTrainingWeeklyTask = (taskId: number) =>
requestJson<LeanTrainingWeeklyTask>(`/api/admin/lean-training/weekly-tasks/${taskId}`, auth());
/** HR 手动推送下一批精益培训视频(无需等待每周一排程),返回本轮推送日志。 */
export const pushAdminLeanTrainingWeeklyTask = (taskId: number) =>
requestJson<LeanTrainingPushLog>(`/api/admin/lean-training/weekly-tasks/${taskId}/push`, {
method: 'POST',
...auth(),
});
/** 读取指定周任务的分批推送日志(含失败明细),供"推送记录"区块展示。 */
export const getAdminLeanTrainingPushLogs = (taskId: number) =>
requestJson<LeanTrainingPushLog[]>(`/api/admin/lean-training/weekly-tasks/${taskId}/push-logs`, auth());
// Users
export const listAdminUsers = () => requestJson<AdminUserRow[]>('/api/admin/users', auth());
@@ -20,23 +20,36 @@ import {
ListChecks,
Plus,
Save,
Send,
Settings2,
ShieldCheck,
Trash2,
Video,
X,
} from 'lucide-vue-next';
import { useMessage } from '@/shared/composables/useMessage';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import {
createAdminTrainingConfig,
createAdminAgentGuide,
createOrUpdateAdminLeanTrainingWeeklyTask,
deleteAdminTrainingConfig,
getAdminLeanTrainingDashboard,
getAdminLeanTrainingPushLogs,
getAdminLeanTrainingWeeklyTask,
listAdminTrainingConfigs,
listAdminAgents,
listAdminTrainingResourceCandidates,
listAdminUsers,
parseAdminTrainingQuestionBank,
pushAdminLeanTrainingWeeklyTask,
updateAdminTrainingConfig,
uploadAdminAgentGuideFile,
} from '../../api/admin.api';
import type {
GenericTrainingStage,
LeanTrainingPushLog,
LeanTrainingWeeklyTask,
SafetyTrainingStage,
TrainingConfig,
TrainingConfigPayload,
@@ -44,7 +57,9 @@ import type {
TrainingLevel,
TrainingProgressItem,
} from '../../types/training-config.types';
import type { AdminUserRow } from '../../types/admin.types';
import TrainingTypeFormModal from './components/TrainingTypeFormModal.vue';
import LeanTargetModal from './components/LeanTargetModal.vue';
const { t } = useI18n();
const msg = useMessage();
@@ -61,9 +76,35 @@ const questionSourceVersionId = ref<number | null>(null);
const isParsingQuestions = ref(false);
const questionParseMeta = ref<{ mode: string; fileName: string; skipped: number[] } | null>(null);
const candidates = ref({ guides: [], documents: [], training_exam_documents: [] } as Awaited<ReturnType<typeof listAdminTrainingResourceCandidates>>);
const leanTask = ref<LeanTrainingWeeklyTask | null>(null);
const leanWeekKey = ref('');
const leanDueAt = ref('');
const leanWeeklyCount = ref(1);
const leanVideoResourceIds = ref<number[]>([]);
const leanTargetRoles = ref<string[]>([]);
const leanTargetUserIds = ref<number[]>([]);
const leanTargetUsers = ref<AdminUserRow[]>([]);
const isSavingLeanTask = ref(false);
const isPushingLeanTask = ref(false);
const leanPushLogs = ref<LeanTrainingPushLog[]>([]);
const isUploadingVideo = ref(false);
const videoInput = ref<HTMLInputElement | null>(null);
// 培训视频列表分页:一页最多 4 条记录(周任务规则)
const LEAN_VIDEO_PAGE_SIZE = 4;
const leanVideoPage = ref(1);
const selected = computed(() => configs.value.find((item) => item.id === selectedId.value) || null);
const form = ref<TrainingConfigPayload>(emptyForm());
const isSafetyConfig = computed(() => form.value.training_type === 'safety');
const supportsDirectVideoUpload = computed(() => (
['lean_management', 'overseas_regulations', 'overseas_regulations_training', 'overseas_training'].includes(form.value.training_type)
|| form.value.name.includes('出国规章')
));
const videoGuideCandidates = computed(() => candidates.value.guides.filter((guide) => guide.file_type.toLowerCase() === 'video'));
const directVideoResources = computed(() => contentResources.value.filter((resource) => (
resource.resource_type === 'agent_guide'
&& videoGuideCandidates.value.some((guide) => guide.id === resource.agent_guide_id)
)));
const contentResources = computed(() => form.value.resources.filter((resource) => resource.resource_type !== 'inline_questions'));
const trainingLevels: TrainingLevel[] = ['company', 'department', 'team'];
const guideGroups = computed(() => {
@@ -97,7 +138,8 @@ const sectionItems = computed(() => [
{ id: 'resources', label: t('admin.trainingConfig.sections.resourcesTitle'), icon: Library },
{ id: 'exam', label: t('admin.trainingConfig.sections.examTitle'), icon: FileQuestion },
{ id: 'review', label: t('admin.trainingConfig.sections.reviewTitle'), icon: ClipboardCheck },
]);
{ id: 'lean', label: t('admin.trainingConfig.sections.leanTitle'), icon: Video },
].filter((item) => item.id !== 'lean' || form.value.training_type === 'lean_management'));
const publishedCount = computed(() => configs.value.filter((config) => config.status === 'published').length);
const resourceCount = computed(() => contentResources.value.length);
const configuredLevelCount = computed(() => trainingLevels.filter((level) => resourcesByLevel(level).length > 0).length);
@@ -120,6 +162,197 @@ const progressItems = computed(() => {
const settings = form.value.settings as TrainingConfigSettings;
return Array.isArray(settings.progress_items) ? settings.progress_items : [];
});
const leanVideoResources = computed(() => form.value.resources.filter((resource) => {
if (resource.resource_type !== 'agent_guide' || !resource.id || !resource.agent_guide_id) return false;
const guide = candidates.value.guides.find((item) => item.id === resource.agent_guide_id);
return Boolean(guide?.file_type?.toLowerCase().startsWith('video'));
}));
const leanTaskVideoNames = computed(() => new Map(leanVideoResources.value.map((resource) => [
resource.id as number,
resource.title || candidates.value.guides.find((guide) => guide.id === resource.agent_guide_id)?.file_name || t('admin.trainingConfig.lean.unnamedVideo'),
])));
// 培训视频分页展示:一页最多 4 条(周任务规则 1)
const leanVideoTotalPages = computed(() => Math.max(1, Math.ceil(leanVideoResources.value.length / LEAN_VIDEO_PAGE_SIZE)));
const leanVideoResourcesPaged = computed(() => (
leanVideoResources.value.slice((leanVideoPage.value - 1) * LEAN_VIDEO_PAGE_SIZE, leanVideoPage.value * LEAN_VIDEO_PAGE_SIZE)
));
const leanRoleOptions = computed(() => [...new Set(leanTargetUsers.value.map((user) => user.role).filter(Boolean))].sort());
// 已选用户 ID → 用户行映射,用于受训对象列表展示真实姓名/用户名
const leanTargetUserMap = computed(() => new Map(leanTargetUsers.value.map((user) => [user.id, user])));
const showLeanTargetModal = ref(false);
/** 已选用户展示名:优先真实姓名,缺失时回退用户名,与弹窗选择列表口径一致。 */
const leanTargetUserName = (userId: number): string => {
const user = leanTargetUserMap.value.get(userId);
if (!user) return `#${userId}`;
return user.real_name || user.username;
};
/** 移除单个已选角色(弹窗外快捷操作,未保存前仅影响草稿状态)。 */
const removeLeanRole = (role: string) => {
leanTargetRoles.value = leanTargetRoles.value.filter((item) => item !== role);
};
/** 移除单个已选员工。 */
const removeLeanUser = (userId: number) => {
leanTargetUserIds.value = leanTargetUserIds.value.filter((item) => item !== userId);
};
/** 接收受训弹窗确认结果,写回角色与用户 ID 草稿,等待"保存任务"统一提交。 */
const handleLeanTargetSave = (payload: { roles: string[]; userIds: number[] }) => {
leanTargetRoles.value = payload.roles;
leanTargetUserIds.value = payload.userIds;
showLeanTargetModal.value = false;
};
function mondayOfCurrentWeek(): string {
const today = new Date();
const monday = new Date(today);
monday.setDate(today.getDate() - ((today.getDay() + 6) % 7));
return monday.toISOString().slice(0, 10);
}
function defaultLeanDueAt(weekKey: string): string {
const due = new Date(`${weekKey}T23:59:00`);
due.setDate(due.getDate() + 6);
const local = new Date(due.getTime() - due.getTimezoneOffset() * 60000);
return local.toISOString().slice(0, 16);
}
/** 将后端 UTC ISO 时间转换为 datetime-local 输入框本地值(YYYY-MM-DDTHH:mm),非法值返回空串。 */
const toLocalDateTimeInput = (iso: string | null | undefined): string => {
if (!iso) return '';
const parsed = new Date(iso);
if (Number.isNaN(parsed.getTime())) return '';
const local = new Date(parsed.getTime() - parsed.getTimezoneOffset() * 60000);
return local.toISOString().slice(0, 16);
};
const loadLeanTask = async () => {
if (form.value.training_type !== 'lean_management') return;
try {
const dashboard = await getAdminLeanTrainingDashboard();
leanTask.value = dashboard.task;
} catch {
leanTask.value = null;
}
// [RULE] 任务周与截止时间支持修改:已有任务回填其周次与截止(本地时区展示),新任务默认当周(周一 ~ 周日 23:59);保存后按所选周创建/更新
leanWeekKey.value = leanTask.value?.week_key || mondayOfCurrentWeek();
leanDueAt.value = leanTask.value?.due_at ? toLocalDateTimeInput(leanTask.value.due_at) : defaultLeanDueAt(leanWeekKey.value);
leanWeeklyCount.value = leanTask.value?.weekly_count ?? 1;
leanVideoResourceIds.value = leanTask.value?.video_resource_ids ? [...leanTask.value.video_resource_ids] : [];
leanTargetRoles.value = leanTask.value?.target_roles ? [...leanTask.value.target_roles] : [];
leanTargetUserIds.value = leanTask.value?.target_user_ids ? [...leanTask.value.target_user_ids] : [];
leanTargetUsers.value = await listAdminUsers();
leanVideoPage.value = 1;
if (leanTask.value) await loadLeanPushLogs();
};
/** 拉取当前周任务的分批推送日志(含失败明细),供"推送记录"区块展示。 */
const loadLeanPushLogs = async () => {
if (!leanTask.value) return;
try {
leanPushLogs.value = await getAdminLeanTrainingPushLogs(leanTask.value.id);
} catch {
leanPushLogs.value = [];
}
};
/** 立即新增任务补推:按现有游标逻辑对新增任务视频增推一批(数量=每周任务数量),无需等待每周一排程;成功后刷新任务与日志。 */
const pushLeanTaskNow = async () => {
if (!leanTask.value || isPushingLeanTask.value) return;
isPushingLeanTask.value = true;
try {
const log = await pushAdminLeanTrainingWeeklyTask(leanTask.value.id);
if (log.status === 'completed') {
msg.warning(t('admin.trainingConfig.lean.pushCompleted'));
} else {
msg.success(t('admin.trainingConfig.lean.pushSuccess', { count: log.pushed_count }));
}
// [STEP] 补推后按所选周任务刷新(而非 dashboard 最新周),保持表单周次/截止/游标上下文一致
try {
leanTask.value = await getAdminLeanTrainingWeeklyTask(leanTask.value.id);
leanVideoResourceIds.value = leanTask.value?.video_resource_ids ? [...leanTask.value.video_resource_ids] : [];
} catch {
// 刷新失败不吞掉推送成功结果,游标以推送日志为准
}
await loadLeanPushLogs();
} catch (error) {
msg.error(error instanceof Error ? error.message : t('admin.trainingConfig.lean.pushFailed'));
} finally {
isPushingLeanTask.value = false;
}
};
/**
* 判断视频是否为已推送(锁定)状态:任务游标前缀内的视频已推送给受训员工。
* 业务约束:推送过的视频默认勾选且不能取消勾选(周任务规则 5)。
*/
const isLeanVideoLocked = (resourceId: number): boolean => {
const pushedCount = leanTask.value?.pushed_video_count ?? 0;
return (leanTask.value?.video_resource_ids || []).slice(0, pushedCount).includes(resourceId);
};
/**
* 已推送视频的周次标签:"第N周 MM-DD至MM-DD"(N=任务期号,范围为该任务周)。
* 仅已推送视频展示(周任务规则 4),未推送视频返回空字符串。
*/
const leanVideoWeekLabel = (resourceId: number): string => {
if (!isLeanVideoLocked(resourceId) || !leanTask.value) return '';
const weekKey = leanTask.value.week_key || '';
const weekEnd = leanTask.value.week_end || '';
const range = weekKey && weekEnd ? `${weekKey.slice(5)}至${weekEnd.slice(5)}` : weekKey;
return t('admin.trainingConfig.lean.weekRangeLabel', { index: leanTask.value.week_index ?? 1, range });
};
/** 培训视频翻页:目标页越界时收敛到有效范围。 */
const goLeanVideoPage = (page: number) => {
leanVideoPage.value = Math.min(Math.max(1, page), leanVideoTotalPages.value);
};
/** 切换视频选择:已推送(锁定)视频禁止取消勾选;新视频可自由追加/移除,保存后按选择顺序继续分批推送。 */
const toggleLeanVideo = (resourceId: number) => {
if (isLeanVideoLocked(resourceId)) return;
leanVideoResourceIds.value = leanVideoResourceIds.value.includes(resourceId)
? leanVideoResourceIds.value.filter((id) => id !== resourceId)
: [...leanVideoResourceIds.value, resourceId];
};
const saveLeanTask = async () => {
// 任务周必须为周一:date input 允许选任意日期,前端先行拦截,后端同规则兜底校验
if (!leanWeekKey.value || new Date(`${leanWeekKey.value}T00:00:00`).getDay() !== 1) {
msg.warning(t('admin.trainingConfig.lean.weekMustBeMonday'));
return;
}
isSavingLeanTask.value = true;
try {
leanTask.value = await createOrUpdateAdminLeanTrainingWeeklyTask({
// 任务周/截止时间支持修改:按表单所选周创建或更新,发布/补推均作用于所选周任务(周任务规则 7)
week_key: leanWeekKey.value,
due_at: new Date(leanDueAt.value).toISOString(),
// 未勾选任何视频时传空数组,服务端自动按上传时间倒序冻结全部视频(周任务规则 6)
video_resource_ids: leanVideoResourceIds.value,
target_roles: leanTargetRoles.value,
target_user_ids: leanTargetUserIds.value,
weekly_count: leanWeeklyCount.value,
});
// 保存后回填勾选状态(空选择时服务端可能已自动填充全部视频)
leanVideoResourceIds.value = leanTask.value?.video_resource_ids ? [...leanTask.value.video_resource_ids] : [];
await loadLeanPushLogs();
msg.success(t('admin.trainingConfig.messages.leanTaskSaved'));
} catch (error) {
msg.error(error instanceof Error ? error.message : t('admin.trainingConfig.messages.saveFailed'));
} finally {
isSavingLeanTask.value = false;
}
};
/** 推送批次展示名:视频序号(从 1 起)+ 资源标题。 */
const leanPushedVideoLabel = (resourceId: number): string => {
const index = leanTask.value?.video_resource_ids.indexOf(resourceId) ?? -1;
const name = leanTaskVideoNames.value.get(resourceId) || `#${resourceId}`;
return index >= 0 ? `${String(index + 1).padStart(2, '0')} ${name}` : name;
};
/** 创建新增培训类型所需的完整默认配置,确保沿用后端既有字段契约。 */
function emptyForm(): TrainingConfigPayload {
@@ -181,6 +414,7 @@ const selectConfig = (config: TrainingConfig) => {
questionJsonText.value = JSON.stringify(questions, null, 2);
questionSourceVersionId.value = null;
questionParseMeta.value = null;
void loadLeanTask();
};
/** 从已选择的员工培训知识库当前 PDF 解析题库,并将结果回填到可继续手工编辑的 JSON。 */
@@ -428,6 +662,54 @@ const updateResourceType = (resource: TrainingConfigPayload['resources'][number]
resource.kb_document_version_id = undefined;
};
const openVideoUpload = () => videoInput.value?.click();
const uploadTrainingVideo = async (event: Event) => {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
input.value = '';
if (!file) return;
if (!file.type.startsWith('video/')) {
msg.warning(t('admin.trainingConfig.messages.videoFileRequired'));
return;
}
isUploadingVideo.value = true;
try {
const trainingAgent = (await listAdminAgents()).find((agent) => (
agent.handler_config?.content_profile === 'training'
|| agent.extra_config?.training_workspace_enabled === true
|| agent.extra_config?.training_mode === true
|| agent.extra_config?.training_agent === true
));
if (!trainingAgent) throw new Error(t('admin.trainingConfig.messages.trainingAgentRequired'));
const uploaded = await uploadAdminAgentGuideFile(file);
const created = await createAdminAgentGuide({
agent_id: trainingAgent.id,
file_name: uploaded.file_name,
file_path: uploaded.file_path,
file_type: uploaded.file_type,
file_size: uploaded.file_size,
guide_usage: 'training_video',
sort_order: candidates.value.guides.length,
status: 1,
}) as { id: number };
candidates.value = await listAdminTrainingResourceCandidates();
form.value.resources.push({
resource_type: 'agent_guide',
agent_guide_id: created.id,
training_level: 'company',
title: uploaded.file_name,
required_duration: 0,
sort_order: form.value.resources.length,
});
msg.success(t('admin.trainingConfig.messages.videoUploaded'));
} catch (error) {
msg.error(error instanceof Error ? error.message : t('admin.trainingConfig.messages.videoUploadFailed'));
} finally {
isUploadingVideo.value = false;
}
};
const scrollToSection = (sectionId: string) => {
activeSection.value = sectionId;
document.getElementById(`training-section-${sectionId}`)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
@@ -614,7 +896,26 @@ onMounted(() => void load());
<p class="mt-1 text-xs text-muted">{{ t('admin.trainingConfig.resourcesEmptyHint') }}</p>
</div>
<div class="flex flex-col gap-5">
<article v-if="supportsDirectVideoUpload" class="w-full overflow-hidden rounded-2xl border border-violet-200 bg-surface shadow-sm">
<div class="flex flex-col gap-3 border-b border-violet-200 bg-violet-50/80 px-5 py-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<h4 class="text-base font-bold text-primary">{{ t('admin.trainingConfig.directVideo.title') }}</h4>
<p class="mt-1 text-xs text-muted">{{ t('admin.trainingConfig.directVideo.hint') }}</p>
</div>
<button class="btn-secondary btn-sm" type="button" :disabled="isUploadingVideo" @click="openVideoUpload"><Plus class="h-4 w-4" />{{ isUploadingVideo ? t('admin.trainingConfig.directVideo.uploading') : t('admin.trainingConfig.directVideo.upload') }}</button>
<input ref="videoInput" type="file" accept="video/*" class="hidden" @change="uploadTrainingVideo" />
</div>
<div class="space-y-3 p-4 md:p-5">
<div v-if="!directVideoResources.length" class="rounded-xl border border-dashed border-default bg-surface-soft/50 px-3 py-8 text-center text-xs text-muted">{{ t('admin.trainingConfig.directVideo.empty') }}</div>
<div v-for="(resource, index) in directVideoResources" v-else :key="resource.id || `direct-video-${index}`" class="grid gap-3 rounded-xl border border-default bg-white p-4 md:grid-cols-[minmax(0,1fr)_180px_auto] md:items-end">
<div class="flex min-w-0 items-center gap-2 text-sm font-medium text-primary"><Video class="h-4 w-4 shrink-0 text-violet-500" /><span class="truncate">{{ resource.title || videoGuideCandidates.find((guide) => guide.id === resource.agent_guide_id)?.file_name || t('admin.trainingConfig.directVideo.unnamed') }}</span></div>
<label class="label-field">{{ t('admin.trainingConfig.fields.requiredDuration') }}<input v-model.number="resource.required_duration" type="number" min="0" class="input-field mt-2" /></label>
<button class="btn-danger btn-sm" type="button" @click="removeResource(resource)"><Trash2 class="h-4 w-4" />{{ t('admin.delete') }}</button>
</div>
</div>
</article>
<article
v-if="isSafetyConfig"
v-for="(level, levelIndex) in trainingLevels"
:key="level"
class="w-full overflow-hidden rounded-2xl border bg-surface shadow-sm"
@@ -667,6 +968,108 @@ onMounted(() => void load());
</div>
</section>
<section v-if="form.training_type === 'lean_management'" id="training-section-lean" class="surface-panel scroll-mt-20 p-5 md:p-7">
<div class="mb-6 flex items-start gap-3">
<span class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-emerald-50 text-emerald-600"><Video class="h-5 w-5" /></span>
<div><h3 class="text-base font-bold text-primary">{{ t('admin.trainingConfig.sections.leanTitle') }}</h3><p class="mt-1 text-sm text-muted">{{ t('admin.trainingConfig.sections.leanDesc') }}</p></div>
</div>
<div v-if="form.status !== 'published'" class="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800">{{ t('admin.trainingConfig.lean.publishRequired') }}</div>
<div v-else class="space-y-5">
<div class="grid gap-5 md:grid-cols-3">
<!-- 任务周/截止时间支持修改:按所选自然周创建或更新任务,【发布周任务】/【立即新增任务补推】均作用于所选周 -->
<label class="label-field">{{ t('admin.trainingConfig.lean.weekKey') }}<input v-model="leanWeekKey" type="date" class="input-field mt-2" /></label>
<label class="label-field">{{ t('admin.trainingConfig.lean.dueAt') }}<input v-model="leanDueAt" type="datetime-local" class="input-field mt-2" /></label>
<!-- 每周任务数量:每周一 09:00 按该数量从视频列表顺序推送下一批给受训对象 -->
<label class="label-field">{{ t('admin.trainingConfig.lean.weeklyCount') }}<input v-model.number="leanWeeklyCount" type="number" min="1" max="50" class="input-field mt-2" /></label>
</div>
<p class="-mt-2 text-xs text-muted">{{ t('admin.trainingConfig.lean.weeklyCountHint', { pushed: leanTask?.pushed_video_count ?? 0, total: leanVideoResourceIds.length }) }}</p>
<div class="rounded-xl border border-default bg-surface-soft/40 p-4">
<div class="flex flex-wrap items-center justify-between gap-2">
<div><h4 class="text-sm font-semibold text-primary">{{ t('admin.trainingConfig.lean.videosTitle') }}</h4><p class="mt-1 text-xs text-muted">{{ t('admin.trainingConfig.lean.videosHint', { count: leanVideoResourceIds.length }) }}</p></div>
<span v-if="leanTask" class="rounded-full bg-emerald-50 px-3 py-1 text-xs font-medium text-emerald-700">{{ t('admin.trainingConfig.lean.pushProgress', { pushed: leanTask.pushed_video_count, total: leanTask.video_resource_ids.length }) }}</span>
</div>
<div v-if="!leanVideoResources.length" class="mt-4 rounded-lg border border-dashed border-default bg-white px-4 py-5 text-sm text-muted">{{ t('admin.trainingConfig.lean.noVideoResources') }}</div>
<template v-else>
<!-- 培训视频分页展示:一页最多 4 条(周任务规则 1);已推送视频锁定勾选并展示周次标签 -->
<div class="mt-4 grid gap-3 md:grid-cols-2">
<label v-for="resource in leanVideoResourcesPaged" :key="resource.id" class="flex items-center gap-3 rounded-xl border bg-white p-4 transition" :class="leanVideoResourceIds.includes(resource.id as number) ? 'border-emerald-400 ring-1 ring-emerald-200' : 'border-default'" :style="isLeanVideoLocked(resource.id as number) ? 'cursor:not-allowed' : 'cursor:pointer'">
<input :checked="leanVideoResourceIds.includes(resource.id as number)" type="checkbox" :disabled="isLeanVideoLocked(resource.id as number)" class="h-4 w-4 rounded border-default text-emerald-600 focus:ring-emerald-500 disabled:opacity-70" @change="toggleLeanVideo(resource.id as number)" />
<span class="min-w-0 flex-1 truncate text-sm text-primary">{{ leanTaskVideoNames.get(resource.id as number) }}</span>
<!-- 已推送视频展示所属周次:"第N周 MM-DD至MM-DD"(不可取消勾选) -->
<span v-if="leanVideoWeekLabel(resource.id as number)" class="shrink-0 rounded-full bg-emerald-50 px-2.5 py-0.5 text-xs font-medium text-emerald-700">{{ leanVideoWeekLabel(resource.id as number) }}</span>
</label>
</div>
<!-- 分页控件:超过一页时展示上一页/下一页与页码概览 -->
<div v-if="leanVideoTotalPages > 1" class="mt-3 flex items-center justify-end gap-2 text-xs text-muted">
<button class="btn-secondary btn-sm" type="button" :disabled="leanVideoPage <= 1" @click="goLeanVideoPage(leanVideoPage - 1)">{{ t('admin.trainingConfig.lean.videoPagePrev') }}</button>
<span>{{ t('admin.trainingConfig.lean.videoPageInfo', { page: leanVideoPage, total: leanVideoTotalPages }) }}</span>
<button class="btn-secondary btn-sm" type="button" :disabled="leanVideoPage >= leanVideoTotalPages" @click="goLeanVideoPage(leanVideoPage + 1)">{{ t('admin.trainingConfig.lean.videoPageNext') }}</button>
</div>
</template>
</div>
<div class="rounded-xl border border-default bg-surface-soft/40 p-4">
<div class="flex flex-wrap items-center justify-between gap-2">
<div><h4 class="text-sm font-semibold text-primary">{{ t('admin.trainingConfig.lean.targetsTitle') }}</h4><p class="mt-1 text-xs text-muted">{{ t('admin.trainingConfig.lean.targetsHint') }}</p></div>
<button class="btn-secondary btn-sm" type="button" @click="showLeanTargetModal = true"><Plus class="h-4 w-4" />{{ t('admin.trainingConfig.lean.addTarget') }}</button>
</div>
<!-- 已选受训对象列表:角色与员工以 chip 展示,支持快捷移除 -->
<div v-if="!leanTargetRoles.length && !leanTargetUserIds.length" class="mt-4 rounded-lg border border-dashed border-default bg-white px-4 py-5 text-sm text-muted">{{ t('admin.trainingConfig.lean.targetEmpty') }}</div>
<div v-else class="mt-4 space-y-3">
<div v-if="leanTargetRoles.length" class="flex flex-wrap items-center gap-2">
<span class="shrink-0 text-xs font-medium text-muted">{{ t('admin.trainingConfig.lean.targetRoles') }}</span>
<span v-for="role in leanTargetRoles" :key="role" class="inline-flex items-center gap-1 rounded-full bg-emerald-50 px-3 py-1 text-xs font-medium text-emerald-700">
{{ role }}
<button type="button" class="rounded-full transition hover:text-emerald-900" :title="t('admin.trainingConfig.lean.removeTarget')" @click="removeLeanRole(role)"><X class="h-3 w-3" /></button>
</span>
</div>
<div v-if="leanTargetUserIds.length" class="flex flex-wrap items-center gap-2">
<span class="shrink-0 text-xs font-medium text-muted">{{ t('admin.trainingConfig.lean.targetUsersCount', { count: leanTargetUserIds.length }) }}</span>
<span v-for="userId in leanTargetUserIds" :key="userId" class="inline-flex items-center gap-1 rounded-full bg-sky-50 px-3 py-1 text-xs font-medium text-sky-700">
{{ leanTargetUserName(userId) }}
<button type="button" class="rounded-full transition hover:text-sky-900" :title="t('admin.trainingConfig.lean.removeTarget')" @click="removeLeanUser(userId)"><X class="h-3 w-3" /></button>
</span>
</div>
</div>
<!-- 添加受训弹窗:按角色 / 按员工多选 -->
<LeanTargetModal
:visible="showLeanTargetModal"
:roles="leanTargetRoles"
:user-ids="leanTargetUserIds"
:users="leanTargetUsers"
:role-options="leanRoleOptions"
@close="showLeanTargetModal = false"
@save="handleLeanTargetSave"
/>
</div>
<div class="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-emerald-200 bg-emerald-50/50 p-4">
<p class="text-sm text-emerald-800">{{ t('admin.trainingConfig.lean.summaryRule', { count: 50 }) }}</p>
<div class="flex flex-wrap items-center gap-2">
<!-- 手动推送:立即按每周任务数量推送下一批视频,无需等待每周一排程 -->
<button class="btn-secondary btn-sm" type="button" :disabled="!leanTask || isPushingLeanTask" @click="pushLeanTaskNow"><Send class="h-4 w-4" />{{ isPushingLeanTask ? t('admin.trainingConfig.lean.pushing') : t('admin.trainingConfig.lean.pushNow') }}</button>
<button class="btn-primary btn-sm" type="button" :disabled="isSavingLeanTask || !leanWeekKey || !leanDueAt || leanVideoResourceIds.length < 1 || (!leanTargetRoles.length && !leanTargetUserIds.length)" @click="saveLeanTask"><Save class="h-4 w-4" />{{ isSavingLeanTask ? t('admin.trainingConfig.saving') : t('admin.trainingConfig.lean.saveTask') }}</button>
</div>
</div>
<!-- 推送记录:每轮发布/排程/手动推送的批次、成败计数与失败明细 -->
<div class="rounded-xl border border-default bg-surface-soft/40 p-4">
<h4 class="text-sm font-semibold text-primary">{{ t('admin.trainingConfig.lean.pushLogsTitle') }}</h4>
<div v-if="!leanPushLogs.length" class="mt-3 rounded-lg border border-dashed border-default bg-white px-4 py-5 text-sm text-muted">{{ t('admin.trainingConfig.lean.pushLogsEmpty') }}</div>
<ul v-else class="mt-3 space-y-3">
<li v-for="log in leanPushLogs" :key="log.id" class="rounded-lg border bg-white p-3 text-sm" :class="log.status === 'failed' ? 'border-red-200' : 'border-default'">
<div class="flex flex-wrap items-center gap-2">
<span class="rounded-full px-2.5 py-0.5 text-xs font-medium" :class="log.status === 'failed' ? 'bg-red-50 text-red-700' : log.status === 'partial' ? 'bg-amber-50 text-amber-700' : 'bg-emerald-50 text-emerald-700'">{{ t(`admin.trainingConfig.lean.pushStatus.${log.status}`) }}</span>
<span class="text-xs text-muted">{{ t(`admin.trainingConfig.lean.pushTrigger.${log.trigger}`) }} · {{ log.created_at ? new Date(log.created_at).toLocaleString() : '' }}</span>
</div>
<p class="mt-2 text-xs text-muted">{{ t('admin.trainingConfig.lean.pushBatch', { count: log.pushed_count, sent: log.sent_count, failed: log.failed_count, recipients: log.recipient_count }) }}</p>
<div v-if="log.pushed_resource_ids?.length" class="mt-2 flex flex-wrap gap-1.5">
<span v-for="resourceId in log.pushed_resource_ids" :key="resourceId" class="rounded-full bg-slate-100 px-2.5 py-0.5 text-xs text-slate-600">{{ leanPushedVideoLabel(resourceId) }}</span>
</div>
<p v-if="log.error_message" class="mt-2 rounded bg-red-50 px-2.5 py-1.5 text-xs text-red-700">{{ log.error_message }}</p>
</li>
</ul>
</div>
</div>
</section>
<section id="training-section-exam" class="surface-panel scroll-mt-20 p-5 md:p-7">
<div class="mb-6 flex items-start justify-between gap-4">
<div class="flex items-start gap-3">
@@ -0,0 +1,138 @@
<script setup lang="ts">
/**
* features/admin/modules/training-config/components/LeanTargetModal.vue
* 用途:精益周任务"受训对象"选择弹窗,支持按角色、按员工两个维度多选(两个范围取并集生效)。
* 依赖:vue-i18n、lucide 图标与父级培训配置页面传入的目标状态(角色/用户 ID/用户列表)。
* 逻辑:弹窗打开时从 props 快照到本地草稿(取消不污染外部状态);员工支持关键字搜索;
* 确认后 emit save({ roles, userIds }),由父级写回表单并随"保存任务"统一落库。
*/
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { Search } from 'lucide-vue-next';
import type { AdminUserRow } from '../../../types/admin.types';
const props = defineProps<{
visible: boolean;
roles: string[];
userIds: number[];
users: AdminUserRow[];
roleOptions: string[];
}>();
const emit = defineEmits<{ close: []; save: [payload: { roles: string[]; userIds: number[] }] }>();
const { t } = useI18n();
const draftRoles = ref<string[]>([]);
const draftUserIds = ref<number[]>([]);
const keyword = ref('');
// [STEP 1] 打开时同步父级当前选择,避免用户在弹窗内取消后残留草稿
watch(() => props.visible, (visible) => {
if (visible) {
draftRoles.value = [...props.roles];
draftUserIds.value = [...props.userIds];
keyword.value = '';
}
});
// [STEP 2] 员工列表按姓名/用户名/部门模糊过滤,便于在大量员工中快速定位
const filteredUsers = computed(() => {
const query = keyword.value.trim().toLowerCase();
if (!query) return props.users;
return props.users.filter((user) => [user.real_name, user.username, user.department]
.some((field) => field && field.toLowerCase().includes(query)));
});
const summaryLabel = computed(() => t('admin.trainingConfig.lean.targetSelectedCount', {
roles: draftRoles.value.length,
users: draftUserIds.value.length,
}));
const toggleRole = (role: string) => {
draftRoles.value = draftRoles.value.includes(role)
? draftRoles.value.filter((item) => item !== role)
: [...draftRoles.value, role];
};
const toggleUser = (userId: number) => {
draftUserIds.value = draftUserIds.value.includes(userId)
? draftUserIds.value.filter((item) => item !== userId)
: [...draftUserIds.value, userId];
};
const handleSave = () => {
emit('save', { roles: [...draftRoles.value], userIds: [...draftUserIds.value] });
};
</script>
<template>
<div v-if="props.visible" class="admin-modal-overlay animate-fade-in items-center" @click.self="emit('close')">
<div class="admin-modal-panel max-w-2xl max-h-[92vh] scale-100">
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
<h3 class="section-title">{{ t('admin.trainingConfig.lean.targetModalTitle') }}</h3>
<p class="mt-1 text-xs text-muted">{{ t('admin.trainingConfig.lean.targetsHint') }}</p>
</div>
<div class="px-5 sm:px-8 py-5 overflow-y-auto">
<div class="grid gap-5 md:grid-cols-2">
<!-- 按角色选择 -->
<div class="space-y-2">
<label class="label-field">{{ t('admin.trainingConfig.lean.targetRoles') }}</label>
<div class="space-y-2 rounded-xl border border-default bg-surface p-3">
<label
v-for="role in props.roleOptions"
:key="role"
class="flex cursor-pointer items-center gap-3 rounded-lg px-2 py-2 text-sm transition hover:bg-surface-soft"
>
<input
type="checkbox"
class="h-4 w-4 rounded border-default text-emerald-600 focus:ring-emerald-500"
:checked="draftRoles.includes(role)"
@change="toggleRole(role)"
/>
<span class="text-primary">{{ role }}</span>
</label>
<p v-if="!props.roleOptions.length" class="px-2 py-3 text-xs text-muted">{{ t('admin.trainingConfig.lean.targetRolesEmpty') }}</p>
</div>
</div>
<!-- 按员工选择 -->
<div class="space-y-2">
<label class="label-field">{{ t('admin.trainingConfig.lean.targetUsers') }}</label>
<div class="relative">
<Search class="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted" />
<input
v-model="keyword"
type="text"
class="input-field pl-9 text-sm"
:placeholder="t('admin.trainingConfig.lean.targetSearchPlaceholder')"
/>
</div>
<div class="max-h-64 space-y-1 overflow-y-auto rounded-xl border border-default bg-surface p-2">
<label
v-for="user in filteredUsers"
:key="user.id"
class="flex cursor-pointer items-center gap-3 rounded-lg px-2 py-2 text-sm transition hover:bg-surface-soft"
>
<input
type="checkbox"
class="h-4 w-4 rounded border-default text-emerald-600 focus:ring-emerald-500"
:checked="draftUserIds.includes(user.id)"
@change="toggleUser(user.id)"
/>
<span class="min-w-0 flex-1 truncate text-primary">{{ user.real_name || user.username }}</span>
<span class="shrink-0 text-xs text-muted">{{ user.username }}</span>
</label>
<p v-if="!filteredUsers.length" class="px-2 py-3 text-xs text-muted">{{ t('admin.trainingConfig.lean.targetUsersEmpty') }}</p>
</div>
</div>
</div>
</div>
<div class="admin-modal-footer">
<p class="mr-auto text-xs text-muted">{{ summaryLabel }}</p>
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
<button type="button" class="btn-primary" @click="handleSave">
{{ t('admin.trainingConfig.lean.targetConfirm') }}
</button>
</div>
</div>
</div>
</template>
@@ -58,6 +58,54 @@ export interface TrainingConfigPayload {
resources: TrainingConfigResource[];
}
/** 精益推送日志:记录每轮(发布/排程/手动)分批推送视频的执行结果与失败明细。 */
export interface LeanTrainingPushLog {
id: number;
weekly_task_id: number;
trigger: 'publish' | 'schedule' | 'manual' | string;
pushed_resource_ids: number[];
pushed_count: number;
recipient_count: number;
sent_count: number;
skipped_count: number;
failed_count: number;
status: 'sent' | 'partial' | 'failed' | 'completed' | string;
error_message: string | null;
created_by_id: number | null;
created_at: string;
}
export interface LeanTrainingWeeklyTask {
id: number;
week_key: string;
/** 任务周周日(ISO 日期),与 week_key 拼装"第N周 MM-DD至MM-DD"周次标签。 */
week_end: string | null;
/** 期号:按周次升序编号,最早一周为第 1 期。 */
week_index: number;
due_at: string;
video_resource_ids: number[];
target_roles: string[];
target_user_ids: number[];
videos: Array<{ id: number; name: string }>;
status: string;
min_summary_length: number;
weekly_count: number;
pushed_video_count: number;
}
export interface LeanTrainingWeeklyTaskPayload {
week_key: string;
due_at: string;
video_resource_ids: number[];
target_roles: string[];
target_user_ids: number[];
weekly_count: number;
}
export interface LeanTrainingDashboard {
task: LeanTrainingWeeklyTask | null;
}
export interface TrainingResourceCandidates {
guides: Array<{
id: number;
+93 -2
View File
@@ -1,8 +1,8 @@
/**
* features/chat/api/training.api.ts
* 用途:培训工作区专用 HTTP API,负责员工进度读取/保存、HR 记录查询、统计和导出。
* 用途:培训工作区专用 HTTP API,负责员工进度读取/保存、HR 记录查询、统计导出和精益任务提醒。
* 依赖:shared/api/client、auth headers、training.types。
* 逻辑:把后端 training 领域的 snake_case 返回值统一映射成前端工作区需要的 camelCase 结构。
* 逻辑:把后端 training 领域的 snake_case 返回值统一映射成前端工作区需要的 camelCase 结构,并提交精益未完成人员提醒请求。
*/
import { requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
@@ -15,10 +15,60 @@ import type {
TrainingRecord,
TrainingStage,
TrainingStats,
LeanTrainingDashboard,
LeanTrainingDashboardRow,
LeanTrainingMyTask,
LeanTrainingTaskStatus,
LeanTrainingWeeklyTask,
TrainingType,
TrainingTypeOption,
} from '../training/training.types';
type LeanTrainingTaskApi = {
id: number; week_key: string; due_at: string; video_resource_ids: number[];
target_roles: string[]; target_user_ids: number[];
videos: Array<{ id: number; name: string; file_url?: string | null }>; status: string; min_summary_length: number;
weekly_count?: number; pushed_video_count?: number;
week_end?: string | null; week_index?: number;
};
type LeanTrainingMyTaskApi = LeanTrainingTaskApi & {
task_status: LeanTrainingTaskStatus;
completion: { summary_text: string; watched_at: Record<string, string>; completed_at?: string | null } | null;
};
type LeanTrainingDashboardRowApi = {
id?: number; user_id: number; employee_id?: string | null; name: string; department?: string | null;
videos: Array<{ name: string; watched_at?: string | null }>;
// 后端序列化层三态归一:completed=已提交感悟;overdue=过截止未完成;in_progress=进行中
summary_text?: string | null; status: 'completed' | 'in_progress' | 'overdue'; completed_at?: string | null;
};
const mapLeanTask = (data: LeanTrainingTaskApi): LeanTrainingWeeklyTask => ({
id: data.id, weekKey: data.week_key, dueAt: data.due_at, videoResourceIds: data.video_resource_ids || [],
targetRoles: data.target_roles || [], targetUserIds: data.target_user_ids || [],
videos: (data.videos || []).map((video) => ({ id: video.id, name: video.name, fileUrl: video.file_url || null })),
status: data.status, minSummaryLength: data.min_summary_length,
weeklyCount: data.weekly_count, pushedVideoCount: data.pushed_video_count,
weekEnd: data.week_end ?? null, weekIndex: data.week_index,
});
const mapLeanMyTask = (data: LeanTrainingMyTaskApi): LeanTrainingMyTask => ({
...mapLeanTask(data),
taskStatus: data.task_status,
completion: data.completion ? {
summaryText: data.completion.summary_text,
watchedAt: data.completion.watched_at || {},
completedAt: data.completion.completed_at || null,
} : null,
});
const mapLeanDashboardRow = (data: LeanTrainingDashboardRowApi): LeanTrainingDashboardRow => ({
id: data.id, userId: data.user_id, employeeId: data.employee_id, name: data.name, department: data.department,
videos: (data.videos || []).map((item) => ({ name: item.name, watchedAt: item.watched_at })),
summaryText: data.summary_text, status: data.status, completedAt: data.completed_at,
});
type TrainingRecordApi = {
id: number;
user_id?: number;
@@ -229,6 +279,47 @@ export async function getMyTrainingTypes(): Promise<TrainingTypeOption[]> {
return requestJson<TrainingTypeOption[]>('/api/user/training-types', authHeaders());
}
export async function getMyLeanTrainingTasks(): Promise<LeanTrainingMyTask[]> {
const response = await requestJson<LeanTrainingMyTaskApi[]>('/api/user/lean-training/my-tasks', authHeaders());
return (response || []).map(mapLeanMyTask);
}
export async function markMyLeanVideoWatched(weeklyTaskId: number, resourceId: number): Promise<void> {
await requestJson<{ watched_at: Record<string, string> }>('/api/user/lean-training/my-tasks/watched', {
method: 'POST',
...jsonAuthHeaders(),
body: JSON.stringify({ weekly_task_id: weeklyTaskId, resource_id: resourceId }),
});
}
export async function saveMyLeanTrainingCompletion(payload: { weeklyTaskId: number; watchedAt: Record<string, string>; summaryText: string }): Promise<LeanTrainingDashboardRow> {
const response = await requestJson<LeanTrainingDashboardRowApi>('/api/user/lean-training/completions', {
method: 'PUT', ...jsonAuthHeaders(), body: JSON.stringify({ weekly_task_id: payload.weeklyTaskId, watched_at: payload.watchedAt, summary_text: payload.summaryText }),
});
return mapLeanDashboardRow(response);
}
export async function getLeanTrainingDashboard(taskId?: number): Promise<LeanTrainingDashboard> {
// task_id 为空时后端返回最新一期;periods 为全部期次摘要(期号按周次升序),供管理端下拉切换第几期。
const query = taskId ? `?task_id=${taskId}` : '';
const response = await requestJson<{ task: LeanTrainingTaskApi | null; completed: LeanTrainingDashboardRowApi[]; incomplete: LeanTrainingDashboardRowApi[]; periods?: Array<{ id: number; week_key: string; index: number }> }>(`/api/admin/lean-training/dashboard${query}`, authHeaders());
return {
task: response.task ? mapLeanTask(response.task) : null,
completed: (response.completed || []).map(mapLeanDashboardRow),
incomplete: (response.incomplete || []).map(mapLeanDashboardRow),
periods: (response.periods || []).map((period) => ({ id: period.id, weekKey: period.week_key, index: period.index })),
};
}
/** HR 对指定成员发起精益培训定向提醒;返回后端实发统计(sent/failed 才是真实送达情况,created 含发送失败)。 */
export async function sendLeanTrainingReminders(weeklyTaskId: number, userIds: number[]): Promise<{ created: number; sent: number; skipped: number; failed: number }> {
return requestJson<{ created: number; sent: number; skipped: number; failed: number }>(`/api/admin/lean-training/weekly-tasks/${weeklyTaskId}/reminders`, {
method: 'POST',
...jsonAuthHeaders(),
body: JSON.stringify({ user_ids: userIds }),
});
}
export async function getMyTrainingProgress(type: string = 'onboarding'): Promise<TrainingProgressRecord | null> {
const data = await requestJson<TrainingRecordApi | null>(`/api/user/training-record?type=${encodeURIComponent(type)}`, authHeaders());
return data ? mapTrainingProgressRecord(data) : null;
@@ -9,8 +9,10 @@
*/
import { computed, reactive, ref, watch, type ShallowUnwrapRef } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import {
BookOpen,
Bell,
CheckCircle2,
ChevronDown,
ChevronUp,
@@ -31,11 +33,11 @@ import FilePreviewModal from '@/shared/components/FilePreviewModal.vue';
import { useMessage } from '@/shared/composables/useMessage';
import { resolveTrainingExamPdfGuide, type TrainingGuideLike } from '@/features/chat/training/trainingWorkspace.utils';
import { getMyTrainingConfig } from '@/features/chat/api/training.api';
import type { TrainingAnswerRecord, TrainingRecord, TrainingQuestion } from '@/features/chat/training/training.types';
import type { TrainingAnswerRecord, TrainingRecord, TrainingQuestion, LeanTrainingMyTask, LeanTrainingTaskStatus, LeanTrainingVideo } from '@/features/chat/training/training.types';
import html2pdf from 'html2pdf.js';
import { getAuthHeaders } from '@/shared/utils/auth';
const props = defineProps<{
currentAgent: Record<string, unknown> | null;
currentUser: Record<string, unknown> | null;
@@ -72,7 +74,8 @@ const learnerStageIconMap = {
result: ShieldCheck,
} as const;
const currentLearnerStageIndex = computed(() => learnerStageOrder.indexOf(workspace.stage));
const showLearnerProgressModule = computed(() => workspace.learnerProgressItems.length > 0);
// 进度模块仅在配置了多阶段流程时展示;单阶段培训(如出国规章培训仅视频学习)无进度追踪意义,主区域卡片与右侧栏面板同步隐藏。
const showLearnerProgressModule = computed(() => workspace.learnerProgressItems.length > 1);
const learnerProgressItems = computed(() => workspace.learnerProgressItems.map((item, index) => {
const stageIndex = learnerStageOrder.indexOf(item.stage as typeof learnerStageOrder[number]);
const status = stageIndex >= 0 && currentLearnerStageIndex.value >= 0
@@ -117,6 +120,12 @@ const handleVideoSeeking = (e: Event) => {
};
const handleVideoEnded = () => {
// 精益任务视频:仅当播放到结尾才记录观看完成(配合防拖拽保证按时长完整观看)
if (activeLeanVideo.value) {
workspace.markLeanVideoWatched(activeLeanVideo.value.taskId, activeLeanVideo.value.resourceId);
msg.success(t('chat.training.lean.videoWatchedToast'));
activeLeanVideo.value = null;
}
workspace.showVideoModal = false;
workspace.stopMaterialTimer();
};
@@ -284,6 +293,33 @@ const openWorkspaceView = (view: typeof workspace.activeView) => {
setWorkspaceExpanded(true, true);
};
// [STEP] 企微提醒卡片深链支持:/chat/<agentId>?training_type=lean_management&weekly_task_id=<id>
// AI 触发时机:员工/HR 从企微“和信AI智能工作台”精益提醒卡片点入时,自动展开精益培训对应页签
// (管理员进管理端看板、学员进学员侧学习页),无需手动点页签,保证卡片“点击直达”体验。
const route = useRoute();
const router = useRouter();
let leanJumpConsumed = false;
watch(
() => [workspace.isTrainingAgent, Boolean(props.currentUser), workspace.canManageTrainingWorkspace] as const,
([isTraining, loggedIn]) => {
// 仅在培训 Agent 且登录态就绪后消费一次,避免身份权限异步未加载时误判视图归属
if (!isTraining || !loggedIn || leanJumpConsumed) return;
leanJumpConsumed = true;
if (route.query.training_type !== 'lean_management') return;
if (workspace.canManageTrainingWorkspace) {
workspace.activeView = 'admin';
workspace.hrTrainingTab = 'lean';
} else {
workspace.activeView = 'learner';
workspace.learnerTab = 'lean_management';
}
setWorkspaceExpanded(true, true);
// 消费后清理深链参数,避免刷新或分享链接时重复自动展开
void router.replace({ query: { ...route.query, training_type: undefined, weekly_task_id: undefined } });
},
{ immediate: true },
);
/**
* 收起培训工作区并回到纯聊天页面。
* AI 触发时机:点击“收起工作区”时,必须立即恢复聊天消息区与输入栏,而不是仅折叠局部内容。
@@ -326,7 +362,7 @@ const applyDefaultExpandedState = () => {
// 监听 Agent/角色切换,重置本地展开态:培训角色首次进入默认展开工作区。
watch(
() => [props.currentAgent?.id, workspace.isAdminViewer],
() => [props.currentAgent?.id, workspace.canManageTrainingWorkspace],
() => {
userExpandedOverride.value = null;
applyDefaultExpandedState();
@@ -414,6 +450,40 @@ const isMaterialCompleted = (material: any) => {
};
const currentPreviewVideoUrl = ref('');
const activeNonSafetyVideoId = ref<number | null>(null);
const nonSafetyVideoMaterials = computed(() => workspace.publishedTrainingMaterials.filter((material) => (
material.resource?.fileType === 'video' && Boolean(material.resource.fileUrl)
)));
const activeNonSafetyVideo = computed(() => (
nonSafetyVideoMaterials.value.find((material) => material.id === activeNonSafetyVideoId.value)
|| nonSafetyVideoMaterials.value[0]
|| null
));
const selectNonSafetyVideo = (material: { id?: number | null; resource?: { fileUrl?: string } | null }) => {
if (!material.resource?.fileUrl) return;
if (workspace.currentViewingMaterialId !== material.id) {
workspace.stopMaterialTimer();
}
activeNonSafetyVideoId.value = material.id ?? null;
workspace.currentViewingMaterialId = material.id ?? null;
};
const startNonSafetyVideoTimer = () => {
if (activeNonSafetyVideo.value?.id != null) {
workspace.startMaterialTimer(activeNonSafetyVideo.value.id);
}
};
const stopNonSafetyVideoTimer = () => {
workspace.stopMaterialTimer();
};
watch([() => workspace.learnerTab, nonSafetyVideoMaterials], () => {
if (!nonSafetyVideoMaterials.value.some((material) => material.id === activeNonSafetyVideoId.value)) {
activeNonSafetyVideoId.value = nonSafetyVideoMaterials.value[0]?.id ?? null;
}
}, { immediate: true });
const videoCountdownSeconds = ref(0);
let videoCountdownTimer: ReturnType<typeof setInterval> | null = null;
@@ -477,11 +547,69 @@ const handlePreviewClose = (val: boolean) => {
};
const handleVideoModalClose = () => {
// 提前关闭弹窗视为未完成观看:清空精益视频定位,不记录观看
activeLeanVideo.value = null;
workspace.showVideoModal = false;
currentPreviewVideoUrl.value = '';
stopVideoCountdown();
workspace.stopMaterialTimer();
};
/** 当前弹窗正在播放的精益任务视频定位(非精益视频播放时为 null),用于播放到结尾时记录对应任务与视频。 */
const activeLeanVideo = ref<{ taskId: number; resourceId: number } | null>(null);
/** 精益任务状态徽章样式与文案键映射:进行中 / 已延期 / 已完成。 */
const leanStatusMeta: Record<LeanTrainingTaskStatus, { badgeClass: string; labelKey: string }> = {
in_progress: { badgeClass: 'border-blue-200 bg-blue-50 text-blue-700', labelKey: 'chat.training.lean.taskStatus.in_progress' },
overdue: { badgeClass: 'border-red-200 bg-red-50 text-red-600', labelKey: 'chat.training.lean.taskStatus.overdue' },
completed: { badgeClass: 'border-emerald-200 bg-emerald-50 text-emerald-700', labelKey: 'chat.training.lean.taskStatus.completed' },
};
/** 看板总结弹框上下文:员工姓名 + 完整总结文案;为 null 时弹框关闭。 */
const summaryModal = ref<{ name: string; text: string } | null>(null);
/** 总结列预览截断:最多显示 15 个字,超出部分以省略号收尾,点击可弹框查看全文。 */
const truncateSummary = (text: string) => (text.length > 15 ? `${text.slice(0, 15)}…` : text);
/** 打开总结详情弹框:仅当该行有总结文案时可点击(无总结的行显示 "--" 不可点)。 */
const openSummaryModal = (name: string, text: string) => {
summaryModal.value = { name, text };
};
/** 视频缩略图取首帧地址:追加 #t=0.1 让浏览器在 preload=metadata 下渲染首帧画面。 */
const leanThumbSrc = (url?: string | null) => (url ? (url.includes('#') ? url : `${url}#t=0.1`) : '');
/**
* 打开精益任务视频弹窗播放。
* AI 触发时机:学员在精益管理时间树上点击任务视频缩略图时调用;无播放地址时给出提示且不打开弹窗。
* 注意:此处不记录观看,观看完成仅在视频播放到结尾(handleVideoEnded)时记录。
*/
const openLeanVideo = (task: LeanTrainingMyTask, video: LeanTrainingVideo) => {
if (!video.fileUrl) {
msg.warning(t('chat.training.lean.videoUnavailable'));
return;
}
activeLeanVideo.value = { taskId: task.id, resourceId: video.id };
workspace.showVideoModal = true;
currentPreviewVideoUrl.value = video.fileUrl;
};
/**
* 提交精益学习感悟前的友好校验:未看完全部已推送视频或感悟字数不足时仅提示,不发请求。
* AI 触发时机:学员点击某期任务的"提交学习感悟"按钮时调用。
*/
const handleLeanSubmit = (task: LeanTrainingMyTask) => {
const watchedCount = Object.keys(workspace.leanWatchedByTask[task.id] || {}).length;
if (watchedCount < task.videos.length) {
msg.warning(t('chat.training.lean.completeVideosFirst'));
return;
}
if ((workspace.leanSummaryByTask[task.id] || '').trim().length < task.minSummaryLength) {
msg.warning(t('chat.training.lean.summaryTooShort', { minSummaryLength: task.minSummaryLength }));
return;
}
void workspace.submitLeanTrainingCompletion(task.id);
};
const jumpToExamQuestion = (index: number) => {
if (!canNavigateExamQuestions.value) return;
workspace.syncExamQuestionIndex(index);
@@ -533,7 +661,7 @@ const currentSafetyStageText = computed(() => {
{{ $t('chat.training.tabs.learner') }}
</button>
<button
v-if="workspace.isAdminViewer"
v-if="workspace.canManageTrainingWorkspace"
type="button"
class="rounded-full px-3 py-1.5 text-xs font-medium transition"
:class="workspace.activeView === 'admin' ? 'bg-brand-600 text-white' : 'bg-surface-soft text-secondary hover:bg-slate-100'"
@@ -546,7 +674,7 @@ const currentSafetyStageText = computed(() => {
<div class="flex flex-wrap items-center justify-end gap-2">
<button
v-if="trainingExamPdfGuide"
v-if="trainingExamPdfGuide && workspace.learnerTab === 'safety'"
type="button"
class="inline-flex h-9 items-center gap-2 rounded-xl border border-default bg-white px-3.5 text-xs font-medium leading-none text-secondary transition hover:bg-surface-soft"
@click="emit('open-guide', Number(trainingExamPdfGuide.id))"
@@ -555,7 +683,7 @@ const currentSafetyStageText = computed(() => {
<span class="leading-none">{{ $t('chat.training.actions.viewExamPdf') }}</span>
</button>
<button
v-if="workspace.stage === 'video'"
v-if="workspace.learnerTab === 'safety' && workspace.safetyViewStage !== 'exam' && workspace.safetyViewStage !== 'result'"
type="button"
class="inline-flex min-h-9 items-center gap-2 rounded-xl border border-brand-200 bg-brand-50 px-3 py-2 text-xs font-medium text-brand-700 transition hover:bg-brand-100"
@click="showVideoModal = true"
@@ -619,7 +747,7 @@ const currentSafetyStageText = computed(() => {
{{ $t('chat.training.tabs.learner') }}
</button>
<button
v-if="workspace.isAdminViewer"
v-if="workspace.canManageTrainingWorkspace"
type="button"
class="rounded-full px-3 py-1.5 text-xs font-medium transition"
:class="workspace.activeView === 'admin' ? 'bg-brand-600 text-white' : 'bg-surface-soft text-secondary hover:bg-slate-100'"
@@ -632,7 +760,7 @@ const currentSafetyStageText = computed(() => {
<div class="flex flex-wrap items-center justify-end gap-2">
<button
v-if="trainingExamPdfGuide"
v-if="trainingExamPdfGuide && workspace.learnerTab === 'safety'"
type="button"
class="inline-flex h-9 items-center gap-2 rounded-xl border border-default bg-white px-3.5 text-xs font-medium leading-none text-secondary transition hover:bg-surface-soft"
@click="emit('open-guide', Number(trainingExamPdfGuide.id))"
@@ -708,7 +836,68 @@ const currentSafetyStageText = computed(() => {
<div class="mt-3 text-base font-semibold text-primary">{{ $t('chat.training.noContent.title') }}</div>
<div class="mt-1 text-sm">{{ $t('chat.training.noContent.description') }}</div>
</div>
<template v-else-if="workspace.learnerTab !== 'safety'">
<div v-if="workspace.learnerTab === 'lean_management'" class="col-span-full">
<div v-if="!workspace.leanMyTasks.length" class="rounded-2xl border border-dashed border-default bg-white px-6 py-12 text-center text-sm text-secondary">
{{ $t('chat.training.lean.learner.empty') }}
</div>
<!-- 时间树:后端按发布周期倒序返回,最新任务在最上方 -->
<div v-else class="rounded-2xl border border-emerald-200 bg-emerald-50/40 p-4">
<div class="text-base font-semibold text-primary">{{ $t('chat.training.lean.learner.title') }}</div>
<div class="relative mt-4">
<div class="absolute bottom-3 left-[7px] top-3 w-px bg-emerald-200" aria-hidden="true"></div>
<div v-for="(task, index) in workspace.leanMyTasks" :key="task.id" class="relative pl-7" :class="index > 0 ? 'pt-4' : ''">
<span class="absolute left-0 top-7 h-[15px] w-[15px] rounded-full border-[3px] bg-white" :class="task.taskStatus === 'completed' ? 'border-emerald-500' : task.taskStatus === 'overdue' ? 'border-red-400' : 'border-blue-500'" aria-hidden="true"></span>
<article class="rounded-2xl border border-default bg-white p-4">
<div class="flex flex-wrap items-start justify-between gap-2">
<div>
<!-- 期号优先用后端 weekIndex(按周次升序,最早为第 1 期),与管理端口径一致;旧数据兜底按返回顺序倒推编号 -->
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.lean.learner.taskTitle', { index: task.weekIndex ?? workspace.leanMyTasks.length - index }) }}</div>
<div class="mt-1 text-xs text-secondary">{{ $t('chat.training.lean.learner.description', { count: task.videos.length, minSummaryLength: task.minSummaryLength }) }}</div>
</div>
<div class="flex flex-wrap items-center gap-2">
<span class="rounded-full border px-3 py-1 text-xs font-medium" :class="leanStatusMeta[task.taskStatus].badgeClass">{{ $t(leanStatusMeta[task.taskStatus].labelKey) }}</span>
<span class="rounded-full bg-surface-soft px-3 py-1 text-xs text-secondary">{{ $t('chat.training.lean.learner.taskPeriod', { start: task.weekKey, end: task.dueAt.slice(0, 10) }) }}</span>
</div>
</div>
<!-- 任务视频缩略图:点击弹出播放器完成学习并记录观看 -->
<div class="mt-3 grid gap-3 md:grid-cols-2">
<div v-for="video in task.videos" :key="video.id" class="overflow-hidden rounded-xl border border-default bg-surface-soft">
<button type="button" class="group relative block h-32 w-full" @click="openLeanVideo(task, video)">
<video v-if="video.fileUrl" :src="leanThumbSrc(video.fileUrl)" preload="metadata" muted playsinline class="h-full w-full object-cover"></video>
<div v-else class="flex h-full w-full items-center justify-center text-secondary"><Video class="h-8 w-8" /></div>
<span class="absolute inset-0 flex items-center justify-center transition group-hover:bg-slate-900/20">
<PlayCircle class="h-9 w-9 text-white drop-shadow" />
</span>
<!-- 观看完成标记:服务端持久化,刷新后仍显示 -->
<span v-if="(workspace.leanWatchedByTask[task.id] || {})[String(video.id)]" class="absolute top-2 right-2 rounded-full bg-emerald-500 px-2 py-0.5 text-xs font-medium text-white shadow">{{ $t('chat.training.lean.videoWatchedBadge') }}</span>
</button>
<div class="p-3">
<div class="flex items-center gap-2 text-sm font-medium text-primary"><Video class="h-4 w-4 shrink-0 text-emerald-600" /><span class="truncate">{{ video.name }}</span></div>
<div class="mt-1 text-xs" :class="(workspace.leanWatchedByTask[task.id] || {})[String(video.id)] ? 'text-emerald-600' : 'text-secondary'">
{{ (workspace.leanWatchedByTask[task.id] || {})[String(video.id)] ? $t('chat.training.lean.watchedAt', { time: ((workspace.leanWatchedByTask[task.id] || {})[String(video.id)] || '').slice(0, 16).replace('T', ' ') }) : $t('chat.training.lean.markVideoWatched') }}
</div>
</div>
</div>
</div>
<!-- 已完成:只读展示已提交感悟与完成时间;进行中/已延期:可继续编辑并提交 -->
<div v-if="task.taskStatus === 'completed' && task.completion" class="mt-3 rounded-xl bg-emerald-50/60 p-3">
<div class="text-xs font-medium text-emerald-700">{{ $t('chat.training.lean.learner.completedSummary') }}<template v-if="task.completion.completedAt"> · {{ $t('chat.training.lean.learner.completedAt', { time: task.completion.completedAt.slice(0, 16).replace('T', ' ') }) }}</template></div>
<p class="mt-1 whitespace-pre-wrap text-sm text-primary">{{ task.completion.summaryText }}</p>
</div>
<template v-else>
<textarea v-model="workspace.leanSummaryByTask[task.id]" rows="4" class="mt-3 w-full rounded-xl border border-default bg-white p-3 text-sm" :placeholder="$t('chat.training.lean.summaryPlaceholder', { minSummaryLength: task.minSummaryLength })" />
<div class="mt-2 flex items-center justify-between gap-3">
<span class="text-xs" :class="(workspace.leanSummaryByTask[task.id] || '').length >= task.minSummaryLength ? 'text-emerald-600' : 'text-amber-600'">{{ $t('chat.training.lean.summaryLength', { current: (workspace.leanSummaryByTask[task.id] || '').length, minSummaryLength: task.minSummaryLength }) }}</span>
<!-- 未看完视频/字数不足时不静默禁用,点击由 handleLeanSubmit 给出友好提示 -->
<button type="button" class="rounded-xl bg-emerald-600 px-4 py-2 text-sm font-medium text-white" @click="handleLeanSubmit(task)">{{ $t('chat.training.lean.submitSummary') }}</button>
</div>
</template>
</article>
</div>
</div>
</div>
</div>
<template v-if="workspace.learnerTab !== 'safety' && workspace.learnerTab !== 'lean_management'">
<div :class="learnerWorkspaceMainClass">
<div v-if="showLearnerProgressModule" :class="progressCardClass">
<div class="flex flex-col gap-1.5 lg:flex-row lg:items-start lg:justify-between">
@@ -762,31 +951,34 @@ const currentSafetyStageText = computed(() => {
<p v-if="learnerStepIntroDescription" class="mt-1 whitespace-pre-line text-sm leading-6 text-secondary">{{ learnerStepIntroDescription }}</p>
</div>
</div>
<div class="mt-3">
<ul v-if="workspace.publishedTrainingMaterials.length" class="space-y-2">
<li
v-for="material in workspace.publishedTrainingMaterials"
:key="material.id || `${material.resourceType}-${material.sortOrder}`"
class="flex items-center justify-between gap-3 rounded-xl border border-slate-100 bg-slate-50 px-3 py-2.5 cursor-pointer transition hover:bg-slate-100"
@click="handleMaterialClick(material)"
>
<div class="flex min-w-0 items-center gap-2 text-sm font-medium text-primary hover:text-brand-600">
<Video v-if="material.resource?.fileType === 'video'" class="h-4 w-4 text-brand-500" />
<FileText v-else class="h-4 w-4 text-slate-400" />
<span class="truncate">{{ material.title || material.resource?.fileName || $t('chat.training.video.playerTitle') }}</span>
</div>
</li>
</ul>
<div v-if="activeNonSafetyVideo" class="mt-3 overflow-hidden rounded-2xl border border-default bg-black shadow-lg">
<video
:key="activeNonSafetyVideo.id ?? activeNonSafetyVideo.resource?.fileUrl"
controls
playsinline
preload="metadata"
class="aspect-video w-full"
:src="activeNonSafetyVideo.resource?.fileUrl"
@play="startNonSafetyVideoTimer"
@pause="stopNonSafetyVideoTimer"
@ended="stopNonSafetyVideoTimer"
/>
</div>
<div class="mt-3 relative group cursor-pointer overflow-hidden rounded-2xl border border-default bg-slate-900 shadow-lg aspect-video flex items-center justify-center" @click="showVideoModal = true">
<img src="https://coresg-normal.trae.ai/api/ide/v1/text_to_image?prompt=Professional%20corporate%20training%20video%20cover%2C%20high-quality%2C%20modern%20office%20background%2C%20play%20button%20overlay&image_size=landscape_16_9" class="absolute inset-0 w-full h-full object-cover opacity-60 group-hover:scale-105 transition-transform duration-500" />
<div class="relative z-10 flex flex-col items-center gap-3">
<div class="h-16 w-16 flex items-center justify-center rounded-full bg-white/20 backdrop-blur-md border border-white/30 group-hover:bg-brand-600 group-hover:border-brand-500 transition-all duration-300">
<PlayCircle class="h-8 w-8 text-white fill-white/20" />
</div>
<span class="text-white font-medium drop-shadow-md">{{ $t('chat.training.video.playerTitle') }}</span>
</div>
<div v-else class="mt-3 rounded-2xl border border-dashed border-default bg-surface-soft px-4 py-10 text-center text-sm text-muted">
{{ $t('chat.training.video.empty') }}
</div>
<div v-if="nonSafetyVideoMaterials.length > 1" class="mt-3 grid gap-2 sm:grid-cols-2">
<button
v-for="(material, index) in nonSafetyVideoMaterials"
:key="material.id || `${material.resourceType}-${material.sortOrder}`"
type="button"
class="flex min-w-0 items-center gap-2 rounded-xl border px-3 py-2.5 text-left text-sm transition"
:class="activeNonSafetyVideo?.id === material.id ? 'border-brand-300 bg-brand-50 text-brand-700' : 'border-default bg-white text-primary hover:border-brand-200'"
@click="selectNonSafetyVideo(material)"
>
<Video class="h-4 w-4 shrink-0" />
<span class="min-w-0 flex-1 truncate">{{ material.title || material.resource?.fileName || `${$t('chat.training.video.playerTitle')} ${index + 1}` }}</span>
</button>
</div>
</div>
@@ -1034,8 +1226,8 @@ const currentSafetyStageText = computed(() => {
</div>
</div>
<!-- 考试题目面板 (在考试或结果阶段展示) -->
<div v-else :class="questionNavPanelClass">
<!-- 考试题目面板 (在考试或结果阶段展示;单阶段培训无考试流程,不渲染任何侧栏面板) -->
<div v-else-if="showLearnerProgressModule" :class="questionNavPanelClass">
<div class="flex items-center gap-2">
<ClipboardCheck class="h-4 w-4 text-brand-600" />
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.examQuestionCard.title') }}</div>
@@ -1079,8 +1271,8 @@ const currentSafetyStageText = computed(() => {
</div>
</template>
<!-- 安全培训视图 -->
<template v-else>
<!-- 安全培训视图(仅安全培训进入该分支;精益管理走独立精益任务卡片,避免误渲染三级安全教育内容) -->
<template v-else-if="workspace.learnerTab === 'safety'">
<div :class="learnerWorkspaceMainClass">
<!-- 进度卡片 -->
<div :class="progressCardClass">
@@ -1428,40 +1620,55 @@ const currentSafetyStageText = computed(() => {
</div>
<div v-else-if="!isCompactMode" class="space-y-4 p-4 md:p-5">
<!-- 管理端内容页签:全部培训=现有统计/筛选/主表;精益管理=精益看板(单任务,状态列区分三态)。 -->
<div>
<div class="inline-flex flex-wrap rounded-xl border border-default bg-surface-soft p-1">
<button
v-for="tab in [{ key: 'all', label: 'chat.training.hr.tabs.allTraining' }, { key: 'lean', label: 'chat.training.hr.tabs.leanManagement' }]"
:key="tab.key"
class="flex items-center gap-2 rounded-lg px-6 py-2 text-sm font-medium transition"
:class="workspace.hrTrainingTab === tab.key ? 'bg-white text-brand-700 shadow-sm border border-brand-200' : 'text-secondary hover:text-primary'"
@click="workspace.hrTrainingTab = tab.key as 'all' | 'lean'"
>
{{ $t(tab.label) }}
</button>
</div>
</div>
<div class="grid gap-3 sm:grid-cols-2 xl:grid-cols-5">
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
<div class="flex items-center justify-center gap-2 text-center">
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.total') }}</div>
<div class="text-2xl font-semibold text-primary">{{ workspace.stats.total }}</div>
<div class="text-2xl font-semibold text-primary">{{ workspace.hrTrainingTab === 'lean' ? workspace.leanStats.total : workspace.stats.total }}</div>
</div>
</div>
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
<div class="flex items-center justify-center gap-2 text-center">
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.passed') }}</div>
<div class="text-2xl font-semibold text-emerald-600">{{ workspace.stats.passed }}</div>
<div class="text-sm text-muted">{{ $t(workspace.hrTrainingTab === 'lean' ? 'chat.training.lean.status.completed' : 'chat.training.hr.stats.passed') }}</div>
<div class="text-2xl font-semibold text-emerald-600">{{ workspace.hrTrainingTab === 'lean' ? workspace.leanStats.passed : workspace.stats.passed }}</div>
</div>
</div>
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
<div class="flex items-center justify-center gap-2 text-center">
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.failed') }}</div>
<div class="text-2xl font-semibold text-amber-600">{{ workspace.stats.failed }}</div>
<div class="text-sm text-muted">{{ $t(workspace.hrTrainingTab === 'lean' ? 'chat.training.lean.status.overdue' : 'chat.training.hr.stats.failed') }}</div>
<div class="text-2xl font-semibold text-amber-600">{{ workspace.hrTrainingTab === 'lean' ? workspace.leanStats.failed : workspace.stats.failed }}</div>
</div>
</div>
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
<div class="flex items-center justify-center gap-2 text-center">
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.inProgress') }}</div>
<div class="text-2xl font-semibold text-blue-600">{{ workspace.stats.inProgress }}</div>
<div class="text-2xl font-semibold text-blue-600">{{ workspace.hrTrainingTab === 'lean' ? workspace.leanStats.inProgress : workspace.stats.inProgress }}</div>
</div>
</div>
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
<div class="flex items-center justify-center gap-2 text-center">
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.passRate') }}</div>
<div class="text-2xl font-semibold text-primary">{{ workspace.stats.passRate }}%</div>
<div class="text-sm text-muted">{{ $t(workspace.hrTrainingTab === 'lean' ? 'chat.training.lean.dashboard.passRate' : 'chat.training.hr.stats.passRate') }}</div>
<div class="text-2xl font-semibold text-primary">{{ workspace.hrTrainingTab === 'lean' ? workspace.leanStats.passRate : workspace.stats.passRate }}%</div>
</div>
</div>
</div>
<div class="rounded-2xl border border-default bg-white p-4 shadow-sm">
<div v-if="workspace.hrTrainingTab === 'all'" class="rounded-2xl border border-default bg-white p-4 shadow-sm">
<div class="flex flex-col gap-3">
<div class="grid gap-3 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)_auto] xl:items-center">
<label>
@@ -1572,6 +1779,87 @@ const currentSafetyStageText = computed(() => {
</table>
</div>
</div>
<!-- 精益管理页签内容:仅当页签切到 lean 且当前用户可见时展示;看板保持单期任务,状态列区分已完成/已延期/进行中。 -->
<div v-if="workspace.hrTrainingTab === 'lean' && workspace.canViewLeanDashboard && workspace.leanDashboard.task" class="rounded-2xl border border-emerald-200 bg-emerald-50/40 p-4 shadow-sm">
<div class="flex flex-wrap items-start justify-between gap-3">
<div>
<div class="flex items-center gap-2 text-base font-semibold text-primary">
<BookOpen class="h-4 w-4 text-emerald-600" />
{{ $t('chat.training.lean.dashboard.title') }}
</div>
<div class="mt-1 flex flex-wrap items-center gap-2 text-xs text-secondary">
<span>{{ $t('chat.training.lean.dashboard.week', { week: workspace.leanDashboard.task.weekKey }) }}</span>
<span class="rounded-full bg-white px-2.5 py-1 font-medium text-emerald-700">{{ $t('chat.training.lean.dashboard.count', { count: workspace.leanRows.length }) }}</span>
<!-- 期次下拉:期号按周次升序区分第几期任务,切换后重拉对应期看板与精益统计。 -->
<select
v-if="workspace.leanDashboard.periods.length"
class="rounded-lg border border-default bg-white px-2 py-1 text-xs font-medium text-primary"
:value="workspace.leanDashboardTaskId ?? workspace.leanDashboard.task.id"
@change="workspace.selectLeanDashboardPeriod(Number(($event.target as HTMLSelectElement).value))"
>
<option v-for="period in workspace.leanDashboard.periods" :key="period.id" :value="period.id">{{ $t('chat.training.lean.dashboard.periodLabel', { index: period.index }) }}({{ period.weekKey }})</option>
</select>
</div>
</div>
<div class="rounded-full bg-white px-3 py-1 text-xs font-medium text-emerald-700">{{ $t('chat.training.lean.dueAt', { time: workspace.leanDashboard.task.dueAt.slice(0, 16).replace('T', ' ') }) }}</div>
</div>
<!-- 用户复测要求:不再分"已完成/未完成"双列,合为单一明细表,仅通过状态列区分已完成/已延期/进行中。 -->
<div class="mt-4 overflow-hidden rounded-2xl border border-default bg-white">
<div class="overflow-x-auto">
<table class="w-full min-w-[900px] border-collapse text-sm">
<thead class="bg-surface-soft">
<tr>
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.lean.columns.employeeId') }}</th>
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.lean.columns.name') }}</th>
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.lean.columns.department') }}</th>
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.lean.columns.videoName') }}</th>
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.lean.columns.watchedAt') }}</th>
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.lean.columns.status') }}</th>
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.lean.columns.summary') }}</th>
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.lean.columns.action') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in workspace.leanRows" :key="row.userId" class="odd:bg-white even:bg-surface-soft/30">
<td class="whitespace-nowrap border-b border-default px-3 py-2.5 text-secondary">{{ row.employeeId || '--' }}</td>
<td class="whitespace-nowrap border-b border-default px-3 py-2.5 font-medium text-primary">{{ row.name }}</td>
<td class="whitespace-nowrap border-b border-default px-3 py-2.5 text-secondary">{{ row.department || '--' }}</td>
<td class="border-b border-default px-3 py-2.5 text-secondary"><div v-for="video in row.videos" :key="video.name" class="whitespace-nowrap">{{ video.name }}</div><span v-if="!row.videos.length">--</span></td>
<!-- [RULE] 观看时间仅展示到分钟(slice(0,16) 去掉秒),与产品要求一致。 -->
<td class="border-b border-default px-3 py-2.5 text-secondary"><div v-for="video in row.videos" :key="`${video.name}-${video.watchedAt}`" class="whitespace-nowrap">{{ video.watchedAt ? video.watchedAt.slice(0, 16).replace('T', ' ') : '--' }}</div><span v-if="!row.videos.length">--</span></td>
<!-- 状态徽章三态:已完成(绿)/已延期(红)/进行中(蓝),文案统一中文(含其余三语言),禁止回显原始键。 -->
<td class="border-b border-default px-3 py-2.5"><span class="inline-flex rounded-full px-2.5 py-1 text-xs font-semibold" :class="row.status === 'completed' ? 'bg-emerald-50 text-emerald-700' : row.status === 'overdue' ? 'bg-red-50 text-red-700' : 'bg-blue-50 text-blue-700'">{{ $t(`chat.training.lean.status.${row.status}`) }}</span></td>
<!-- [RULE] 总结列最多显示 15 个字:超出截断并显示省略号,点击弹框查看全部文案;无总结显示 "--"。
常显虚线下划线提示可点击(用户复测反馈点击无效,实为部署版本差异,此处强化可点性视觉)。 -->
<td class="border-b border-default px-3 py-2.5 text-secondary">
<button v-if="row.summaryText" type="button" class="max-w-56 cursor-pointer text-left whitespace-pre-wrap break-words underline decoration-dotted decoration-secondary/60 underline-offset-2 transition hover:decoration-solid hover:text-primary" :title="$t('chat.training.lean.summaryModal.viewHint')" @click="openSummaryModal(row.name, row.summaryText)">{{ truncateSummary(row.summaryText) }}</button>
<span v-else>--</span>
</td>
<!-- 仅未完成(进行中/已延期)提供提醒操作,已完成无需催办。 -->
<td class="border-b border-default px-3 py-2.5">
<button
v-if="row.status !== 'completed'"
type="button"
class="inline-flex whitespace-nowrap items-center gap-1.5 rounded-lg bg-amber-500 px-2.5 py-1.5 text-xs font-medium text-white transition hover:bg-amber-600 disabled:cursor-not-allowed disabled:opacity-60"
:disabled="workspace.leanReminderLoading[row.userId]"
@click="workspace.remindLeanTrainingMember(row.userId)"
>
<Bell class="h-3.5 w-3.5" />
{{ workspace.leanReminderLoading[row.userId] ? $t('chat.training.lean.reminder.sending') : $t('chat.training.lean.reminder.action') }}
</button>
<span v-else class="text-secondary">--</span>
</td>
</tr>
<tr v-if="!workspace.leanRows.length">
<td colspan="8" class="px-4 py-6 text-center text-sm text-muted">{{ $t('chat.training.lean.dashboard.empty') }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</section>
@@ -1724,10 +2012,35 @@ const currentSafetyStageText = computed(() => {
</div>
</div>
</div>
<!-- 总结详情弹框:看板总结列最多预览 15 字,点击后在此查看完整文案(点击遮罩或关闭按钮关闭)。 -->
<div v-if="summaryModal" class="fixed inset-0 z-[110] flex items-center justify-center bg-slate-950/80 p-4 backdrop-blur-sm" @click.self="summaryModal = null">
<div class="w-full max-w-lg rounded-2xl bg-white p-5 shadow-2xl">
<div class="flex items-start justify-between gap-3">
<div>
<h3 class="text-base font-semibold text-primary">{{ $t('chat.training.lean.summaryModal.title') }}</h3>
<p class="mt-0.5 text-xs text-secondary">{{ summaryModal.name }}</p>
</div>
<button type="button" class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-secondary transition hover:bg-surface-soft hover:text-primary" :aria-label="$t('chat.training.lean.summaryModal.close')" @click="summaryModal = null">
<XCircle class="h-5 w-5" />
</button>
</div>
<div class="mt-4 max-h-96 overflow-y-auto whitespace-pre-wrap break-words rounded-xl bg-surface-soft/60 p-4 text-sm leading-relaxed text-secondary">{{ summaryModal.text }}</div>
</div>
</div>
</Teleport>
</template>
<style scoped>
/* 期次下拉自绘右置箭头:与全局 .select-field 同思路但尺寸紧凑(text-xs 头部场景)。
[FIX] 用户复测反馈箭头压住日期数字:appearance-none 移除原生箭头,箭头整体右移贴边
(距右缘 0.3rem),配合 pr-8 预留 2rem 空间,确保与文案完全无重叠。 */
.lean-period-select {
background-image: linear-gradient(45deg, transparent 50%, currentColor 50%), linear-gradient(135deg, currentColor 50%, transparent 50%);
background-position: calc(100% - 0.55rem) 50%, calc(100% - 0.3rem) 50%;
background-repeat: no-repeat;
background-size: 0.3rem 0.3rem, 0.3rem 0.3rem;
}
.report-pdf-page {
width: 100%;
max-width: 794px;
@@ -1,9 +1,9 @@
/**
* features/chat/composables/useTrainingWorkspace.ts
* 用途:封装员工培训 Agent 的工作区状态,包括学员考试流、进度持久化与 HR 真实统计导出。
* 用途:封装员工培训 Agent 的工作区状态,包括学员考试流、进度持久化、HR 真实统计导出与精益定向提醒。
* 依赖:Vue reactivity、vue-i18n、training.api,以及 training.types。
* 逻辑:仅在培训 Agent 下启用;学员端按“视频 -> 知识点 -> 一题一答 -> 结算”推进,并把进度同步到后端;
* 非安全培训页额外按后台配置动态渲染进度项与步骤说明文案。
* 非安全培训页额外按后台配置动态渲染进度项与步骤说明文案;精益管理面板通过独立状态提交未完成人员提醒。
*/
import { computed, ref, watch, type ComputedRef } from 'vue';
import { useI18n } from 'vue-i18n';
@@ -15,8 +15,13 @@ import {
getMyTrainingProgress,
getMyTrainingTypes,
getTrainingStats,
getMyLeanTrainingTasks,
getLeanTrainingDashboard,
sendLeanTrainingReminders,
listTrainingRecords,
markMyLeanVideoWatched,
saveMyTrainingProgress,
saveMyLeanTrainingCompletion,
} from '@/features/chat/api/training.api';
import type {
SafetyProgressState,
@@ -36,6 +41,9 @@ import type {
TrainingType,
TrainingTypeOption,
TrainingWorkspaceView,
LeanTrainingDashboard,
LeanTrainingDashboardRow,
LeanTrainingMyTask,
} from '@/features/chat/training/training.types';
import {
SAFETY_STAGE_GUIDE_USAGE_MAP,
@@ -107,7 +115,21 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
});
const hasAuthenticatedUser = computed(() => Boolean(String(currentUser.value?.username || '').trim()));
const isAdminViewer = computed(() => Boolean(currentUser.value?.feature_permissions?.training_hr_manage));
const defaultActiveView = computed<TrainingWorkspaceView>(() => (isAdminViewer.value ? 'admin' : 'learner'));
const canViewLeanDashboard = computed(() => isAdminViewer.value);
const canManageTrainingWorkspace = computed(() => isAdminViewer.value);
/** 学员端精益周任务列表(后端按发布周期倒序,最新在前),并附每期任务状态与完成信息。 */
const leanMyTasks = ref<LeanTrainingMyTask[]>([]);
const leanDashboard = ref<LeanTrainingDashboard>({ task: null, completed: [], incomplete: [], periods: [] });
/** 管理端内容页签:all=全部培训(现有统计/筛选/主表);lean=精益管理(精益看板单任务,按状态列区分三态)。 */
const hrTrainingTab = ref<'all' | 'lean'>('all');
/** 管理端精益看板当前选中的期次任务 ID;为空表示最新一期,切换后重新拉取对应期看板。 */
const leanDashboardTaskId = ref<number | null>(null);
const leanReminderLoading = ref<Record<number, boolean>>({});
/** 按任务 ID 分组的感悟草稿,支持时间树上多期任务并行编辑。 */
const leanSummaryByTask = ref<Record<number, string>>({});
/** 按任务 ID 分组的观看记录(资源 ID -> 观看时间),提交时随感悟一并交由服务端校验。 */
const leanWatchedByTask = ref<Record<number, Record<string, string>>>({});
const defaultActiveView = computed<TrainingWorkspaceView>(() => (canManageTrainingWorkspace.value ? 'admin' : 'learner'));
const activeView = ref<TrainingWorkspaceView>('learner');
const learnerTab = ref<TrainingType>('onboarding');
const trainingTypes = ref<TrainingTypeOption[]>([
@@ -162,6 +184,28 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
passRate: 0,
averageScore: 0,
});
/** 精益看板合并行:已完成+未完成名单合为单表遍历,状态列区分已完成/已延期/进行中三态。 */
const leanRows = computed<LeanTrainingDashboardRow[]>(() => [...leanDashboard.value.completed, ...leanDashboard.value.incomplete]);
/**
* 精益管理页签统计:按看板行三态(completed/in_progress/overdue)实际计数,供统计卡片随页签切换数据源。
* total=参训人数(已完成+未完成名单行数);passed=已完成;failed=已延期;inProgress=进行中;passRate=完成率。
*/
const leanStats = computed<TrainingStats>(() => {
// [STEP 1] 合并已完成/未完成两组行后按后端归一的三态计数,避免只扫 incomplete 组漏算已延期。
const rows = [...leanDashboard.value.completed, ...leanDashboard.value.incomplete];
const total = rows.length;
const completedCount = rows.filter((row) => row.status === 'completed').length;
const overdueCount = rows.filter((row) => row.status === 'overdue').length;
const inProgressCount = rows.filter((row) => row.status === 'in_progress').length;
return {
total,
passed: completedCount,
failed: overdueCount,
inProgress: inProgressCount,
passRate: total > 0 ? Math.round((completedCount / total) * 100) : 0,
averageScore: 0,
};
});
let persistQueue: Promise<void> = Promise.resolve();
watch(isTrainingAgent, (enabled) => {
@@ -172,7 +216,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
});
watch(
[isTrainingAgent, isAdminViewer],
[isTrainingAgent, canManageTrainingWorkspace],
([enabled]) => {
if (!enabled) return;
activeView.value = defaultActiveView.value;
@@ -780,6 +824,92 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
}
};
/** 拉取管理端精益看板(按 leanDashboardTaskId 指定期次,空则最新一期),失败时清空兜底。 */
const loadLeanDashboard = async () => {
if (!canViewLeanDashboard.value) return;
try {
leanDashboard.value = await getLeanTrainingDashboard(leanDashboardTaskId.value ?? undefined);
} catch {
leanDashboard.value = { task: null, completed: [], incomplete: [], periods: [] };
}
};
/** 切换精益看板期次:记录任务 ID 后仅重拉看板与精益统计,不动学员任务列表。 */
const selectLeanDashboardPeriod = async (taskId: number) => {
if (leanDashboardTaskId.value === taskId) return;
leanDashboardTaskId.value = taskId;
await loadLeanDashboard();
};
/** 读取学员端全部已发布精益周任务(含状态与播放地址),并以服务端完成记录回填各任务的感悟/观看草稿。 */
const loadLeanTraining = async () => {
if (!isTrainingAgent.value || !hasAuthenticatedUser.value) return;
try {
leanMyTasks.value = await getMyLeanTrainingTasks();
// [STEP 1] 回填草稿:已完成任务还原当时提交的感悟与观看时间;进行中/已延期任务保留已有观看记录,避免刷新后丢失。
const summaries: Record<number, string> = {};
const watched: Record<number, Record<string, string>> = {};
leanMyTasks.value.forEach((task) => {
summaries[task.id] = task.completion?.summaryText || '';
watched[task.id] = { ...(task.completion?.watchedAt || {}) };
});
leanSummaryByTask.value = summaries;
leanWatchedByTask.value = watched;
await loadLeanDashboard();
} catch {
leanMyTasks.value = [];
leanDashboard.value = { task: null, completed: [], incomplete: [], periods: [] };
}
};
/**
* 记录某期任务的指定视频已完成观看:本地即时生效,并异步持久化到服务端(刷新后仍保留)。
* AI 触发时机:学员在精益管理时间树上点击任务视频并完整播放到结尾时调用;已有观看记录的资源保留首次时间不覆盖。
*/
const markLeanVideoWatched = (taskId: number, resourceId: number) => {
const taskWatched = leanWatchedByTask.value[taskId] || {};
if (taskWatched[String(resourceId)]) return;
leanWatchedByTask.value = { ...leanWatchedByTask.value, [taskId]: { ...taskWatched, [String(resourceId)]: new Date().toISOString() } };
// 持久化失败不阻塞本地状态;下次刷新列表会以服务端记录为准,未持久化的视频需重新完整观看
void markMyLeanVideoWatched(taskId, resourceId).catch(() => {});
};
/**
* 提交指定周任务的学习感悟;服务端校验该任务已推送视频全部完成且达到最少字数,成功后刷新任务列表与看板。
*/
const submitLeanTrainingCompletion = async (taskId: number) => {
await saveMyLeanTrainingCompletion({ weeklyTaskId: taskId, watchedAt: leanWatchedByTask.value[taskId] || {}, summaryText: leanSummaryByTask.value[taskId] || '' });
await loadLeanTraining();
};
/**
* HR 对看板中未完成成员发起定向提醒,并按服务端实发统计如实提示。
* AI 触发时机:HR 在精益培训完成名单点击行内【提醒】按钮时调用。
* 核心逻辑:后端 created 计数包含"企微发送失败"的提醒(仅代表已尝试),
* 成功提示必须以 sent(企微受理成功)为准,failed>0 时明确告知失败,避免误报已送达。
*/
const remindLeanTrainingMember = async (userId: number) => {
if (!leanDashboard.value.task || leanReminderLoading.value[userId]) return;
leanReminderLoading.value[userId] = true;
try {
const result = await sendLeanTrainingReminders(leanDashboard.value.task.id, [userId]);
if (result.sent > 0 && result.failed > 0) {
msg.warning(t('chat.training.lean.reminder.partial', { sent: result.sent, failed: result.failed }));
} else if (result.sent > 0) {
msg.success(t('chat.training.lean.reminder.success', { count: result.sent }));
} else if (result.failed > 0) {
msg.error(t('chat.training.lean.reminder.sendFailed', { count: result.failed }));
} else {
msg.warning(t('chat.training.lean.reminder.notSent'));
}
await loadLeanTraining();
} catch (error) {
msg.error(error instanceof BusinessError ? error.message : t('chat.training.lean.reminder.failed'));
} finally {
leanReminderLoading.value[userId] = false;
}
};
watch(
[
currentAgent,
@@ -812,6 +942,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
void loadTrainingTypes();
void loadTrainingConfig();
void loadTrainingProgress();
void loadLeanTraining();
},
{ immediate: true },
);
@@ -1160,6 +1291,13 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
return {
isTrainingAgent,
isAdminViewer,
canViewLeanDashboard,
canManageTrainingWorkspace,
leanDashboard,
leanReminderLoading,
leanSummaryByTask,
leanWatchedByTask,
leanMyTasks,
isHydrated,
trainingConfigLoading,
hasPublishedTrainingConfig,
@@ -1215,6 +1353,11 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
departmentOptions,
filteredRecords,
stats,
hrTrainingTab,
leanStats,
leanRows,
leanDashboardTaskId,
selectLeanDashboardPeriod,
learnerChatPrompt,
newSessionReminderMessage,
shouldShowNewSessionReminder,
@@ -1230,6 +1373,10 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
restartExam,
setSafetyStage,
exportRecords,
loadLeanTraining,
markLeanVideoWatched,
submitLeanTrainingCompletion,
remindLeanTrainingMember,
showVideoModal,
videoUrl,
startMaterialTimer,
@@ -139,3 +139,70 @@ export interface TrainingStats {
passRate: number;
averageScore: number;
}
export interface LeanTrainingVideo {
id: number;
name: string;
/** MinIO 公开播放地址,供缩略图首帧与弹窗播放使用 */
fileUrl?: string | null;
}
/** 学员视角任务状态:in_progress=进行中;overdue=已延期(过截止未完成);completed=已完成 */
export type LeanTrainingTaskStatus = 'in_progress' | 'overdue' | 'completed';
export interface LeanTrainingCompletionBrief {
summaryText: string;
watchedAt: Record<string, string>;
completedAt: string | null;
}
export interface LeanTrainingWeeklyTask {
id: number;
weekKey: string;
dueAt: string;
videoResourceIds: number[];
targetRoles: string[];
targetUserIds: number[];
videos: LeanTrainingVideo[];
status: string;
minSummaryLength: number;
weeklyCount?: number;
pushedVideoCount?: number;
/** 任务周周日(ISO 日期),供前端拼装"第N周 MM-DD至MM-DD"周次区间标签。 */
weekEnd?: string | null;
/** 期号:按周次升序编号,最早一周为第 1 期,与管理端口径一致。 */
weekIndex?: number;
}
/** 学员端时间树任务项:周任务 + 任务状态 + 完成信息 */
export interface LeanTrainingMyTask extends LeanTrainingWeeklyTask {
taskStatus: LeanTrainingTaskStatus;
completion: LeanTrainingCompletionBrief | null;
}
export interface LeanTrainingDashboardRow {
id?: number;
userId: number;
employeeId?: string | null;
name: string;
department?: string | null;
videos: Array<{ name: string; watchedAt?: string | null }>;
summaryText?: string | null;
/** 管理端三态:completed=已完成(感悟已提交);in_progress=进行中;overdue=已延期(过截止未完成),由后端序列化层归一 */
status: 'completed' | 'in_progress' | 'overdue';
completedAt?: string | null;
}
/** 精益看板期次摘要:index 为期号(按周次升序,最早为第 1 期),供管理端下拉区分第几期任务。 */
export interface LeanTrainingPeriod {
id: number;
weekKey: string;
index: number;
}
export interface LeanTrainingDashboard {
task: LeanTrainingWeeklyTask | null;
completed: LeanTrainingDashboardRow[];
incomplete: LeanTrainingDashboardRow[];
periods: LeanTrainingPeriod[];
}
@@ -1,7 +1,7 @@
/**
* 合同付款预警 API 类型与请求封装。
* 依赖:统一 requestJson;后端 /api/contract-payment。
* 逻辑:台账/合同详情查询、待发送摘要、每日扫描入队、周五汇总入队及批次附件下载。
* 逻辑:台账/合同详情查询、汇总卡统计、待发送摘要、每日扫描入队、周五汇总入队及批次附件下载。
*/
import { requestBlob, requestJson } from '@/shared/api/client';
@@ -21,11 +21,27 @@ export interface ContractPaymentContract {
status: string; parse_status: string; plan_status: string; parse_issues?: string[]; nodes: PaymentNode[]; alerts?: PaymentAlert[]; attachments?: ContractAttachment[];
}
export interface ContractListResponse { total: number; page: number; page_size: number; pages: number; items: ContractPaymentContract[]; }
export type LedgerFocus = 'due' | 'overdue' | 'needs_completion' | 'due_this_month';
export interface LedgerSummary {
due: number;
overdue: number;
needs_completion: number;
due_this_month: number;
}
export interface AlertBatch { id: number; batch_no: string; week_key: string; status: string; summary?: { total?: number; stages?: Record<string, number> }; excel_file_name?: string | null; excel_file_size?: number | null; sent_at?: string | null; }
export interface AlertSummary { pending_count: number; next_send_at?: string | null; timezone?: string | null; }
export const listContractPaymentContracts = (params?: { keyword?: string; parse_status?: string; reviewOnly?: boolean; page?: number; pageSize?: number }) => {
const query = new URLSearchParams(); if (params?.keyword) query.set('keyword', params.keyword); if (params?.parse_status) query.set('parse_status', params.parse_status); if (params?.reviewOnly) query.set('review_only', '1'); if (params?.page) query.set('page', String(params.page)); if (params?.pageSize) query.set('page_size', String(params.pageSize));
/**
* 分页查询合同付款台账或待确认合同。
* 核心逻辑:keyword 同时匹配合同号、流程号、采购单号和供应商;reviewOnly 走待确认列表。
* @param params.keyword - 模糊检索词,可为空。
* @param params.parse_status - 解析状态精确筛选。
* @param params.reviewOnly - 为 true 时只查 needs_review。
* @param params.focus - 汇总卡口径:即将到期 / 逾期未付 / 待补充 / 本月应付。
* @returns 分页后的合同列表。
*/
export const listContractPaymentContracts = (params?: { keyword?: string; parse_status?: string; reviewOnly?: boolean; focus?: LedgerFocus; page?: number; pageSize?: number }) => {
const query = new URLSearchParams(); if (params?.keyword) query.set('keyword', params.keyword); if (params?.parse_status) query.set('parse_status', params.parse_status); if (params?.reviewOnly) query.set('review_only', '1'); if (params?.focus) query.set('focus', params.focus); if (params?.page) query.set('page', String(params.page)); if (params?.pageSize) query.set('page_size', String(params.pageSize));
const suffix = query.toString() ? `?${query.toString()}` : ''; return requestJson<ContractListResponse>(`/api/contract-payment/contracts${suffix}`);
};
/** 获取单份合同的概览、原文附件、付款计划与预警审计详情。 */
@@ -42,6 +58,12 @@ export const enqueueContractPaymentAlertScan = () => requestJson<{ job_id: strin
export const enqueueContractPaymentWeeklyAlert = () => requestJson<{ job_id: string }>('/api/contract-payment/alerts/weekly-run', { method: 'POST' });
/** 查询本周待发送笔数和下一次周五汇总发送时间。 */
export const getContractPaymentAlertSummary = () => requestJson<AlertSummary>('/api/contract-payment/alerts/summary');
/**
* 查询合同台账四张汇总卡的合同份数。
* 核心逻辑:始终统计全部已解析台账,不跟当前 keyword;与点卡片过滤共用 focus 口径。
* @returns due / overdue / needs_completion / due_this_month。
*/
export const getContractPaymentLedgerSummary = () => requestJson<LedgerSummary>('/api/contract-payment/contracts/summary');
export const listContractPaymentAlertBatches = () => requestJson<{ items: AlertBatch[] }>('/api/contract-payment/alert-batches');
/** 下载已归档的合同付款预警周汇总 Excel 明细。 */
export const downloadContractPaymentAlertBatchExcel = (batchId: number) => requestBlob(`/api/contract-payment/alert-batches/${batchId}/excel`);
@@ -1,6 +1,6 @@
<!--
合同付款预警工作台:展示合同台账、付款阶段字段、本周待发送摘要,并提供预警任务入口。
依赖:contract-payment.api、PaginationBar、统一消息提示;周汇总批次由独立页面展示。
合同付款预警工作台:展示汇总卡、合同台账、付款阶段字段、本周待发送摘要;同步/扫描/发送仅管理员可见。
依赖:contract-payment.api、PaginationBar、useAuthStore、统一消息提示;周汇总批次由独立页面展示。
-->
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
@@ -11,6 +11,7 @@ import { BusinessError } from '@/shared/api/client';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import PaginationBar from '@/shared/components/PaginationBar.vue';
import { useMessage } from '@/shared/composables/useMessage';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import { WORKSPACE_PATHS } from '@/features/workspace/constants/routes';
import {
enqueueContractPaymentAlertScan,
@@ -18,21 +19,34 @@ import {
enqueueContractPaymentSync,
enqueueContractPaymentWeeklyAlert,
getContractPaymentAlertSummary,
getContractPaymentLedgerSummary,
listContractPaymentContracts,
type AlertSummary,
type ContractPaymentContract,
type LedgerFocus,
type LedgerSummary,
} from '../api/contract-payment.api';
import { displayCurrency } from '../utils/currency';
import { aggregateContractNodeStatus, type ContractNodeStatusCode } from '../utils/paymentStatus';
const { t } = useI18n();
const router = useRouter();
const auth = useAuthStore();
const isAdmin = computed(() => auth.isAdmin);
const msg = useMessage(); const keyword = ref(''); const loading = ref(false); const actionLoading = ref(false);
const showForceSyncConfirm = ref(false);
const showReparseExistingConfirm = ref(false);
const contracts = ref<ContractPaymentContract[]>([]);
const alertSummary = ref<AlertSummary | null>(null);
const ledgerSummary = ref<LedgerSummary>({ due: 0, overdue: 0, needs_completion: 0, due_this_month: 0 });
const ledgerFocus = ref<LedgerFocus | ''>('');
const page = ref(1); const pageSize = ref(20); const total = ref(0); const pages = ref(1);
const ledgerFocusCards = computed(() => ([
{ key: 'due' as const, label: t('admin.contractPayment.ledgerFocus.due'), hint: t('admin.contractPayment.ledgerFocus.dueHint'), value: ledgerSummary.value.due, tone: 'due' },
{ key: 'overdue' as const, label: t('admin.contractPayment.ledgerFocus.overdue'), hint: '', value: ledgerSummary.value.overdue, tone: 'overdue' },
{ key: 'needs_completion' as const, label: t('admin.contractPayment.ledgerFocus.needsCompletion'), hint: '', value: ledgerSummary.value.needs_completion, tone: 'needs' },
{ key: 'due_this_month' as const, label: t('admin.contractPayment.ledgerFocus.dueThisMonth'), hint: t('admin.contractPayment.ledgerFocus.dueThisMonthHint'), value: ledgerSummary.value.due_this_month, tone: 'month' },
]));
const stage = (item: ContractPaymentContract, name: string) => item.nodes.find((node) => node.node_type === name);
/**
* 以整数格式展示付款比例,不改变接口返回的精确比例值。
@@ -123,19 +137,37 @@ async function refreshSummary(): Promise<void> {
if (!alertSummary.value) alertSummary.value = { pending_count: 0, next_send_at: null, timezone: 'Asia/Shanghai' };
}
}
/**
* 刷新四张汇总卡的合同份数。
* 核心逻辑:始终统计全部已解析台账,失败时保留上次数字,不阻断列表。
*/
async function refreshLedgerSummary(): Promise<void> {
try {
ledgerSummary.value = await getContractPaymentLedgerSummary();
} catch {
/* 汇总失败不影响台账列表 */
}
}
/**
* 加载当前页合同台账。
* 核心逻辑:合同列表使用服务端分页;搜索和每页条数变化均从第一页开始,并并行刷新待发送摘要。
* @param resetPage - 为 true 时重置为第一页,用于关键词查询。
* @returns 完成后更新当前列表、分页元数据和待发送摘要。
* 核心逻辑:合同列表使用服务端分页;关键词同时匹配合同号、流程号、采购单号和供应商;
* 汇总卡 focus 与关键词叠加;搜索、点卡片和每页条数变化均从第一页开始,并并行刷新待发送摘要与汇总卡。
* @param resetPage - 为 true 时重置为第一页,用于关键词查询或切换汇总卡。
* @returns 完成后更新当前列表、分页元数据、待发送摘要和汇总卡。
*/
async function load(resetPage = false): Promise<void> {
if (resetPage) page.value = 1;
loading.value = true;
try {
const [result] = await Promise.all([
listContractPaymentContracts({ keyword: keyword.value.trim(), page: page.value, pageSize: pageSize.value }),
listContractPaymentContracts({
keyword: keyword.value.trim(),
focus: ledgerFocus.value || undefined,
page: page.value,
pageSize: pageSize.value,
}),
refreshSummary(),
refreshLedgerSummary(),
]);
contracts.value = result.items || [];
total.value = result.total || 0;
@@ -147,13 +179,23 @@ async function load(resetPage = false): Promise<void> {
loading.value = false;
}
}
/**
* 点击汇总卡过滤台账;再次点击同一张卡则取消过滤。
* 核心逻辑:focus 写入列表查询;汇总数字本身仍看全部台账。
* @param key - 汇总卡口径。
*/
function toggleLedgerFocus(key: LedgerFocus): void {
ledgerFocus.value = ledgerFocus.value === key ? '' : key;
void load(true);
}
/**
* 提交合同付款预警后台任务。
* 核心逻辑:按操作类型调用相应的异步接口,任务入队成功后仅展示任务编号,不等待长耗时同步或发送完成。
* 核心逻辑:仅管理员可提交;按操作类型调用相应的异步接口,任务入队成功后仅展示任务编号,不等待长耗时同步或发送完成。
* @param action - sync 同步 OA、force-sync 强制覆盖、reparse-existing 刷新存量解析、scan 扫描预警、weekly 周汇总。
* @returns 任务提交完成后显示成功或失败提示。
*/
async function submitAction(action: 'sync' | 'force-sync' | 'reparse-existing' | 'scan' | 'weekly'): Promise<void> {
if (!isAdmin.value) return;
actionLoading.value = true;
try {
if (action === 'sync' || action === 'force-sync') {
@@ -181,6 +223,7 @@ async function submitAction(action: 'sync' | 'force-sync' | 'reparse-existing' |
* @param action - 待提交的预警任务类型。
*/
function run(action: 'sync' | 'force-sync' | 'reparse-existing' | 'scan' | 'weekly'): void {
if (!isAdmin.value) return;
if (action === 'force-sync') {
showForceSyncConfirm.value = true;
return;
@@ -212,8 +255,33 @@ onMounted(() => void load());
</script>
<template>
<section class="section-gap animate-fade-in-up">
<div class="flex flex-wrap items-start justify-between gap-4"><div><h2 class="text-2xl font-bold text-primary">{{ t('admin.contractPayment.title') }}</h2><p class="text-sm text-muted mt-1">{{ t('admin.contractPayment.subtitle') }}</p></div><div class="flex gap-2"><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('sync')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.sync') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('force-sync')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.forceSync') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('reparse-existing')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.reparseExisting') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('scan')"><CalendarClock class="w-4 h-4" />{{ t('admin.contractPayment.scanAlerts') }}</button><button class="btn-primary" :disabled="actionLoading" @click="run('weekly')"><Send class="w-4 h-4" />{{ t('admin.contractPayment.weeklySend') }}</button></div></div>
<div class="surface-panel rounded-2xl p-4 mt-5"><div class="flex flex-wrap gap-3 items-center"><div class="relative w-full md:w-[360px]"><Search class="absolute left-3 top-2.5 w-4 h-4 text-muted" /><input v-model="keyword" class="input-field pl-9" :placeholder="t('admin.contractPayment.searchPlaceholder')" @keyup.enter="load(true)" /></div><button class="btn-secondary-ds" @click="load(true)">{{ t('admin.contractPayment.search') }}</button><span v-if="weeklyPendingText" class="text-xs text-muted">{{ weeklyPendingText }}</span></div></div>
<div class="flex flex-wrap items-start justify-between gap-4"><div><h2 class="text-2xl font-bold text-primary">{{ t('admin.contractPayment.title') }}</h2><p class="text-sm text-muted mt-1">{{ t('admin.contractPayment.subtitle') }}</p></div><div v-if="isAdmin" class="flex flex-wrap gap-2"><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('sync')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.sync') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('force-sync')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.forceSync') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('reparse-existing')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.reparseExisting') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('scan')"><CalendarClock class="w-4 h-4" />{{ t('admin.contractPayment.scanAlerts') }}</button><button class="btn-primary" :disabled="actionLoading" @click="run('weekly')"><Send class="w-4 h-4" />{{ t('admin.contractPayment.weeklySend') }}</button></div></div>
<div class="contract-stat-grid">
<button
v-for="card in ledgerFocusCards"
:key="card.key"
type="button"
class="contract-stat-card"
:class="[card.tone, { active: ledgerFocus === card.key }]"
@click="toggleLedgerFocus(card.key)"
>
<span class="contract-stat-label">{{ card.label }}<small v-if="card.hint">({{ card.hint }})</small></span>
<strong class="contract-stat-value">{{ card.value }}</strong>
</button>
</div>
<div class="contract-filter-bar">
<div class="contract-filter-search">
<Search class="contract-filter-icon" />
<input
v-model="keyword"
class="contract-filter-input"
:placeholder="t('admin.contractPayment.searchPlaceholder')"
@keyup.enter="load(true)"
/>
</div>
<button type="button" class="contract-filter-submit" @click="load(true)">{{ t('admin.contractPayment.search') }}</button>
<span v-if="weeklyPendingText" class="contract-filter-meta">{{ weeklyPendingText }}</span>
</div>
<div class="surface-panel contract-ledger-panel mt-4 overflow-x-auto">
<table class="contract-ledger-table text-sm">
<thead><tr>
@@ -233,8 +301,9 @@ onMounted(() => void load());
</tbody>
</table>
</div>
<PaginationBar v-model:page="page" v-model:page-size="pageSize" :total="total" :pages="pages" :visible="total > 0 || !!keyword.trim()" @update:page="() => load()" @update:page-size="() => load()" />
<PaginationBar v-model:page="page" v-model:page-size="pageSize" :total="total" :pages="pages" :visible="total > 0 || !!keyword.trim() || !!ledgerFocus" @update:page="() => load()" @update:page-size="() => load()" />
<DeleteConfirmDialog
v-if="isAdmin"
v-model="showForceSyncConfirm"
:title="t('admin.contractPayment.forceSync')"
:message="t('admin.contractPayment.forceSyncConfirm')"
@@ -242,6 +311,7 @@ onMounted(() => void load());
@confirm="confirmForceSync"
/>
<DeleteConfirmDialog
v-if="isAdmin"
v-model="showReparseExistingConfirm"
:title="t('admin.contractPayment.reparseExisting')"
:message="t('admin.contractPayment.reparseExistingConfirm')"
@@ -251,6 +321,83 @@ onMounted(() => void load());
</section>
</template>
<style scoped>
.contract-stat-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 12px;
margin-top: 16px;
}
.contract-stat-card {
display: flex;
flex-direction: column;
align-items: flex-start;
min-height: 88px;
padding: 14px 16px 12px;
border: 1px solid #d7e1ef;
border-radius: 14px;
background: #fff;
box-shadow: 0 6px 20px rgba(33, 65, 111, .05);
text-align: left;
cursor: pointer;
}
.contract-stat-card.active { border-color: #93c5fd; box-shadow: 0 0 0 2px rgba(59, 130, 246, .16); }
.contract-stat-label { color: #8aa0bd; font-size: 12px; font-weight: 600; line-height: 1.35; }
.contract-stat-label small { margin-left: 2px; font-size: 12px; font-weight: 600; }
.contract-stat-value { margin-top: 8px; font-size: 28px; font-weight: 800; line-height: 1; }
.contract-stat-card.due .contract-stat-value { color: #d97706; }
.contract-stat-card.overdue .contract-stat-value { color: #dc2626; }
.contract-stat-card.needs .contract-stat-value { color: #0f172a; }
.contract-stat-card.month .contract-stat-value { color: #16a34a; }
@media (max-width: 900px) { .contract-stat-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.contract-filter-bar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-top: 16px;
padding: 10px 14px;
border: 1px solid #d7e1ef;
border-radius: 12px;
background: #fff;
}
.contract-filter-search { position: relative; width: min(100%, 320px); }
.contract-filter-icon {
position: absolute;
left: 10px;
top: 50%;
width: 14px;
height: 14px;
color: #8aa0bd;
transform: translateY(-50%);
pointer-events: none;
}
.contract-filter-input {
box-sizing: border-box;
width: 100%;
height: 36px;
padding: 0 12px 0 30px;
border: 1px solid #d7e1ef;
border-radius: 8px;
background: #f7faff;
color: #183c72;
font-size: 14px;
line-height: 36px;
outline: none;
}
.contract-filter-input::placeholder { color: #8aa0bd; font-size: 14px; }
.contract-filter-input:focus { border-color: #93c5fd; box-shadow: 0 0 0 2px rgba(59, 130, 246, .12); }
.contract-filter-submit {
height: 36px;
padding: 0 14px;
border: 1px solid #d7e1ef;
border-radius: 8px;
background: #fff;
color: #426493;
font-size: 14px;
font-weight: 600;
}
.contract-filter-submit:hover { background: #f7faff; color: #183c72; }
.contract-filter-meta { color: #8aa0bd; font-size: 13px; line-height: 1.4; }
.contract-ledger-panel { border: 1px solid #d7e1ef; border-radius: 14px; background: #fff; box-shadow: 0 6px 20px rgba(33, 65, 111, .05); }
.contract-ledger-table { width: 100%; min-width: 1260px; border-collapse: collapse; color: #183c72; }
.contract-ledger-table th { height: 59px; padding: 11px 12px; background: #f7faff; border-bottom: 1px solid #d7e1ef; color: #426493; font-size: 13px; font-weight: 700; line-height: 1.35; text-align: left; vertical-align: top; white-space: nowrap; }
@@ -28,7 +28,7 @@ const pages = ref(1);
/**
* 读取需要人工确认的合同列表。
* 核心逻辑:明确传入 reviewOnly,避免前端仅按显示状态过滤而遗漏后端新产生的待确认合同。
* 核心逻辑:明确传入 reviewOnly,避免前端仅按显示状态过滤而遗漏后端新产生的待确认合同;关键词同样匹配供应商。
* @param resetPage - 为 true 时重置到第一页,供关键词查询使用。
* @returns 请求完成后更新分页数据;失败时保留已有列表并提示原因。
*/
@@ -66,7 +66,18 @@ onMounted(() => void load());
<template>
<section class="section-gap animate-fade-in-up">
<div><h2 class="text-2xl font-bold text-primary">{{ t('admin.contractPaymentReview.title') }}</h2><p class="mt-1 text-sm text-muted">{{ t('admin.contractPaymentReview.subtitle') }}</p></div>
<div class="surface-panel mt-5 rounded-2xl p-4"><div class="flex flex-wrap items-center gap-3"><div class="relative w-full md:w-[360px]"><Search class="absolute left-3 top-2.5 h-4 w-4 text-muted" /><input v-model="keyword" class="input-field pl-9" :placeholder="t('admin.contractPaymentReview.searchPlaceholder')" @keyup.enter="load(true)" /></div><button class="btn-secondary-ds" @click="load(true)">{{ t('admin.contractPayment.search') }}</button></div></div>
<div class="contract-filter-bar">
<div class="contract-filter-search">
<Search class="contract-filter-icon" />
<input
v-model="keyword"
class="contract-filter-input"
:placeholder="t('admin.contractPaymentReview.searchPlaceholder')"
@keyup.enter="load(true)"
/>
</div>
<button type="button" class="contract-filter-submit" @click="load(true)">{{ t('admin.contractPayment.search') }}</button>
</div>
<div class="surface-panel mt-4 overflow-x-auto rounded-2xl">
<table class="review-table text-sm"><thead><tr><th>{{ t('admin.contractPaymentReview.contractWorkflow') }}</th><th>{{ t('admin.contractPayment.purchaseOrder') }}</th><th>{{ t('admin.contractPayment.supplier') }}</th><th>{{ t('admin.contractPayment.amount') }}</th><th>{{ t('admin.contractPaymentReview.reason') }}</th></tr></thead>
<tbody><tr v-for="item in contracts" :key="item.id" class="cursor-pointer hover:bg-surface-soft" @click="openContractDetail(item.id)"><td><strong>{{ item.contract_no || t('admin.contractPayment.contractNoPending') }}</strong><span>{{ item.workflow_no || '—' }}</span></td><td>{{ item.purchase_order_no || '—' }}</td><td>{{ item.supplier_name || '—' }}</td><td>{{ item.total_amount || '—' }}</td><td><ul><li v-for="issue in item.parse_issues || [t('admin.contractPaymentReview.fallbackIssue')]" :key="issue">{{ issue }}</li></ul></td></tr><tr v-if="!loading && !contracts.length"><td colspan="5" class="py-9 text-center text-muted">{{ t('admin.contractPaymentReview.empty') }}</td></tr></tbody>
@@ -77,5 +88,53 @@ onMounted(() => void load());
</template>
<style scoped>
.contract-filter-bar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-top: 16px;
padding: 10px 14px;
border: 1px solid #d7e1ef;
border-radius: 12px;
background: #fff;
}
.contract-filter-search { position: relative; width: min(100%, 320px); }
.contract-filter-icon {
position: absolute;
left: 10px;
top: 50%;
width: 14px;
height: 14px;
color: #8aa0bd;
transform: translateY(-50%);
pointer-events: none;
}
.contract-filter-input {
box-sizing: border-box;
width: 100%;
height: 36px;
padding: 0 12px 0 30px;
border: 1px solid #d7e1ef;
border-radius: 8px;
background: #f7faff;
color: #183c72;
font-size: 14px;
line-height: 36px;
outline: none;
}
.contract-filter-input::placeholder { color: #8aa0bd; font-size: 14px; }
.contract-filter-input:focus { border-color: #93c5fd; box-shadow: 0 0 0 2px rgba(59, 130, 246, .12); }
.contract-filter-submit {
height: 36px;
padding: 0 14px;
border: 1px solid #d7e1ef;
border-radius: 8px;
background: #fff;
color: #426493;
font-size: 14px;
font-weight: 600;
}
.contract-filter-submit:hover { background: #f7faff; color: #183c72; }
.review-table { width: 100%; min-width: 980px; border-collapse: collapse; color: #183c72; }.review-table th { padding: 13px 14px; border-bottom: 1px solid #d7e1ef; background: #f7faff; color: #426493; text-align: left; }.review-table td { padding: 13px 14px; border-bottom: 1px solid #d7e1ef; vertical-align: top; }.review-table tbody tr:last-child td { border-bottom: 0; }.review-table strong, .review-table span { display: block; }.review-table strong { color: #102d59; }.review-table span, .review-table li { color: #9a3412; }.review-table ul { margin: 0; padding-left: 18px; }.review-table li + li { margin-top: 3px; }
</style>
@@ -1,16 +1,17 @@
<!--
features/contract-payment/views/ContractPaymentWeeklyBatchesPage.vue
用途:独立展示合同付款预警的周汇总批次及其企业微信发送审计摘要,并下载 Excel 明细。
依赖:contract-payment.api、统一消息提示;由工作台“合同付款预警 > 周汇总批次”路由加载。
逻辑:后端扫描产生的批次在此集中查看;Excel 经受控接口下载,手动发送仅提交异步任务。
依赖:contract-payment.api、useAuthStore、统一消息提示;由工作台“合同付款预警 > 周汇总批次”路由加载。
逻辑:后端扫描产生的批次在此集中查看;Excel 经受控接口下载;手动发送仅管理员可见并提交异步任务。
-->
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { CalendarClock, Download, RefreshCw, Send } from 'lucide-vue-next';
import { computed, onMounted, ref } from 'vue';
import { CalendarClock, Download, Send } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { formatLocalDateTime } from '@/shared/utils/dateTime';
import { useMessage } from '@/shared/composables/useMessage';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import {
downloadContractPaymentAlertBatchExcel,
enqueueContractPaymentWeeklyAlert,
@@ -19,6 +20,8 @@ import {
} from '../api/contract-payment.api';
const { t, te } = useI18n();
const auth = useAuthStore();
const isAdmin = computed(() => auth.isAdmin);
const msg = useMessage();
const batches = ref<AlertBatch[]>([]);
const loading = ref(false);
@@ -44,10 +47,11 @@ async function load(): Promise<void> {
/**
* 手动提交本周汇总发送任务。
* 核心逻辑:调用异步入队接口,避免浏览器等待企业微信发送和 Excel 文件生成完成。
* 核心逻辑:仅管理员可调用异步入队接口,避免浏览器等待企业微信发送和 Excel 文件生成完成。
* @returns 提交结果通过统一消息提示反馈,成功后刷新批次列表。
*/
async function runWeeklyAlert(): Promise<void> {
if (!isAdmin.value) return;
actionLoading.value = true;
try {
await enqueueContractPaymentWeeklyAlert();
@@ -128,10 +132,7 @@ onMounted(() => void load());
<h2 class="text-2xl font-bold text-primary">{{ t('admin.contractPayment.weeklyBatchesTitle') }}</h2>
<p class="mt-1 text-sm text-muted">{{ t('admin.contractPayment.weeklyBatchesSubtitle') }}</p>
</div>
<div class="flex gap-2">
<button class="btn-secondary-ds" :disabled="loading" @click="() => load()">
<RefreshCw class="h-4 w-4" />{{ t('admin.contractPayment.refresh') }}
</button>
<div v-if="isAdmin" class="flex gap-2">
<button class="btn-primary" :disabled="actionLoading" @click="runWeeklyAlert">
<Send class="h-4 w-4" />{{ t('admin.contractPayment.weeklySend') }}
</button>
+11 -6
View File
@@ -1,12 +1,14 @@
/**
* features/kb/api/kb.api.ts
* 用途:知识库 HTTP API 封装。
* 依赖:auth、requestJson/BusinessError、vue-i18n(错误 fallback 文案)。
* 依赖:auth、requestJson/BusinessError、vue-i18n(错误 fallback 文案)、shared/utils/download。
* 逻辑:KbWorkspace / composables 调用;失败时优先保留 BusinessError.message,否则回退本地化 fallback。
* 源文件下载走 ?download=1,文件名由 Content-Disposition filename* 或调用方 source_file_name 决定。
*/
import i18n from '@/i18n';
import { getAuthHeaders } from '@/shared/utils/auth';
import { BusinessError, requestJson } from '@/shared/api/client';
import { parseContentDispositionFilename } from '@/shared/utils/download';
const kbT = (key: string) => String(i18n.global.t(key));
const kbErrorMessage = (e: unknown, fallbackKey: string) =>
@@ -300,11 +302,17 @@ export const getKbDocumentVersions = async (
return getJson<KbDocumentVersionItem[]>(`/api/kb/documents/${documentId}/versions`, []);
};
/**
* 拉取知识库版本原始文件,供作业面触发本地下载。
* 核心逻辑:带 download=1 走附件响应;文件名优先 RFC 5987 filename*,失败由调用方回退 source_file_name。
* @param versionId - 文档版本 ID
* @returns 成功时含 blob 与解析出的文件名;失败时 ok=false
*/
export const getKbDocumentVersionSourceFile = async (
versionId: number
): Promise<{ ok: boolean; error?: string; blob?: Blob; filename?: string; contentType?: string }> => {
try {
const res = await fetch(`/api/kb/document-versions/${versionId}/source-file`, {
const res = await fetch(`/api/kb/document-versions/${versionId}/source-file?download=1`, {
headers: getAuthHeaders(),
});
if (!res.ok) {
@@ -318,13 +326,10 @@ export const getKbDocumentVersionSourceFile = async (
}
return { ok: false, error: message };
}
const disposition = res.headers.get('content-disposition') || '';
const filenameMatch = disposition.match(/filename\*=UTF-8''([^;]+)|filename="?([^"]+)"?/i);
const filename = decodeURIComponent(filenameMatch?.[1] || filenameMatch?.[2] || '');
return {
ok: true,
blob: await res.blob(),
filename: filename || undefined,
filename: parseContentDispositionFilename(res.headers.get('content-disposition')),
contentType: res.headers.get('content-type') || undefined,
};
} catch {
@@ -1,7 +1,10 @@
/**
* features/kb/composables/kb-workspace/useKbWorkspaceModals.ts
* 记录/来源/Markdown/失败弹窗与原始文件预览。
* 用途:记录/来源/Markdown/失败弹窗与原始文件下载。
* 依赖:kb.api、kb-workspace state/computed/data、shared/utils/download。
* 逻辑:KbWorkspaceOverlays 调用;源文件点击只触发一次 a[download],保存名与上传时一致。
*/
import { triggerBlobDownload } from '@/shared/utils/download';
import type { KbDocumentItem, KbDocumentMarkdown, KbDocumentVersionItem } from '../../api/kb.api';
import {
getKbDocumentMarkdown,
@@ -74,6 +77,11 @@ export function useKbWorkspaceModals(
showSourceInfoModal.value = false;
};
/**
* 下载当前版本的原始文件,保存名与上传时的源文件名一致。
* 核心逻辑:拉 blob 后只触发一次 a[download];不用 window.open blob URL,避免再下一份 UUID 名文件。
* @param version - 源文件信息弹窗中的版本项
*/
const openOriginalSourceFile = async (version: KbDocumentVersionItem) => {
openingSourceVersionId.value = version.id;
const result = await getKbDocumentVersionSourceFile(version.id);
@@ -84,15 +92,8 @@ export function useKbWorkspaceModals(
return;
}
const objectUrl = window.URL.createObjectURL(result.blob);
const opened = window.open(objectUrl, '_blank', 'noopener,noreferrer');
if (!opened) {
const link = window.document.createElement('a');
link.href = objectUrl;
link.download = result.filename || version.source_file_name || `source-${version.id}`;
link.click();
}
window.setTimeout(() => window.URL.revokeObjectURL(objectUrl), 60_000);
const filename = version.source_file_name || result.filename || `source-${version.id}`;
triggerBlobDownload(result.blob, filename);
};
const openFailureModal = (type: 'upload' | 'clean' | 'sync') => {
+78 -4
View File
@@ -1186,12 +1186,17 @@
"username": "Username",
"email": "Email",
"department": "Department",
"team": "Team",
"jobTitle": "Job title",
"isTeamLeader": "Team leader",
"role": "Role",
"featurePermissions": "Feature Permissions",
"trainingHrManage": "Training HR Admin",
"trainingHrManageHint": "Allows this user to open the employee training agent HR Management view for stats, filtering, and Excel export.",
"trainingLeanManage": "Lean training full management",
"trainingLeanTeamManage": "Lean training team management",
"contractPaymentAccess": "Contract payment alert access",
"contractPaymentAccessHint": "Allows this user to open the contract payment workbench (ledger, review, weekly batches) and trigger sync or scans.",
"contractPaymentAccessHint": "Allows this user to open the contract payment workbench (ledger, review, weekly batches). Syncing OA, scanning alerts, and sending weekly alerts remain admin-only.",
"password": "Password",
"passwordHint": "(leave blank to keep)",
"noAgents": "No agents available."
@@ -4758,7 +4763,7 @@
}
},
"contractPayment": {
"title": "Contract Payment Alerts", "subtitle": "Sync OA contract, acceptance, and vendor prepayment requests; notify procurement roles through three escalation rounds.", "sync": "Sync OA data", "forceSync": "Force overwrite OA fields", "forceSyncConfirm": "This will overwrite existing OA data with non-empty fields returned this time and record an audit trail. Continue?", "reparseExisting": "Reparse existing contracts", "reparseExistingConfirm": "This will refresh all existing contract parsing results from archived attachments using the current rules. OA fields will not be synced or overwritten. Continue?", "scanAlerts": "Scan to generate alerts", "jobSubmitted": "Job submitted", "actionFailed": "Action failed", "loadFailed": "Failed to load contracts", "searchPlaceholder": "Search contract or purchase order number", "allStatus": "All", "search": "Search", "ledger": "Contract ledger", "items": "items", "empty": "No contract data", "purchaseOrder": "Purchase order", "supplier": "Supplier", "amount": "Contract amount", "deliveryDate": "Delivery due date", "timeline": "Payment plan timeline", "notAvailable": "—", "stats": {"contracts": "Contracts", "pendingParse": "Pending contracts", "readyPlans": "Plans ready", "alerts": "Alert nodes"}, "status": {"completed": "Completed", "needs_review": "Needs review", "pending": "Pending parse"}, "stateLabel": {"parsed": "Parsed", "needs_review": "Needs review", "pending": "Pending parse", "active": "Active"}, "nodeType": {"prepayment": "Prepayment", "shipment": "Shipment payment", "acceptance": "Acceptance payment", "warranty": "Warranty payment"}, "ruleConfirmed": "Confirmed", "prepaymentRule": "Alerts at 7/14/21 days after contract archival; request status comes from OA vendor prepayment requests.", "shipmentRule": "Alerts 7 days before delivery, on the due date, and 14 days after; request status comes from OA vendor prepayment requests.", "acceptanceRule": "Alerts at 30/40/60 days after acceptance archival; warranty alerts are 7 days before, on, and 14 days after maturity.", "pendingAlerts": "Pending alerts", "processing": "Payment initiated", "dataPending": "Data pending", "paid": "Paid", "amountRatioDate": "Amount / ratio · date", "applicant": "Applicant", "statusLabel": "Status", "contractPrefix": "Contract", "datePending": "Date pending", "statusNormal": "Normal", "statusNeedsCompletion": "Needs completion", "statusOverdue": "Overdue", "statusUpcoming": "Due soon", "statusActive": "In progress", "statusCompleted": "Completed", "totalPrefix": "Total", "contractSupplier": "Contract / supplier", "nextAlert": "Next alert", "triggerBasis": "Trigger basis", "alertDate": "Alert date", "alertFirstRound": "Round 1", "payDate": "Payment date", "processStatus": "Status", "owner": "Procurement owner", "oaData": "OA data", "contractRule": "Contract rule", "ownerDefault": "Procurement owner", "workflowNo": "Workflow number", "contractNoPending": "Contract number pending attachment parsing", "synced": "Synced", "detailSubtitle": "OA data, payment nodes, and WeCom alert records", "backToOverview": "Back to overview", "contractInfo": "OA contract details", "alertHistory": "Alert history", "alertRound": "Alert round {round}", "alertAudit": "Alert delivery record", "alertAuditEmpty": "No alert records", "alertNode": "Payment stage", "alertScheduledAt": "Scheduled date", "alertSentAt": "Sent at", "alertStatus": {"pending": "Pending", "sent": "Sent", "failed": "Failed"}, "roundValue": "Round {round}", "weeklyBatchesTitle": "Weekly Summary Batches", "weeklyBatchesSubtitle": "Review recipient-level payment-alert summaries, Excel attachments, and delivery records.", "refresh": "Refresh", "weeklySend": "Send alerts", "weeklyBatchSubmitted": "Send alert job submitted", "weeklyBatchesLoadFailed": "Failed to load weekly summary batches", "batchNo": "Batch no.", "weekKey": "Week", "batchStatusLabel": "Delivery status", "batchTotal": "Summary count", "batchExcel": "Excel attachment", "batchSentAt": "Sent at", "weeklyBatchesEmpty": "No weekly summary batches", "weeklyPendingSummary": "{count} pending this week · next send {datetime}", "weeklyPendingCountOnly": "{count} pending this week", "downloadExcel": "Download Excel", "excelDownloadFailed": "Failed to download the alert attachment", "batchStatus": {"pending": "Pending", "sent": "Sent", "failed": "Failed", "processing": "Processing", "resolved": "Alerts stopped"}, "backToLedger": "Back", "detailLoadFailed": "Failed to load contract details", "detailLoading": "Loading contract details…", "detailOverview": "Contract Overview", "detailAttachments": "Original Attachments", "detailPaymentPlan": "Payment Plan", "detailAlertHistory": "Alert History", "archiveDate": "Contract archive date", "archiveDateHint": "This date is when the contract application form was archived", "parseStatus": "Parsing status", "parseIssueTitle": "Parse issues", "planStatus": "Plan status", "attachmentsEmpty": "No archived original contract attachments", "downlLine truncated
"title": "Contract Payment Alerts", "subtitle": "Sync OA contract, acceptance, and vendor prepayment requests; notify procurement roles through three escalation rounds.", "sync": "Sync OA data", "forceSync": "Force overwrite OA fields", "forceSyncConfirm": "This will overwrite existing OA data with non-empty fields returned this time and record an audit trail. Continue?", "reparseExisting": "Reparse existing contracts", "reparseExistingConfirm": "This will refresh all existing contract parsing results from archived attachments using the current rules. OA fields will not be synced or overwritten. Continue?", "scanAlerts": "Scan to generate alerts", "jobSubmitted": "Job submitted", "actionFailed": "Action failed", "loadFailed": "Failed to load contracts", "searchPlaceholder": "Search contract number, purchase order, or supplier", "allStatus": "All", "search": "Search", "ledger": "Contract ledger", "items": "items", "empty": "No contract data", "purchaseOrder": "Purchase order", "supplier": "Supplier", "amount": "Contract amount", "deliveryDate": "Delivery due date", "timeline": "Payment plan timeline", "notAvailable": "—", "stats": {"contracts": "Contracts", "pendingParse": "Pending contracts", "readyPlans": "Plans ready", "alerts": "Alert nodes"}, "ledgerFocus": {"due": "Due soon", "dueHint": "within 7 days", "overdue": "Overdue unpaid", "needsCompletion": "Needs completion", "dueThisMonth": "Due this month", "dueThisMonthHint": "this calendar month"}, "status": {"completed": "Completed", "needs_review": "Needs review", "pending": "Pending parse"}, "stateLabel": {"parsed": "Parsed", "needs_review": "Needs review", "pending": "Pending parse", "active": "Active"}, "nodeType": {"prepayment": "Prepayment", "shipment": "Shipment payment", "acceptance": "Acceptance payment", "warranty": "Warranty payment"}, "ruleConfirmed": "Confirmed", "prepaymentRule": "Alerts at 7/14/21 days after contract archival; request status comes from OA vendor prepayment requests.", "shipmentRule": "Alerts 7 days before delivery, on the due date, and 14 days after; request status comes from OA vendor prepayment requests.", "acceptanceRule": "Alerts at 30/40/60 days after acceptance archival; warranty alerts are 7 days before, on, and 14 days after maturity.", "pendingAlerts": "Pending alerts", "processing": "Payment initiated", "dataPending": "Data pending", "paid": "Paid", "amountRatioDate": "Amount / ratio · date", "applicant": "Applicant", "statusLabel": "Status", "contractPrefix": "Contract", "datePending": "Date pending", "statusNormal": "Normal", "statusNeedsCompletion": "Needs completion", "statusOverdue": "Overdue", "statusUpcoming": "Due soon", "statusActive": "In progress", "statusCompleted": "Completed", "totalPrefix": "Total", "contractSupplier": "Contract / supplier", "nextAlert": "Next alert", "triggerBasis": "Trigger basis", "alertDate": "Alert date", "alertFirstRound": "Round 1", "payDate": "Payment date", "processStatus": "Status", "owner": "Procurement owner", "oaData": "OA data", "contractRule": "Contract rule", "ownerDefault": "Procurement owner", "workflowNo": "Workflow number", "contractNoPending": "Contract number pending attachment parsing", "synced": "Synced", "detailSubtitle": "OA data, payment nodes, and WeCom alert records", "backToOverview": "Back to overview", "contractInfo": "OA contract details", "alertHistory": "Alert history", "alertRound": "Alert round {round}", "alertAudit": "Alert delivery record", "alertAuditEmpty": "No alert records", "alertNode": "Payment stage", "alertScheduledAt": "Scheduled date", "alertSentAt": "Sent at", "alertStatus": {"pending": "Pending", "sent": "Sent", "failed": "Failed"}, "roundValue": "Round {round}", "weeklyBatchesTitle": "Weekly Summary Batches", "weeklyBatchesSubtitle": "Review recipient-level payment-alert summaries, Excel attachments, and delivery records.", "weeklySend": "Send alerts", "weeklyBatchSubmitted": "Send alert job submitted", "weeklyBatchesLoadFailed": "Failed to load weekly summary batches", "batchNo": "Batch no.", "weekKey": "Week", "batchStatusLabel": "Delivery status", "batchTotal": "Summary count", "batchExcel": "Excel attachment", "batchSentAt": "Sent at", "weeklyBatchesEmpty": "No weekly summary batches", "weeklyPendingSummary": "{count} pending this week · next send {datetime}", "weeklyPendingCountOnly": "{count} pending this week", "downloadExcel": "Download Excel", "excelDownloadFailed": "Failed to download the alert attachment", "batchStatus": {"pending": "Pending", "sent": "Sent", "failed": "Failed", "processing": "Processing", "resolved": "Alerts stopped"}, "backToLedger": "Back", "detailLoadFailed": "Failed to load contract details", "detailLoading": "Loading contract details…", "detailOverview": "Contract Overview", "detailAttachments": "Original Attachments", "detailPaymentPlan": "Payment Plan", "detailAlertHistory": "Alert History", "archiveDate": "Contract archive date", "archiveDateHint": "This date is when the contract apLine truncated
},
"contractPaymentReview": {"title": "Contracts for Confirmation", "subtitle": "Contracts that do not match the equipment procurement synonym title groups, fail payment-ratio validation, or conflict with OA fields are excluded from payment alerts. Download the original contract to verify it.", "searchPlaceholder": "Contract number, purchase order, or supplier", "loadFailed": "Failed to load contracts for confirmation", "contractWorkflow": "Contract / workflow number", "reason": "Reason for confirmation", "fallbackIssue": "Parsing result requires manual confirmation", "empty": "No contracts need confirmation"},
"contractPaymentReparse": {"action": "Reparse contract original", "success": "Reparsed with attachment “{attachment}”", "failed": "Failed to reparse contract"},
@@ -4957,7 +4962,9 @@
"examTitle": "Question Bank",
"examDesc": "Maintain structured question data for controlled examinations",
"reviewTitle": "Review & Checklist",
"reviewDesc": "Configure review points, pre-exam checklists, and guided chat questions"
"reviewDesc": "Configure review points, pre-exam checklists, and guided chat questions",
"leanTitle": "Lean Weekly Task",
"leanDesc": "Choose the weekly video list, set videos per week, and configure the deadline for that week"
},
"guideGroups": {
"company": "Company-level Safety Training",
@@ -4984,6 +4991,7 @@
"progressItemLabel": "Progress item label",
"progressHintText": "Training progress note",
"stepIntroText": "Training step guide copy",
"requiredDuration": "Required time (minutes)",
"summaryPoints": "Review points",
"summaryChecklist": "Pre-exam checklist",
"employeeQuestions": "Employee FAQs",
@@ -5012,6 +5020,66 @@
"guide": "Guide resource",
"document": "Knowledge document"
},
"directVideo": {
"title": "Training Videos",
"hint": "Upload videos directly. Uploaded videos are automatically added to this training configuration.",
"upload": "Upload Video",
"uploading": "Uploading...",
"empty": "No training videos uploaded",
"unnamed": "Unnamed video"
},
"lean": {
"weekKey": "Task week (Monday)",
"dueAt": "Due time",
"weekMustBeMonday": "The task week must be a Monday",
"weeklyCount": "Videos per week",
"weeklyCountHint": "Every Monday 09:00, the next batch of this many videos is pushed in selection order ({pushed}/{total} pushed); trainees get access immediately after publishing",
"videosTitle": "Required training videos",
"videosHint": "{count} videos selected (pushed weekly in batches by selection order)",
"targetsTitle": "Training targets",
"targetsHint": "Select roles or users; both scopes are combined.",
"targetRoles": "Target roles",
"targetUsers": "Target users",
"addTarget": "Add trainees",
"targetEmpty": "No training targets selected yet. Click \"Add trainees\" to configure by role or employee.",
"targetModalTitle": "Add training targets",
"targetSearchPlaceholder": "Search name / username / department",
"targetSelectedCount": "{roles} roles · {users} employees selected",
"targetUsersCount": "Target users ({count})",
"targetRolesEmpty": "No roles available",
"targetUsersEmpty": "No matching employees found",
"removeTarget": "Remove",
"targetConfirm": "Confirm",
"noVideoResources": "Save at least one video resource in Training Materials first",
"summaryRule": "Employees must watch the assigned videos and submit a learning reflection of at least {count} characters",
"pushNow": "Push new-task supplement now",
"pushing": "Pushing…",
"weekRangeLabel": "Week {index} · {range}",
"videoPagePrev": "Previous",
"videoPageNext": "Next",
"videoPageInfo": "Page {page} / {total}",
"pushCompleted": "All videos have been pushed",
"pushSuccess": "Pushed {count} videos and notified trainees",
"pushFailed": "Video push failed, please retry later",
"pushLogsTitle": "Push logs",
"pushLogsEmpty": "No push logs yet",
"pushProgress": "{pushed}/{total} videos pushed",
"pushBatch": "Pushed {count} videos · sent {sent} · failed {failed} · {recipients} recipients",
"pushStatus": {
"sent": "All sent",
"partial": "Partially failed",
"failed": "Push failed",
"completed": "Fully pushed"
},
"pushTrigger": {
"publish": "On publish",
"schedule": "Weekly schedule",
"manual": "Manual push"
},
"saveTask": "Publish weekly task",
"publishRequired": "Save and publish the Lean Management configuration before creating a weekly task",
"unnamedVideo": "Unnamed video"
},
"messages": {
"loadFailed": "Failed to load training configurations",
"saveFailed": "Failed to save training configuration",
@@ -5026,7 +5094,13 @@
"parseSuccess": "Parsed {count} questions. Review before saving.",
"parseFailed": "Question bank parsing failed",
"saved": "Training configuration saved",
"deleted": "Training configuration deleted"
"deleted": "Training configuration deleted",
"leanVideoCount": "Select at least one training video",
"leanTaskSaved": "Lean weekly task published",
"videoFileRequired": "Please select a video file",
"trainingAgentRequired": "The Employee Training agent was not found, so a video resource cannot be created",
"videoUploaded": "Training video uploaded and added to configuration resources",
"videoUploadFailed": "Failed to upload training video"
}
},
"integrationConnector": {
+74
View File
@@ -1014,11 +1014,81 @@
"description": "The administrator has not published the current training configuration yet."
},
"unknownDepartment": "Department pending",
"lean": {
"learner": {
"title": "Lean Management Weekly Training",
"taskTitle": "Session {index}",
"description": "Complete {count} required videos and submit a learning reflection of at least {minSummaryLength} characters for this session.",
"taskPeriod": "Task period: {start} to {end}",
"completedSummary": "Learning Reflection",
"completedAt": "Completed at: {time}",
"empty": "No lean training tasks yet"
},
"taskStatus": {
"in_progress": "In Progress",
"overdue": "Overdue",
"completed": "Completed"
},
"videoUnavailable": "This video has no playable URL yet",
"dueAt": "Due {time}",
"watchedAt": "Watched: {time}",
"markVideoWatched": "Click to record video completion",
"videoWatchedToast": "Video watching completed",
"videoWatchedBadge": "Completed",
"completeVideosFirst": "Please watch all required videos of this session in full before submitting your reflection",
"summaryTooShort": "The learning reflection must be at least {minSummaryLength} characters. Please keep writing",
"summaryPlaceholder": "Enter this week's learning reflection (at least {minSummaryLength} characters)",
"summaryLength": "{current}/{minSummaryLength} characters",
"submitSummary": "Submit Learning Reflection",
"dashboard": {
"title": "Lean Training Completion Lists",
"week": "Training week: {week}",
"completed": "Completed",
"incomplete": "Incomplete",
"count": "{count} people",
"empty": "No personnel data",
"passRate": "Completion Rate",
"periodLabel": "Period {index}"
},
"columns": {
"employeeId": "Employee ID",
"name": "Name",
"department": "Department",
"team": "Team",
"jobTitle": "Job Title",
"videoName": "Video Name",
"watchedAt": "Watch Time",
"status": "Status",
"summary": "Summary",
"action": "Action"
},
"status": {
"completed": "Completed",
"in_progress": "In Progress",
"overdue": "Overdue",
"incomplete": "Incomplete"
},
"reminder": {
"action": "Remind",
"sending": "Sending...",
"success": "Reminder sent ({count} people)",
"partial": "Reminder sent ({sent} people), {failed} failed. See the WeCom notify audit in the admin console for details.",
"sendFailed": "Failed to send reminder ({count} people). Check the WeCom notification settings, or see the notify audit in the admin console.",
"notSent": "No reminder sent: the member may have completed the training or is not bound to WeCom.",
"failed": "Failed to send reminder. Please try again later."
},
"summaryModal": {
"title": "Summary Details",
"viewHint": "Click to view the full summary",
"close": "Close"
}
},
"video": {
"title": "Step 1: Watch the training video",
"description": "Employees first complete the onboarding video, then move on to the knowledge review and exam.",
"completeAction": "I finished watching the video",
"playerTitle": "Video player slot",
"empty": "No playable training video is configured yet",
"playerHint": "This area can later connect to an enterprise video URL or internal player. The frontend container and completion action are already prepared."
},
"summary": {
@@ -1078,6 +1148,10 @@
"rule4": "HR can view statistics and export Excel from the same chat page."
},
"hr": {
"tabs": {
"allTraining": "All Training",
"leanManagement": "Lean Management"
},
"stats": {
"total": "Participants",
"passed": "Passed",
+1
View File
@@ -129,6 +129,7 @@
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "The peer-service login assertion could not be issued. Please retry.",
"AUTH_FORBIDDEN": "You do not have permission to perform this action.",
"CONTRACT_PAYMENT_FORBIDDEN": "You do not have access to contract payment alerts.",
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "Only administrators can sync, scan, or send contract payment alerts.",
"SHIPPING_TASK_SELECTION_INVALID": "Select between 1 and 100 shipping tasks.",
"SHIPPING_TASK_DELETE_REASON_REQUIRED": "A reason is required to delete or void tasks.",
"SHIPPING_TASK_EXTERNAL_VOID_BLOCKED": "The task is uploading externally or has been uploaded. It can only be archived.",
+1 -1
View File
@@ -284,7 +284,7 @@
"loading": "Loading source file info...",
"empty": "No source file info. Upload a version to see it here.",
"currentVersion": "Current version",
"opening": "Opening...",
"opening": "Downloading...",
"fileName": "File: {name}",
"fileSize": "Size: {size}",
"fileType": "Type: {ext}"
+78 -4
View File
@@ -1186,12 +1186,17 @@
"username": "ชื่อผู้ใช้",
"email": "อีเมล",
"department": "แผนก",
"team": "ทีม",
"jobTitle": "ตำแหน่งงาน",
"isTeamLeader": "หัวหน้าทีม",
"role": "บทบาท",
"featurePermissions": "สิทธิ์ฟีเจอร์",
"trainingHrManage": "จัดการ HR การฝึกอบรม",
"trainingHrManageHint": "เมื่อเปิดแล้ว ผู้ใช้นี้จะเข้าใช้มุมมอง HR 管理 ใน employee training agent เพื่อดูสถิติ คัดกรองข้อมูล และส่งออก Excel ได้",
"trainingLeanManage": "จัดการการฝึกอบรม Lean ทั้งหมด",
"trainingLeanTeamManage": "จัดการการฝึกอบรม Lean ระดับทีม",
"contractPaymentAccess": "สิทธิ์แจ้งเตือนการชำระเงินตามสัญญา",
"contractPaymentAccessHint": "เมื่อเปิดแล้ว ผู้ใช้นี้จะเข้าโต๊ะทำงานแจ้งเตือนการชำระเงินตามสัญญา (บัญชีสัญญา รายการรอยืนยัน และชุดสรุปรายสัปดาห์) และสั่งซิงค์หรือสแกนได้",
"contractPaymentAccessHint": "เมื่อเปิดแล้ว ผู้ใช้นี้จะเข้าโต๊ะทำงานแจ้งเตือนการชำระเงินตามสัญญา (บัญชีสัญญา รายการรอยืนยัน และชุดสรุปรายสัปดาห์) ได้ การซิงก์ OA สแกนแจ้งเตือน และส่งสรุปรายสัปดาห์ใช้ได้เฉพาะผู้ดูแลระบบ",
"password": "รหัสผ่าน",
"passwordHint": "(เว้นว่างไว้หากไม่ต้องการเปลี่ยน)",
"noAgents": "ไม่มีตัวแทนที่ใช้ได้"
@@ -4627,7 +4632,7 @@
}
},
"contractPayment": {
"title": "แจ้งเตือนการชำระเงินตามสัญญา", "subtitle": "ซิงก์สัญญา OA การรับมอบ และคำขอเบิกเงินล่วงหน้าของผู้ขาย พร้อมแจ้งเตือน 3 ระดับ", "sync": "ซิงก์ข้อมูล OA", "forceSync": "เขียนทับฟิลด์ OA แบบบังคับ", "forceSyncConfirm": "ระบบจะเขียนทับข้อมูล OA เดิมด้วยฟิลด์ที่ไม่ว่างจาก OA ครั้งนี้และบันทึกการตรวจสอบ ต้องการดำเนินการต่อหรือไม่?", "reparseExisting": "แยกวิเคราะห์สัญญาเดิมทั้งหมดใหม่", "reparseExistingConfirm": "ระบบจะรีเฟรชผลการแยกข้อมูลของสัญญาเดิมทั้งหมดจากไฟล์แนบที่จัดเก็บตามกฎปัจจุบัน โดยจะไม่ซิงก์หรือเขียนทับฟิลด์ OA ต้องการดำเนินการต่อหรือไม่?", "scanAlerts": "สแกนเพื่อสร้างแจ้งเตือน", "jobSubmitted": "ส่งงานแล้ว", "actionFailed": "ดำเนินการไม่สำเร็จ", "loadFailed": "โหลดสัญญาไม่สำเร็จ", "searchPlaceholder": "ค้นหาเลขที่สัญญาหรือใบสั่งซื้อ", "allStatus": "ทั้งหมด", "search": "ค้นหา", "ledger": "ทะเบียนสัญญา", "items": "รายการ", "empty": "ไม่มีข้อมูลสัญญา", "purchaseOrder": "ใบสั่งซื้อ", "supplier": "ผู้ขาย", "amount": "มูลค่าสัญญา", "deliveryDate": "กำหนดส่งมอบ", "timeline": "ไทม์ไลน์แผนการชำระเงิน", "notAvailable": "—", "stats": {"contracts": "สัญญา", "pendingParse": "สัญญาที่รอดำเนินการ", "readyPlans": "แผนพร้อมใช้", "alerts": "จุดแจ้งเตือน"}, "status": {"completed": "เสร็จสิ้น", "needs_review": "ต้องตรวจสอบ", "pending": "รอแยกข้อมูล"}, "stateLabel": {"parsed": "แยกข้อมูลแล้ว", "needs_review": "ต้องตรวจสอบ", "pending": "รอแยกข้อมูล", "active": "ใช้งานอยู่"}, "nodeType": {"prepayment": "เงินล่วงหน้า", "shipment": "เงินก่อนส่ง", "acceptance": "เงินรับมอบ", "warranty": "เงินประกัน"}, "ruleConfirmed": "ยืนยันแล้ว", "prepaymentRule": "แจ้งเตือนวันที่ 7/14/21 หลังจัดเก็บสัญญา; สถานะคำขออ้างอิง OA.", "shipmentRule": "แจ้งเตือนก่อนกำหนดส่ง 7 วัน วันครบกำหนด และหลังครบกำหนด 14 วัน; สถานะคำขออ้างอิง OA.", "acceptanceRule": "แจ้งเตือนวันที่ 30/40/60 หลังจัดเก็บใบรับมอบ; เงินประกันแจ้งก่อนครบกำหนด 7 วัน วันครบกำหนด และหลังครบกำหนด 14 วัน.", "pendingAlerts": "แจ้งเตือนที่รอดำเนินการ", "processing": "เริ่มชำระแล้ว", "dataPending": "รอข้อมูล", "paid": "ชำระแล้ว", "amountRatioDate": "จำนวนเงิน / สัดส่วน · วันที่", "applicant": "ผู้ขอ", "statusLabel": "สถานะ", "contractPrefix": "สัญญา", "datePending": "รอระบุวันที่", "statusNormal": "ปกติ", "statusNeedsCompletion": "ต้องเติมข้อมูล", "statusOverdue": "เกินกำหนดชำระ", "statusUpcoming": "ใกล้ถึงกำหนด", "statusActive": "กำลังดำเนินการ", "statusCompleted": "เสร็จสิ้น", "totalPrefix": "รวม", "contractSupplier": "สัญญา / ผู้ขาย", "nextAlert": "แจ้งเตือนถัดไป", "triggerBasis": "เกณฑ์เริ่ม", "alertDate": "วันที่แจ้งเตือน", "alertFirstRound": "รอบ 1", "payDate": "วันที่ชำระLine truncated
"title": "แจ้งเตือนการชำระเงินตามสัญญา", "subtitle": "ซิงก์สัญญา OA การรับมอบ และคำขอเบิกเงินล่วงหน้าของผู้ขาย พร้อมแจ้งเตือน 3 ระดับ", "sync": "ซิงก์ข้อมูล OA", "forceSync": "เขียนทับฟิลด์ OA แบบบังคับ", "forceSyncConfirm": "ระบบจะเขียนทับข้อมูล OA เดิมด้วยฟิลด์ที่ไม่ว่างจาก OA ครั้งนี้และบันทึกการตรวจสอบ ต้องการดำเนินการต่อหรือไม่?", "reparseExisting": "แยกวิเคราะห์สัญญาเดิมทั้งหมดใหม่", "reparseExistingConfirm": "ระบบจะรีเฟรชผลการแยกข้อมูลของสัญญาเดิมทั้งหมดจากไฟล์แนบที่จัดเก็บตามกฎปัจจุบัน โดยจะไม่ซิงก์หรือเขียนทับฟิลด์ OA ต้องการดำเนินการต่อหรือไม่?", "scanAlerts": "สแกนเพื่อสร้างแจ้งเตือน", "jobSubmitted": "ส่งงานแล้ว", "actionFailed": "ดำเนินการไม่สำเร็จ", "loadFailed": "โหลดสัญญาไม่สำเร็จ", "searchPlaceholder": "ค้นหาเลขที่สัญญา ใบสั่งซื้อ หรือผู้ขาย", "allStatus": "ทั้งหมด", "search": "ค้นหา", "ledger": "ทะเบียนสัญญา", "items": "รายการ", "empty": "ไม่มีข้อมูลสัญญา", "purchaseOrder": "ใบสั่งซื้อ", "supplier": "ผู้ขาย", "amount": "มูลค่าสัญญา", "deliveryDate": "กำหนดส่งมอบ", "timeline": "ไทม์ไลน์แผนการชำระเงิน", "notAvailable": "—", "stats": {"contracts": "สัญญา", "pendingParse": "สัญญาที่รอดำเนินการ", "readyPlans": "แผนพร้อมใช้", "alerts": "จุดแจ้งเตือน"}, "ledgerFocus": {"due": "ใกล้ครบกำหนด", "dueHint": "ใน 7 วัน", "overdue": "ค้างชำระเกินกำหนด", "needsCompletion": "รอข้อมูลเพิ่ม", "dueThisMonth": "ถึงกำหนดเดือนนี้", "dueThisMonthHint": "เดือนปฏิทินนี้"}, "status": {"completed": "เสร็จสิ้น", "needs_review": "ต้องตรวจสอบ", "pending": "รอแยกข้อมูล"}, "stateLabel": {"parsed": "แยกข้อมูลแล้ว", "needs_review": "ต้องตรวจสอบ", "pending": "รอแยกข้อมูล", "active": "ใช้งานอยู่"}, "nodeType": {"prepayment": "เงินล่วงหน้า", "shipment": "เงินก่อนส่ง", "acceptance": "เงินรับมอบ", "warranty": "เงินประกัน"}, "ruleConfirmed": "ยืนยันแล้ว", "prepaymentRule": "แจ้งเตือนวันที่ 7/14/21 หลังจัดเก็บสัญญา; สถานะคำขออ้างอิง OA.", "shipmentRule": "แจ้งเตือนก่อนกำหนดส่ง 7 วัน วันครบกำหนด และหลังครบกำหนด 14 วัน; สถานะคำขออ้างอิง OA.", "acceptanceRule": "แจ้งเตือนวันที่ 30/40/60 หลังจัดเก็บใบรับมอบ; เงินประกันแจ้งก่อนครบกำหนด 7 วัน วันครบกำหนด และหลังครบกำหนด 14 วัน.", "pendingAlerts": "แจ้งเตือนที่รอดำเนินการ", "processing": "เริ่มชำระแล้ว", "dataPending": "รอข้อมูล", "paid": "ชำระแล้ว", "amountRatioDate": "จำนวนเงิน / สัดส่วน · วันที่", "applicant": "ผู้ขอ", "statusLabel": "สถานะ", "contractPrefix": "สัญญา", "datePending": "รอระบุวันที่", "statusNormal": "ปกติ", "statusNeedsCompletion": "ต้องเติมข้อมูล", "statusOverdue": "เกินกำหนดชำระ", "statusUpcoming": "ใกล้ถึงกำหนด", "statusActive": "กำลังดำเนินการ", "statusLine truncated
},
"contractPaymentReview": {"title": "สัญญาที่รอยืนยัน", "subtitle": "สัญญาที่ไม่ตรงกับกลุ่มหัวข้อคำพ้องของสัญญาจัดซื้ออุปกรณ์ ตรวจสอบสัดส่วนการชำระเงินไม่ผ่าน หรือขัดแย้งกับฟิลด์ OA จะไม่เข้าสู่การแจ้งเตือนการชำระเงิน โปรดดาวน์โหลดต้นฉบับเพื่อตรวจสอบ", "searchPlaceholder": "เลขที่สัญญา ใบสั่งซื้อ หรือผู้ขาย", "loadFailed": "โหลดสัญญาที่รอยืนยันไม่สำเร็จ", "contractWorkflow": "เลขที่สัญญา / เวิร์กโฟลว์", "reason": "เหตุผลที่ต้องยืนยัน", "fallbackIssue": "ผลการแยกข้อมูลต้องยืนยันโดยผู้ใช้", "empty": "ไม่มีสัญญาที่รอยืนยัน"},
"contractPaymentReparse": {"action": "แยกข้อมูลจากต้นฉบับอีกครั้ง", "success": "แยกข้อมูลใหม่ด้วยไฟล์แนบ “{attachment}” แล้ว", "failed": "แยกข้อมูลสัญญาใหม่ไม่สำเร็จ"},
@@ -4826,7 +4831,9 @@
"examTitle": "คลังข้อสอบ",
"examDesc": "ดูแลข้อมูลคำถามแบบมีโครงสร้างสำหรับการสอบที่ควบคุม",
"reviewTitle": "ทบทวนและรายการตรวจสอบ",
"reviewDesc": "กำหนดประเด็นทบทวน รายการก่อนสอบ และคำถามแนะนำในการสนทนา"
"reviewDesc": "กำหนดประเด็นทบทวน รายการก่อนสอบ และคำถามแนะนำในการสนทนา",
"leanTitle": "ภารกิจ Lean รายสัปดาห์",
"leanDesc": "เลือกรายการวิดีโอประจำสัปดาห์ กำหนดจำนวนวิดีโอต่อสัปดาห์ และตั้งเส้นตายของสัปดาห์นั้น"
},
"guideGroups": {
"company": "การฝึกอบรมความปลอดภัยระดับบริษัท",
@@ -4853,6 +4860,7 @@
"progressItemLabel": "ชื่อรายการความคืบหน้า",
"progressHintText": "คำอธิบายความคืบหน้าการฝึกอบรม",
"stepIntroText": "ข้อความแนะนำขั้นตอนการฝึกอบรม",
"requiredDuration": "เวลาที่ต้องใช้ (นาที)",
"summaryPoints": "ประเด็นทบทวน",
"summaryChecklist": "รายการก่อนสอบ",
"employeeQuestions": "คำถามที่พบบ่อยของพนักงาน",
@@ -4881,6 +4889,66 @@
"guide": "ทรัพยากรคู่มือ",
"document": "เอกสารคลังความรู้"
},
"directVideo": {
"title": "วิดีโอการฝึกอบรม",
"hint": "อัปโหลดวิดีโอโดยตรง และวิดีโอจะถูกเพิ่มในทรัพยากรการกำหนดค่านี้โดยอัตโนมัติ",
"upload": "อัปโหลดวิดีโอ",
"uploading": "กำลังอัปโหลด...",
"empty": "ยังไม่มีวิดีโอการฝึกอบรม",
"unnamed": "วิดีโอไม่มีชื่อ"
},
"lean": {
"weekKey": "สัปดาห์ภารกิจ (วันจันทร์)",
"dueAt": "เวลาครบกำหนด",
"weekMustBeMonday": "สัปดาห์ของงานต้องเป็นวันจันทร์",
"weeklyCount": "จำนวนวิดีโอต่อสัปดาห์",
"weeklyCountHint": "ทุกวันจันทร์ 09:00 ระบบจะส่งวิดีโอชุดถัดไปตามจำนวนนี้ตามลำดับที่เลือก (ส่งแล้ว {pushed}/{total}) ผู้เข้าอบรมเริ่มเรียนได้ทันทีหลังเผยแพร่",
"videosTitle": "วิดีโอการฝึกอบรมที่กำหนด",
"videosHint": "เลือกแล้ว {count} วิดีโอ (ส่งเป็นชุดรายสัปดาห์ตามลำดับที่เลือก)",
"targetsTitle": "กลุ่มผู้เข้ารับการฝึกอบรม",
"targetsHint": "เลือกตามบทบาทหรือผู้ใช้ที่ระบุ โดยรวมทั้งสองขอบเขต",
"targetRoles": "บทบาทที่ระบุ",
"targetUsers": "ผู้ใช้ที่ระบุ",
"addTarget": "เพิ่มผู้เข้ารับการฝึกอบรม",
"targetEmpty": "ยังไม่ได้เลือกกลุ่มผู้เข้ารับการฝึกอบรม โปรดคลิก \"เพิ่มผู้เข้ารับการฝึกอบรม\" เพื่อกำหนดตามบทบาทหรือพนักงาน",
"targetModalTitle": "เพิ่มกลุ่มผู้เข้ารับการฝึกอบรม",
"targetSearchPlaceholder": "ค้นหาชื่อ / ชื่อผู้ใช้ / แผนก",
"targetSelectedCount": "เลือกแล้ว {roles} บทบาท · {users} พนักงาน",
"targetUsersCount": "ผู้ใช้ที่ระบุ ({count})",
"targetRolesEmpty": "ไม่มีบทบาทให้เลือก",
"targetUsersEmpty": "ไม่พบพนักงานที่ตรงกัน",
"removeTarget": "นำออก",
"targetConfirm": "ยืนยัน",
"noVideoResources": "โปรดบันทึกทรัพยากรวิดีโออย่างน้อยหนึ่งรายการในเอกสารฝึกอบรมก่อน",
"summaryRule": "พนักงานต้องดูวิดีโอที่กำหนดและส่งความเห็นการเรียนรู้อย่างน้อย {count} อักขระ",
"pushNow": "เพิ่มงานใหม่และส่งเพิ่มทันที",
"pushing": "กำลังส่ง…",
"weekRangeLabel": "สัปดาห์ที่ {index} {range}",
"videoPagePrev": "ก่อนหน้า",
"videoPageNext": "ถัดไป",
"videoPageInfo": "หน้า {page} / {total}",
"pushCompleted": "ส่งวิดีโอครบทุกรายการแล้ว",
"pushSuccess": "ส่งวิดีโอ {count} รายการและแจ้งผู้เข้าอบรมแล้ว",
"pushFailed": "การส่งวิดีโอล้มเหลว โปรดลองอีกครั้งภายหลัง",
"pushLogsTitle": "บันทึกการส่ง",
"pushLogsEmpty": "ยังไม่มีบันทึกการส่ง",
"pushProgress": "ส่งแล้ว {pushed}/{total} วิดีโอ",
"pushBatch": "ส่ง {count} วิดีโอ · สำเร็จ {sent} · ล้มเหลว {failed} · ผู้รับ {recipients} คน",
"pushStatus": {
"sent": "สำเร็จทั้งหมด",
"partial": "ล้มเหลวบางส่วน",
"failed": "การส่งล้มเหลว",
"completed": "ส่งครบแล้ว"
},
"pushTrigger": {
"publish": "ส่งเมื่อเผยแพร่",
"schedule": "ตารางรายสัปดาห์",
"manual": "ส่งด้วยตนเอง"
},
"saveTask": "เผยแพร่ภารกิจรายสัปดาห์",
"publishRequired": "โปรดบันทึกและเผยแพร่การกำหนดค่า Lean Management ก่อนสร้างภารกิจรายสัปดาห์",
"unnamedVideo": "วิดีโอไม่มีชื่อ"
},
"messages": {
"loadFailed": "โหลดการกำหนดค่าไม่สำเร็จ",
"saveFailed": "บันทึกการกำหนดค่าไม่สำเร็จ",
@@ -4895,7 +4963,13 @@
"parseSuccess": "วิเคราะห์ได้ {count} ข้อ โปรดตรวจสอบก่อนบันทึก",
"parseFailed": "วิเคราะห์คลังข้อสอบไม่สำเร็จ",
"saved": "บันทึกการกำหนดค่าแล้ว",
"deleted": "ลบการกำหนดค่าแล้ว"
"deleted": "ลบการกำหนดค่าแล้ว",
"leanVideoCount": "โปรดเลือกวิดีโอการฝึกอบรมอย่างน้อยหนึ่งรายการ",
"leanTaskSaved": "เผยแพร่ภารกิจ Lean รายสัปดาห์แล้ว",
"videoFileRequired": "โปรดเลือกไฟล์วิดีโอ",
"trainingAgentRequired": "ไม่พบ Agent การฝึกอบรมพนักงาน จึงไม่สามารถสร้างทรัพยากรวิดีโอได้",
"videoUploaded": "อัปโหลดวิดีโอการฝึกอบรมและเพิ่มในทรัพยากรการกำหนดค่าแล้ว",
"videoUploadFailed": "อัปโหลดวิดีโอการฝึกอบรมไม่สำเร็จ"
}
},
"integrationConnector": {
+74
View File
@@ -1014,11 +1014,81 @@
"description": "ผู้ดูแลระบบยังไม่ได้เผยแพร่การกำหนดค่าการฝึกอบรมปัจจุบัน"
},
"unknownDepartment": "ยังไม่ได้ระบุแผนก",
"lean": {
"learner": {
"title": "การอบรมการจัดการแบบลีนประจำสัปดาห์",
"taskTitle": "รอบที่ {index}",
"description": "รอบนี้ต้องดูวิดีโอที่กำหนด {count} รายการและส่งสรุปการเรียนรู้อย่างน้อย {minSummaryLength} ตัวอักษร",
"taskPeriod": "รอบงาน: {start} ถึง {end}",
"completedSummary": "สรุปการเรียนรู้",
"completedAt": "เสร็จสิ้นเมื่อ: {time}",
"empty": "ยังไม่มีงานอบรมลีน"
},
"taskStatus": {
"in_progress": "กำลังดำเนินการ",
"overdue": "เกินกำหนด",
"completed": "เสร็จสิ้น"
},
"videoUnavailable": "วิดีโอนี้ยังไม่มีลิงก์สำหรับเล่น",
"dueAt": "กำหนดส่ง {time}",
"watchedAt": "ดูแล้ว: {time}",
"markVideoWatched": "คลิกเพื่อบันทึกว่าดูวิดีโอเสร็จแล้ว",
"videoWatchedToast": "ดูวิดีโอครบแล้ว",
"videoWatchedBadge": "เสร็จสิ้น",
"completeVideosFirst": "กรุณาดูวิดีโอที่กำหนดของรอบนี้ให้ครบก่อนส่งสรุปการเรียนรู้",
"summaryTooShort": "สรุปการเรียนรู้ต้องมีอย่างน้อย {minSummaryLength} ตัวอักษร กรุณาเขียนต่อ",
"summaryPlaceholder": "กรอกสรุปการเรียนรู้ประจำสัปดาห์ (อย่างน้อย {minSummaryLength} ตัวอักษร)",
"summaryLength": "{current}/{minSummaryLength} ตัวอักษร",
"submitSummary": "ส่งสรุปการเรียนรู้",
"dashboard": {
"title": "รายชื่อผลการอบรมลีน",
"week": "สัปดาห์อบรม: {week}",
"completed": "รายชื่อผู้เสร็จสิ้น",
"incomplete": "รายชื่อผู้ยังไม่เสร็จ",
"count": "{count} คน",
"empty": "ไม่มีข้อมูลบุคลากร",
"passRate": "อัตราความสำเร็จ",
"periodLabel": "รอบที่ {index}"
},
"columns": {
"employeeId": "รหัสพนักงาน",
"name": "ชื่อ",
"department": "แผนก",
"team": "ทีม",
"jobTitle": "ตำแหน่ง",
"videoName": "ชื่อวิดีโอ",
"watchedAt": "เวลาที่รับชม",
"status": "สถานะ",
"summary": "สรุป",
"action": "การดำเนินการ"
},
"status": {
"completed": "เสร็จสิ้น",
"in_progress": "กำลังดำเนินการ",
"overdue": "เกินกำหนด",
"incomplete": "ยังไม่เสร็จ"
},
"reminder": {
"action": "เตือน",
"sending": "กำลังส่ง...",
"success": "ส่งการเตือนแล้ว ({count} คน)",
"partial": "ส่งการเตือนแล้ว ({sent} คน) แต่ {failed} คนส่งไม่สำเร็จ โปรดตรวจสอบบันทึกการแจ้งเตือน WeCom ในหน้าผู้ดูแลระบบ",
"sendFailed": "ส่งการเตือนไม่สำเร็จ ({count} คน) โปรดตรวจสอบการตั้งค่าการแจ้งเตือน WeCom หรือดูบันทึกการแจ้งเตือนในหน้าผู้ดูแลระบบ",
"notSent": "ยังไม่ได้ส่งการเตือน: สมาชิกอาจเรียนเสร็จแล้วหรือยังไม่ได้ผูกบัญชี WeCom",
"failed": "ส่งการเตือนไม่สำเร็จ โปรดลองอีกครั้งภายหลัง"
},
"summaryModal": {
"title": "รายละเอียดสรุป",
"viewHint": "คลิกเพื่อดูสรุปทั้งหมด",
"close": "ปิด"
}
},
"video": {
"title": "ขั้นตอน 1: ดูวิดีโออบรม",
"description": "พนักงานใหม่ต้องดูวิดีโออบรมก่อน แล้วจึงเข้าสู่การทบทวนความรู้และการสอบ",
"completeAction": "ฉันดูวิดีโอเสร็จแล้ว",
"playerTitle": "ตำแหน่งตัวเล่นวิดีโอ",
"empty": "ยังไม่ได้กำหนดวิดีโอการฝึกอบรมที่เล่นได้",
"playerHint": "ส่วนนี้สามารถเชื่อมต่อกับลิงก์วิดีโอภายในบริษัทหรือเครื่องเล่นภายในได้ในภายหลัง"
},
"summary": {
@@ -1078,6 +1148,10 @@
"rule4": "HR สามารถดูสถิติและส่งออก Excel ได้จากหน้าแชตเดียวกัน"
},
"hr": {
"tabs": {
"allTraining": "การอบรมทั้งหมด",
"leanManagement": "การจัดการแบบลีน"
},
"stats": {
"total": "จำนวนผู้เข้าอบรม",
"passed": "ผ่านแล้ว",
+1
View File
@@ -129,6 +129,7 @@
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "ไม่สามารถออกข้อมูลยืนยันการเข้าสู่ระบบสำหรับบริการในผลิตภัณฑ์ได้ โปรดลองใหม่",
"AUTH_FORBIDDEN": "คุณไม่มีสิทธิ์ดำเนินการนี้",
"CONTRACT_PAYMENT_FORBIDDEN": "คุณไม่มีสิทธิ์เข้าถึงการแจ้งเตือนการชำระเงินตามสัญญา",
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "เฉพาะผู้ดูแลระบบเท่านั้นที่ซิงก์ สแกน หรือส่งการแจ้งเตือนการชำระเงินตามสัญญาได้",
"SHIPPING_TASK_SELECTION_INVALID": "เลือกงานจัดส่งได้ 1 ถึง 100 งาน",
"SHIPPING_TASK_DELETE_REASON_REQUIRED": "ต้องระบุเหตุผลในการลบหรือยกเลิกงาน",
"SHIPPING_TASK_EXTERNAL_VOID_BLOCKED": "งานกำลังอัปโหลดภายนอกหรืออัปโหลดแล้ว จึงทำได้เพียงเก็บถาวร",
+1 -1
View File
@@ -284,7 +284,7 @@
"loading": "กำลังโหลดข้อมูลไฟล์ต้นฉบับ...",
"empty": "ยังไม่มีข้อมูลไฟล์ต้นฉบับ อัปโหลดเวอร์ชันเพื่อดูที่นี่",
"currentVersion": "เวอร์ชันปัจจุบัน",
"opening": "กำลังเปิด...",
"opening": "กำลังดาวน์โหลด...",
"fileName": "ไฟล์: {name}",
"fileSize": "ขนาด: {size}",
"fileType": "ประเภท: {ext}"
+80 -5
View File
@@ -1320,12 +1320,17 @@
"username": "用户名",
"email": "邮箱",
"department": "部门",
"team": "班组",
"jobTitle": "职务",
"isTeamLeader": "班组长",
"role": "角色",
"featurePermissions": "功能权限",
"trainingHrManage": "培训 HR 管理",
"trainingHrManageHint": "勾选后可进入员工培训 Agent 的【HR 管理】视图,查看统计、筛选记录并导出 Excel。",
"trainingLeanManage": "精益培训全量管理",
"trainingLeanTeamManage": "精益培训班组管理",
"contractPaymentAccess": "合同付款预警访问",
"contractPaymentAccessHint": "勾选后可进入工作台合同付款预警(台账、待确认、周汇总),并触发同步与扫描。",
"contractPaymentAccessHint": "勾选后可进入工作台合同付款预警(台账、待确认、周汇总)。同步 OA、扫描预警和发送预警仅管理员可用。",
"password": "密码",
"passwordHint": "(留空表示不修改)",
"noAgents": "暂无可用应用"
@@ -4754,7 +4759,7 @@
"jobSubmitted": "任务已提交",
"actionFailed": "操作失败",
"loadFailed": "加载合同失败",
"searchPlaceholder": "搜索合同编号或采购单号",
"searchPlaceholder": "搜索合同编号、采购单号或供应商",
"allStatus": "全部",
"search": "查询",
"ledger": "合同台账",
@@ -4767,6 +4772,7 @@
"timeline": "付款计划时间线",
"notAvailable": "—",
"stats": {"contracts": "合同总数", "pendingParse": "待处理合同", "readyPlans": "计划已生成", "alerts": "待预警节点"},
"ledgerFocus": {"due": "即将到期", "dueHint": "7日内", "overdue": "逾期未付", "needsCompletion": "待补充", "dueThisMonth": "本月应付", "dueThisMonthHint": "本自然月"},
"status": {"completed": "已完成", "needs_review": "待复核", "pending": "待解析"}, "stateLabel": {"parsed": "已解析", "needs_review": "待复核", "pending": "待解析", "active": "已生效"},
"nodeType": {"prepayment": "预付款", "shipment": "出货款", "acceptance": "验收款", "warranty": "质保款"},
"ruleConfirmed": "已确定",
@@ -4774,7 +4780,7 @@
"shipmentRule": "交货期限前 7 天、到期日、到期后 14 天预警;请款以 OA 厂商预付款请款作业为准。",
"acceptanceRule": "验收归档后第 30/40/60 天预警;质保款在质保到期前 7 天、到期日、到期后 14 天预警。",
"pendingAlerts": "待处理预警", "processing": "已发起付款", "dataPending": "数据待确认", "paid": "已付款", "amountRatioDate": "金额 / 比例 · 日期", "applicant": "申请人", "statusLabel": "状态", "contractPrefix": "合同", "datePending": "待补充日期", "statusNormal": "正常", "statusNeedsCompletion": "待补充", "statusOverdue": "已逾期", "statusUpcoming": "即将到期", "statusActive": "进行中", "statusCompleted": "已完成",
"totalPrefix": "共", "contractSupplier": "合同号 / 供应商", "nextAlert": "下一预警", "triggerBasis": "触发依据", "alertDate": "预警日期", "alertFirstRound": "首轮", "payDate": "付款日期", "processStatus": "处理状态", "owner": "采购负责人", "oaData": "OA 数据", "contractRule": "合同规则", "ownerDefault": "采购负责人", "workflowNo": "流程编号", "contractNoPending": "合同号待从附件解析", "synced": "已同步", "detailSubtitle": "OA 数据、付款节点与企业微信提醒记录", "backToOverview": "返回总览", "contractInfo": "OA 合同信息", "alertHistory": "预警记录", "alertRound": "第 {round} 次预警", "alertAudit": "预警发送记录", "alertAuditEmpty": "暂无预警记录", "alertNode": "付款节点", "alertScheduledAt": "计划日期", "alertSentAt": "发送时间", "alertStatus": {"pending": "待发送", "sent": "已发送", "failed": "发送失败"}, "roundValue": "第 {round} 次", "weeklyBatchesTitle": "周汇总批次", "weeklyBatchesSubtitle": "查看按收件人生成的付款预警周汇总、Excel 附件及发送记录。", "refresh": "刷新", "weeklySend": "发送预警", "weeklyBatchSubmitted": "发送预警任务已提交", "weeklyBatchesLoadFailed": "加载周汇总批次失败", "batchNo": "批次号", "weekKey": "周次", "batchStatusLabel": "发送状态", "batchTotal": "汇总笔数", "batchExcel": "Excel 附件", "batchSentAt": "发送时间", "weeklyBatchesEmpty": "暂无周汇总批次", "weeklyPendingSummary": "本周待发送 {count} 笔 · 下次发送 {datetime}", "weeklyPendingCountOnly": "本周待发送 {count} 笔", "downloadExcel": "下载 Excel", "excelDownloadFailed": "下载预警附件失败", "batchStatus": {"pending": "待发送", "sent": "已发送", "failed": "发送失败", "processing": "处理中", "resolved": "已停止提醒"}, "backToLedger": "返回", "detailLoadFailed": "加载合同详情失败", "detailLoading": "正在加载合同详情…", "detailOverview": "合同概览", "detailAttachments": "原文附件", "detailPaymentPlan": "付款计划", "detailAlertHistory": "预警记录", "archiveDate": "合同归档日期", "archiveDateHint": "该日期为合同申请单的归档日期", "parseStatus": "解析状态", "parseIssueTitle": "解析提示", "planStatus": "计划状态", "attachmentsEmpty": "暂无已归档的合同原文附件", "downloadAttachment": "下载附件", "attachmentDownloadFailed": "下载合同附件失败", "paymentPlanEmpty": "暂无可展示的付款计划", "anchorDate": "日期依据", "nodeStatus": {"pending": "待处理", "active": "进行中", "paid": "已付", "processing": "处理中", "resolved": "已停止提醒", "upcoming": "即将到期", "notStarted": "待起算", "overdue": "已逾期", "review": "待复核"}, "reparse": "重新解析合同原文", "reparseSuccess": "已使用附件“{attachment}”重新解析", "reparseFailed": "重新解析合同失败", "reviewTitle": "待确认合同", "reviewSubtitle": "未匹配设备采购合同同义标题组、付款比例校验失败或关键字段冲突的合同不会进入付款预警,请下载原文核对。", "reviewSearchPlaceholder": "合同编号、采购编号或供应商", "reviewLoadFailed": "待确认合同加载失败", "reviewContractWorkflow": "合同号 / 流程编号", "reviewReason": "待确认原因", "reviewFallbackIssue": "解析结果待人工确认", "reviewEmpty": "暂无待确认合同"
"totalPrefix": "共", "contractSupplier": "合同号 / 供应商", "nextAlert": "下一预警", "triggerBasis": "触发依据", "alertDate": "预警日期", "alertFirstRound": "首轮", "payDate": "付款日期", "processStatus": "处理状态", "owner": "采购负责人", "oaData": "OA 数据", "contractRule": "合同规则", "ownerDefault": "采购负责人", "workflowNo": "流程编号", "contractNoPending": "合同号待从附件解析", "synced": "已同步", "detailSubtitle": "OA 数据、付款节点与企业微信提醒记录", "backToOverview": "返回总览", "contractInfo": "OA 合同信息", "alertHistory": "预警记录", "alertRound": "第 {round} 次预警", "alertAudit": "预警发送记录", "alertAuditEmpty": "暂无预警记录", "alertNode": "付款节点", "alertScheduledAt": "计划日期", "alertSentAt": "发送时间", "alertStatus": {"pending": "待发送", "sent": "已发送", "failed": "发送失败"}, "roundValue": "第 {round} 次", "weeklyBatchesTitle": "周汇总批次", "weeklyBatchesSubtitle": "查看按收件人生成的付款预警周汇总、Excel 附件及发送记录。", "weeklySend": "发送预警", "weeklyBatchSubmitted": "发送预警任务已提交", "weeklyBatchesLoadFailed": "加载周汇总批次失败", "batchNo": "批次号", "weekKey": "周次", "batchStatusLabel": "发送状态", "batchTotal": "汇总笔数", "batchExcel": "Excel 附件", "batchSentAt": "发送时间", "weeklyBatchesEmpty": "暂无周汇总批次", "weeklyPendingSummary": "本周待发送 {count} 笔 · 下次发送 {datetime}", "weeklyPendingCountOnly": "本周待发送 {count} 笔", "downloadExcel": "下载 Excel", "excelDownloadFailed": "下载预警附件失败", "batchStatus": {"pending": "待发送", "sent": "已发送", "failed": "发送失败", "processing": "处理中", "resolved": "已停止提醒"}, "backToLedger": "返回", "detailLoadFailed": "加载合同详情失败", "detailLoading": "正在加载合同详情…", "detailOverview": "合同概览", "detailAttachments": "原文附件", "detailPaymentPlan": "付款计划", "detailAlertHistory": "预警记录", "archiveDate": "合同归档日期", "archiveDateHint": "该日期为合同申请单的归档日期", "parseStatus": "解析状态", "parseIssueTitle": "解析提示", "planStatus": "计划状态", "attachmentsEmpty": "暂无已归档的合同原文附件", "downloadAttachment": "下载附件", "attachmentDownloadFailed": "下载合同附件失败", "paymentPlanEmpty": "暂无可展示的付款计划", "anchorDate": "日期依据", "nodeStatus": {"pending": "待处理", "active": "进行中", "paid": "已付", "processing": "处理中", "resolved": "已停止提醒", "upcoming": "即将到期", "notStarted": "待起算", "overdue": "已逾期", "review": "待复核"}, "reparse": "重新解析合同原文", "reparseSuccess": "已使用附件“{attachment}”重新解析", "reparseFailed": "重新解析合同失败", "reviewTitle": "待确认合同", "reviewSubtitle": "未匹配设备采购合同同义标题组、付款比例校验失败或关键字段冲突的合同不会进入付款预警,请下载原文核对。", "reviewSearchPlaceholder": "合同编号、采购编号或供应商", "reviewLoadFailed": "待确认合同加载失败", "reviewContractWorkflow": "合同号 / 流程编号", "reviewReason": "待确认原因", "reviewFallbackIssue": "解析结果待人工确认", "reviewEmpty": "暂无待确认合同"
},
"contractPaymentReview": {"title": "待确认合同", "subtitle": "未匹配设备采购合同同义标题组、付款比例校验失败或关键字段冲突的合同不会进入付款预警,请下载原文核对。", "searchPlaceholder": "合同编号、采购编号或供应商", "loadFailed": "待确认合同加载失败", "contractWorkflow": "合同号 / 流程编号", "reason": "待确认原因", "fallbackIssue": "解析结果待人工确认", "empty": "暂无待确认合同"},
"contractPaymentReparse": {"action": "重新解析合同原文", "success": "已使用附件“{attachment}”重新解析", "failed": "重新解析合同失败"},
@@ -4982,7 +4988,9 @@
"examTitle": "考试题库",
"examDesc": "维护受控考试使用的结构化题目数据",
"reviewTitle": "复盘与清单",
"reviewDesc": "配置培训完成后的复盘重点、考前清单与聊天引导问题"
"reviewDesc": "配置培训完成后的复盘重点、考前清单与聊天引导问题",
"leanTitle": "精益周任务",
"leanDesc": "为指定自然周选择视频列表、设置每周推送数量并配置周截止时间"
},
"guideGroups": {
"company": "公司级安全培训",
@@ -5009,6 +5017,7 @@
"progressItemLabel": "进度项名称",
"progressHintText": "培训进度说明",
"stepIntroText": "培训步骤引导文案",
"requiredDuration": "所需时间(分钟)",
"summaryPoints": "复盘要点",
"summaryChecklist": "考前清单",
"employeeQuestions": "员工常见问题",
@@ -5037,6 +5046,66 @@
"guide": "指南资源",
"document": "知识库文档"
},
"directVideo": {
"title": "培训视频",
"hint": "可直接上传视频,上传后自动加入当前培训配置资源。",
"upload": "上传视频",
"uploading": "上传中...",
"empty": "暂未上传培训视频",
"unnamed": "未命名视频"
},
"lean": {
"weekKey": "任务周(周一)",
"dueAt": "截止时间",
"weekMustBeMonday": "任务周必须选择周一",
"weeklyCount": "每周任务数量",
"weeklyCountHint": "每周一 09:00 按该数量从视频列表顺序推送下一批(已推送 {pushed}/{total}),受训员工发布后立即可学",
"videosTitle": "指定培训视频",
"videosHint": "已选择 {count} 个视频(按选择顺序每周分批推送)",
"targetsTitle": "受训对象",
"targetsHint": "按角色或指定用户选择,两个范围取并集",
"targetRoles": "指定角色",
"targetUsers": "指定用户",
"addTarget": "添加受训",
"targetEmpty": "尚未选择受训对象,请点击\"添加受训\"按角色或员工配置",
"targetModalTitle": "添加受训对象",
"targetSearchPlaceholder": "搜索姓名 / 用户名 / 部门",
"targetSelectedCount": "已选 {roles} 个角色 · {users} 名员工",
"targetUsersCount": "指定用户({count})",
"targetRolesEmpty": "暂无可选角色",
"targetUsersEmpty": "未找到匹配员工",
"removeTarget": "移除",
"targetConfirm": "确认添加",
"noVideoResources": "请先在培训资料中保存至少一个视频资源",
"summaryRule": "员工需完成指定视频观看并提交不少于 {count} 字的学习感悟",
"pushNow": "立即新增任务补推",
"pushing": "推送中…",
"weekRangeLabel": "第{index}周 {range}",
"videoPagePrev": "上一页",
"videoPageNext": "下一页",
"videoPageInfo": "第 {page} / {total} 页",
"pushCompleted": "全部视频已推送完毕",
"pushSuccess": "已推送 {count} 个视频并通知受训员工",
"pushFailed": "视频推送失败,请稍后重试",
"pushLogsTitle": "推送记录",
"pushLogsEmpty": "暂无推送记录",
"pushProgress": "已推送 {pushed}/{total} 个视频",
"pushBatch": "推送 {count} 个视频 · 发送 {sent} · 失败 {failed} · 接收 {recipients} 人",
"pushStatus": {
"sent": "全部成功",
"partial": "部分失败",
"failed": "推送失败",
"completed": "已全部推送"
},
"pushTrigger": {
"publish": "发布推送",
"schedule": "每周排程",
"manual": "手动推送"
},
"saveTask": "发布周任务",
"publishRequired": "请先保存并发布精益管理培训配置,再创建周任务",
"unnamedVideo": "未命名视频"
},
"messages": {
"loadFailed": "加载培训配置失败",
"saveFailed": "保存培训配置失败",
@@ -5051,7 +5120,13 @@
"parseSuccess": "已解析 {count} 道题目,请复核后保存",
"parseFailed": "题库解析失败",
"saved": "培训配置已保存",
"deleted": "培训配置已删除"
"deleted": "培训配置已删除",
"leanVideoCount": "请至少选择一个培训视频",
"leanTaskSaved": "精益周任务已发布",
"videoFileRequired": "请选择视频文件",
"trainingAgentRequired": "未找到员工培训 Agent,无法创建视频资源",
"videoUploaded": "培训视频已上传并加入配置资源",
"videoUploadFailed": "培训视频上传失败"
}
},
"integrationConnector": {
+74
View File
@@ -1048,11 +1048,81 @@
"description": "管理员尚未发布当前培训配置,请稍后再试。"
},
"unknownDepartment": "待补充部门",
"lean": {
"learner": {
"title": "精益管理周度培训",
"taskTitle": "第 {index} 期",
"description": "本期需完成 {count} 个指定视频,并提交不少于 {minSummaryLength} 字的学习感悟。",
"taskPeriod": "任务周期:{start} 至 {end}",
"completedSummary": "学习感悟",
"completedAt": "完成时间:{time}",
"empty": "暂无精益培训任务"
},
"taskStatus": {
"in_progress": "进行中",
"overdue": "已延期",
"completed": "已完成"
},
"videoUnavailable": "该视频暂无可播放地址",
"dueAt": "截止 {time}",
"watchedAt": "已观看:{time}",
"markVideoWatched": "点击记录观看完成",
"videoWatchedToast": "视频观看完成",
"videoWatchedBadge": "已完成",
"completeVideosFirst": "请先完整观看本期全部任务视频,再提交学习感悟",
"summaryTooShort": "学习感悟不少于 {minSummaryLength} 字,请继续补充",
"summaryPlaceholder": "请填写本周学习感悟(不少于 {minSummaryLength} 字)",
"summaryLength": "{current}/{minSummaryLength} 字",
"submitSummary": "提交学习感悟",
"dashboard": {
"title": "精益培训完成名单",
"week": "培训周次:{week}",
"completed": "已完成名单",
"incomplete": "未完成名单",
"count": "共 {count} 人",
"empty": "暂无人员数据",
"passRate": "完成率",
"periodLabel": "第 {index} 期"
},
"columns": {
"employeeId": "工号",
"name": "姓名",
"department": "部门",
"team": "班组",
"jobTitle": "职务",
"videoName": "视频名称",
"watchedAt": "观看时间",
"status": "状态",
"summary": "总结",
"action": "操作"
},
"status": {
"completed": "已完成",
"in_progress": "进行中",
"overdue": "已延期",
"incomplete": "未完成"
},
"reminder": {
"action": "提醒",
"sending": "发送中...",
"success": "已发送提醒({count} 人)",
"partial": "已发送提醒({sent} 人),{failed} 人发送失败,请在管理端企微通知审计中查看原因",
"sendFailed": "提醒发送失败({count} 人),请检查企业微信通知配置,或在管理端企微通知审计中查看原因",
"notSent": "未发送提醒:对方可能已完成培训或未绑定企业微信",
"failed": "提醒发送失败,请稍后重试"
},
"summaryModal": {
"title": "总结详情",
"viewHint": "点击查看全部总结",
"close": "关闭"
}
},
"video": {
"title": "第一步:观看培训视频",
"description": "员工先完成入职培训视频学习,再进入知识点复盘和考试环节。",
"completeAction": "我已完成视频学习",
"playerTitle": "视频播放位",
"empty": "暂未配置可播放的培训视频",
"playerHint": "这里可接入企业视频链接或内部播放器。当前前端已预留完整容器与学习完成按钮。"
},
"summary": {
@@ -1181,6 +1251,10 @@
}
},
"hr": {
"tabs": {
"allTraining": "全部培训",
"leanManagement": "精益管理"
},
"stats": {
"total": "参训人数",
"passed": "已通过",
+1
View File
@@ -129,6 +129,7 @@
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "平级服务登录声明签发失败,请重试。",
"AUTH_FORBIDDEN": "你没有权限执行该操作。",
"CONTRACT_PAYMENT_FORBIDDEN": "你没有合同付款预警的访问权限。",
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "仅管理员可执行合同付款预警的同步、扫描或发送操作。",
"SHIPPING_TASK_SELECTION_INVALID": "请选择 1 到 100 个发货任务。",
"SHIPPING_TASK_DELETE_REASON_REQUIRED": "删除或作废任务必须填写原因。",
"SHIPPING_TASK_EXTERNAL_VOID_BLOCKED": "任务正在外部上传或已上传,只能归档,不能作废或删除。",
+1 -1
View File
@@ -284,7 +284,7 @@
"loading": "正在加载源文件信息...",
"empty": "暂无源文件信息,上传版本后会显示在这里。",
"currentVersion": "当前版本",
"opening": "正在打开...",
"opening": "正在下载...",
"fileName": "文件名:{name}",
"fileSize": "大小:{size}",
"fileType": "类型:{ext}"
+78 -4
View File
@@ -1191,12 +1191,17 @@
"username": "用戶名",
"email": "郵箱",
"department": "部門",
"team": "班組",
"jobTitle": "職務",
"isTeamLeader": "班組長",
"role": "角色",
"featurePermissions": "功能權限",
"trainingHrManage": "培訓 HR 管理",
"trainingHrManageHint": "勾選後可進入員工培訓 Agent 的【HR 管理】視圖,查看統計、篩選記錄並匯出 Excel。",
"trainingLeanManage": "精益培訓全量管理",
"trainingLeanTeamManage": "精益培訓班組管理",
"contractPaymentAccess": "合約付款預警存取",
"contractPaymentAccessHint": "勾選後可進入工作臺合約付款預警(臺帳、待確認、週彙總),並觸發同步與掃描。",
"contractPaymentAccessHint": "勾選後可進入工作臺合約付款預警(臺帳、待確認、週彙總)。同步 OA、掃描預警與發送預警僅管理員可用。",
"password": "密碼",
"passwordHint": "(留空表示不修改)",
"noAgents": "暫無可用應用"
@@ -4632,7 +4637,7 @@
}
},
"contractPayment": {
"title": "合約付款預警", "subtitle": "同步 OA 合約、驗收和廠商預付款請款作業,按三輪規則通知採購職位", "sync": "同步 OA 資料", "forceSync": "強制覆蓋 OA 欄位", "forceSyncConfirm": "將以本次 OA 回傳的非空欄位覆蓋既有 OA 資料,並記錄變更稽核。是否繼續?", "reparseExisting": "批量重新解析既有合約", "reparseExistingConfirm": "將使用已歸檔的合約附件依目前規則更新所有既有合約的解析結果,不會同步或覆蓋 OA 欄位。是否繼續?", "scanAlerts": "掃描產生預警", "jobSubmitted": "工作已提交", "actionFailed": "操作失敗", "loadFailed": "載入合約失敗", "searchPlaceholder": "搜尋合約編號或採購單號", "allStatus": "全部", "search": "查詢", "ledger": "合約台帳", "items": "筆", "empty": "暫無合約資料", "purchaseOrder": "採購單號", "supplier": "供應商", "amount": "合約金額", "deliveryDate": "交貨期限", "timeline": "付款計畫時間線", "notAvailable": "—", "stats": {"contracts": "合約總數", "pendingParse": "待處理合約", "readyPlans": "計畫已產生", "alerts": "待預警節點"}, "status": {"completed": "已完成", "needs_review": "待覆核", "pending": "待解析"}, "stateLabel": {"parsed": "已解析", "needs_review": "待複核", "pending": "待解析", "active": "已生效"}, "nodeType": {"prepayment": "預付款", "shipment": "出貨款", "acceptance": "驗收款", "warranty": "質保款"}, "ruleConfirmed": "已確定", "prepaymentRule": "合約歸檔後第 7/14/21 天預警;請款以 OA 廠商預付款請款作業為準。", "shipmentRule": "交貨期限前 7 天、到期日、到期後 14 天預警;請款以 OA 廠商預付款請款作業為準。", "acceptanceRule": "驗收歸檔後第 30/40/60 天預警;質保款在質保到期前 7 天、到期日、到期後 14 天預警。", "pendingAlerts": "待處理預警", "processing": "已發起付款", "dataPending": "資料待確認", "paid": "已付款", "amountRatioDate": "金額 / 比例 · 日期", "applicant": "申請人", "statusLabel": "狀態", "contractPrefix": "合約", "datePending": "待補充日期", "statusNormal": "正常", "statusNeedsCompletion": "待補充", "statusOverdue": "已逾期", "statusUpcoming": "即將到期", "statusActive": "進行中", "statusCompleted": "已完成", "totalPrefix": "共", "contractSupplier": "合約號 / 供應商", "nextAlert": "下一預警", "triggerBasis": "觸發依據", "alertDate": "預警日期", "alertFirstRound": "首輪", "payDate": "付款日期", "processStatus": "處理狀態", "owner": "採購負責人", "oaData": "OA 資料", "contractRule": "合約規則", "ownerDefault": "採購負責人", "workflowNo": "流程編號", "contractNoPending": "合約號待從附件解析", "synced": "已同步", "detailSubtitle": "OA 資料、付款節點與企業微信提醒記錄", "backToOverview": "返回總覽", "contractInfo": "OA 合約資訊", "alertHistory": "預警記錄", "alertRound": "第 {round} 次預警", "alertAudit": "預警發送記錄", "alertAuditEmpty": "暫無預警記錄", "alertNode": "付款節點", "alertScheduledAt": "計畫日期", "alertSentAt": "發送時間", "alertStatus": {"pending": "待發送", "sent": "已發送", "failed": "發送失敗"}, "roundValue": "第 {round} 次", "weeklyBatchesTitle": "週彙總批次", "weeklyBatchesSubtitle": "查看依收件人產生的付款預警週彙總、Excel 附件與發送記錄。", "refresh": "重新整理", "weeklySend": "傳送預警", "weeklyBatchSubmitted": "發送預警任務已提交", "weeklyBatchesLoadFailed": "載入週彙總批次失敗", "batchNo": "批次號", "weekKey": "週次", "batchStatusLabel": "發送狀態", "batchTotal": "彙總筆數", "batchExcel": "Excel 附件", "batchSentAt": "發送時間", "weeklyBatchesEmpty": "暫無週彙總批次", "weeklyPendingSummary": "本週待發送 {count} 筆 · 下次發送 {datetime}", "weeklyPendingCountOnly": "本週待發送 {count} 筆", "downloadExcel": "下載 Excel", "excelDownloadFailed": "下載預警附件失敗", "batchStatus": {"pending": "待發送", "sent": "已發送", "failed": "發送失敗", "processing": "處理中", "resolved": "已停止提醒"}, "backToLedger": "返回", "detailLoadFailed": "載入合約詳情失敗", "detailLoading": "正在載入合約詳情…", "detailOverview": "合約概覽", "detailAttachments": "原文附件", "detailPaymentPlan": "付款計畫", "detailAlertHistory": "預警記錄", "archiveDate": "合約歸檔日期", "archiveDateHint": "該日期為合約申請單的歸檔日期", "parseStatus": "解析狀態", "parseIssueTitle": "解析提示", "planStatus": "計畫狀態", "attachmentsEmpty": "暫無已歸檔的合約原文附件", "downloadAttachment": "下載附件", "attachmentDownloadFailed": "下載合約附件失敗", "paymentPlanEmpty": "暫無可展示的付款計畫", "anchorDate": "日期依據", "nodeStatus": {"pending":Line truncated
"title": "合約付款預警", "subtitle": "同步 OA 合約、驗收和廠商預付款請款作業,按三輪規則通知採購職位", "sync": "同步 OA 資料", "forceSync": "強制覆蓋 OA 欄位", "forceSyncConfirm": "將以本次 OA 回傳的非空欄位覆蓋既有 OA 資料,並記錄變更稽核。是否繼續?", "reparseExisting": "批量重新解析既有合約", "reparseExistingConfirm": "將使用已歸檔的合約附件依目前規則更新所有既有合約的解析結果,不會同步或覆蓋 OA 欄位。是否繼續?", "scanAlerts": "掃描產生預警", "jobSubmitted": "工作已提交", "actionFailed": "操作失敗", "loadFailed": "載入合約失敗", "searchPlaceholder": "搜尋合約編號、採購單號或供應商", "allStatus": "全部", "search": "查詢", "ledger": "合約台帳", "items": "筆", "empty": "暫無合約資料", "purchaseOrder": "採購單號", "supplier": "供應商", "amount": "合約金額", "deliveryDate": "交貨期限", "timeline": "付款計畫時間線", "notAvailable": "—", "stats": {"contracts": "合約總數", "pendingParse": "待處理合約", "readyPlans": "計畫已產生", "alerts": "待預警節點"}, "ledgerFocus": {"due": "即將到期", "dueHint": "7日內", "overdue": "逾期未付", "needsCompletion": "待補充", "dueThisMonth": "本月應付", "dueThisMonthHint": "本自然月"}, "status": {"completed": "已完成", "needs_review": "待覆核", "pending": "待解析"}, "stateLabel": {"parsed": "已解析", "needs_review": "待複核", "pending": "待解析", "active": "已生效"}, "nodeType": {"prepayment": "預付款", "shipment": "出貨款", "acceptance": "驗收款", "warranty": "質保款"}, "ruleConfirmed": "已確定", "prepaymentRule": "合約歸檔後第 7/14/21 天預警;請款以 OA 廠商預付款請款作業為準。", "shipmentRule": "交貨期限前 7 天、到期日、到期後 14 天預警;請款以 OA 廠商預付款請款作業為準。", "acceptanceRule": "驗收歸檔後第 30/40/60 天預警;質保款在質保到期前 7 天、到期日、到期後 14 天預警。", "pendingAlerts": "待處理預警", "processing": "已發起付款", "dataPending": "資料待確認", "paid": "已付款", "amountRatioDate": "金額 / 比例 · 日期", "applicant": "申請人", "statusLabel": "狀態", "contractPrefix": "合約", "datePending": "待補充日期", "statusNormal": "正常", "statusNeedsCompletion": "待補充", "statusOverdue": "已逾期", "statusUpcoming": "即將到期", "statusActive": "進行中", "statusCompleted": "已完成", "totalPrefix": "共", "contractSupplier": "合約號 / 供應商", "nextAlert": "下一預警", "triggerBasis": "觸發依據", "alertDate": "預警日期", "alertFirstRound": "首輪", "payDate": "付款日期", "processStatus": "處理狀態", "owner": "採購負責人", "oaData": "OA 資料", "contractRule": "合約規則", "ownerDefault": "採購負責人", "workflowNo": "流程編號", "contractNoPending": "合約號待從附件解析", "synced": "已同步", "detailSubtitle": "OA 資料、付款節點與企業微信提醒記錄", "backToOverview": "返回總覽", "contractInfo": "OA 合約資訊", "alertHistory": "預警記錄", "alertRound": "第 {round} 次預警", "alertAudit": "預警發送記錄", "alertAuditEmpty": "暫無預警記錄", "alertNode": "付款節點", "alertScheduledAt": "計畫日期", "alertSentAt": "發送時間", "alertStatus": {"pending": "待發送", "sent": "已發送", "failed": "發送失敗"}, "roundValue": "第 {round} 次", "weeklyBatchesTitle": "週彙總批次", "weeklyBatchesSubtitle": "查看依收件人產生的付款預警週彙總、Excel 附件與發送記錄。", "weeklySend": "傳送預警", "weeklyBatchSubmitted": "發送預警任務已提交", "weeklyBatchesLoadFailed": "載入週彙總批次失敗", "batchNo": "批次號", "weekKey": "週次", "batchStatusLabel": "發送狀態", "batchTotal": "彙總筆數", "batchExcel": "Excel 附件", "batchSentAt": "發送時間", "weeklyBatchesEmpty": "暫無週彙總批次", "weeklyPendingSummary": "本週待發送 {count} 筆 · 下次發送 {datetime}", "weeklyPendingCountOnly": "本週待發送 {count} 筆", "downloadExcel": "下載 Excel", "excelDownloadFailed": "下載預警附件失敗", "batchStatus": {"pending": "待發送", "sent": "已發送", "failed": "發送失敗", "processing": "處理中", "resolved": "已停止提醒"}, "backToLedger": "返回", "detailLoadFailed": "載入合約詳情失敗", "detailLoading": "正在載入合約詳情…", "detailOverview": "合約概覽", "detailAttachments": "原文附件", "detailPaymentPlan": "付款計畫", "detailAlertHistory": "預警記錄", "archiveDate": "合約歸檔日期", "archiveDateHint": "該日期為合約申請單的歸檔日期", "parseStatus": "解析狀態", "parseIssueTitle": "解析提示", "planStatus": "計畫狀態", "attachmentsEmpty": "暫無已歸檔的合約原文附件", "downloadAttachment": "下載Line truncated
},
"contractPaymentReview": {"title": "待確認合約", "subtitle": "未符合設備採購合約同義標題組、付款比例驗證失敗或關鍵欄位衝突的合約,不會進入付款預警,請下載原文核對。", "searchPlaceholder": "合約編號、採購單號或供應商", "loadFailed": "待確認合約載入失敗", "contractWorkflow": "合約號 / 流程編號", "reason": "待確認原因", "fallbackIssue": "解析結果待人工確認", "empty": "暫無待確認合約"},
"contractPaymentReparse": {"action": "重新解析合約原文", "success": "已使用附件“{attachment}”重新解析", "failed": "重新解析合約失敗"},
@@ -4831,7 +4836,9 @@
"examTitle": "考試題庫",
"examDesc": "維護受控考試使用的結構化題目資料",
"reviewTitle": "複盤與清單",
"reviewDesc": "配置培訓完成後的複盤重點、考前清單與聊天引導問題"
"reviewDesc": "配置培訓完成後的複盤重點、考前清單與聊天引導問題",
"leanTitle": "精益每週任務",
"leanDesc": "為指定自然週選擇影片清單、設定每週推送數量並配置週截止時間"
},
"guideGroups": {
"company": "公司級安全培訓",
@@ -4858,6 +4865,7 @@
"progressItemLabel": "進度項名稱",
"progressHintText": "培訓進度說明",
"stepIntroText": "培訓步驟引導文案",
"requiredDuration": "所需時間(分鐘)",
"summaryPoints": "複盤要點",
"summaryChecklist": "考前清單",
"employeeQuestions": "員工常見問題",
@@ -4886,6 +4894,66 @@
"guide": "指南資源",
"document": "知識庫文件"
},
"directVideo": {
"title": "培訓影片",
"hint": "可直接上傳影片;上傳後會自動加入目前培訓配置資源。",
"upload": "上傳影片",
"uploading": "上傳中...",
"empty": "尚未上傳培訓影片",
"unnamed": "未命名影片"
},
"lean": {
"weekKey": "任務週(週一)",
"dueAt": "截止時間",
"weekMustBeMonday": "任務週必須選擇週一",
"weeklyCount": "每週任務數量",
"weeklyCountHint": "每週一 09:00 按該數量從影片清單順序推送下一批(已推送 {pushed}/{total}),受訓員工發布後立即可學",
"videosTitle": "指定培訓影片",
"videosHint": "已選擇 {count} 部影片(按選擇順序每週分批推送)",
"targetsTitle": "受訓對象",
"targetsHint": "依角色或指定使用者選擇,兩個範圍取聯集",
"targetRoles": "指定角色",
"targetUsers": "指定使用者",
"addTarget": "新增受訓",
"targetEmpty": "尚未選擇受訓對象,請點擊「新增受訓」按角色或員工配置",
"targetModalTitle": "新增受訓對象",
"targetSearchPlaceholder": "搜尋姓名 / 使用者名稱 / 部門",
"targetSelectedCount": "已選 {roles} 個角色 · {users} 位員工",
"targetUsersCount": "指定使用者({count})",
"targetRolesEmpty": "暫無可選角色",
"targetUsersEmpty": "未找到符合的員工",
"removeTarget": "移除",
"targetConfirm": "確認新增",
"noVideoResources": "請先在培訓資料中儲存至少一部影片資源",
"summaryRule": "員工須完成指定影片觀看並提交不少於 {count} 字的學習感悟",
"pushNow": "立即新增任務補推",
"pushing": "推送中…",
"weekRangeLabel": "第{index}週 {range}",
"videoPagePrev": "上一頁",
"videoPageNext": "下一頁",
"videoPageInfo": "第 {page} / {total} 頁",
"pushCompleted": "全部影片已推送完畢",
"pushSuccess": "已推送 {count} 部影片並通知受訓員工",
"pushFailed": "影片推送失敗,請稍後重試",
"pushLogsTitle": "推送記錄",
"pushLogsEmpty": "暫無推送記錄",
"pushProgress": "已推送 {pushed}/{total} 部影片",
"pushBatch": "推送 {count} 部影片 · 發送 {sent} · 失敗 {failed} · 接收 {recipients} 人",
"pushStatus": {
"sent": "全部成功",
"partial": "部分失敗",
"failed": "推送失敗",
"completed": "已全部推送"
},
"pushTrigger": {
"publish": "發布推送",
"schedule": "每週排程",
"manual": "手動推送"
},
"saveTask": "發佈每週任務",
"publishRequired": "請先儲存並發佈精益管理培訓配置,再建立每週任務",
"unnamedVideo": "未命名影片"
},
"messages": {
"loadFailed": "載入培訓配置失敗",
"saveFailed": "儲存培訓配置失敗",
@@ -4900,7 +4968,13 @@
"parseSuccess": "已解析 {count} 道題目,請複核後儲存",
"parseFailed": "題庫解析失敗",
"saved": "培訓配置已儲存",
"deleted": "培訓配置已刪除"
"deleted": "培訓配置已刪除",
"leanVideoCount": "請至少選擇一部培訓影片",
"leanTaskSaved": "精益每週任務已發佈",
"videoFileRequired": "請選擇影片檔案",
"trainingAgentRequired": "未找到員工培訓 Agent,無法建立影片資源",
"videoUploaded": "培訓影片已上傳並加入配置資源",
"videoUploadFailed": "培訓影片上傳失敗"
}
},
"integrationConnector": {
+74
View File
@@ -1014,11 +1014,81 @@
"description": "管理員尚未發布當前培訓配置,請稍後再試。"
},
"unknownDepartment": "待補充部門",
"lean": {
"learner": {
"title": "精益管理週度培訓",
"taskTitle": "第 {index} 期",
"description": "本期需完成 {count} 個指定影片,並提交不少於 {minSummaryLength} 字的學習心得。",
"taskPeriod": "任務週期:{start} 至 {end}",
"completedSummary": "學習心得",
"completedAt": "完成時間:{time}",
"empty": "暫無精益培訓任務"
},
"taskStatus": {
"in_progress": "進行中",
"overdue": "已延期",
"completed": "已完成"
},
"videoUnavailable": "該影片暫無可播放地址",
"dueAt": "截止 {time}",
"watchedAt": "已觀看:{time}",
"markVideoWatched": "點擊記錄完成觀看",
"videoWatchedToast": "影片觀看完成",
"videoWatchedBadge": "已完成",
"completeVideosFirst": "請先完整觀看本期全部任務影片,再提交學習心得",
"summaryTooShort": "學習心得不少於 {minSummaryLength} 字,請繼續補充",
"summaryPlaceholder": "請填寫本週學習心得(不少於 {minSummaryLength} 字)",
"summaryLength": "{current}/{minSummaryLength} 字",
"submitSummary": "提交學習心得",
"dashboard": {
"title": "精益培訓完成名單",
"week": "培訓週次:{week}",
"completed": "已完成名單",
"incomplete": "未完成名單",
"count": "共 {count} 人",
"empty": "暫無人員資料",
"passRate": "完成率",
"periodLabel": "第 {index} 期"
},
"columns": {
"employeeId": "工號",
"name": "姓名",
"department": "部門",
"team": "班組",
"jobTitle": "職務",
"videoName": "影片名稱",
"watchedAt": "觀看時間",
"status": "狀態",
"summary": "總結",
"action": "操作"
},
"status": {
"completed": "已完成",
"in_progress": "進行中",
"overdue": "已延期",
"incomplete": "未完成"
},
"reminder": {
"action": "提醒",
"sending": "發送中...",
"success": "已發送提醒({count} 人)",
"partial": "已發送提醒({sent} 人),{failed} 人發送失敗,請在管理端企微通知審計中查看原因",
"sendFailed": "提醒發送失敗({count} 人),請檢查企業微信通知配置,或在管理端企微通知審計中查看原因",
"notSent": "未發送提醒:對方可能已完成培訓或未綁定企業微信",
"failed": "提醒發送失敗,請稍後重試"
},
"summaryModal": {
"title": "總結詳情",
"viewHint": "點擊查看全部總結",
"close": "關閉"
}
},
"video": {
"title": "第一步:觀看培訓影片",
"description": "員工先完成入職培訓影片學習,再進入知識點複盤與考試環節。",
"completeAction": "我已完成影片學習",
"playerTitle": "影片播放區",
"empty": "尚未配置可播放的培訓影片",
"playerHint": "此處可接入企業影片連結或內部播放器。當前前端已預留完整容器與完成按鈕。"
},
"summary": {
@@ -1078,6 +1148,10 @@
"rule4": "HR 管理端可在同一聊天頁查看統計並匯出 Excel。"
},
"hr": {
"tabs": {
"allTraining": "全部培訓",
"leanManagement": "精益管理"
},
"stats": {
"total": "參訓人數",
"passed": "已通過",
+1
View File
@@ -129,6 +129,7 @@
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "平級服務登入聲明簽發失敗,請重試。",
"AUTH_FORBIDDEN": "你沒有權限執行此操作。",
"CONTRACT_PAYMENT_FORBIDDEN": "你沒有合約付款預警的存取權限。",
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "僅管理員可執行合約付款預警的同步、掃描或發送操作。",
"SHIPPING_TASK_SELECTION_INVALID": "請選擇 1 到 100 個發貨任務。",
"SHIPPING_TASK_DELETE_REASON_REQUIRED": "刪除或作廢任務必須填寫原因。",
"SHIPPING_TASK_EXTERNAL_VOID_BLOCKED": "任務正在外部上傳或已上傳,只能歸檔,不能作廢或刪除。",
+1 -1
View File
@@ -284,7 +284,7 @@
"loading": "正在載入源文件信息...",
"empty": "暫無源文件信息,上傳版本後會顯示在這裡。",
"currentVersion": "當前版本",
"opening": "正在打開...",
"opening": "正在下載...",
"fileName": "文件名:{name}",
"fileSize": "大小:{size}",
"fileType": "類型:{ext}"
+3 -3
View File
@@ -1,9 +1,11 @@
/**
* shared/api/client.ts
* 跨域 HTTP 客户端:envelope 解析、BusinessError、requestJson、requestBlob。
* 依赖:auth、vue-i18n、shared/utils/download(Content-Disposition 文件名)。
* 所有 feature API 层应通过此模块发起请求;二进制下载走 requestBlob,失败仍为 BusinessError。
*/
import { getAuthHeaders } from '@/shared/utils/auth';
import { parseContentDispositionFilename } from '@/shared/utils/download';
import i18n from '@/i18n';
export interface ApiSuccessEnvelope<T> {
@@ -217,11 +219,9 @@ export async function requestBlob(url: string, init?: RequestInit): Promise<Blob
}
const blob = await res.blob();
const disposition = res.headers.get('Content-Disposition') || '';
const filename = disposition.match(/filename\*?=(?:UTF-8''|")?([^";]+)"?/i)?.[1];
return {
blob,
filename: filename ? decodeURIComponent(filename) : undefined,
filename: parseContentDispositionFilename(res.headers.get('Content-Disposition')),
requestId: requestIdHeader,
};
}
@@ -0,0 +1,73 @@
/**
* shared/utils/download.test.ts
* 用途:校验 Content-Disposition 解析与单次 blob 下载不会拼出怪名。
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
parseContentDispositionFilename,
sanitizeDownloadFilename,
triggerBlobDownload,
} from './download';
describe('parseContentDispositionFilename', () => {
it('prefers RFC 5987 filename* over ASCII fallback', () => {
// 断言:Werkzeug/Flask 中文名会留下 ASCII 回退段,必须取 filename*。
const encoded = encodeURIComponent('企业文化.docx');
const disposition = `attachment; filename="download.docx"; filename*=UTF-8''${encoded}`;
expect(parseContentDispositionFilename(disposition)).toBe('企业文化.docx');
});
it('does not concatenate unquoted ASCII fallback with filename*', () => {
// 断言:旧实现会得到 `docx; filename_=UTF-8''企业文化.docx`。
const encoded = encodeURIComponent('企业文化.docx');
const disposition = `inline; filename=docx; filename*=UTF-8''${encoded}`;
expect(parseContentDispositionFilename(disposition)).toBe('企业文化.docx');
});
it('reads quoted filename when filename* is absent', () => {
expect(parseContentDispositionFilename('attachment; filename="report.pdf"')).toBe('report.pdf');
});
it('returns undefined for empty header', () => {
expect(parseContentDispositionFilename('')).toBeUndefined();
expect(parseContentDispositionFilename(null)).toBeUndefined();
});
});
describe('sanitizeDownloadFilename', () => {
it('keeps only the last path segment', () => {
expect(sanitizeDownloadFilename('dir/企业文化.docx')).toBe('企业文化.docx');
});
});
describe('triggerBlobDownload', () => {
afterEach(() => {
vi.unstubAllGlobals();
document.body.innerHTML = '';
});
it('clicks a single anchor with the original filename', () => {
// 断言:一次下载只产生一个 a[download],文件名与源文件一致。
const clicks: string[] = [];
const createObjectURL = vi.fn(() => 'blob:http://localhost/fake');
const revokeObjectURL = vi.fn();
vi.stubGlobal('URL', { createObjectURL, revokeObjectURL });
const originalCreateElement = document.createElement.bind(document);
vi.spyOn(document, 'createElement').mockImplementation((tagName: string) => {
const el = originalCreateElement(tagName);
if (tagName === 'a') {
vi.spyOn(el, 'click').mockImplementation(() => {
clicks.push(el.download);
});
}
return el;
});
triggerBlobDownload(new Blob(['hello']), '企业文化.docx');
expect(createObjectURL).toHaveBeenCalledTimes(1);
expect(clicks).toEqual(['企业文化.docx']);
expect(document.body.querySelectorAll('a')).toHaveLength(0);
});
});
+67
View File
@@ -0,0 +1,67 @@
/**
* shared/utils/download.ts
* 用途:浏览器受控下载的文件名解析与单次触发,避免 blob URL 被 window.open 再下一份。
* 依赖:无业务模块;仅使用 DOM URL / a[download]。
* 逻辑:requestBlob、知识库源文件等调用;Content-Disposition 优先 RFC 5987 filename*。
*/
/**
* 去掉路径与非法换行,得到可写入 a[download] 的纯文件名。
* 核心逻辑:只保留最后一段路径分量,避免把目录或响应头片段写进保存名。
* @param filename - 原始或解析得到的文件名
* @param fallback - 清洗后为空时的回退名
* @returns 可安全用作下载名的字符串
*/
export function sanitizeDownloadFilename(filename: string, fallback = 'download'): string {
const name = String(filename || '').replace(/\\/g, '/').split('/').pop()?.trim() || '';
const cleaned = name.replace(/[\r\n"]/g, '');
return cleaned || fallback;
}
/**
* 从 Content-Disposition 解析下载文件名,优先 RFC 5987 的 filename*。
* 核心逻辑:先取 filename*=UTF-8'',再取带引号或到分号为止的 filename=。
* 不能用贪婪的 filename="?([^"]+)"?,否则会把 `filename=docx; filename*=UTF-8''原名.docx` 整段当成文件名。
* @param disposition - 响应头原文
* @returns 解码后的文件名;无法解析时返回 undefined
*/
export function parseContentDispositionFilename(
disposition: string | null | undefined,
): string | undefined {
const value = String(disposition || '');
if (!value) return undefined;
const utf8Match = value.match(/filename\*\s*=\s*UTF-8''([^;]+)/i);
const quotedMatch = value.match(/filename\s*=\s*"([^"]+)"/i);
const unquotedMatch = value.match(/filename\s*=\s*([^;]+)/i);
const raw = (utf8Match?.[1] || quotedMatch?.[1] || unquotedMatch?.[1] || '').trim();
if (!raw) return undefined;
let decoded = raw;
try {
decoded = decodeURIComponent(raw);
} catch {
decoded = raw;
}
const name = sanitizeDownloadFilename(decoded, '');
return name || undefined;
}
/**
* 用 blob 触发一次浏览器下载,保存名使用给定文件名。
* 核心逻辑:只创建一条 a[download] 并 click;禁止 window.open blob URL,
* 因为 docx 等无法预览的类型会再下一份 UUID 名文件,且 noopener 使 open 返回 null 导致双下载。
* @param blob - 文件内容
* @param filename - 保存文件名,应与源文件名一致
*/
export function triggerBlobDownload(blob: Blob, filename: string): void {
const objectUrl = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = objectUrl;
link.download = sanitizeDownloadFilename(filename);
link.rel = 'noopener';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
}