From 3da29f2d9ffd10c4b1619908dfb014a91581de79 Mon Sep 17 00:00:00 2001 From: "David.Chen" Date: Fri, 13 Nov 2026 10:06:48 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=8F=91=E8=B5=B7=E5=8F=98=E6=9B=B4?= =?UTF-8?q?=E9=A1=B5=20AI=20=E6=8E=A5=E5=8F=A3=E5=85=A8=E9=87=8F=E6=8E=A5?= =?UTF-8?q?=E5=85=A5(T02~T10)=E2=80=94=E2=80=94=E9=A2=84=E8=AF=86=E5=88=AB?= =?UTF-8?q?=E6=99=BA=E8=83=BD=E9=A3=8E=E9=99=A9=E5=88=86=E6=9E=90=E5=BC=82?= =?UTF-8?q?=E6=AD=A5=E4=BB=BB=E5=8A=A1=E5=9B=9B=E6=AE=B5=E5=B1=95=E7=A4=BA?= =?UTF-8?q?(DeepAnalysisPanel)+precheck.deep=5Fanalysis=EF=BC=9B=E9=A3=8E?= =?UTF-8?q?=E9=99=A9=E9=A1=B5=20aiOrganize/preInfo=20=E4=B8=8B=E5=8F=91/ge?= =?UTF-8?q?nerateRiskCheck=20=E5=90=8E=E5=8F=B0=E7=BC=96=E6=8E=92(?= =?UTF-8?q?=E4=B8=8D=E5=BC=B9=E6=8A=BD=E5=B1=89)=EF=BC=9BriskPre/hazop/fme?= =?UTF-8?q?a/riskCheck=20=E5=9B=9B=E6=8F=92=E4=BB=B6=E7=A9=BA=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=E4=B8=8E=E6=A8=A1=E6=8B=9F=20loading=20=E5=85=A8?= =?UTF-8?q?=E9=83=A8=E6=9B=BF=E6=8D=A2=E4=B8=BA=E7=9C=9F=E5=AE=9E=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3(hazop=20=E8=8A=82=E7=82=B9/=E5=81=8F=E7=A6=BB?= =?UTF-8?q?=E6=8E=A8=E6=BC=94=E3=80=81fmea=20=E6=AD=A5=E9=AA=A4/=E5=A4=B1?= =?UTF-8?q?=E6=95=88=E6=A8=A1=E5=BC=8F=E6=8E=A8=E6=BC=94=E3=80=81=E5=85=A8?= =?UTF-8?q?=E9=83=A8=E5=81=8F=E7=A6=BB/=E5=A4=B1=E6=95=88=E6=A8=A1?= =?UTF-8?q?=E5=BC=8F=E9=A1=BA=E5=BA=8F=E7=94=9F=E6=88=90)=EF=BC=9B?= =?UTF-8?q?=E5=9F=B9=E8=AE=AD/PSSR=20=E4=BC=A0=E5=85=A5=E7=9C=9F=E5=AE=9E?= =?UTF-8?q?=E9=A3=8E=E9=99=A9=E8=AE=B0=E5=BD=95+=E8=A1=8C=E5=8A=A8?= =?UTF-8?q?=E9=A1=B9+=E5=9B=BA=E5=AE=9A=E5=9B=9B=E7=BB=84=E6=A8=A1?= =?UTF-8?q?=E6=9D=BF(group=5Ftype=20=E4=BC=98=E5=85=88=E5=8C=B9=E9=85=8D)?= =?UTF-8?q?=EF=BC=9B=E7=AD=89=E7=BA=A7=E8=AF=84=E5=88=86=E6=8C=89=20dim=20?= =?UTF-8?q?=E5=8C=B9=E9=85=8D+=E7=BC=BA=E5=A4=B1=E7=BB=B4=E5=BA=A6?= =?UTF-8?q?=E4=BA=BA=E5=B7=A5=E8=A1=A5=E8=AF=84=E6=8F=90=E7=A4=BA=EF=BC=9B?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E4=BB=85=E7=9C=8B=E6=98=AF=E8=BF=87=E6=BB=A4?= =?UTF-8?q?=E4=B8=A2=E6=95=B0=E6=8D=AE=EF=BC=9Btypecheck=20=E5=9F=BA?= =?UTF-8?q?=E7=BA=BF=E6=8C=81=E5=B9=B3/build=20=E9=80=9A=E8=BF=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/service/api/ai.ts | 156 +++++++++++++- src/typings/components.d.ts | 8 - src/views/my/initiateChange/index.vue | 20 +- .../modules/DeepAnalysisPanel.vue | 182 ++++++++++++++++ .../my/initiateChange/modules/changeApply.vue | 24 ++- .../my/initiateChange/modules/changePre.vue | 114 +++++++--- .../initiateChange/modules/changeTraining.vue | 24 ++- src/views/my/initiateChange/modules/fmea.vue | 181 ++++++++++++++-- src/views/my/initiateChange/modules/hazop.vue | 198 ++++++++++++++++-- src/views/my/initiateChange/modules/pssr.vue | 27 ++- .../initiateChange/modules/riskAnalysis.vue | 177 ++++++++++++++-- .../my/initiateChange/modules/riskCheck.vue | 171 ++++++++------- .../modules/riskCheckTemplate.ts | 77 +++++++ .../my/initiateChange/modules/riskPre.vue | 84 +++++++- 14 files changed, 1262 insertions(+), 181 deletions(-) create mode 100644 src/views/my/initiateChange/modules/DeepAnalysisPanel.vue create mode 100644 src/views/my/initiateChange/modules/riskCheckTemplate.ts diff --git a/src/service/api/ai.ts b/src/service/api/ai.ts index a46f7c7..377fb96 100644 --- a/src/service/api/ai.ts +++ b/src/service/api/ai.ts @@ -323,6 +323,95 @@ export const aiHazopDeviation = (payload: { ...payload }); +/* ---------- HAZOP 节点/偏离建议(无状态推演,仅建议不落库) ---------- */ + +export interface HazopNodeSuggest { + node_name: string; + description: string; +} + +export const aiHazopNodeSuggest = (content: string, changeContext: object = {}) => + aiFetch<{ nodes: HazopNodeSuggest[] }>('/open/v1/moc/hazop/node-suggest', { + request_id: nextRequestId('hazop-node'), + content, + change_context: changeContext + }); + +export interface HazopDeviationSuggestObject { + obj_name: string; + deviations: string[]; +} + +export const aiHazopDeviationSuggest = (payload: { + node_name: string; + process_desc?: string; + operation_desc?: string; + measures_desc?: string; + existing_objects?: { obj_name: string; deviations: string[] }[]; + change_context?: object; +}) => + aiFetch<{ objects: HazopDeviationSuggestObject[]; exclusions: string[] }>('/open/v1/moc/hazop/deviation-suggest', { + request_id: nextRequestId('hazop-dev'), + ...payload + }); + +/* ---------- FMEA 无状态接口(不依赖 ai-server 项目 ID) ---------- */ + +export interface FmeaStepSuggest { + node_name: string; + description: string; +} + +export const aiFmeaProcessSuggest = (content: string, changeContext: object = {}) => + aiFetch<{ steps: FmeaStepSuggest[] }>('/open/v1/moc/fmea/process-suggest', { + request_id: nextRequestId('fmea-proc'), + content, + change_context: changeContext + }); + +export interface FmeaModeSuggest { + deviation: string; + rationale: string; +} + +export const aiFmeaModeSuggest = (payload: { + step_name: string; + step_description?: string; + existing_modes?: string[]; + change_context?: object; +}) => + aiFetch<{ deviations: FmeaModeSuggest[] }>('/open/v1/moc/fmea/mode-suggest', { + request_id: nextRequestId('fmea-mode'), + ...payload + }); + +export interface FmeaAnalyzeRow { + effect: string; + cause: string; + s: number | null; + p: number | null; + d: number | null; + s_basis: string; + p_basis: string; + d_basis: string; + safeguards: string; + suggestions: string; + rationale: string; +} + +export const aiFmeaAnalyze = (payload: { + step_name: string; + step_description?: string; + deviation: string; + existing_rows?: any[]; + change_context?: object; + matrix_payload?: object; +}) => + aiFetch<{ rows: FmeaAnalyzeRow[] }>('/open/v1/moc/fmea/analyze', { + request_id: nextRequestId('fmea-row'), + ...payload + }); + export interface JsaStep { step: string; desc: string; @@ -369,11 +458,18 @@ export const aiTraining = (content: string, rows: CompareRow[], riskRecords?: an risk_records: riskRecords ?? [] }); -export const aiPssr = (payload: { content: string; change_type?: string; risk_records?: any[]; action_items?: any[] }) => - aiFetch<{ groups: { g: string; items: { content: string; phase: string }[] }[] }>('/open/v1/moc/change/pssr', { - request_id: nextRequestId('pssr'), - ...payload - }); +export const aiPssr = (payload: { + content: string; + rows?: CompareRow[]; + change_type?: string; + risk_records?: any[]; + action_items?: any[]; + pssr_template?: object; +}) => + aiFetch<{ groups: { g: string; group_type?: number | null; items: { content: string; phase: string; phase_value?: number }[] }[] }>( + '/open/v1/moc/change/pssr', + { request_id: nextRequestId('pssr'), ...payload } + ); export const aiAcceptance = (payload: { purpose?: string; effect?: string }) => aiFetch<{ rows: { item: string; basis: string; standard: string; method: string; owner_suggest: string }[] }>( @@ -402,6 +498,56 @@ export interface OpenTask { result?: any; } +/* ---------- 深度风险分析(异步任务,四段结果) ---------- */ + +/** 法规合规性分析条目(regulations_data,P-01 契约) */ +export interface RegulationItem { + index: string; + regulation: string; + clause: string; + analysis: string; + suggestion: string; + verified: boolean; +} + +/** 深度分析总结风险表行(risk_table) */ +export interface DeepRiskTableRow { + risk_item: string; + risk_description: string; + inherent_risk_level: string; + existing_measures: string; + suggested_measures: string; + residual_risk_level: string; +} + +/** 深度分析完整结果(任务 result 契约,§5.5) */ +export interface DeepAnalysisResult { + report_risk_identification: string; + report_risk_analysis: string; + regulations_data?: RegulationItem[]; + /** 旧三组结构(laws/national_standards/industry_standards),兼容保留 */ + regulations?: { laws: any[]; national_standards: any[]; industry_standards: any[] }; + summary_text: string; + risk_table: DeepRiskTableRow[]; + conclusion_text: string; + overall_risk_level?: string; + change_grade_suggestion?: string; +} + +/** 提交异步深度风险分析任务(/open/v1/risk/identify,双模鉴权:会员 JWT 直连) */ +export const aiDeepRiskAnalysis = (content: string, rows: CompareRow[], organizationId = 0) => + aiFetch<{ task_id: string; status: string; estimated_seconds: number }>('/open/v1/risk/identify', { + content, + rows, + organization_id: organizationId + }); + +/** 深度分析任务轮询(复用 pollTask,返回 §5.5 结果契约) */ +export const pollDeepAnalysisTask = ( + taskId: string, + opts: { intervalMs?: number; timeoutMs?: number; onProgress?: (t: OpenTask) => void } = {} +): Promise => pollTask(taskId, { intervalMs: 3000, timeoutMs: 600_000, ...opts }); + export const aiApprovalAssist = (payload: { snapshot: object; change_id_ref?: string; diff --git a/src/typings/components.d.ts b/src/typings/components.d.ts index 9630714..cb03329 100644 --- a/src/typings/components.d.ts +++ b/src/typings/components.d.ts @@ -23,7 +23,6 @@ declare module 'vue' { GithubLink: typeof import('./../components/custom/github-link.vue')['default'] IconAntDesignEnterOutlined: typeof import('~icons/ant-design/enter-outlined')['default'] IconAntDesignReloadOutlined: typeof import('~icons/ant-design/reload-outlined')['default'] - 'IconBi:bell': typeof import('~icons/bi/bell')['default'] IconGridiconsFullscreen: typeof import('~icons/gridicons/fullscreen')['default'] IconGridiconsFullscreenExit: typeof import('~icons/gridicons/fullscreen-exit')['default'] IconMdiArrowDownThin: typeof import('~icons/mdi/arrow-down-thin')['default'] @@ -31,7 +30,6 @@ declare module 'vue' { IconMdiKeyboardEsc: typeof import('~icons/mdi/keyboard-esc')['default'] IconMdiKeyboardReturn: typeof import('~icons/mdi/keyboard-return')['default'] IconTooltip: typeof import('./../components/common/icon-tooltip.vue')['default'] - IconUilBell: typeof import('~icons/uil/bell')['default'] IconUilSearch: typeof import('~icons/uil/search')['default'] LangSwitch: typeof import('./../components/common/lang-switch.vue')['default'] LookForward: typeof import('./../components/custom/look-forward.vue')['default'] @@ -63,7 +61,6 @@ declare module 'vue' { NImage: typeof import('naive-ui')['NImage'] NInput: typeof import('naive-ui')['NInput'] NInputGroup: typeof import('naive-ui')['NInputGroup'] - NInputGroupLabel: typeof import('naive-ui')['NInputGroupLabel'] NInputNumber: typeof import('naive-ui')['NInputNumber'] NLoadingBarProvider: typeof import('naive-ui')['NLoadingBarProvider'] NMenu: typeof import('naive-ui')['NMenu'] @@ -73,7 +70,6 @@ declare module 'vue' { NPagination: typeof import('naive-ui')['NPagination'] NPopconfirm: typeof import('naive-ui')['NPopconfirm'] NPopover: typeof import('naive-ui')['NPopover'] - NPopselect: typeof import('naive-ui')['NPopselect'] NProgress: typeof import('naive-ui')['NProgress'] NRadio: typeof import('naive-ui')['NRadio'] NRadioGroup: typeof import('naive-ui')['NRadioGroup'] @@ -121,7 +117,6 @@ declare global { const GithubLink: typeof import('./../components/custom/github-link.vue')['default'] const IconAntDesignEnterOutlined: typeof import('~icons/ant-design/enter-outlined')['default'] const IconAntDesignReloadOutlined: typeof import('~icons/ant-design/reload-outlined')['default'] - const 'IconBi:bell': typeof import('~icons/bi/bell')['default'] const IconGridiconsFullscreen: typeof import('~icons/gridicons/fullscreen')['default'] const IconGridiconsFullscreenExit: typeof import('~icons/gridicons/fullscreen-exit')['default'] const IconMdiArrowDownThin: typeof import('~icons/mdi/arrow-down-thin')['default'] @@ -129,7 +124,6 @@ declare global { const IconMdiKeyboardEsc: typeof import('~icons/mdi/keyboard-esc')['default'] const IconMdiKeyboardReturn: typeof import('~icons/mdi/keyboard-return')['default'] const IconTooltip: typeof import('./../components/common/icon-tooltip.vue')['default'] - const IconUilBell: typeof import('~icons/uil/bell')['default'] const IconUilSearch: typeof import('~icons/uil/search')['default'] const LangSwitch: typeof import('./../components/common/lang-switch.vue')['default'] const LookForward: typeof import('./../components/custom/look-forward.vue')['default'] @@ -161,7 +155,6 @@ declare global { const NImage: typeof import('naive-ui')['NImage'] const NInput: typeof import('naive-ui')['NInput'] const NInputGroup: typeof import('naive-ui')['NInputGroup'] - const NInputGroupLabel: typeof import('naive-ui')['NInputGroupLabel'] const NInputNumber: typeof import('naive-ui')['NInputNumber'] const NLoadingBarProvider: typeof import('naive-ui')['NLoadingBarProvider'] const NMenu: typeof import('naive-ui')['NMenu'] @@ -171,7 +164,6 @@ declare global { const NPagination: typeof import('naive-ui')['NPagination'] const NPopconfirm: typeof import('naive-ui')['NPopconfirm'] const NPopover: typeof import('naive-ui')['NPopover'] - const NPopselect: typeof import('naive-ui')['NPopselect'] const NProgress: typeof import('naive-ui')['NProgress'] const NRadio: typeof import('naive-ui')['NRadio'] const NRadioGroup: typeof import('naive-ui')['NRadioGroup'] diff --git a/src/views/my/initiateChange/index.vue b/src/views/my/initiateChange/index.vue index c259b2c..5221444 100644 --- a/src/views/my/initiateChange/index.vue +++ b/src/views/my/initiateChange/index.vue @@ -470,13 +470,14 @@ onMounted(() => {
- {
- + + + diff --git a/src/views/my/initiateChange/modules/changeApply.vue b/src/views/my/initiateChange/modules/changeApply.vue index 01ac9df..a7a398f 100644 --- a/src/views/my/initiateChange/modules/changeApply.vue +++ b/src/views/my/initiateChange/modules/changeApply.vue @@ -316,12 +316,28 @@ const useAiLevel = async () => { // 重新评分前清零,避免多次点击分数累加 totalScore.value = 0; levelAiBasis.value = []; - res?.dims?.forEach((d, i) => { - totalScore.value += d.score ?? 0; - questions.value[i].score = d.score ?? 0; - levelAiBasis.value[i] = d.basis ?? ""; + // 按 dim 编码精确匹配回填(不依赖返回数组下标);缺失/非法评分不当作有效 0 分 + const byDim = new Map((res?.dims ?? []).map((d: any) => [String(d.dim ?? ''), d])); + const missing: string[] = []; + questions.value.forEach((q: any, i: number) => { + const hit = byDim.get(`DIM_${i + 1}`); + const rawScore = hit?.score; + const numericScore = rawScore !== null && rawScore !== undefined && rawScore !== '' && Number.isFinite(Number(rawScore)) ? Number(rawScore) : null; + const maxScore = Math.max(...q.options.map((o: any) => Number(o.score))); + const score = numericScore !== null && Number.isInteger(numericScore) && numericScore >= 1 && numericScore <= maxScore ? numericScore : null; + levelAiBasis.value[i] = hit?.basis ?? ''; + if (score === null) { + missing.push(q.name ?? `第 ${i + 1} 维`); + q.score = 0; + } else { + q.score = score; + totalScore.value += score; + } }); levelAiText.value = res?.analysis_text ?? ""; + if (missing.length) { + window.$message?.warning(`AI 有 ${missing.length} 个维度未给出有效评分(${missing.join('、')}),请人工补评`); + } } catch (e: any) { aiFail(e); } finally { diff --git a/src/views/my/initiateChange/modules/changePre.vue b/src/views/my/initiateChange/modules/changePre.vue index 419513b..b864bb2 100644 --- a/src/views/my/initiateChange/modules/changePre.vue +++ b/src/views/my/initiateChange/modules/changePre.vue @@ -4,9 +4,11 @@ import { inject, watch, ref, computed } from 'vue'; import { Icon } from '@iconify/vue' import { useThemeStore } from '@/store/modules/theme'; import { getColorWithOpacity } from "@/utils/common"; -import { AiError, aiApplication, aiRecognize, aiRiskPreAnalysis } from "@/service/api/ai"; +import { AiError, aiApplication, aiRecognize, aiDeepRiskAnalysis, pollDeepAnalysisTask } from "@/service/api/ai"; +import type { DeepAnalysisResult, OpenTask } from "@/service/api/ai"; import ChangeCompareTable from "./ChangeCompareTable.vue"; import PreRisk from "./preRisk.vue"; +import DeepAnalysisPanel from "./DeepAnalysisPanel.vue"; const themeStore = useThemeStore(); @@ -23,25 +25,46 @@ const aiFail = (e: any) => { const preLoading = ref(false); // 生成变更申请单loading const generateLoading = ref(false); -// 风险预分析loading +// 风险预分析(异步深度分析)loading const analyzing = ref(false); -// 是否显示险预分析 -const preRiskShow = computed(() => form.value.severity || form.value.probability || form.value.protection); +// 异步任务进度 +const taskProgress = ref<{ progress: number; step: string } | null>(null); +// 深度分析错误信息(可重试) +const deepError = ref(''); +// 深度分析任务是否在跑(禁止重复提交) +const deepRunning = computed(() => analyzing.value); +// 是否显示险预分析(旧三段字段,读取兼容) +const preRiskShow = computed(() => !!(form.value.severity || form.value.probability || form.value.protection)); +// 是否已生成深度分析结果(任一部分有内容即展示,避免法规/表格部分结果被隐藏) +const deepShow = computed(() => { + const data = form.value.deep_analysis; + return !!data && !!(data.risk_identification || data.risk_analysis || data.summary_text || data.conclusion_text || data.regulations_data?.length || data.risk_table?.length); +}); // 是否显示变更识别结果 const identifyShow = computed(() => form.value.compare_rows.length > 0); +// 任务步骤文案 +const STEP_LABELS: Record = { + regulations: '法规合规性分析', + risk_identification: '风险辨识', + risk_analysis: '专家研讨分析', + deep_summary: '深度总结' +}; +const stepLabel = (step?: string) => STEP_LABELS[step ?? ''] ?? step ?? ''; // 表单 const form = ref<{ description: string, compare_rows: {item: string, before_text: string, after_text: string}[], severity: string, probability: string, - protection: string + protection: string, + deep_analysis: any }>({ description: '', compare_rows: [], severity: "", probability: "", protection: "", + deep_analysis: null, }); // AI 变更识别 const runIdentify = async () => { @@ -63,27 +86,48 @@ const runIdentify = async () => { btnDisabled.value = false; } }; -// 运行风险预分析 +// 运行智能风险分析(异步深度分析:识别→分析→法规→总结 四段) const runRiskAnalysis = async () => { if(form.value.description.trim() === '') { return window.$message?.warning('请先填写变更内容描述'); } + if (deepRunning.value) { + return window.$message?.warning('智能风险分析正在执行中,请勿重复提交'); + } analyzing.value = true; btnDisabled.value = true; + deepError.value = ''; + taskProgress.value = { progress: 0, step: '' }; try { - const res = await aiRiskPreAnalysis(form.value.description, form.value.compare_rows); - form.value = { - ...form.value, - severity: res?.severity ?? form.value.severity, - probability: res?.probability ?? form.value.probability, - protection: res?.protection ?? form.value.protection, + const created = await aiDeepRiskAnalysis(form.value.description, form.value.compare_rows); + const taskId = created?.task_id ?? ''; + if (!taskId) throw new AiError(-1, '任务创建失败(未返回 task_id)'); + const result: DeepAnalysisResult = await pollDeepAnalysisTask(taskId, { + onProgress: (t: OpenTask) => { + taskProgress.value = { progress: t?.progress ?? 0, step: t?.current_step ?? '' }; + } + }); + // 已生成内容不无故清空:逐字段回填,缺省保留原值 + form.value.deep_analysis = { + ...(form.value.deep_analysis ?? {}), + task_id: taskId, + status: 'completed', + risk_identification: result?.report_risk_identification ?? form.value.deep_analysis?.risk_identification ?? '', + risk_analysis: result?.report_risk_analysis ?? form.value.deep_analysis?.risk_analysis ?? '', + regulations_data: result?.regulations_data ?? form.value.deep_analysis?.regulations_data ?? [], + summary_text: result?.summary_text ?? form.value.deep_analysis?.summary_text ?? '', + risk_table: result?.risk_table ?? form.value.deep_analysis?.risk_table ?? [], + conclusion_text: result?.conclusion_text ?? form.value.deep_analysis?.conclusion_text ?? '' }; - window.$message?.success("AI 风险预分析报告已生成(危害严重性 / 事件概率 / 保护措施影响),内容支持手动修改"); + window.$message?.success("智能风险分析完成:风险辨识 / 专家研讨 / 法规合规 / 风险总结 四段结果已生成,支持编辑"); } catch (e: any) { + deepError.value = e?.message || '智能风险分析失败'; + // 失败保留已生成部分内容,仅提示 aiFail(e); } finally { analyzing.value = false; btnDisabled.value = false; + taskProgress.value = null; } }; // 生成变更申请单 @@ -105,21 +149,26 @@ const genForm = async () => { } }; +// 深度分析结果编辑回写 +const onDeepUpdate = (val: any) => { + form.value.deep_analysis = { ...form.value.deep_analysis, ...val }; +}; + // 保存草稿 const saveDraft = () => { emit('save'); } -defineExpose({form}) +defineExpose({form, runRiskAnalysis}) watch(() => props.currentForm, (newVal:any) => { - const { + const { attachments, - change_id, - created_at, - id, - updated_at, - ...rest + change_id, + created_at, + id, + updated_at, + ...rest } = newVal; form.value = rest; }) @@ -153,18 +202,35 @@ watch(() => props.currentForm, (newVal:any) => { @update:data="(d) => form.compare_rows = d" /> - + +
+
+ + 智能风险分析执行中{{ taskProgress?.step ? `:${stepLabel(taskProgress.step)}` : '' }}({{ taskProgress?.progress ?? 0 }}%),通常需要 2~5 分钟,请勿关闭页面 +
+ +
+ +
+ + {{ deepError }};已生成内容已保留,可点击「智能风险分析」重试,或继续手动填写 +
+ + +
- 预识别阶段不设审批人与提交:完成识别与预分析后,请切换至「变更申请表」选择审批人并提交 + 预识别阶段不设审批人与提交:完成识别与智能风险分析后,请切换至「变更申请表」选择审批人并提交
- 风险预分析 + 智能风险分析 保存 @@ -178,4 +244,4 @@ watch(() => props.currentForm, (newVal:any) => { height: calc(100vh - 326px); overflow-y: auto; } - \ No newline at end of file + diff --git a/src/views/my/initiateChange/modules/changeTraining.vue b/src/views/my/initiateChange/modules/changeTraining.vue index 45d32de..15319e9 100644 --- a/src/views/my/initiateChange/modules/changeTraining.vue +++ b/src/views/my/initiateChange/modules/changeTraining.vue @@ -8,7 +8,7 @@ import Footer from './footer.vue'; const themeStore = useThemeStore(); -const props = defineProps(['type','isAiOpen','title','currentId','formInfo', 'currentForm', 'confirmed','members','steps']) +const props = defineProps(['type','isAiOpen','title','currentId','formInfo','riskRecords', 'currentForm', 'confirmed','members','steps']) const emit = defineEmits(['save','submit','confirmTab','update:steps']); watch(() => props.currentForm, (newVal:any) => { @@ -36,6 +36,19 @@ const form = ref<{ content: string }>({ content: '' }); +// 风险记录归一:优先当前风险插件记录(riskAnalysis 汇总表),无则回退预识别深度分析 risk_table +const collectRiskRecords = (): { item: string; scene: string; safeguards: string; suggestions: string }[] => { + const fromTable = (props.riskRecords ?? []).map((r: any) => ({ + item: r.item ?? '', scene: r.scene ?? '', safeguards: r.safeguards ?? '', suggestions: r.suggestions ?? '' + })).filter((r: any) => r.item || r.scene || r.suggestions); + if (fromTable.length) return fromTable; + const riskTable = props.formInfo?.deep_analysis?.risk_table ?? []; + return riskTable.map((r: any) => ({ + item: r.risk_item ?? '', scene: r.risk_description ?? '', + safeguards: r.existing_measures ?? '', suggestions: r.suggested_measures ?? '' + })).filter((r: any) => r.item || r.scene || r.suggestions); +}; + // 重新生成变更培训内容(footer 派发) const onRegenerate = async () => { const info = props.formInfo; @@ -44,11 +57,16 @@ const onRegenerate = async () => { } footerRef.value?.setRegenerateLoading(true); try { - const res = await aiTraining(info.description, (info.compare_rows ?? []).map((x: any) => ({ item: x.item, before_text: x.before_text, after_text: x.after_text }))); + const riskRecords = collectRiskRecords(); + const res = await aiTraining( + info.description, + (info.compare_rows ?? []).map((x: any) => ({ item: x.item, before_text: x.before_text, after_text: x.after_text })), + riskRecords + ); if (res?.training_text) { form.value.content = res.training_text; isAiGenerated.value = true; - window.$message?.success("变更培训内容已由 AI 生成,可直接修改"); + window.$message?.success(`变更培训内容已由 AI 生成${riskRecords.length ? `(已结合 ${riskRecords.length} 条风险记录)` : ''},可直接修改`); } else { window.$message?.warning("AI 未返回培训内容,请手动填写"); } diff --git a/src/views/my/initiateChange/modules/fmea.vue b/src/views/my/initiateChange/modules/fmea.vue index 4199b2d..45cf215 100644 --- a/src/views/my/initiateChange/modules/fmea.vue +++ b/src/views/my/initiateChange/modules/fmea.vue @@ -5,11 +5,12 @@ import { useThemeStore } from '@/store/modules/theme'; import { useDialog, NInput, NPopconfirm, NButton } from 'naive-ui'; import { peopleListApi } from '@/service/api/system'; import { fmeaNodesApi, fmeaSaveApi } from "@/service/api/plugin"; +import { AiError, aiFmeaProcessSuggest, aiFmeaModeSuggest, aiFmeaAnalyze } from '@/service/api/ai'; const themeStore = useThemeStore(); const dialog = useDialog(); -const props = defineProps(['isAiOpen','currentId','fmeaRiskMatrixConfig']) +const props = defineProps(['isAiOpen','currentId','fmeaRiskMatrixConfig','preInfo']) const emit = defineEmits(['close','toTable']); const loading = ref(false); @@ -393,7 +394,9 @@ const enterToTable = (type: string, rowIndex: number = -1) => { item: `${currentDev.value?.deviation}${currentNode.value?.node_name?`(${currentNode.value?.node_name})`:''}`, safeguards: row?.safeguards || '', suggestions: row?.suggestions || '', - residual_level: row?.residual_level || '', + // 当前评分档作为固有风险;无措施后评分,剩余风险留空人工判定(不照抄固有) + inherent_level: row?.residual_level || '', + residual_level: '', to_pssr: 0, source_row_id: row?.id || 0, }; @@ -429,7 +432,9 @@ const enterToTable = (type: string, rowIndex: number = -1) => { item: `${deviation}${node_ame?`(${node_ame})`:''}`, safeguards: row?.safeguards || '', suggestions: row?.suggestions || '', - residual_level: row?.residual_level || '', + // 当前评分档作为固有风险;无措施后评分,剩余风险留空人工判定(不照抄固有) + inherent_level: row?.residual_level || '', + residual_level: '', to_pssr: 0, source_row_id: row.id || 0, }); @@ -448,30 +453,180 @@ const exportWord = () => { // AI 自动分析失效模式 const runAi = async (type: string) => { - if(currentDev.value.rows.length){ + if (type==='current' && currentDev.value?.rows?.length){ return window.$message?.info("当前失效模式已有分析记录,可手动新增行补充"); } - // 分析当前失效模式 if(type==='current'){ if(!currentDev.value){ return window.$message?.warning("请先在左侧选择失效模式") } + if(analyzing.value) return; + analyzing.value = true; + try { + await analyzeOneMode(currentDev.value); + window.$message?.success("AI 已生成当前失效模式分析行(S/P/D 越界或缺失项请人工补评)"); + await save(); + } catch (e: any) { + aiFmeaFail(e); + } finally { + analyzing.value = false; + } } - // 分析全部失效模式 + // 分析全部失效模式(当前步骤全部失效模式,顺序逐个处理,单条失败不覆盖已成功记录) if(type==='all'){ - + const node = nodes.value?.[currentNodeIndex.value]; + const devs = node?.deviations ?? []; + if (!devs.length) { + return window.$message?.warning("当前步骤暂无失效模式,请先添加或使用「AI设置失效模式」"); + } + if(analyzing.value) return; + analyzing.value = true; + let ok = 0; + let skip = 0; + let fail = 0; + try { + for (const dev of devs) { + if (dev.rows?.length) { + skip += 1; // 已有分析记录跳过,不覆盖 + continue; + } + try { + // eslint-disable-next-line no-await-in-loop + await analyzeOneMode(dev); + ok += 1; + } catch (err) { + fail += 1; // 单条失败隔离 + } + } + window.$message?.success(`全部失效模式分析完成:成功 ${ok} 条${skip ? `、跳过已有 ${skip} 条` : ''}${fail ? `、失败 ${fail} 条(可单条重试)` : ''}`); + await save(); + } finally { + analyzing.value = false; + } } }; -// AI 自动推演 + +/** 单失效模式 AI 分析:S/P/D 按页面评分表传入并夹取,非法值置 null 待人工补评 */ +const analyzeOneMode = async (dev: any) => { + const node = nodes.value?.[currentNodeIndex.value]; + if (!node || !dev) throw new Error('未找到失效模式所属步骤'); + const res = await aiFmeaAnalyze({ + step_name: node.node_name ?? '', + step_description: node.description ?? '', + deviation: dev.deviation ?? '', + change_context: { + description: props.preInfo?.description ?? '', + compare_rows: (props.preInfo?.compare_rows ?? []).map((r: any) => ({ item: r.item, before_text: r.before_text, after_text: r.after_text })) + }, + matrix_payload: { + s_grades: props.fmeaRiskMatrixConfig?.s_grades ?? [], + p_grades: props.fmeaRiskMatrixConfig?.p_grades ?? [], + d_grades: props.fmeaRiskMatrixConfig?.d_grades ?? [], + risk_grades: props.fmeaRiskMatrixConfig?.risk_grades ?? [] + } + }); + const rows = res?.rows ?? []; + if (!rows.length) throw new Error('AI 未返回分析行'); + rows.forEach((r: any) => { + dev.rows.push({ + id: 0, + cause: r.cause ?? '', + effect: r.effect ?? '', + s_value: r.s ?? null, + p_value: r.p ?? null, + d_value: r.d ?? null, + residual_level: '', + safeguards: r.safeguards ?? '', + suggestions: r.suggestions ?? '', + }); + }); +}; + +const aiFmeaFail = (e: any) => { + if (e instanceof AiError) window.$message?.warning(`FMEA AI 分析失败:${e.message}`); + else window.$message?.warning(`FMEA AI 分析失败:${e?.message ?? '未知错误'}`); +}; + +// AI 自动推演(/open/v1/moc/fmea/process-suggest:总体工艺描述 → 工作步骤,只补空缺) const runInference = async () => { + if (!description.value.trim()) { + return window.$message?.warning('请先填写项目总体工艺描述'); + } inferring.value = true inferred.value = false - setTimeout(() => { - inferring.value = false - inferred.value = true - }, 1000) + try { + const res = await aiFmeaProcessSuggest(description.value, { + compare_rows: (props.preInfo?.compare_rows ?? []).map((r: any) => ({ item: r.item, before_text: r.before_text, after_text: r.after_text })) + }); + const steps = res?.steps ?? []; + if (!steps.length) { + window.$message?.warning('AI 未推演出工作步骤,请手动添加或补充工艺描述'); + return; + } + const existing = new Set(nodeList.value.map((n: any) => String(n.node_name ?? ''))); + let added = 0; + steps.forEach((s: any) => { + if (existing.has(String(s.node_name ?? ''))) return; + nodeList.value.push({ + id: 0, + node_name: s.node_name ?? '', + deviations: [], + description: s.description ?? '' + }); + added += 1; + }); + inferred.value = true; + window.$message?.success(added > 0 + ? `AI 推演出 ${added} 个工作步骤(已加入列表,请人工确认后点「确定」保存)` + : 'AI 推演步骤均与现有步骤重名,未新增'); + } catch (e: any) { + aiFmeaFail(e); + } finally { + inferring.value = false; + } } +// AI 设置失效模式(/open/v1/moc/fmea/mode-suggest:当前步骤 → 候选失效模式,进暂存区人工确认) +const aiSetMode = async () => { + const node = nodes.value?.[currentNodeIndex.value]; + if (!node) { + return window.$message?.warning('请先在左侧选择步骤'); + } + if (aiModeSuggesting.value) return; + aiModeSuggesting.value = true; + try { + const res = await aiFmeaModeSuggest({ + step_name: node.node_name ?? '', + step_description: node_description.value ?? node.description ?? '', + existing_modes: (currentNodeList.value ?? []).map((d: any) => d.deviation).filter(Boolean), + change_context: { description: props.preInfo?.description ?? '' } + }); + const deviations = res?.deviations ?? []; + if (!deviations.length) { + window.$message?.warning('AI 未返回失效模式建议(可能已有内容已覆盖),可手动添加'); + return; + } + const existing = new Set((currentNodeList.value ?? []).map((d: any) => String(d.deviation ?? ''))); + let added = 0; + deviations.forEach((s: any) => { + if (existing.has(String(s.deviation ?? ''))) return; + currentNodeList.value.push({ id: 0, deviation: s.deviation ?? '', rows: [] }); + existing.add(String(s.deviation ?? '')); + added += 1; + }); + saveData(); + window.$message?.success(added > 0 + ? `AI 失效模式建议已加入暂存区 ${added} 条,请人工确认后点「保存」` + : 'AI 建议失效模式均与现有重名,未新增'); + } catch (e: any) { + aiFmeaFail(e); + } finally { + aiModeSuggesting.value = false; + } +}; +// AI 设置失效模式 loading +const aiModeSuggesting = ref(false); + // 计算风险等级 const calculateRiskGrade = (s: number,p: number,d: number) => { const rpn = s * p * d; @@ -1144,7 +1299,7 @@ onBeforeUnmount(() => {
失效模式 - AI设置失效模式 + AI设置失效模式 (false); @@ -517,32 +518,205 @@ const exportWord = () => { window.$message?.info('还差接口') } -// AI 自动分析偏离 +// AI 自动分析偏离(/open/v1/moc/hazop/deviation-analyze;仅出 L/S,RR/RR1 由本地矩阵计算) const runAi = async (type: string) => { - if(currentDev.value.rows.length){ + if (type==='current' && currentDev.value?.rows?.length){ return window.$message?.info("当前偏离已有分析记录,可手动新增行补充"); } - // 分析当前偏离 if(type==='current'){ if(!currentDev.value){ return window.$message?.warning("请先在左侧选择偏离") } + if(analyzing.value) return; + analyzing.value = true; + try { + await analyzeOneDeviation(currentDev.value); + window.$message?.success("AI 已生成当前偏离分析行,措施降维值(L/S)请人工评估填写"); + await save(); + } catch (e: any) { + aiHazopFail(e); + } finally { + analyzing.value = false; + } } - // 分析全部偏离 + // 分析全部偏离(当前节点全部偏离,顺序逐个处理,单条失败不覆盖已成功记录) if(type==='all'){ - + const node = nodes.value?.[currentNodeIndex.value]; + const devs = (node?.objects ?? []).flatMap((o: any) => (o.deviations ?? []).map((d: any) => ({ obj: o, dev: d }))); + if (!devs.length) { + return window.$message?.warning("当前节点暂无偏离,请先在分析列表中添加"); + } + if(analyzing.value) return; + analyzing.value = true; + let ok = 0; + let skip = 0; + let fail = 0; + try { + for (const { dev } of devs) { + if (dev.rows?.length) { + skip += 1; // 已有分析记录的偏离跳过,不覆盖 + continue; + } + try { + // eslint-disable-next-line no-await-in-loop + await analyzeOneDeviation(dev); + ok += 1; + } catch (err) { + fail += 1; // 单条失败隔离,继续处理其余偏离 + } + } + window.$message?.success(`全部偏离分析完成:成功 ${ok} 条${skip ? `、跳过已有 ${skip} 条` : ''}${fail ? `、失败 ${fail} 条(可单条重试)` : ''}`); + await save(); + } finally { + analyzing.value = false; + } } }; -// AI 自动推演 + +/** 单偏离 AI 分析:组 change_context(含三段节点描述)→ 调接口 → 映射行(措施拆 {name,value:''},不虚构降维值) */ +const analyzeOneDeviation = async (dev: any) => { + const nodeIndex = currentNodeIndex.value; + const node = nodes.value?.[nodeIndex]; + if (!node || !dev) throw new Error('未找到偏离所属节点'); + const obj = (node.objects ?? []).find((o: any) => (o.deviations ?? []).includes(dev)); + const res = await aiHazopDeviation({ + node_name: node.node_name ?? '', + object_name: obj?.obj_name ?? '', + deviation: dev.deviation ?? '', + change_context: { + description: props.preInfo?.description ?? '', + compare_rows: (props.preInfo?.compare_rows ?? []).map((r: any) => ({ item: r.item, before_text: r.before_text, after_text: r.after_text })), + process_desc: node_description.value ?? '', + operation_desc: node_way.value ?? '', + measures_desc: node_protection.value ?? '' + } + }); + const rows = res?.rows ?? []; + if (!rows.length) throw new Error('AI 未返回分析行'); + rows.forEach((r: any) => { + const l = Number(r.l ?? l_options.value[0]?.key ?? 1); + const s = Number(r.s ?? s_options.value[0]?.key ?? 1); + dev.rows.push({ + cause: r.cause ?? '', + consequence: r.consequence ?? '', + l_value: l, + s_value: s, + risk_value: riskLevel(l, s)?.name ?? '', + safeguards: splitMeasureText(r.safeguards), + suggestions: splitMeasureText(r.suggestions), + }); + }); +}; + +/** 措施文本(「;」分隔)拆为 {name, value:''} 数组;AI 未提供降维值,留空人工评估 */ +const splitMeasureText = (text: any): { name: string; value: string }[] => { + const str = String(text ?? '').trim(); + if (!str || str === '无') return []; + return str.split(/[;;]/).map((x: string) => x.trim()).filter(Boolean).map((name: string) => ({ name, value: '' })); +}; + +const aiHazopFail = (e: any) => { + if (e instanceof AiError) window.$message?.warning(`HAZOP AI 分析失败:${e.message}`); + else window.$message?.warning(`HAZOP AI 分析失败:${e?.message ?? '未知错误'}`); +}; + +// AI 自动推演(/open/v1/moc/hazop/node-suggest:总体工艺描述 → 节点划分,只补空缺) const runInference = async () => { + if (!description.value.trim()) { + return window.$message?.warning('请先填写工艺描述'); + } inferring.value = true inferred.value = false - setTimeout(() => { - inferring.value = false - inferred.value = true - }, 1000) + try { + const res = await aiHazopNodeSuggest(description.value, { + compare_rows: (props.preInfo?.compare_rows ?? []).map((r: any) => ({ item: r.item, before_text: r.before_text, after_text: r.after_text })) + }); + const suggested = res?.nodes ?? []; + if (!suggested.length) { + window.$message?.warning('AI 未推演出节点,请手动添加或补充工艺描述'); + return; + } + // 只补空缺:已有同名节点跳过 + const existing = new Set(nodeList.value.map((n: any) => String(n.node_name ?? ''))); + let added = 0; + suggested.forEach((n: any) => { + if (existing.has(String(n.node_name ?? ''))) return; + nodeList.value.push({ + id: 0, + node_name: n.node_name ?? '', + change_id: props.currentId, + description: n.description ?? '', + objects: [] + }); + added += 1; + }); + inferred.value = true; + window.$message?.success(added > 0 + ? `AI 推演出 ${added} 个节点(已加入列表,请人工确认后点「确定」保存)` + : 'AI 推演节点均与现有节点重名,未新增'); + } catch (e: any) { + aiHazopFail(e); + } finally { + inferring.value = false; + } } +// AI 设置偏离(/open/v1/moc/hazop/deviation-suggest:节点三段描述 → 对象与偏离建议,进暂存区人工确认) +const aiSetDeviation = async () => { + const node = nodes.value?.[currentNodeIndex.value]; + if (!node) { + return window.$message?.warning('请先在左侧选择节点'); + } + if (aiDevSuggesting.value) return; + aiDevSuggesting.value = true; + try { + const res = await aiHazopDeviationSuggest({ + node_name: node.node_name ?? '', + process_desc: node_description.value ?? '', + operation_desc: node_way.value ?? '', + measures_desc: node_protection.value ?? '', + existing_objects: currentNodeList.value.map((o: any) => ({ obj_name: o.obj_name, deviations: (o.deviations ?? []).map((d: any) => d.deviation) })), + change_context: { description: props.preInfo?.description ?? '' } + }); + const objects = res?.objects ?? []; + if (!objects.length) { + window.$message?.warning('AI 未返回偏离建议(可能已有内容已覆盖),可手动添加'); + return; + } + // 只补空缺:已有对象补缺失偏离;新对象追加 + let addedObj = 0; + let addedDev = 0; + objects.forEach((sug: any) => { + const exist = currentNodeList.value.find((o: any) => o.obj_name === sug.obj_name); + if (exist) { + (sug.deviations ?? []).forEach((d: string) => { + if (!(exist.deviations ?? []).some((x: any) => x.deviation === d)) { + exist.deviations.push({ id: 0, object_id: exist.id, deviation: d, rows: [] }); + addedDev += 1; + } + }); + } else { + currentNodeList.value.push({ + id: 0, + obj_name: sug.obj_name, + node_id: node.id, + deviations: (sug.deviations ?? []).map((d: string) => ({ id: 0, object_id: 0, deviation: d, rows: [] })) + }); + addedObj += 1; + addedDev += (sug.deviations ?? []).length; + } + }); + saveData(); + window.$message?.success(`AI 偏离建议已加入暂存区(新增对象 ${addedObj} 个、偏离 ${addedDev} 条),请人工确认后点「保存」`); + } catch (e: any) { + aiHazopFail(e); + } finally { + aiDevSuggesting.value = false; + } +}; +// AI 设置偏离 loading +const aiDevSuggesting = ref(false); + // 根据l和s计算RR风险等级 const riskLevel = (l: number, s: number) => { const num = l * s; @@ -1393,7 +1567,7 @@ onBeforeUnmount(() => {
分析对象 - AI设置偏离 + AI设置偏离 props.currentForm, (newVal:any) => { @@ -64,7 +64,7 @@ const list = ref<{ g: string; type:number; na_flag:number; items: any[] }[]>([ ]); const pssrNa = ref>({}); -// 重新生成 PSSR 检查内容(footer 派发):AI 输出按固定四组名称匹配回填 +// 重新生成 PSSR 检查内容(footer 派发):传 rows/风险记录/行动项/固定四组模板;AI 输出优先按 group_type 匹配回填 const onRegenerate = async () => { const info = props.formInfo; if (!info?.description) { @@ -72,9 +72,25 @@ const onRegenerate = async () => { } footerRef.value?.setRegenerateLoading(true); try { + // 风险记录:优先风险插件汇总记录,回退预识别深度分析 risk_table + const riskRecords = (props.riskRecords ?? []).map((r: any) => ({ + item: r.item ?? '', scene: r.scene ?? '', safeguards: r.safeguards ?? '', suggestions: r.suggestions ?? '' + })).filter((r: any) => r.item || r.scene || r.suggestions); + const fallbackRisk = (info.deep_analysis?.risk_table ?? []).map((r: any) => ({ + item: r.risk_item ?? '', scene: r.risk_description ?? '', + safeguards: r.existing_measures ?? '', suggestions: r.suggested_measures ?? '' + })).filter((r: any) => r.item || r.scene || r.suggestions); + const riskCtx = riskRecords.length ? riskRecords : fallbackRisk; + // 行动项:已转 PSSR 的建议措施(to_pssr=1);无插件记录时用全部建议措施兜底 + const actionItems = (riskRecords.length ? riskRecords.filter((r: any) => r.suggestions) : riskCtx.filter((r: any) => r.suggestions)) + .map((r: any, i: number) => ({ content: r.suggestions, phase: 1, no: i + 1 })); const res = await aiPssr({ content: info.description, + rows: (info.compare_rows ?? []).map((x: any) => ({ item: x.item, before_text: x.before_text, after_text: x.after_text })), ...(props.changeType ? { change_type: props.changeType } : {}), + risk_records: riskCtx, + action_items: actionItems, + pssr_template: { groups: list.value.map((g) => ({ group_type: g.type, g: g.g })) }, }); const groups = (res?.groups ?? []).filter((g: any) => g && Array.isArray(g.items)); if (!groups.length) { @@ -82,8 +98,9 @@ const onRegenerate = async () => { } const used = new Set(); list.value = list.value.map((g) => { - // 优先按分组名匹配,兜底按剩余顺序对齐 - let gi = groups.findIndex((x: any, i: number) => !used.has(i) && (x.g === g.g || x.g.includes(g.g) || g.g.includes(x.g))); + // 优先 group_type 精确匹配,其次固定组名匹配,最后剩余顺序兜底(不只用顺序猜组) + let gi = groups.findIndex((x: any, i: number) => !used.has(i) && Number(x.group_type) === g.type); + if (gi < 0) gi = groups.findIndex((x: any, i: number) => !used.has(i) && (x.g === g.g || x.g?.includes(g.g) || g.g.includes(x.g ?? ''))); if (gi < 0) gi = groups.findIndex((_: any, i: number) => !used.has(i)); if (gi < 0) return g; used.add(gi); @@ -100,7 +117,7 @@ const onRegenerate = async () => { }; }); isAiGenerated.value = true; - window.$message?.success("PSSR 检查清单已由 AI 生成,点击条目可直接编辑"); + window.$message?.success(`PSSR 检查清单已由 AI 生成${riskCtx.length ? `(已结合 ${riskCtx.length} 条风险记录)` : ''},点击条目可直接编辑`); } catch (e: any) { aiFail(e); } finally { diff --git a/src/views/my/initiateChange/modules/riskAnalysis.vue b/src/views/my/initiateChange/modules/riskAnalysis.vue index ca5019a..f1088aa 100644 --- a/src/views/my/initiateChange/modules/riskAnalysis.vue +++ b/src/views/my/initiateChange/modules/riskAnalysis.vue @@ -10,16 +10,19 @@ import Fmea from "./fmea.vue"; import RiskCheck from "./riskCheck.vue"; import Footer from './footer.vue' import { matrixConfigApi } from "@/service/api/system"; +import { AiError, aiRiskOrganize, aiRiskCheck } from "@/service/api/ai"; +import { riskCheckDetailApi, riskCheckSaveApi } from "@/service/api/plugin"; +import { RISK_CHECKS_INIT } from './riskCheckTemplate'; const themeStore = useThemeStore(); -const props = defineProps(['type','isAiOpen','title','currentId','formInfo', 'currentForm', 'confirmed','members','steps']); +const props = defineProps(['type','isAiOpen','title','currentId','formInfo', 'preInfo', 'currentForm', 'confirmed','members','steps']); const emit = defineEmits(['save','submit','confirmTab','update:steps']); const hazopRiskMatrixConfig = ref(null); const fmeaRiskMatrixConfig = ref(null); const jsaRiskMatrixConfig = ref(null); -const pluginDone = computed(() => +const pluginDone = computed(() => riskRecords.value.reduce((acc:any, item:any) => { const s = item.source; if (s) acc[s] = (acc[s] || 0) + 1; @@ -30,6 +33,14 @@ const tools = ref(["RISK","HAZOP","FMEA", "RISK_CHECK"]); const riskRecords = ref([]); const pluginDrawer = ref(false); const currentPlugin = ref(''); +// AI 自动整理 loading +const organizing = ref(false); +// 风险检查表后台生成 loading +const riskCheckGenerating = ref(false); + +/** 变更上下文(优先 preInfo=预识别页数据;缺省回退 formInfo) */ +const changeContext = computed(() => props.preInfo ?? props.formInfo ?? {}); +const changeRows = computed(() => (changeContext.value?.compare_rows ?? []).map((r: any) => ({ item: r.item, before_text: r.before_text, after_text: r.after_text }))); watch(() => props.currentForm, (newVal:any) => { const omit = (obj:any, fields: string[]) => Object.fromEntries(Object.entries(obj).filter(([k]) => !fields.includes(k))); @@ -99,9 +110,149 @@ const toPssrAll = () => { window.$message?.success(`已将建议措施全部转为 PSSR 行动项(见「PSSR 检查内容」)`); }; -// AI 自动整理 +// AI 自动整理:聚合变更信息与已选用工具结果 → /open/v1/moc/risk/organize,映射入汇总表 const aiOrganize = async () => { - + const description = (changeContext.value?.description ?? '').trim(); + if (!description) { + return window.$message?.warning('缺少变更描述(请先在「变更预识别」填写)'); + } + if (organizing.value) return; + organizing.value = true; + try { + // 工具结果按来源分组(已保存/未保存记录均纳入) + const toolResults: Record = {}; + riskRecords.value.forEach((r: any) => { + const key = String(r.source ?? '').toUpperCase(); + if (!key || key === 'AI') return; + (toolResults[key] ??= []).push({ + item: r.item, scene: r.scene, safeguards: r.safeguards, + suggestions: r.suggestions, inherent_level: r.inherent_level, residual_level: r.residual_level + }); + }); + const res = await aiRiskOrganize(description, changeRows.value, toolResults); + const records = res?.records ?? []; + if (!records.length) { + window.$message?.warning('AI 未整理出风险记录(可补充工具结果后重试)'); + return; + } + // 去重:已保存记录按 id+source,未保存按 source+item+scene + const seen = new Set(); + riskRecords.value.forEach((r: any) => { + const id = Number(r.id ?? 0); + seen.add(id > 0 ? `${id}_${r.source}` : `${r.source}_${r.item}_${r.scene}`); + seen.add(`AI_${r.item ?? ''}_${r.scene ?? ''}`); + }); + let added = 0; + records.forEach((rec: any) => { + const item = String(rec.item ?? ''); + const scene = String(rec.scene ?? ''); + const dedupeKey = `AI_${item}_${scene}`; + if (seen.has(dedupeKey)) return; + seen.add(dedupeKey); + riskRecords.value.push({ + id: 0, + item, + scene, + safeguards: rec.existing ?? '', + suggestions: rec.suggest ?? '', + inherent_level: organizeLevel(rec.l, rec.s), + residual_level: organizeLevel(rec.residual_l, rec.residual_s), + source: 'AI', + to_pssr: 0 + }); + added += 1; + }); + window.$message?.success(added > 0 + ? `AI 已整理 ${added} 条风险记录(来源「AI 整理」,可编辑/去重/转 PSSR)` + : 'AI 整理结果与现有记录重复,未新增'); + } catch (e: any) { + if (e instanceof AiError) window.$message?.warning(`AI 自动整理失败:${e.message}`); + else window.$message?.warning('AI 自动整理失败'); + } finally { + organizing.value = false; + } +}; + +/** L/S → 汇总表风险等级(本地矩阵换算:L×S 落 risk_grades 区间;AI 整理行沿用 HAZOP 矩阵配色渲染) */ +const organizeLevel = (l: number | null, s: number | null): string => { + const grades = hazopRiskMatrixConfig.value?.risk_grades ?? []; + if (!grades.length || !l || !s) return ''; + const score = l * s; + const hit = grades.find((g: any) => score >= (Number(g.min) || 0) && score <= (Number(g.max) || 999)); + return hit?.name ?? ''; +}; + +/** + * 后台编排入口(index.vue onApplyGenerated 调用):风险检查表 AI 生成。 + * 不依赖插件组件实例、不自动打开抽屉:拉取已存检查表(缺省用当前 7 项权威模板)→ + * AI 判定(仅回填未答项,人工判定不覆盖)→ 保存换取真实 ID。 + * 用户打开插件抽屉时经详情接口看到结果,可修改后单条/全部入表。 + */ +const generateRiskCheck = async () => { + const description = (changeContext.value?.description ?? '').trim(); + if (!description) { + window.$message?.info('后台任务:缺少变更描述,风险检查表未生成(可在插件内手动生成)'); + return; + } + if (riskCheckGenerating.value) return; + riskCheckGenerating.value = true; + try { + // 已存检查表优先(保留人工判定);无则用当前 7 项权威模板 + let groups: any[] = []; + const detail = await riskCheckDetailApi(props.currentId); + if (!detail.error && detail.data?.length) { + groups = detail.data; + } else { + groups = JSON.parse(JSON.stringify(RISK_CHECKS_INIT)); + } + const checkTemplate = { + groups: groups.map((group: any) => ({ + group_id: group.group_id, + group_label: group.group_label, + items: (group.items ?? []).map((item: any) => ({ question_id: item.question_id, question: item.question })) + })) + }; + const res = await aiRiskCheck(description, changeRows.value, checkTemplate); + const aiItems: any[] = res?.items ?? []; + const byId = new Map(); + const byQuestion = new Map(); + aiItems.forEach((it: any) => { + if (it?.no !== undefined && it.no !== '') byId.set(String(it.no), it); + const q = String(it?.q ?? '').replace(/\s+/g, '').toLowerCase(); + if (q) byQuestion.set(q, it); + }); + let filled = 0; + groups.forEach((group: any) => { + (group.items ?? []).forEach((item: any) => { + const qNorm = String(item.question ?? '').replace(/\s+/g, '').toLowerCase(); + const hit = byId.get(String(item.question_id)) ?? byQuestion.get(qNorm); + if (!hit) return; + if (item.answer !== null && item.answer !== undefined) return; // 人工判定不覆盖 + const ans = hit.ans === '是' ? 1 : hit.ans === '否' ? 0 : hit.ans === 'NA' ? 2 : null; + if (ans === null) return; + item.answer = ans; + if (ans === 1) { + item.risk_desc = hit.risk ?? ''; + item.control_measure = hit.measure ?? ''; + } else { + item.risk_desc = ''; + item.control_measure = ''; + } + filled += 1; + }); + }); + const saved = await riskCheckSaveApi(props.currentId, { groups }); + if (saved.error) { + window.$message?.info('后台任务:风险检查表 AI 判定完成但保存失败,请在插件内手动保存'); + } else { + window.$message?.success(`后台任务:风险检查表 AI 已判定 ${filled} 项并保存,可在「风险分析记录表」插件中查放入表`); + } + } catch (e: any) { + const msg = e instanceof AiError ? e.message : 'AI 调用失败'; + window.$message?.info(`后台任务:风险检查表生成失败(${msg}),可在插件内重试`); + } finally { + riskCheckGenerating.value = false; + } }; /** @@ -171,7 +322,7 @@ const getRiskMatrixConfig = async () => { } } -defineExpose({riskRecords}) +defineExpose({riskRecords, aiOrganize, generateRiskCheck}) onMounted(() => { getRiskMatrixConfig(); @@ -232,7 +383,7 @@ onMounted(() => { 全部转 PSSR 行动项 - + AI 自动整理 @@ -289,7 +440,7 @@ onMounted(() => { {{rec.inherent_level}}
-
+
{ {{rec.residual_level}}
-
+
{
- {{ rec.source==='RISK'?'风险预分析':rec.source==='RISK_CHECK'?'风险检查': rec.source }} + {{ rec.source==='RISK'?'风险预分析':rec.source==='RISK_CHECK'?'风险检查': rec.source==='AI' ? 'AI 整理' : rec.source }} 已转 PSSR @@ -470,16 +621,16 @@ onMounted(() => { diff --git a/src/views/my/initiateChange/modules/riskCheck.vue b/src/views/my/initiateChange/modules/riskCheck.vue index 907d44e..5ebc1b2 100644 --- a/src/views/my/initiateChange/modules/riskCheck.vue +++ b/src/views/my/initiateChange/modules/riskCheck.vue @@ -2,90 +2,33 @@ import {onMounted, ref } from "vue"; import { Icon } from '@iconify/vue' import { riskCheckDetailApi, riskCheckSaveApi } from '@/service/api/plugin' +import { AiError, aiRiskCheck } from '@/service/api/ai' +import { RISK_CHECKS_INIT } from './riskCheckTemplate' -const props = defineProps(['isAiOpen','currentId']) +const props = defineProps(['isAiOpen','currentId','preInfo']) const emit = defineEmits(['close','toTable']); // answer 1 是 // answer 0 否 // answer 2 NA -const RISK_CHECKS_INIT = [ - { - group_id: 1, - group_label: "安全健康", - items: [ - { - question_id: 1, - answer: null, - question: "是否存在任何可能导致安全问题的化学反应?检查化学反应禁忌表。", - risk_desc: "", - control_measure: "", - }, - { - question_id: 2, - answer: null, - question: "是否存在任何易燃易爆化学物质或粉尘?", - risk_desc: "", - control_measure: "", - }, - { - question_id: 3, - answer: null, - question: "是否存在任何有危险的原材料流速、成分或温度条件变更?", - risk_desc: "", - control_measure: "", - }, - { - question_id: 4, - answer: null, - question: "是否会因加热、冷却或精确的温度控制失控而导致安全问题?", - risk_desc: "", - control_measure: "", - }, - { - question_id: 5, - answer: null, - question: "是否具有为安全操作所必需的仪表、控制、紧急制动、开关或报警?", - risk_desc: "", - control_measure: " ", - }, - ], - }, - { - group_id: 2, - group_label: "工艺与操作", - items: [ - { - question_id: 6, - answer: null, - question: "变更后是否需要对操作人员进行专门培训?", - risk_desc: "", - control_measure: "", - }, - { - question_id: 7, - answer: null, - question: "是否涉及应急预案或消防设施的调整?", - risk_desc: "", - control_measure: "" - }, - ], - } -]; const loading = ref(false); -const riskGroups = ref(RISK_CHECKS_INIT); +// 深拷贝共享模板(避免直接修改共享常量) +const cloneTemplate = () => JSON.parse(JSON.stringify(RISK_CHECKS_INIT)); +const riskGroups = ref(cloneTemplate()); +// 全量数据副本:「仅看是」过滤只改显示视图,不丢已编辑/已加载内容 +const allGroups = ref(cloneTemplate()); const riskFilter = ref(-1); const analyzing = ref(false); -// 过滤风险项 +// 过滤风险项(基于全量副本,显示层过滤) const filterChange = (v: number) => { riskFilter.value = v; if(v===-1){ - riskGroups.value = RISK_CHECKS_INIT; + riskGroups.value = allGroups.value; }else{ - const result = RISK_CHECKS_INIT.map(group => ({ - ...group, + const result = allGroups.value.map(group => ({ + ...group, items: group.items.filter((item:any) => item.answer === 1) })).filter(group => group.items.length > 0); riskGroups.value = result; @@ -95,7 +38,7 @@ const filterChange = (v: number) => { const save = async () => { loading.value = true; const {error} = await riskCheckSaveApi(props.currentId,{ - groups: riskGroups.value + groups: allGroups.value }); if(!error){ window.$message?.success("保存成功"); @@ -126,14 +69,14 @@ const enterToTable = (type: string, groupIndex: number = -1, questionIndex: numb emit('toTable',type,newRow?[newRow]:[]); } if(type==='all'){ - const result = riskGroups.value.flatMap((group:any) => - group.items.map((item:any, index:number) => ({ group_id: group.group_id, group_label: group.group_label, index, item })).filter(({ item }:any) => !item.id) + const result = allGroups.value.flatMap((group:any) => + group.items.map((item:any, index:number) => ({ group_id: group.group_id, group_label: group.group_label, index, item })).filter(({ item }:any) => !item.id) ); if(result.length){ return window.$message?.warning("请先保存再入表"); } const enrichedRows:any[] = []; - riskGroups.value.forEach((group:any) => { + allGroups.value.forEach((group:any) => { group.items.forEach((row:any) => { enrichedRows.push({ id: row.id || 0, @@ -153,12 +96,75 @@ const enterToTable = (type: string, groupIndex: number = -1, questionIndex: numb } } -// AI 自动分析工序 -const runAi = async () => { +// AI 自动分析(/open/v1/moc/change/risk-check;当前 7 项模板为唯一权威,仅回填未判定项) +// silent=true 为后台编排调用(申请单生成后):不弹交互提示、失败静默返回 +const runAi = async (silent = false) => { + const description = (props.preInfo?.description ?? '').trim(); + if (!description) { + if (!silent) window.$message?.warning('缺少变更描述(请先在「变更预识别」填写)'); + return; + } + if (analyzing.value) return; + // 以当前全量 7 项为权威模板(含 question_id 与问题原文),旧 58/66 项不得覆盖 + const checkTemplate = { + groups: allGroups.value.map((group: any) => ({ + group_id: group.group_id, + group_label: group.group_label, + items: (group.items ?? []).map((item: any) => ({ question_id: item.question_id, question: item.question })) + })) + }; analyzing.value = true; - setTimeout(() => { + try { + const rows = (props.preInfo?.compare_rows ?? []).map((r: any) => ({ item: r.item, before_text: r.before_text, after_text: r.after_text })); + const res = await aiRiskCheck(description, rows, checkTemplate); + const aiItems: any[] = res?.items ?? []; + // 按 question_id 索引(no 字段为 question_id 原值),规范化问题原文兜底 + const byId = new Map(); + const byQuestion = new Map(); + aiItems.forEach((it: any) => { + if (it?.no !== undefined && it.no !== '') byId.set(String(it.no), it); + const q = String(it?.q ?? '').replace(/\s+/g, '').toLowerCase(); + if (q) byQuestion.set(q, it); + }); + let filled = 0; + let keptManual = 0; + allGroups.value.forEach((group: any) => { + (group.items ?? []).forEach((item: any) => { + const qNorm = String(item.question ?? '').replace(/\s+/g, '').toLowerCase(); + const hit = byId.get(String(item.question_id)) ?? byQuestion.get(qNorm); + if (!hit) return; // AI 缺失项:保留人工回答 + if (item.answer !== null && item.answer !== undefined) { + keptManual += 1; // 已有人工判定不覆盖 + return; + } + const ans = hit.ans === '是' ? 1 : hit.ans === '否' ? 0 : hit.ans === 'NA' ? 2 : null; + if (ans === null) return; + item.answer = ans; + if (ans === 1) { + item.risk_desc = hit.risk ?? ''; + item.control_measure = hit.measure ?? ''; + } else { + // 否/NA:两字段清空 + item.risk_desc = ''; + item.control_measure = ''; + } + filled += 1; + }); + }); + // 过滤视图下同步显示 + if (riskFilter.value !== -1) filterChange(riskFilter.value); + if (!silent) { + window.$message?.success(`AI 已判定 ${filled} 项${keptManual ? `(保留人工判定 ${keptManual} 项)` : ''},正在自动保存…`); + } + // 自动保存换取真实 ID(入表前置条件) + await save(); + } catch (e: any) { + // 后台失败静默(单项重试入口在插件内) + if (e instanceof AiError) window.$message?.warning(`AI 自动分析失败:${e.message},可手动判定`); + else window.$message?.warning('AI 自动分析失败,可手动判定'); + } finally { analyzing.value = false; - }, 1000); + } }; // 获取风险检查表详情 @@ -167,16 +173,21 @@ const getRiskCheckDetail = async () => { const {data,error} = await riskCheckDetailApi(props.currentId); if(!error){ if(data.length){ - riskGroups.value = data; + allGroups.value = data; }else{ - riskGroups.value = RISK_CHECKS_INIT; + allGroups.value = cloneTemplate(); } + // 详情刷新后保持当前过滤视图 + if (riskFilter.value !== -1) filterChange(riskFilter.value); + else riskGroups.value = allGroups.value; } loading.value = false; } onMounted(() => { getRiskCheckDetail(); }) + +defineExpose({ runAi })