Pārlūkot izejas kodu

三级校审ai助手

Alex 1 dienu atpakaļ
vecāks
revīzija
34c25dd7cf
24 mainītis faili ar 3768 papildinājumiem un 5 dzēšanām
  1. 98 0
      docs/sql/addsql/20261124_ai-audit.sql
  2. 102 1
      docs/sql/fullsql/20261113.sql
  3. 1357 0
      docs/设计方案/校审ai助手/校审AI助手整体设计方案.md
  4. 113 0
      docs/设计方案/校审ai助手/校审意见生成助手-系统提示词.md
  5. 159 0
      docs/设计方案/知识助手/知识助手整体设计方案.md
  6. 5 0
      jeeplus-modules/jeeplus-assess/pom.xml
  7. 470 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/client/WeKnoraAgentClient.java
  8. 28 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/config/ProgramAuditAiAsyncConfig.java
  9. 53 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/config/WeKnoraAiAuditProperties.java
  10. 58 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/controller/ProgramAuditAiController.java
  11. 88 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/domain/ProgramAuditAiGeneration.java
  12. 50 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/domain/ProgramAuditAiGenerationFile.java
  13. 9 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/mapper/ProgramAuditAiGenerationFileMapper.java
  14. 9 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/mapper/ProgramAuditAiGenerationMapper.java
  15. 514 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/service/ProgramAuditAiAsyncService.java
  16. 436 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/service/ProgramAuditAiService.java
  17. 26 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/service/dto/AiAttachmentDTO.java
  18. 23 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/service/dto/AiGenerateReqDTO.java
  19. 21 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/service/dto/AiGenerateRespDTO.java
  20. 49 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/service/dto/AiGenerationStatusDTO.java
  21. 31 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/support/ProgramAuditAiException.java
  22. 1 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/workContract/mapper/xml/WorkContractInfoMapper.xml
  23. 34 2
      jeeplus-modules/jeeplus-assess/src/main/resources/application-assess-development.yml
  24. 34 2
      jeeplus-modules/jeeplus-assess/src/main/resources/application-assess-production.yml

+ 98 - 0
docs/sql/addsql/20261124_ai-audit.sql

@@ -0,0 +1,98 @@
+-- 校审 AI 助手:生成记录与附件快照
+-- 手工在目标库执行,仓库无迁移框架。
+--
+
+CREATE TABLE IF NOT EXISTS `program_audit_ai_generation` (
+    `id`                  varchar(64)  NOT NULL COMMENT '主键 UUID',
+    `program_id`          varchar(64)  NOT NULL COMMENT '项目ID',
+    `audit_id`            varchar(64)           DEFAULT NULL COMMENT '当前校审记录ID,可为空',
+    `audit_level`         varchar(32)  NOT NULL DEFAULT '' COMMENT '校审级别:一级/二级/三级',
+    `operator_id`         varchar(64)           DEFAULT NULL COMMENT '发起人生成记录时的用户ID',
+    `operator_name`       varchar(128)          DEFAULT NULL COMMENT '发起人姓名',
+    `status`              varchar(16)  NOT NULL DEFAULT 'running' COMMENT 'running/success/partial/failed/cancelled',
+    `detail_content`      longtext              DEFAULT NULL COMMENT '明细表 AI 草稿',
+    `report_content`      longtext              DEFAULT NULL COMMENT '评估报告 AI 草稿',
+    `remarks_content`     longtext              DEFAULT NULL COMMENT '技术说明 AI 草稿',
+    `work_content`        longtext              DEFAULT NULL COMMENT '工作底稿 AI 草稿',
+    `detail_status`       varchar(16)           DEFAULT NULL COMMENT 'generated/skipped/failed',
+    `report_status`       varchar(16)           DEFAULT NULL COMMENT 'generated/skipped/failed',
+    `remarks_status`      varchar(16)           DEFAULT NULL COMMENT 'generated/skipped/failed',
+    `work_status`         varchar(16)           DEFAULT NULL COMMENT 'generated/skipped/failed',
+    `result_json`         longtext              DEFAULT NULL COMMENT '校审 Agent 返回的原始 JSON',
+    `weknora_session_id`  varchar(64)           DEFAULT NULL COMMENT '本次 WeKnora 会话ID',
+    `weknora_agent_id`    varchar(64)           DEFAULT NULL COMMENT '校审 Agent ID',
+    `file_count`          int          NOT NULL DEFAULT 0 COMMENT '本次文件数量',
+    `error_code`          varchar(64)           DEFAULT NULL COMMENT '错误码',
+    `error_message`       varchar(1000)         DEFAULT NULL COMMENT '错误信息',
+    `started_at`          datetime              DEFAULT NULL COMMENT '开始时间',
+    `finished_at`         datetime              DEFAULT NULL COMMENT '结束时间',
+    `duration_ms`         bigint                DEFAULT NULL COMMENT '耗时毫秒',
+    `create_by_id`        varchar(64)           DEFAULT NULL,
+    `create_time`         datetime              DEFAULT NULL,
+    `update_by_id`        varchar(64)           DEFAULT NULL,
+    `update_time`         datetime              DEFAULT NULL,
+    `del_flag`            int                   DEFAULT 0,
+    `tenant_id`           varchar(64)           DEFAULT '10000',
+    PRIMARY KEY (`id`),
+    KEY `idx_paig_program_audit` (`program_id`, `audit_id`, `create_time`),
+    KEY `idx_paig_status` (`status`, `create_time`),
+    KEY `idx_paig_operator` (`operator_id`, `create_time`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='校审 AI 生成记录';
+
+
+CREATE TABLE IF NOT EXISTS `program_audit_ai_generation_file` (
+   `id`                    varchar(64)  NOT NULL COMMENT '主键 UUID',
+    `generation_id`         varchar(64)  NOT NULL COMMENT '生成记录ID',
+    `attachment_id`         varchar(64)           DEFAULT NULL COMMENT 'work_attachment.id',
+    `file_name`             varchar(255) NOT NULL DEFAULT '' COMMENT '文件名',
+    `file_type`             varchar(32)  NOT NULL DEFAULT '' COMMENT 'pdf/doc/docx/xls/xlsx/txt/jpg/png',
+    `file_size`             bigint       NOT NULL DEFAULT 0 COMMENT '文件字节数',
+    `storage_path`          varchar(2000)         DEFAULT NULL COMMENT 'OSS object key',
+    `weknora_attachment_id` varchar(64)           DEFAULT NULL COMMENT 'WeKnora 会话附件ID',
+    `parse_status`          varchar(16)  NOT NULL DEFAULT 'processing' COMMENT 'uploaded/processing/ready/failed/skipped',
+    `parse_error`           varchar(1000)         DEFAULT NULL COMMENT '解析失败原因',
+    `page_count`            int                   DEFAULT NULL COMMENT '页数(可空)',
+    `sort_no`               int          NOT NULL DEFAULT 0 COMMENT '排序',
+    `create_by_id`          varchar(64)           DEFAULT NULL,
+    `create_time`           datetime              DEFAULT NULL,
+    `update_by_id`          varchar(64)           DEFAULT NULL,
+    `update_time`           datetime              DEFAULT NULL,
+    `del_flag`              int                   DEFAULT 0,
+    `tenant_id`             varchar(64)           DEFAULT '10000',
+    PRIMARY KEY (`id`),
+    KEY `idx_paigf_generation` (`generation_id`, `sort_no`),
+    KEY `idx_paigf_attachment` (`attachment_id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='校审 AI 生成附件快照';
+
+
+-- 按钮权限:校审 AI 生成。
+-- 挂在“项目登记”菜单下,权限标识与后端 @PreAuthorize 保持一致。
+INSERT INTO `sys_menu`
+(`id`, `parent_id`, `parent_ids`, `name`, `sort`, `href`, `target`, `icon`, `is_show`,
+ `permission`, `create_time`, `del_flag`, `menu_type`, `tenant_id`, `code`, `hidden_breadcrumb`)
+SELECT '2026112412000000001',
+       '1574716304741044226',
+       '0,1,1573209906643443714,1574716304741044226,',
+       'AI生成校审意见',
+       360,
+       '',
+       '',
+       '',
+       '0',
+       'assess:programAudit:aiGenerate',
+       NOW(),
+       0,
+       '2',
+       '10000',
+       '',
+       '0'
+FROM DUAL
+WHERE NOT EXISTS (
+    SELECT 1 FROM `sys_menu` WHERE `permission` = 'assess:programAudit:aiGenerate'
+);
+
+-- 给已有“项目登记-修改”权限的角色同步授予 AI 生成权限。
+INSERT IGNORE INTO `sys_role_menu` (`role_id`, `menu_id`, `tenant_id`)
+SELECT rm.`role_id`, '2026112412000000001', rm.`tenant_id`
+FROM `sys_role_menu` rm
+WHERE rm.`menu_id` = '1574716607968251905';

+ 102 - 1
docs/sql/fullsql/20261113.sql

@@ -67,4 +67,105 @@ CREATE TABLE IF NOT EXISTS `material_boweiyun_save_data` (
     UNIQUE KEY `uk_mbysd_period` (`site_code`, `mode_code`, `particular_year`, `time_version`),
     UNIQUE KEY `uk_mbysd_file` (`file_name`),
     KEY `idx_mbysd_year` (`particular_year`, `time_version`)
-    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='博微电力价格已入库期数登记';
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='博微电力价格已入库期数登记';
+
+
+
+-- 校审 AI 助手:生成记录与附件快照
+-- 手工在目标库执行,仓库无迁移框架。
+--
+
+CREATE TABLE IF NOT EXISTS `program_audit_ai_generation` (
+                                                             `id`                  varchar(64)  NOT NULL COMMENT '主键 UUID',
+    `program_id`          varchar(64)  NOT NULL COMMENT '项目ID',
+    `audit_id`            varchar(64)           DEFAULT NULL COMMENT '当前校审记录ID,可为空',
+    `audit_level`         varchar(32)  NOT NULL DEFAULT '' COMMENT '校审级别:一级/二级/三级',
+    `operator_id`         varchar(64)           DEFAULT NULL COMMENT '发起人生成记录时的用户ID',
+    `operator_name`       varchar(128)          DEFAULT NULL COMMENT '发起人姓名',
+    `status`              varchar(16)  NOT NULL DEFAULT 'running' COMMENT 'running/success/partial/failed/cancelled',
+    `detail_content`      longtext              DEFAULT NULL COMMENT '明细表 AI 草稿',
+    `report_content`      longtext              DEFAULT NULL COMMENT '评估报告 AI 草稿',
+    `remarks_content`     longtext              DEFAULT NULL COMMENT '技术说明 AI 草稿',
+    `work_content`        longtext              DEFAULT NULL COMMENT '工作底稿 AI 草稿',
+    `detail_status`       varchar(16)           DEFAULT NULL COMMENT 'generated/skipped/failed',
+    `report_status`       varchar(16)           DEFAULT NULL COMMENT 'generated/skipped/failed',
+    `remarks_status`      varchar(16)           DEFAULT NULL COMMENT 'generated/skipped/failed',
+    `work_status`         varchar(16)           DEFAULT NULL COMMENT 'generated/skipped/failed',
+    `result_json`         longtext              DEFAULT NULL COMMENT '校审 Agent 返回的原始 JSON',
+    `weknora_session_id`  varchar(64)           DEFAULT NULL COMMENT '本次 WeKnora 会话ID',
+    `weknora_agent_id`    varchar(64)           DEFAULT NULL COMMENT '校审 Agent ID',
+    `file_count`          int          NOT NULL DEFAULT 0 COMMENT '本次文件数量',
+    `error_code`          varchar(64)           DEFAULT NULL COMMENT '错误码',
+    `error_message`       varchar(1000)         DEFAULT NULL COMMENT '错误信息',
+    `started_at`          datetime              DEFAULT NULL COMMENT '开始时间',
+    `finished_at`         datetime              DEFAULT NULL COMMENT '结束时间',
+    `duration_ms`         bigint                DEFAULT NULL COMMENT '耗时毫秒',
+    `create_by_id`        varchar(64)           DEFAULT NULL,
+    `create_time`         datetime              DEFAULT NULL,
+    `update_by_id`        varchar(64)           DEFAULT NULL,
+    `update_time`         datetime              DEFAULT NULL,
+    `del_flag`            int                   DEFAULT 0,
+    `tenant_id`           varchar(64)           DEFAULT '10000',
+    PRIMARY KEY (`id`),
+    KEY `idx_paig_program_audit` (`program_id`, `audit_id`, `create_time`),
+    KEY `idx_paig_status` (`status`, `create_time`),
+    KEY `idx_paig_operator` (`operator_id`, `create_time`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='校审 AI 生成记录';
+
+
+CREATE TABLE IF NOT EXISTS `program_audit_ai_generation_file` (
+    `id`                    varchar(64)  NOT NULL COMMENT '主键 UUID',
+    `generation_id`         varchar(64)  NOT NULL COMMENT '生成记录ID',
+    `attachment_id`         varchar(64)           DEFAULT NULL COMMENT 'work_attachment.id',
+    `file_name`             varchar(255) NOT NULL DEFAULT '' COMMENT '文件名',
+    `file_type`             varchar(32)  NOT NULL DEFAULT '' COMMENT 'pdf/doc/docx/xls/xlsx/txt/jpg/png',
+    `file_size`             bigint       NOT NULL DEFAULT 0 COMMENT '文件字节数',
+    `storage_path`          varchar(2000)         DEFAULT NULL COMMENT 'OSS object key',
+    `weknora_attachment_id` varchar(64)           DEFAULT NULL COMMENT 'WeKnora 会话附件ID',
+    `parse_status`          varchar(16)  NOT NULL DEFAULT 'processing' COMMENT 'uploaded/processing/ready/failed/skipped',
+    `parse_error`           varchar(1000)         DEFAULT NULL COMMENT '解析失败原因',
+    `page_count`            int                   DEFAULT NULL COMMENT '页数(可空)',
+    `sort_no`               int          NOT NULL DEFAULT 0 COMMENT '排序',
+    `create_by_id`          varchar(64)           DEFAULT NULL,
+    `create_time`           datetime              DEFAULT NULL,
+    `update_by_id`          varchar(64)           DEFAULT NULL,
+    `update_time`           datetime              DEFAULT NULL,
+    `del_flag`              int                   DEFAULT 0,
+    `tenant_id`             varchar(64)           DEFAULT '10000',
+    PRIMARY KEY (`id`),
+    KEY `idx_paigf_generation` (`generation_id`, `sort_no`),
+    KEY `idx_paigf_attachment` (`attachment_id`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='校审 AI 生成附件快照';
+
+
+-- 按钮权限:校审 AI 生成。
+-- 挂在“项目登记”菜单下,权限标识与后端 @PreAuthorize 保持一致。
+INSERT INTO `sys_menu`
+(`id`, `parent_id`, `parent_ids`, `name`, `sort`, `href`, `target`, `icon`, `is_show`,
+ `permission`, `create_time`, `del_flag`, `menu_type`, `tenant_id`, `code`, `hidden_breadcrumb`)
+SELECT '2026112412000000001',
+       '1574716304741044226',
+       '0,1,1573209906643443714,1574716304741044226,',
+       'AI生成校审意见',
+       360,
+       '',
+       '',
+       '',
+       '0',
+       'assess:programAudit:aiGenerate',
+       NOW(),
+       0,
+       '2',
+       '10000',
+       '',
+       '0'
+FROM DUAL
+WHERE NOT EXISTS (
+    SELECT 1 FROM `sys_menu` WHERE `permission` = 'assess:programAudit:aiGenerate'
+);
+
+-- 给已有“项目登记-修改”权限的角色同步授予 AI 生成权限。
+INSERT IGNORE INTO `sys_role_menu` (`role_id`, `menu_id`, `tenant_id`)
+SELECT rm.`role_id`, '2026112412000000001', rm.`tenant_id`
+FROM `sys_role_menu` rm
+WHERE rm.`menu_id` = '1574716607968251905';

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 1357 - 0
docs/设计方案/校审ai助手/校审AI助手整体设计方案.md


+ 113 - 0
docs/设计方案/校审ai助手/校审意见生成助手-系统提示词.md

@@ -0,0 +1,113 @@
+# 校审意见生成助手 系统提示词(线上版本)
+
+> 本文与 WeKnora 线上“校审意见生成助手”的系统提示词保持一致,更新日期 2026-11-24。本文件用于版本留档,线上生效以 WeKnora 配置为准。
+
+你是“资产评估项目三级校审意见生成器”。你只生成校审意见草稿,不审批、不改变流程状态、不写“同意/驳回”结论。
+
+用户消息会包含:
+- 项目 ID、校审级别、校审记录 ID
+- 本次附件清单
+- image_texts:前置图片解析助手把图片、扫描页转成的结构化文字
+- 本会话附件内容:Word、PDF、Excel 等文件或其解析文本
+
+字段固定为:
+- detail = 明细表审核意见
+- report = 评估报告审核意见
+- remarks = 技术说明审核意见
+- work = 工作底稿审核意见
+
+一、读取与判断规则
+1. 必须读取本会话全部附件内容,不得只看文件名或附件清单;图片内容以 image_texts 为准,不要假设自己还能看到原图,也不要要求用户再提供图片附件。
+2. 只使用输入资料、image_texts 和知识库中的公开准则;不得编造项目事实、金额、日期、编号、签字、页码、附件名称。
+3. 固定输出 detail、report、remarks、work 四段,每段 status 只能是 generated、skipped、failed:
+   - 有可用资料并能形成该段意见时,status 填 generated,content 写正式校审意见;
+   - 没有可用资料、无法形成该段意见时,status 填 skipped,content 直接写清楚缺少哪些文件、哪类资料,以及因此无法审核什么;
+   - 有资料但读取、解析或生成过程中出错,无法形成该段意见时,status 填 failed,content 直接写清楚发生了什么错误,以及因此无法形成意见的原因。
+4. 不再输出 reason 字段。只要 status 不是 generated,原因全部写进 content;content 不能留空,不能只写“资料不足”或“生成失败”,必须写清楚是缺文件还是出错,缺什么、错在哪里。
+5. 不再输出 coverage_mode、coverage_note,也不要输出任何覆盖率、覆盖范围字段。该段仍能生成但资料不完整时,把缺失资料作为 issue 写入 content 和 issues,status 仍填 generated。
+6. 逐项检查不等于逐项输出。只输出实际发现的问题;核对相符的检查项不写入 issues,不得为了凑条数编造问题。
+7. 同一数据在不同资料中冲突时,写“需复核”,并列明两处来源,不得自行选定其中一个。
+8. 无法判断字体、字号、打印边界等版式问题时,不要臆断;只有输入材料能明确显示版式异常时才输出。
+
+二、审核要点
+【detail 明细表】
+1. 被评估单位名称、产权持有人是否与评估报告中的相应名称一致。
+2. 各明细表页脚是否填写齐全。
+3. 万元汇总表内部同列纵向相加是否相符,是否存在尾数错误;同行横向相减、勾稽关系是否相符。
+4. 万元汇总表增值率与分类汇总表是否相符。
+5. 分类汇总表账面值与审计报表是否相符;审计报表未提供时标注资料缺失,不得假定。
+6. 分类汇总表评估值与各明细表是否相符,并反查其他汇总表是否存在链接错误。
+7. 各明细表评估值的汇总公式是否漏汇总项。
+8. 各表字体字号是否一致,打印边界是否调整,表格整体是否美观;仅在可读取版式或页面图像时判断。
+9. 其他问题。
+
+【report 评估报告】
+1. 封面标题与目录、评估师声明、摘要、正文、附件是否一致。
+2. 封面报告日期与报告正文最后一项、签字评估师承诺函日期是否一致。
+3. 目录页码与各部分内容是否一致。
+4. 页眉页脚与各部分内容是否一致。
+5. 摘要、正文中的委托人、被评估单位全称、简称是否一致。
+6. 摘要与正文措辞、口径是否一致;评估基准日与明细表是否一致且正确。
+7. 摘要文字中的评估值、账面值、增值率与汇总表是否一致;摘要汇总表与正文相关数据是否一致。
+8. 委托人、被评估单位全称、简称是否一致,是否出现无关单位名称。
+9. 被评估单位近几年财务状况数据与“关于评估有关事宜说明”是否一致,基准日口径是否一致。
+10. 评估范围账面值与分类汇总表是否一致。
+11. 评估基准日是否正确,并与明细表一致。
+12. 评估结论文字中的评估值、账面值、增值率与汇总表是否一致;结论汇总表与正文是否一致。
+13. 特别事项说明中有数据描述的内容与明细表是否相符。
+14. 其他问题。
+
+【remarks 技术说明】
+- 核对技术说明与评估报告、明细表在评估对象、评估范围、评估方法、关键参数、计算过程、评估结论和特别事项上是否一致。
+- 核对引用的准则、依据、参数来源是否完整;发现缺少依据或前后矛盾时输出。
+- 用户未提供专项审核清单时,只按资料实际内容审查,不得硬套报告清单。
+
+【work 工作底稿】
+- 核对工作底稿与报告、明细表在项目名称、评估基准日、资产范围、数量、金额、成新率、计算过程、签字及日期上是否一致。
+- 核对附件清单、现场勘查记录、询价记录、权属资料等是否完整、可追溯。
+- 用户未提供专项审核清单时,只按资料实际内容审查,不得硬套报告清单。
+
+三、问题与引用
+- severity:high 表示金额、日期、主体名称、评估结论等实质性矛盾;medium 表示汇总勾稽、跨章节引用、附件或依据缺失;low 表示字体字号、措辞、版式美观。
+- citation:Excel 写“文件名/工作表/行号或单元格区域”;PDF/Word 写“文件名/页码或章节”;图片写“image_texts 的 file_name/page”;跨文件问题同时列出两处来源。
+- issues 中每条问题都要有 title、description、severity、citation;content 用正式中文概述问题,和 issues 对应,不写思考过程。
+
+四、输出要求
+- 每段都必须有 content。status=generated 时,content 是正式校审意见;status=skipped 或 failed 时,content 是未生成的原因说明,不能留空。
+- 每段按实际发现写,不强制字数和问题条数;没有发现问题的段落,content 写“经审核,未发现明显问题”,issues 为空数组。
+- 只输出 status、content、issues、citations 四个字段;不要输出 reason、coverage_mode、coverage_note 或其他字段。
+- content 用纯文本,段落用 \n\n 分隔;不要输出 HTML,不要输出 Markdown 代码块。
+- 只输出一个 JSON 对象,不要输出 JSON 之外的任何文字。四段的 issues 数组元素结构相同;下面 detail 中的对象是示例,其他段有问题时按同一结构填写。结构如下:
+{
+  "detail": {
+    "status": "generated|skipped|failed",
+    "content": "",
+    "issues": [
+      {
+        "title": "",
+        "description": "",
+        "severity": "high|medium|low",
+        "citation": ""
+      }
+    ],
+    "citations": []
+  },
+  "report": {
+    "status": "generated|skipped|failed",
+    "content": "",
+    "issues": [],
+    "citations": []
+  },
+  "remarks": {
+    "status": "generated|skipped|failed",
+    "content": "",
+    "issues": [],
+    "citations": []
+  },
+  "work": {
+    "status": "generated|skipped|failed",
+    "content": "",
+    "issues": [],
+    "citations": []
+  }
+}

+ 159 - 0
docs/设计方案/知识助手/知识助手整体设计方案.md

@@ -0,0 +1,159 @@
+# 知识助手(WeKnora Embed)设计方案
+
+> 一句话:把 WeKnora 知识库智能体嵌进评估系统的右上角面板,**后端只管发牌和记账,问答流量不进本系统**。
+
+---
+
+## 1. 目标与范围
+
+| 要做 | 不做 |
+|---|---|
+| 在系统内直接问「评估知识助手」,带引用出处 | 不做第二个聊天页面,不做知识库管理页 |
+| 按角色控制「谁能用」和「能用哪个渠道」 | 不把问答正文落库 |
+| 记录谁在什么时候用过(合规审计) | 不代理问答流量(不转发 SSE) |
+
+渠道清单由配置驱动(Nacos),不入库、不做后台维护界面。
+
+---
+
+## 2. 总体架构
+
+```
+浏览器
+ ├─ 右上角按钮 → 面板(Vue 组件,自建 iframe 宿主壳)
+ │    ├─ GET /aiAssistant/channels  → 渠道目录(不含令牌)
+ │    ├─ GET /aiAssistant/token     → 短期票 ems_
+ │    └─ iframe 直连 WeKnora ────────→ 问答 / SSE 流式输出
+ └─ 后端(jeeplus-assess)
+      ├─ 渠道目录:读配置 + 权限过滤
+      ├─ 发牌:em_ → ems_(唯一的外部 HTTP 出口)
+      └─ 审计:写 ai_assistant_access
+```
+
+要点:**瘦后端 + iframe 直连**。后端只做三件事(目录、发牌、记账),回答内容全程不经过本系统。
+
+---
+
+## 3. 代码位置
+
+| 端 | 位置 |
+|---|---|
+| 后端模块 | `jeeplus-assess/src/main/java/com/jeeplus/assess/aiAssistant/` |
+| ├ controller | `AiAssistantController`(channels / token / accessList) |
+| ├ service | `AiAssistantChannelService`(目录、发牌、渠道鉴权)、`AiAssistantAccessService`(使用记录) |
+| ├ client | `WeKnoraEmbedClient`(换票,模块内唯一外部 HTTP 出口) |
+| └ config | `WeKnoraProperties`(绑定 `weknora.*`) |
+| 前端 | `src/api/aiAssistant/`、`src/layout/components/aiAssistant.vue` |
+| 表 | `ai_assistant_access` |
+
+---
+
+## 4. 接口
+
+| 接口 | 方法 | 作用 | 说明 |
+|---|---|---|---|
+| `/aiAssistant/channels` | GET | 返回当前用户可见的渠道列表 | 纯内存计算,不查库、不打 WeKnora;剔除 `publishToken` |
+| `/aiAssistant/token` | GET | 用 `em_` 换 `ems_` | 服务端二次校验渠道权限;返回 `sessionToken` + `expiresIn` |
+| `/aiAssistant/accessList` | GET | 我的使用记录 | 按日期区间查询 |
+
+权限两层:
+
+- 总开关 `ai:assistant:use`
+- 渠道级 `ai:assistant:{code}`(如 `ai:assistant:assessKb`)
+
+前端传的 `channelCode` 只用于选择,**授权一律以服务端校验为准**。
+
+---
+
+## 5. 令牌模型(关键约束)
+
+| 令牌 | 谁持有 | 寿命 | 用途 |
+|---|---|---|---|
+| `em_` 发布令牌 | **仅后端**(Nacos 配置) | 长期 | 调 WeKnora 换票接口,绝不能下发浏览器 |
+| `ems_` 会话令牌 | iframe(浏览器内存/请求头) | **1800 秒** | iframe 直连问答接口 |
+
+WeKnora 的 embed 页首次引导成功后会锁住内部标志位,**后续再推新票会被忽略**,所以「到期前续票」这条路无效——票一过期只能**销毁 iframe 重建**。
+
+面板的处理策略(`aiAssistant.vue`):
+
+- 每 30 秒查一次票龄;
+- 到 92%(约 27.5 分钟)且用户已静默 60 秒 → 静默重连;
+- 已到 100% → 立即重连;
+- 切回前台 / 窗口重新获得焦点时补查一次(后台标签页定时器会被节流)。
+
+代价:重连等于换一个新 iframe,滚动位置与未发送草稿会丢;对话能否续上取决于 WeKnora 侧旧会话是否还活着。
+
+---
+
+## 6. 面板交互
+
+| 能力 | 实现要点 |
+|---|---|
+| 打开/关闭 | 关闭只隐藏不销毁 iframe,回来还是原会话 |
+| 拖拽缩放 | 右边缘固定,只给左边缘(调宽)、底边(调高)、左下角(同调,双击复原);下限 320×380,上限视口减留白 |
+| 尺寸记忆 | localStorage `APP_AI_SIZE`,不写库 |
+| 最大化 | 四边贴 0(inset)铺满视口,去掉圆角和 `max-height`;再点还原为最大化前的尺寸(没拖过则回 CSS 默认 420×620) |
+| 遮罩 | 拖拽期间铺全屏透明层,防止 iframe 吃掉 `mousemove` |
+
+---
+
+## 7. 配置(Nacos:namespace=pro,data-id `jeeplus-assess.yml`)
+
+```yaml
+weknora:
+  base-url: http://192.168.8.136        # 换票地址 + iframe 页面地址的共同前缀,浏览器必须可达
+  allowed-origin: http://localhost:2800 # 后端换票时手写的 Origin,必须命中 WeKnora 白名单
+  access-retention-days: 180            # 使用记录保留天数
+  channels:
+    - code: assessKb                    # 渠道编码,对应权限 ai:assistant:assessKb
+      name: 评估知识助手
+      channel-id: 8a27...               # WeKnora 渠道 ID,决定 /embed/{channelId} 与 API 路径
+      agent-id: dcab...                 # WeKnora 智能体 ID
+      publish-token: em_...             # 长期发布令牌,仅后端持有
+      sort: 10                          # 下拉排序
+      is-default: true                  # 默认选中
+      page-title: 评估知识助手           # 面板标题
+```
+
+---
+
+## 8. 部署注意(踩过的坑)
+
+**三个源不是一回事**,白名单只认第三个:
+
+| 源 | 是什么 |
+|---|---|
+| 宿主源 | 用户浏览器打开的业务系统地址,如 `http://47.110.234.14` |
+| 后端手写 Origin | `allowed-origin` 配置值,只影响 `/token` 换票 |
+| **iframe 自身源** | `base-url` 的 origin,**WeKnora 白名单必须包含它** |
+
+iframe 页面同源加载时不带 Origin,WeKnora 会退化为用 **Referer** 判定,所以白名单必须覆盖用户实际访问 iframe 的那个地址(含端口)。缺了就是 403 `origin not allowed`。
+
+其他:
+
+- `em_` 已在历史对话中暴露过,需在 WeKnora 后台轮换后只回写 Nacos;
+- 生产环境后端地址若经端口映射(如 `183.212.233.18:13680`),该地址也要进白名单。
+
+---
+
+## 9. 审计与隐私
+
+`ai_assistant_access` 只记:
+
+```
+user_id / user_name / channel_code / channel_id / remote_addr / create_time
+```
+
+**不存问答正文、不存 (sessionId, sig)**,因此系统里不存在「某个员工的个人问答档案」。问答内容的责任边界留在 WeKnora 侧。
+
+---
+
+## 10. 已知限制 / 待办
+
+| 项 | 现状 |
+|---|---|
+| 30 分钟硬过期 | 只能靠重建 iframe 解决;根治需 WeKnora 支持「只换票不重载」 |
+| 重连丢草稿 | 未做草稿保存/回填 |
+| 回答中重连 | 未判断「是否正在流式输出」,极端情况下会打断长回答 |
+| 渠道维护 | 只能改 Nacos,无管理界面 |
+| 沙箱开关 | `AI_SANDBOX=false`(同机换人可能续上上一个人的会话,已按业务决定接受) |

+ 5 - 0
jeeplus-modules/jeeplus-assess/pom.xml

@@ -113,6 +113,11 @@
             <artifactId>spring-boot-starter-freemarker</artifactId>
             <version>${spring.boot.version}</version>
         </dependency>
+        <dependency>
+            <groupId>org.apache.httpcomponents</groupId>
+            <artifactId>httpmime</artifactId>
+            <version>4.5.13</version>
+        </dependency>
     </dependencies>
 
     <build>

+ 470 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/client/WeKnoraAgentClient.java

@@ -0,0 +1,470 @@
+package com.jeeplus.assess.programAuditAi.client;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.jeeplus.assess.programAuditAi.config.WeKnoraAiAuditProperties;
+import com.jeeplus.assess.programAuditAi.support.ProgramAuditAiException;
+import lombok.Data;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.HttpEntity;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.ContentType;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.entity.mime.HttpMultipartMode;
+import org.apache.http.entity.mime.MultipartEntityBuilder;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * WeKnora Agent API 客户端。
+ *
+ */
+@Slf4j
+@Component
+public class WeKnoraAgentClient {
+
+    private static final String HEADER_API_KEY = "X-API-Key";
+    private static final int ERROR_BODY_LOG_LIMIT = 300;
+
+    @Resource
+    private WeKnoraAiAuditProperties properties;
+
+    public String createSession(String title) {
+        String url = baseUrl() + "/api/v1/sessions";
+        JSONObject body = new JSONObject();
+        body.put("title", StringUtils.left(StringUtils.defaultIfBlank(title, "校审AI生成"), 128));
+        JSONObject root = postJson(url, body.toJSONString(), connectTimeout(), readTimeout());
+        JSONObject data = dataObject(root);
+        String id = stringOf(data, "id", "session_id");
+        if (StringUtils.isBlank(id)) {
+            throw new ProgramAuditAiException("WEKNORA_SESSION_FAILED", "WeKnora 建会话失败:响应缺少 session id", HttpStatus.BAD_GATEWAY);
+        }
+        return id;
+    }
+
+    public AttachmentResult uploadAttachment(String sessionId, String fileName, byte[] bytes, String agentId) {
+        if (StringUtils.isBlank(sessionId)) {
+            throw new ProgramAuditAiException("WEKNORA_SESSION_FAILED", "WeKnora 会话为空", HttpStatus.BAD_GATEWAY);
+        }
+        if (bytes == null || bytes.length == 0) {
+            throw new ProgramAuditAiException("EMPTY_FILE", "附件内容为空:" + fileName);
+        }
+        String url = baseUrl() + "/api/v1/sessions/" + sessionId + "/attachments";
+        try (CloseableHttpClient client = HttpClients.createDefault()) {
+            HttpPost post = new HttpPost(url);
+            post.setHeader(HEADER_API_KEY, apiKey());
+            post.setConfig(timeoutConfig(connectTimeout(), readTimeout()));
+
+            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
+            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
+            builder.setCharset(StandardCharsets.UTF_8);
+            builder.addBinaryBody("file", bytes, ContentType.APPLICATION_OCTET_STREAM, fileName);
+            if (StringUtils.isNotBlank(agentId)) {
+                builder.addTextBody("agent_id", agentId, ContentType.TEXT_PLAIN);
+            }
+            post.setEntity(builder.build());
+
+            long begin = System.currentTimeMillis();
+            try (CloseableHttpResponse response = client.execute(post)) {
+                int status = response.getStatusLine().getStatusCode();
+                String responseBody = response.getEntity() == null ? "" : EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
+                if (status != 200 && status != 201 && status != 202) {
+                    log.warn("WeKnora 上传附件失败 status={} file={} body={}", status, fileName, leftForLog(responseBody));
+                    throw new ProgramAuditAiException("WEKNORA_UPLOAD_FAILED", "WeKnora 上传附件失败:" + fileName, HttpStatus.BAD_GATEWAY);
+                }
+                JSONObject root = JSON.parseObject(responseBody);
+                JSONObject data = dataObject(root);
+                AttachmentResult result = new AttachmentResult();
+                result.setId(stringOf(data, "id", "attachment_id"));
+                result.setStatus(stringOf(data, "status", "parse_status"));
+                result.setFileName(stringOf(data, "file_name", "name"));
+                log.info("WeKnora 上传附件成功 file={} attachmentId={} status={} cost={}ms",
+                        fileName, result.getId(), result.getStatus(), System.currentTimeMillis() - begin);
+                return result;
+            }
+        } catch (ProgramAuditAiException e) {
+            throw e;
+        } catch (Exception e) {
+            throw new ProgramAuditAiException("WEKNORA_UPLOAD_FAILED", "WeKnora 上传附件异常:" + fileName + "," + e.getMessage(), HttpStatus.BAD_GATEWAY);
+        }
+    }
+
+    /**
+     * 等待附件解析完成。WeKnora 上传接口返回 202,解析是异步的。
+     */
+    public AttachmentResult waitAttachmentReady(String sessionId, String attachmentId) {
+        if (StringUtils.isBlank(sessionId) || StringUtils.isBlank(attachmentId)) {
+            throw new ProgramAuditAiException("WEKNORA_UPLOAD_FAILED", "附件会话或附件ID为空", HttpStatus.BAD_GATEWAY);
+        }
+        String url = baseUrl() + "/api/v1/sessions/" + sessionId + "/attachments/" + attachmentId;
+        long deadline = System.currentTimeMillis() + 120000L;
+        while (System.currentTimeMillis() < deadline) {
+            JSONObject root = getJson(url);
+            JSONObject data = dataObject(root);
+            AttachmentResult result = new AttachmentResult();
+            result.setId(stringOf(data, "id", "attachment_id"));
+            result.setStatus(stringOf(data, "status", "parse_status"));
+            result.setFileName(stringOf(data, "file_name", "name"));
+            String status = StringUtils.lowerCase(StringUtils.defaultString(result.getStatus()));
+            if ("ready".equals(status) || "processed".equals(status)
+                    || "completed".equals(status) || "success".equals(status)) {
+                return result;
+            }
+            if ("failed".equals(status) || "error".equals(status)) {
+                throw new ProgramAuditAiException("ATTACHMENT_PARSE_FAILED",
+                        "WeKnora 附件解析失败:" + StringUtils.defaultString(result.getFileName()), HttpStatus.BAD_GATEWAY);
+            }
+            try {
+                Thread.sleep(1500L);
+            } catch (InterruptedException e) {
+                Thread.currentThread().interrupt();
+                throw new ProgramAuditAiException("AI_GENERATION_ABORTED", "等待附件解析被中断", HttpStatus.INTERNAL_SERVER_ERROR);
+            }
+        }
+        throw new ProgramAuditAiException("ATTACHMENT_PARSE_TIMEOUT", "等待附件解析超时", HttpStatus.BAD_GATEWAY);
+    }
+
+    /**
+     * 发一次 Agent 对话,返回完整 answer 文本。
+     */
+    public String chat(String sessionId, String query, String agentId, List<String> attachmentIds) {
+        if (StringUtils.isBlank(sessionId)) {
+            throw new ProgramAuditAiException("WEKNORA_SESSION_FAILED", "WeKnora 会话为空", HttpStatus.BAD_GATEWAY);
+        }
+        if (StringUtils.isBlank(agentId)) {
+            throw new ProgramAuditAiException("AGENT_NOT_CONFIGURED", "校审 Agent 未配置", HttpStatus.INTERNAL_SERVER_ERROR);
+        }
+        String url = baseUrl() + "/api/v1/agent-chat/" + sessionId;
+        JSONObject body = new JSONObject();
+        body.put("query", query);
+        body.put("agent_enabled", true);
+        body.put("agent_id", agentId);
+        body.put("channel", "api");
+        if (attachmentIds != null && !attachmentIds.isEmpty()) {
+            body.put("attachment_ids", attachmentIds);
+        }
+
+        long begin = System.currentTimeMillis();
+        StringBuilder answer = new StringBuilder();
+        AtomicBoolean completed = new AtomicBoolean(false);
+        try (CloseableHttpClient client = HttpClients.createDefault()) {
+            HttpPost post = new HttpPost(url);
+            post.setHeader(HEADER_API_KEY, apiKey());
+            post.setHeader("Accept", "text/event-stream");
+            post.setHeader("Content-Type", "application/json; charset=UTF-8");
+            post.setConfig(timeoutConfig(connectTimeout(), readTimeout()));
+            post.setEntity(new StringEntity(body.toJSONString(), StandardCharsets.UTF_8));
+
+            try (CloseableHttpResponse response = client.execute(post)) {
+                int status = response.getStatusLine().getStatusCode();
+                if (status != 200) {
+                    String responseBody = response.getEntity() == null ? "" : EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
+                    log.warn("WeKnora Agent 对话失败 status={} body={}", status, leftForLog(responseBody));
+                    throw new ProgramAuditAiException("WEKNORA_CHAT_FAILED", "WeKnora Agent 对话失败,HTTP " + status, HttpStatus.BAD_GATEWAY);
+                }
+                HttpEntity entity = response.getEntity();
+                if (entity == null) {
+                    throw new ProgramAuditAiException("WEKNORA_EMPTY_RESPONSE", "WeKnora Agent 未返回内容", HttpStatus.BAD_GATEWAY);
+                }
+                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), StandardCharsets.UTF_8));
+                String line;
+                StringBuilder dataBuffer = new StringBuilder();
+                while ((line = reader.readLine()) != null) {
+                    if (line.isEmpty()) {
+                        if (dataBuffer.length() > 0) {
+                            consumeSseFrame(dataBuffer.toString(), answer, completed);
+                            dataBuffer.setLength(0);
+                        }
+                        if (completed.get()) {
+                            break;
+                        }
+                        continue;
+                    }
+                    if (line.startsWith("data:")) {
+                        dataBuffer.append(line.substring(5).trim());
+                    }
+                    // event: 行不参与正文解析;type 以 data JSON 为准
+                }
+                if (dataBuffer.length() > 0) {
+                    consumeSseFrame(dataBuffer.toString(), answer, completed);
+                }
+            }
+        } catch (ProgramAuditAiException e) {
+            throw e;
+        } catch (Exception e) {
+            throw new ProgramAuditAiException("WEKNORA_CHAT_FAILED", "WeKnora Agent 调用异常:" + e.getMessage(), HttpStatus.BAD_GATEWAY);
+        }
+        log.info("WeKnora Agent 对话结束 session={} agent={} answerChars={} cost={}ms",
+                sessionId, agentId, answer.length(), System.currentTimeMillis() - begin);
+        if (StringUtils.isBlank(answer.toString())) {
+            throw new ProgramAuditAiException("WEKNORA_EMPTY_RESPONSE", "WeKnora Agent 未返回有效文本", HttpStatus.BAD_GATEWAY);
+        }
+        return answer.toString();
+    }
+
+    private void consumeSseFrame(String data, StringBuilder answer, AtomicBoolean completed) {
+        String text = StringUtils.trimToEmpty(data);
+        if (text.isEmpty() || "[DONE]".equals(text)) {
+            return;
+        }
+        JSONObject root;
+        try {
+            root = JSON.parseObject(text);
+        } catch (Exception e) {
+            // 少数实现可能直接回纯文本;没有 type 时按正文增量处理
+            appendDelta(answer, text);
+            return;
+        }
+        collect(root, answer, completed, 0);
+    }
+
+    /**
+     * 递归读取 WeKnora 的流式 JSON,兼容 response_type/type、data 嵌套等版本差异。
+     */
+    private void collect(JSONObject node, StringBuilder answer, AtomicBoolean completed, int depth) {
+        if (node == null || depth > 3) {
+            return;
+        }
+        String type = stringOf(node, "response_type", "type", "event_type", "event");
+        String normalized = StringUtils.lowerCase(StringUtils.defaultString(type));
+
+        if (normalized.contains("error")) {
+            String message = stringOf(node, "message", "error", "content");
+            throw new ProgramAuditAiException("WEKNORA_AGENT_ERROR",
+                    StringUtils.defaultIfBlank(message, "WeKnora Agent 返回错误"), HttpStatus.BAD_GATEWAY);
+        }
+
+        if (normalized.contains("complete") || normalized.contains("done") || normalized.contains("finish")) {
+            completed.set(true);
+        }
+
+        boolean answerType = normalized.isEmpty() || normalized.contains("answer") || normalized.contains("content");
+        if (answerType) {
+            String delta = extractText(node);
+            if (StringUtils.isBlank(delta)) {
+                JSONObject data = node.getJSONObject("data");
+                if (data != null) {
+                    delta = extractText(data);
+                }
+            }
+            appendDelta(answer, delta);
+        } else if (normalized.contains("complete") && answer.length() == 0) {
+            String finalText = extractText(node);
+            appendDelta(answer, finalText);
+        }
+
+        // 兼容 { "data": { ... } } 结构;但 answer 类型已经从 data 取过,避免重复
+        JSONObject data = node.getJSONObject("data");
+        if (data != null && data != node && !answerType) {
+            collect(data, answer, completed, depth + 1);
+        }
+        Object nested = node.get("data");
+        if (nested instanceof JSONArray) {
+            for (Object item : (JSONArray) nested) {
+                if (item instanceof JSONObject) {
+                    collect((JSONObject) item, answer, completed, depth + 1);
+                }
+            }
+        }
+    }
+
+    private String extractText(JSONObject node) {
+        if (node == null) {
+            return null;
+        }
+        Object content = node.get("content");
+        if (content instanceof String) {
+            return (String) content;
+        }
+        Object answer = node.get("answer");
+        if (answer instanceof String) {
+            return (String) answer;
+        }
+        if (answer instanceof JSONObject) {
+            Object nested = ((JSONObject) answer).get("content");
+            if (nested instanceof String) {
+                return (String) nested;
+            }
+        }
+        Object text = node.get("text");
+        if (text instanceof String) {
+            return (String) text;
+        }
+        Object delta = node.get("delta");
+        if (delta instanceof String) {
+            return (String) delta;
+        }
+        return null;
+    }
+
+    private void appendDelta(StringBuilder answer, String delta) {
+        if (StringUtils.isEmpty(delta)) {
+            return;
+        }
+        String current = answer.toString();
+        if (current.isEmpty()) {
+            answer.append(delta);
+            return;
+        }
+        // 有些实现会重复推完整答案;检测到“全量覆盖增量”时替换,避免正文翻倍
+        if (delta.length() > current.length() && delta.startsWith(current)) {
+            answer.setLength(0);
+            answer.append(delta);
+            return;
+        }
+        if (!current.endsWith(delta)) {
+            answer.append(delta);
+        }
+    }
+
+    private JSONObject getJson(String url) {
+        try (CloseableHttpClient client = HttpClients.createDefault()) {
+            HttpGet get = new HttpGet(url);
+            get.setHeader(HEADER_API_KEY, apiKey());
+            get.setHeader("Accept", "application/json");
+            get.setConfig(timeoutConfig(connectTimeout(), readTimeout()));
+            try (CloseableHttpResponse response = client.execute(get)) {
+                int status = response.getStatusLine().getStatusCode();
+                String body = response.getEntity() == null ? "" : EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
+                if (status != 200) {
+                    log.warn("WeKnora 查询失败 url={} status={} body={}", url, status, leftForLog(body));
+                    throw new ProgramAuditAiException("WEKNORA_REQUEST_FAILED", "WeKnora 查询失败,HTTP " + status, HttpStatus.BAD_GATEWAY);
+                }
+                JSONObject root = JSON.parseObject(body);
+                if (root != null && Boolean.FALSE.equals(root.getBoolean("success"))) {
+                    String message = stringOf(root, "message", "msg", "error");
+                    throw new ProgramAuditAiException("WEKNORA_REQUEST_FAILED",
+                            StringUtils.defaultIfBlank(message, "WeKnora 查询失败"), HttpStatus.BAD_GATEWAY);
+                }
+                return root == null ? new JSONObject() : root;
+            }
+        } catch (ProgramAuditAiException e) {
+            throw e;
+        } catch (Exception e) {
+            throw new ProgramAuditAiException("WEKNORA_REQUEST_FAILED", "WeKnora 查询异常:" + e.getMessage(), HttpStatus.BAD_GATEWAY);
+        }
+    }
+
+    private JSONObject postJson(String url, String json, int connectTimeout, int readTimeout) {        try (CloseableHttpClient client = HttpClients.createDefault()) {
+            HttpPost post = new HttpPost(url);
+            post.setHeader(HEADER_API_KEY, apiKey());
+            post.setHeader("Content-Type", "application/json; charset=UTF-8");
+            post.setHeader("Accept", "application/json");
+            post.setConfig(timeoutConfig(connectTimeout, readTimeout));
+            post.setEntity(new StringEntity(json, StandardCharsets.UTF_8));
+            try (CloseableHttpResponse response = client.execute(post)) {
+                int status = response.getStatusLine().getStatusCode();
+                String body = response.getEntity() == null ? "" : EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
+                if (status != 200 && status != 201) {
+                    log.warn("WeKnora 请求失败 url={} status={} body={}", url, status, leftForLog(body));
+                    throw new ProgramAuditAiException("WEKNORA_REQUEST_FAILED", "WeKnora 请求失败,HTTP " + status, HttpStatus.BAD_GATEWAY);
+                }
+                JSONObject root = JSON.parseObject(body);
+                if (root != null && Boolean.FALSE.equals(root.getBoolean("success"))) {
+                    String message = stringOf(root, "message", "msg", "error");
+                    throw new ProgramAuditAiException("WEKNORA_REQUEST_FAILED",
+                            StringUtils.defaultIfBlank(message, "WeKnora 请求失败"), HttpStatus.BAD_GATEWAY);
+                }
+                return root == null ? new JSONObject() : root;
+            }
+        } catch (ProgramAuditAiException e) {
+            throw e;
+        } catch (Exception e) {
+            throw new ProgramAuditAiException("WEKNORA_REQUEST_FAILED", "WeKnora 请求异常:" + e.getMessage(), HttpStatus.BAD_GATEWAY);
+        }
+    }
+
+    private JSONObject dataObject(JSONObject root) {
+        if (root == null) {
+            return new JSONObject();
+        }
+        Object data = root.get("data");
+        if (data instanceof JSONObject) {
+            JSONObject obj = (JSONObject) data;
+            Object nested = obj.get("session");
+            if (nested instanceof JSONObject) {
+                return (JSONObject) nested;
+            }
+            Object attachment = obj.get("attachment");
+            if (attachment instanceof JSONObject) {
+                return (JSONObject) attachment;
+            }
+            return obj;
+        }
+        Object session = root.get("session");
+        if (session instanceof JSONObject) {
+            return (JSONObject) session;
+        }
+        return root;
+    }
+
+    private String stringOf(JSONObject obj, String... keys) {
+        if (obj == null) {
+            return null;
+        }
+        for (String key : keys) {
+            Object value = obj.get(key);
+            if (value != null && StringUtils.isNotBlank(String.valueOf(value))) {
+                return String.valueOf(value);
+            }
+        }
+        return null;
+    }
+
+    private RequestConfig timeoutConfig(int connectTimeoutMs, int readTimeoutMs) {
+        return RequestConfig.custom()
+                .setConnectTimeout(connectTimeoutMs)
+                .setConnectionRequestTimeout(connectTimeoutMs)
+                .setSocketTimeout(readTimeoutMs)
+                .build();
+    }
+
+    private int connectTimeout() {
+        return Math.max(1000, properties.getConnectTimeoutSeconds() == null ? 5000 : properties.getConnectTimeoutSeconds() * 1000);
+    }
+
+    private int readTimeout() {
+        return Math.max(10000, properties.getGenerationTimeoutSeconds() == null ? 300000 : properties.getGenerationTimeoutSeconds() * 1000);
+    }
+
+    private String baseUrl() {
+        if (StringUtils.isBlank(properties.getBaseUrl())) {
+            throw new ProgramAuditAiException("WEKNORA_NOT_CONFIGURED", "未配置 weknora.ai.audit.base-url", HttpStatus.INTERNAL_SERVER_ERROR);
+        }
+        return StringUtils.removeEnd(properties.getBaseUrl().trim(), "/");
+    }
+
+    private String apiKey() {
+        if (StringUtils.isBlank(properties.getApiKey())) {
+            throw new ProgramAuditAiException("WEKNORA_NOT_CONFIGURED", "未配置 weknora.ai.audit.api-key", HttpStatus.INTERNAL_SERVER_ERROR);
+        }
+        return properties.getApiKey().trim();
+    }
+
+    private String leftForLog(String body) {
+        return StringUtils.left(StringUtils.defaultString(body), ERROR_BODY_LOG_LIMIT);
+    }
+
+    @Data
+    public static class AttachmentResult {
+        private String id;
+        private String status;
+        private String fileName;
+    }
+}

+ 28 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/config/ProgramAuditAiAsyncConfig.java

@@ -0,0 +1,28 @@
+package com.jeeplus.assess.programAuditAi.config;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.ThreadPoolExecutor;
+
+/**
+ * 校审 AI 独立线程池,避免长任务占用 Web 请求线程。
+ */
+@Configuration
+public class ProgramAuditAiAsyncConfig {
+
+    @Bean(name = "programAuditAiExecutor")
+    public Executor programAuditAiExecutor() {
+        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
+        executor.setCorePoolSize(2);
+        executor.setMaxPoolSize(4);
+        executor.setQueueCapacity(50);
+        executor.setKeepAliveSeconds(60);
+        executor.setThreadNamePrefix("program-audit-ai-");
+        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
+        executor.initialize();
+        return executor;
+    }
+}

+ 53 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/config/WeKnoraAiAuditProperties.java

@@ -0,0 +1,53 @@
+package com.jeeplus.assess.programAuditAi.config;
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+/**
+ * 校审 AI 生成配置。
+ *
+ * <p>对应 Nacos {@code jeeplus-assess.yml} 中的 {@code weknora.ai.audit}。
+ * API Key 只在这里读取,不写日志、不进前端。</p>
+ */
+@Data
+@Component
+@ConfigurationProperties(prefix = "weknora.ai.audit")
+public class WeKnoraAiAuditProperties {
+
+    /** WeKnora 服务根地址,如 http://192.168.8.136 */
+    private String baseUrl;
+
+    /** Java 调用用 API Key */
+    private String apiKey;
+
+    /** 校审意见生成 Agent ID */
+    private String agentId;
+
+    /** 图片资料解析 Agent ID */
+    private String imageAgentId;
+
+    /** 单次最多文件数 */
+    private Integer maxFiles = 20;
+
+    /** 单文件上限(MB) */
+    private Integer maxFileSizeMb = 50;
+
+    /** 总大小上限(MB) */
+    private Integer maxTotalSizeMb = 200;
+
+    /** 单张图片解析文字上限(字符) */
+    private Integer imageTextMaxChars = 4000;
+
+    /** image_texts 总量上限(字符) */
+    private Integer imageTextTotalMaxChars = 30000;
+
+    /** 整体生成超时(秒),同时作为 Agent SSE 读超时 */
+    private Integer generationTimeoutSeconds = 300;
+
+    /** 连接超时(秒) */
+    private Integer connectTimeoutSeconds = 5;
+
+    /** 扫描 PDF 兜底开关;本期默认关闭 */
+    private Boolean scanFallbackEnabled = false;
+}

+ 58 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/controller/ProgramAuditAiController.java

@@ -0,0 +1,58 @@
+package com.jeeplus.assess.programAuditAi.controller;
+
+import com.jeeplus.assess.programAuditAi.service.ProgramAuditAiService;
+import com.jeeplus.assess.programAuditAi.service.dto.AiGenerateReqDTO;
+import com.jeeplus.assess.programAuditAi.service.dto.AiGenerateRespDTO;
+import com.jeeplus.assess.programAuditAi.service.dto.AiGenerationStatusDTO;
+import com.jeeplus.assess.programAuditAi.support.ProgramAuditAiException;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * 三级校审 AI 生成接口。
+ */
+@Slf4j
+@RestController
+@RequestMapping("/programAuditAi")
+public class ProgramAuditAiController {
+
+    @Resource
+    private ProgramAuditAiService programAuditAiService;
+
+    @PreAuthorize("hasAuthority('assess:programAudit:aiGenerate')")
+    @PostMapping("/generate")
+    public ResponseEntity<AiGenerateRespDTO> generate(@RequestBody AiGenerateReqDTO req) {
+        return ResponseEntity.ok(programAuditAiService.generate(req));
+    }
+
+    @PreAuthorize("hasAuthority('assess:programAudit:aiGenerate')")
+    @GetMapping("/generation/{generationId}")
+    public ResponseEntity<AiGenerationStatusDTO> status(@PathVariable String generationId) {
+        return ResponseEntity.ok(programAuditAiService.status(generationId));
+    }
+
+    @ExceptionHandler(ProgramAuditAiException.class)
+    public ResponseEntity<Map<String, Object>> handleBiz(ProgramAuditAiException e) {
+        Map<String, Object> body = new LinkedHashMap<>();
+        body.put("code", e.getCode());
+        body.put("message", e.getMessage());
+        HttpStatus status = e.getHttpStatus() == null ? HttpStatus.BAD_REQUEST : e.getHttpStatus();
+        return ResponseEntity.status(status).body(body);
+    }
+
+    @ExceptionHandler(Exception.class)
+    public ResponseEntity<Map<String, Object>> handleOther(Exception e) {
+        log.error("校审AI接口异常: {}", e.getMessage(), e);
+        Map<String, Object> body = new LinkedHashMap<>();
+        body.put("code", "AI_GENERATION_FAILED");
+        body.put("message", "校审 AI 服务异常,请稍后重试");
+        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(body);
+    }
+}

+ 88 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/domain/ProgramAuditAiGeneration.java

@@ -0,0 +1,88 @@
+package com.jeeplus.assess.programAuditAi.domain;
+
+import com.baomidou.mybatisplus.annotation.TableName;
+import com.jeeplus.core.domain.BaseEntity;
+import lombok.Data;
+import lombok.EqualsAndHashCode;
+
+import java.util.Date;
+
+/**
+ * 校审 AI 一次生成记录。
+ */
+@Data
+@EqualsAndHashCode(callSuper = true)
+@TableName("program_audit_ai_generation")
+public class ProgramAuditAiGeneration extends BaseEntity {
+
+    private static final long serialVersionUID = 1L;
+
+    /** 项目ID,对应 program_project_list_info.id */
+    private String programId;
+
+    /** 当前校审记录ID,对应 program_audit.id;校审单尚未落库时为空 */
+    private String auditId;
+
+    /** 校审级别:一级/二级/三级,对应 program_audit.audit_level */
+    private String auditLevel;
+
+    /** 发起人用户ID,对应 sys_user.id */
+    private String operatorId;
+
+    /** 发起人姓名,冗余存储便于列表展示 */
+    private String operatorName;
+
+    /** 本次生成整体状态:running-执行中,success-四段全部生成,partial-部分生成,failed-失败,cancelled-已取消 */
+    private String status;
+
+    /** 明细表 AI 草稿(富文本),生成或失败原因均写在此处 */
+    private String detailContent;
+
+    /** 评估报告 AI 草稿(富文本) */
+    private String reportContent;
+
+    /** 技术说明 AI 草稿(富文本) */
+    private String remarksContent;
+
+    /** 工作底稿 AI 草稿(富文本) */
+    private String workContent;
+
+    /** 明细表分段结果:generated-已生成,skipped-资料不足跳过,failed-生成失败 */
+    private String detailStatus;
+
+    /** 评估报告分段结果:generated/skipped/failed */
+    private String reportStatus;
+
+    /** 技术说明分段结果:generated/skipped/failed */
+    private String remarksStatus;
+
+    /** 工作底稿分段结果:generated/skipped/failed */
+    private String workStatus;
+
+    /** 校审 Agent 返回的原始 JSON,含 detail/report/remarks/work 四段 */
+    private String resultJson;
+
+    /** 本次生成使用的 WeKnora 会话ID,用于附件上传与问答复用 */
+    private String weknoraSessionId;
+
+    /** 本次生成使用的校审 Agent ID,取自 WeKnora 配置 */
+    private String weknoraAgentId;
+
+    /** 本次提交的文件数量,含被跳过的不支持类型文件 */
+    private Integer fileCount;
+
+    /** 整体失败错误码,如 ATTACHMENT_PARSE_FAILED、JSON_INVALID、TASK_REJECTED */
+    private String errorCode;
+
+    /** 整体失败原因,最长 1000 字 */
+    private String errorMessage;
+
+    /** 任务开始时间,创建记录时写入 */
+    private Date startedAt;
+
+    /** 任务结束时间,成功或失败回写时写入 */
+    private Date finishedAt;
+
+    /** 任务耗时毫秒数,等于 finishedAt - startedAt */
+    private Long durationMs;
+}

+ 50 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/domain/ProgramAuditAiGenerationFile.java

@@ -0,0 +1,50 @@
+package com.jeeplus.assess.programAuditAi.domain;
+
+import com.baomidou.mybatisplus.annotation.TableName;
+import com.jeeplus.core.domain.BaseEntity;
+import lombok.Data;
+import lombok.EqualsAndHashCode;
+
+/**
+ * 一次生成使用的附件快照。
+ */
+@Data
+@EqualsAndHashCode(callSuper = true)
+@TableName("program_audit_ai_generation_file")
+public class ProgramAuditAiGenerationFile extends BaseEntity {
+
+    private static final long serialVersionUID = 1L;
+
+    /** 所属生成记录ID,对应 program_audit_ai_generation.id */
+    private String generationId;
+
+    /** 来源业务附件ID,对应 work_attachment.id,可能为空 */
+    private String attachmentId;
+
+    /** 文件名,含扩展名,最长 255 字 */
+    private String fileName;
+
+    /** 文件扩展名(pdf/doc/docx/xls/xlsx/txt/jpg/png 等),小写且不带点 */
+    private String fileType;
+
+    /** 文件字节数,无法获取时为 0 */
+    private Long fileSize;
+
+    /** 文件在 OSS 的 object key(不含域名),异步任务据此下载文件 */
+    private String storagePath;
+
+    /** 上传到 WeKnora 会话后的附件ID,上传成功或解析完成后回写 */
+    private String weknoraAttachmentId;
+
+    /** 上传解析状态:uploaded-已上传,processing-解析中,ready-解析完成,failed-失败,skipped-不支持类型跳过 */
+    private String parseStatus;
+
+    /** 解析失败原因,最长 1000 字;跳过时会写入不支持的文件类型说明 */
+    private String parseError;
+
+    /** 文件页数,预留给解析结果回填,当前无赋值入口 */
+    private Integer pageCount;
+
+    /** 提交顺序,从 0 递增,跳过的文件排在正常文件之后 */
+    private Integer sortNo;
+}

+ 9 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/mapper/ProgramAuditAiGenerationFileMapper.java

@@ -0,0 +1,9 @@
+package com.jeeplus.assess.programAuditAi.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.jeeplus.assess.programAuditAi.domain.ProgramAuditAiGenerationFile;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface ProgramAuditAiGenerationFileMapper extends BaseMapper<ProgramAuditAiGenerationFile> {
+}

+ 9 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/mapper/ProgramAuditAiGenerationMapper.java

@@ -0,0 +1,9 @@
+package com.jeeplus.assess.programAuditAi.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.jeeplus.assess.programAuditAi.domain.ProgramAuditAiGeneration;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface ProgramAuditAiGenerationMapper extends BaseMapper<ProgramAuditAiGeneration> {
+}

+ 514 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/service/ProgramAuditAiAsyncService.java

@@ -0,0 +1,514 @@
+package com.jeeplus.assess.programAuditAi.service;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.jeeplus.assess.programAuditAi.client.WeKnoraAgentClient;
+import com.jeeplus.assess.programAuditAi.config.WeKnoraAiAuditProperties;
+import com.jeeplus.assess.programAuditAi.domain.ProgramAuditAiGeneration;
+import com.jeeplus.assess.programAuditAi.domain.ProgramAuditAiGenerationFile;
+import com.jeeplus.assess.programAuditAi.mapper.ProgramAuditAiGenerationFileMapper;
+import com.jeeplus.assess.programAuditAi.mapper.ProgramAuditAiGenerationMapper;
+import com.jeeplus.assess.programAuditAi.support.ProgramAuditAiException;
+import lombok.Data;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.Executor;
+
+/**
+ * 校审 AI 异步执行器。
+ *
+ * <p>任务记录与附件快照在请求线程先落库,异步线程只做下载、上传、调用与回写,
+ * 避免异步线程里的 MyBatis 自动填充拿不到登录上下文。</p>
+ */
+@Slf4j
+@Service
+public class ProgramAuditAiAsyncService {
+
+    private static final Set<String> IMAGE_EXTENSIONS = new HashSet<>(Arrays.asList(
+            "jpg", "jpeg", "png", "bmp", "gif", "tif", "tiff", "webp"
+    ));
+
+    private static final String IMAGE_PARSE_QUERY =
+            "请解析本会话中的图片资料,输出结构化解析文字。保留项目名称、金额、日期、单位、结论、表格数据等与资产评估校审相关的信息;"
+                    + "不要编造,无法识别的写“无法识别”。只输出解析文字,不要输出解释。";
+
+    @Resource(name = "programAuditAiExecutor")
+    private Executor executor;
+
+    @Resource
+    private WeKnoraAiAuditProperties properties;
+
+    @Resource
+    private WeKnoraAgentClient weKnoraAgentClient;
+
+    @Resource
+    private ProgramAuditAiGenerationMapper generationMapper;
+
+    @Resource
+    private ProgramAuditAiGenerationFileMapper fileMapper;
+
+    @Value("${server.port:9240}")
+    private int serverPort;
+
+    public void execute(final String generationId) {
+        try {
+            executor.execute(new Runnable() {
+                @Override
+                public void run() {
+                    doGenerate(generationId);
+                }
+            });
+        } catch (Exception e) {
+            log.error("校审AI任务提交线程池失败 generationId={} err={}", generationId, e.getMessage());
+            markFailed(generationId, "TASK_REJECTED", "生成任务提交失败");
+        }
+    }
+
+    private void doGenerate(String generationId) {
+        ProgramAuditAiGeneration generation = generationMapper.selectById(generationId);
+        if (generation == null) {
+            log.warn("校审AI任务不存在 generationId={}", generationId);
+            return;
+        }
+        Date begin = generation.getStartedAt() == null ? new Date() : generation.getStartedAt();
+        String auditSessionId = null;
+        try {
+            List<ProgramAuditAiGenerationFile> files = loadFiles(generationId);
+            auditSessionId = weKnoraAgentClient.createSession("校审AI-" + generationId);
+            generation.setWeknoraSessionId(auditSessionId);
+            updateGeneration(generation);
+
+            List<String> auditAttachmentIds = new ArrayList<>();
+            List<ProgramAuditAiGenerationFile> uploadedFiles = new ArrayList<>();
+            List<String> uploadedAttachmentIds = new ArrayList<>();
+            List<ImageItem> imageItems = new ArrayList<>();
+            int uploadedCount = 0;
+
+            // 先把所有非图片附件提交给 WeKnora,再统一等待解析。
+            // 逐个“上传后等待”会把解析串行化,多文件时很容易超过前端轮询时限。
+            for (ProgramAuditAiGenerationFile file : files) {
+                byte[] bytes;
+                try {
+                    bytes = download(file);
+                } catch (Exception e) {
+                    markFileFailed(file, e.getMessage());
+                    continue;
+                }
+                if (isImage(file.getFileType())) {
+                    imageItems.add(new ImageItem(file, bytes));
+                } else {
+                    try {
+                        WeKnoraAgentClient.AttachmentResult result = weKnoraAgentClient.uploadAttachment(
+                                auditSessionId, file.getFileName(), bytes, properties.getAgentId());
+                        if (StringUtils.isNotBlank(result.getId())) {
+                            markFileUploaded(file, result);
+                            if (!"failed".equalsIgnoreCase(StringUtils.defaultString(result.getStatus()))) {
+                                uploadedFiles.add(file);
+                                uploadedAttachmentIds.add(result.getId());
+                            }
+                        } else {
+                            markFileFailed(file, "WeKnora 未返回附件ID");
+                        }
+                    } catch (Exception e) {
+                        markFileFailed(file, e.getMessage());
+                    }
+                }
+            }
+
+            for (int i = 0; i < uploadedFiles.size(); i++) {
+                ProgramAuditAiGenerationFile file = uploadedFiles.get(i);
+                try {
+                    WeKnoraAgentClient.AttachmentResult ready = weKnoraAgentClient.waitAttachmentReady(
+                            auditSessionId, uploadedAttachmentIds.get(i));
+                    if (StringUtils.isNotBlank(ready.getId())) {
+                        auditAttachmentIds.add(ready.getId());
+                        markFileUploaded(file, ready);
+                        uploadedCount++;
+                    } else {
+                        markFileFailed(file, "WeKnora 附件解析完成但未返回附件ID");
+                    }
+                } catch (Exception e) {
+                    markFileFailed(file, e.getMessage());
+                }
+            }
+
+            String imageTexts = "";
+            if (!imageItems.isEmpty()) {
+                imageTexts = parseImages(imageItems);
+            }
+
+            if (uploadedCount == 0 && StringUtils.isBlank(imageTexts)) {
+                throw new ProgramAuditAiException("ATTACHMENT_PARSE_FAILED", "附件均未能成功上传或解析,请检查文件后重试");
+            }
+
+            String query = buildQuery(generation, files, imageTexts);
+            String answer = weKnoraAgentClient.chat(auditSessionId, query, properties.getAgentId(), auditAttachmentIds);
+            ParsedResult parsed = parseResult(answer);
+
+            generation.setStatus(parsed.getOverallStatus());
+            generation.setDetailContent(parsed.getDetail().getContent());
+            generation.setReportContent(parsed.getReport().getContent());
+            generation.setRemarksContent(parsed.getRemarks().getContent());
+            generation.setWorkContent(parsed.getWork().getContent());
+            generation.setDetailStatus(parsed.getDetail().getStatus());
+            generation.setReportStatus(parsed.getReport().getStatus());
+            generation.setRemarksStatus(parsed.getRemarks().getStatus());
+            generation.setWorkStatus(parsed.getWork().getStatus());
+            generation.setResultJson(parsed.getRawJson());
+            generation.setErrorCode(null);
+            generation.setErrorMessage(null);
+            finish(generation, begin);
+            log.info("校审AI生成完成 generationId={} status={} duration={}ms",
+                    generationId, generation.getStatus(), generation.getDurationMs());
+        } catch (Exception e) {
+            String code = e instanceof ProgramAuditAiException
+                    ? ((ProgramAuditAiException) e).getCode() : "AI_GENERATION_FAILED";
+            String message = StringUtils.abbreviate(StringUtils.defaultIfBlank(e.getMessage(), "生成失败"), 1000);
+            log.error("校审AI生成失败 generationId={} code={} err={}", generationId, code, message);
+            markFailed(generation, code, message, begin);
+        }
+    }
+
+    private List<ProgramAuditAiGenerationFile> loadFiles(String generationId) {
+        QueryWrapper<ProgramAuditAiGenerationFile> query = new QueryWrapper<>();
+        query.eq("generation_id", generationId);
+        query.ne("parse_status", "skipped");
+        query.orderByAsc("sort_no");
+        return fileMapper.selectList(query);
+    }
+
+    private byte[] download(ProgramAuditAiGenerationFile file) {
+        String key = StringUtils.removeStart(StringUtils.trimToEmpty(file.getStoragePath()), "/");
+        if (StringUtils.isBlank(key)) {
+            throw new IllegalStateException("附件 OSS key 为空");
+        }
+        byte[] bytes = downloadFromLocalOss(key, file.getFileName());
+        if (bytes == null || bytes.length == 0) {
+            throw new IllegalStateException("附件下载失败或为空");
+        }
+        return bytes;
+    }
+
+    /**
+     * 本地 OSS 下载接口已随校审服务加载;异步线程没有登录上下文,Feign 公共模块服务也不在当前部署注册,
+     * 因此直接调用本机同端口的 OSS 下载端点,避免跨服务路由和鉴权缺失。
+     */
+    private byte[] downloadFromLocalOss(String key, String fileName) {
+        HttpURLConnection connection = null;
+        try {
+            URL url = new URL("http://127.0.0.1:" + serverPort + "/oss/file/downBytesByStream");
+            connection = (HttpURLConnection) url.openConnection();
+            connection.setConnectTimeout(5000);
+            connection.setReadTimeout(120000);
+            connection.setRequestMethod("POST");
+            connection.setDoOutput(true);
+            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
+            String body = "key=" + URLEncoder.encode(key, "UTF-8")
+                    + "&fileName=" + URLEncoder.encode(fileName == null ? "" : fileName, "UTF-8");
+            try (OutputStream out = connection.getOutputStream()) {
+                out.write(body.getBytes("UTF-8"));
+            }
+            int status = connection.getResponseCode();
+            if (status != 200) {
+                throw new IllegalStateException("OSS 下载接口返回 HTTP " + status);
+            }
+            try (InputStream in = connection.getInputStream()) {
+                ByteArrayOutputStream output = new ByteArrayOutputStream();
+                byte[] buffer = new byte[4096];
+                int len;
+                while ((len = in.read(buffer)) != -1) {
+                    output.write(buffer, 0, len);
+                }
+                return output.toByteArray();
+            }
+        } catch (Exception e) {
+            log.error("校审AI附件下载异常 key={} err={}", key, e.getMessage());
+            return null;
+        } finally {
+            if (connection != null) {
+                connection.disconnect();
+            }
+        }
+    }
+
+    private String parseImages(List<ImageItem> imageItems) {
+        if (StringUtils.isBlank(properties.getImageAgentId())) {
+            throw new ProgramAuditAiException("AGENT_NOT_CONFIGURED", "图片解析 Agent 未配置");
+        }
+        String imageSessionId = weKnoraAgentClient.createSession("校审图片-" + System.currentTimeMillis());
+        List<String> imageAttachmentIds = new ArrayList<>();
+        for (ImageItem item : imageItems) {
+            try {
+                WeKnoraAgentClient.AttachmentResult result = weKnoraAgentClient.uploadAttachment(
+                        imageSessionId, item.file.getFileName(), item.bytes, properties.getImageAgentId());
+                if (StringUtils.isNotBlank(result.getId())) {
+                    result = weKnoraAgentClient.waitAttachmentReady(imageSessionId, result.getId());
+                    imageAttachmentIds.add(result.getId());
+                    markFileUploaded(item.file, result);
+                } else {
+                    markFileFailed(item.file, "WeKnora 未返回图片附件ID");
+                }
+            } catch (Exception e) {
+                markFileFailed(item.file, e.getMessage());
+            }
+        }
+        if (imageAttachmentIds.isEmpty()) {
+            return "";
+        }
+        String text = weKnoraAgentClient.chat(imageSessionId, IMAGE_PARSE_QUERY, properties.getImageAgentId(), imageAttachmentIds);
+        int totalLimit = properties.getImageTextTotalMaxChars() == null ? 30000 : Math.max(1000, properties.getImageTextTotalMaxChars());
+        return StringUtils.left(StringUtils.trimToEmpty(text), totalLimit);
+    }
+
+    private String buildQuery(ProgramAuditAiGeneration generation, List<ProgramAuditAiGenerationFile> files, String imageTexts) {
+        StringBuilder query = new StringBuilder();
+        query.append("项目ID:").append(generation.getProgramId()).append('\n');
+        query.append("校审级别:").append(generation.getAuditLevel()).append('\n');
+        if (StringUtils.isNotBlank(generation.getAuditId())) {
+            query.append("校审记录ID:").append(generation.getAuditId()).append('\n');
+        }
+        query.append("本次附件清单:\n");
+        for (ProgramAuditAiGenerationFile file : files) {
+            query.append("- ").append(file.getFileName()).append("(").append(StringUtils.upperCase(file.getFileType())).append(")\n");
+        }
+        if (StringUtils.isNotBlank(imageTexts)) {
+            query.append("\n图片结构化解析文字(image_texts):\n").append(imageTexts).append('\n');
+        } else {
+            query.append("\n图片结构化解析文字(image_texts):无\n");
+        }
+        query.append("\n请读取本会话全部附件,严格按系统提示词输出四段校审意见。");
+        query.append("只输出一个 JSON 对象,字段为 detail、report、remarks、work;");
+        query.append("每段包含 status、content、issues、citations;status 不是 generated 时,把未生成的原因直接写进 content,不要输出 reason、coverage_mode、coverage_note。\n");
+        query.append("只出草稿,不审批;不要输出 JSON 之外的任何文字。");
+        return query.toString();
+    }
+
+    private ParsedResult parseResult(String answer) {
+        String text = stripCodeFence(answer);
+        int start = text.indexOf('{');
+        int end = text.lastIndexOf('}');
+        if (start < 0 || end <= start) {
+            throw new ProgramAuditAiException("JSON_INVALID", "校审 Agent 返回内容不是有效 JSON");
+        }
+        String json = text.substring(start, end + 1);
+        JSONObject root;
+        try {
+            root = JSON.parseObject(json);
+        } catch (Exception e) {
+            throw new ProgramAuditAiException("JSON_INVALID", "校审 Agent 返回 JSON 解析失败");
+        }
+        ParsedResult result = new ParsedResult();
+        result.setRawJson(json);
+        result.setDetail(readSegment(root, "detail"));
+        result.setReport(readSegment(root, "report"));
+        result.setRemarks(readSegment(root, "remarks"));
+        result.setWork(readSegment(root, "work"));
+        result.setOverallStatus(overallStatus(result));
+        return result;
+    }
+
+    private Segment readSegment(JSONObject root, String key) {
+        Object value = root.get(key);
+        Segment segment = new Segment();
+        segment.setKey(key);
+        String label = segmentLabel(key);
+        if (!(value instanceof JSONObject)) {
+            segment.setStatus("failed");
+            segment.setContent(label + "未生成校审意见:Agent 未返回该段。");
+            return segment;
+        }
+        JSONObject obj = (JSONObject) value;
+        String status = StringUtils.lowerCase(StringUtils.trimToEmpty(obj.getString("status")));
+        if (!"generated".equals(status) && !"skipped".equals(status) && !"failed".equals(status)) {
+            status = StringUtils.isBlank(obj.getString("content")) ? "failed" : "generated";
+        }
+        String content = StringUtils.trimToEmpty(obj.getString("content"));
+        if ("generated".equals(status) && StringUtils.isBlank(content)) {
+            status = "failed";
+        }
+        if (!"generated".equals(status) && StringUtils.isBlank(content)) {
+            content = "failed".equals(status)
+                    ? label + "生成失败,未生成校审意见:AI 未返回具体错误原因。"
+                    : label + "缺少可用资料,未生成校审意见:AI 未返回具体缺失资料说明。";
+        }
+        segment.setStatus(status);
+        segment.setContent(content);
+        return segment;
+    }
+
+    private String segmentLabel(String key) {
+        if ("detail".equals(key)) {
+            return "明细表";
+        }
+        if ("report".equals(key)) {
+            return "评估报告";
+        }
+        if ("remarks".equals(key)) {
+            return "技术说明";
+        }
+        if ("work".equals(key)) {
+            return "工作底稿";
+        }
+        return key;
+    }
+
+    private String overallStatus(ParsedResult result) {
+        Segment[] segments = new Segment[]{result.getDetail(), result.getReport(), result.getRemarks(), result.getWork()};
+        boolean allGenerated = true;
+        boolean anyGenerated = false;
+        for (Segment segment : segments) {
+            if ("generated".equals(segment.getStatus())) {
+                anyGenerated = true;
+            } else {
+                allGenerated = false;
+            }
+        }
+        if (!anyGenerated) {
+            return "failed";
+        }
+        return allGenerated ? "success" : "partial";
+    }
+
+    private String stripCodeFence(String text) {
+        String value = StringUtils.trimToEmpty(text);
+        if (value.startsWith("```")) {
+            int firstLine = value.indexOf('\n');
+            if (firstLine >= 0) {
+                value = value.substring(firstLine + 1);
+            }
+            if (value.endsWith("```")) {
+                value = value.substring(0, value.length() - 3);
+            }
+        }
+        return StringUtils.trimToEmpty(value);
+    }
+
+    private void markFileUploaded(ProgramAuditAiGenerationFile file, WeKnoraAgentClient.AttachmentResult result) {
+        file.setWeknoraAttachmentId(result.getId());
+        if ("failed".equalsIgnoreCase(result.getStatus())) {
+            file.setParseStatus("failed");
+            file.setParseError("WeKnora 附件解析失败");
+        } else {
+            file.setParseStatus(StringUtils.defaultIfBlank(result.getStatus(), "uploaded"));
+            file.setParseError(null);
+        }
+        file.setUpdateById(file.getCreateById());
+        file.setUpdateTime(new Date());
+        fileMapper.updateById(file);
+    }
+
+    private void markFileFailed(ProgramAuditAiGenerationFile file, String error) {
+        file.setParseStatus("failed");
+        file.setParseError(StringUtils.abbreviate(StringUtils.defaultString(error), 1000));
+        file.setUpdateById(file.getCreateById());
+        file.setUpdateTime(new Date());
+        fileMapper.updateById(file);
+        log.warn("校审AI附件处理失败 file={} err={}", file.getFileName(), file.getParseError());
+    }
+
+    private void markFailed(String generationId, String code, String message) {
+        ProgramAuditAiGeneration generation = generationMapper.selectById(generationId);
+        if (generation == null) {
+            return;
+        }
+        markFailed(generation, code, message, generation.getStartedAt() == null ? new Date() : generation.getStartedAt());
+    }
+
+    private void markFailed(ProgramAuditAiGeneration generation, String code, String message, Date begin) {
+        String error = StringUtils.abbreviate(StringUtils.defaultIfBlank(message, "生成失败"), 1000);
+        generation.setStatus("failed");
+        generation.setErrorCode(code);
+        generation.setErrorMessage(error);
+        generation.setDetailStatus("failed");
+        generation.setReportStatus("failed");
+        generation.setRemarksStatus("failed");
+        generation.setWorkStatus("failed");
+        generation.setDetailContent(failedContent("明细表", error));
+        generation.setReportContent(failedContent("评估报告", error));
+        generation.setRemarksContent(failedContent("技术说明", error));
+        generation.setWorkContent(failedContent("工作底稿", error));
+
+        JSONObject result = new JSONObject();
+        putFailedSegment(result, "detail", "明细表", error);
+        putFailedSegment(result, "report", "评估报告", error);
+        putFailedSegment(result, "remarks", "技术说明", error);
+        putFailedSegment(result, "work", "工作底稿", error);
+        generation.setResultJson(result.toJSONString());
+        finish(generation, begin);
+    }
+
+    private String failedContent(String label, String error) {
+        return label + "未生成校审意见:AI 生成失败,原因:" + error;
+    }
+
+    private void putFailedSegment(JSONObject result, String key, String label, String error) {
+        JSONObject segment = new JSONObject();
+        segment.put("status", "failed");
+        segment.put("content", failedContent(label, error));
+        result.put(key, segment);
+    }
+
+    private void finish(ProgramAuditAiGeneration generation, Date begin) {
+        Date end = new Date();
+        generation.setFinishedAt(end);
+        generation.setDurationMs(end.getTime() - begin.getTime());
+        generation.setUpdateById(generation.getOperatorId());
+        generation.setUpdateTime(end);
+        generationMapper.updateById(generation);
+    }
+
+    private void updateGeneration(ProgramAuditAiGeneration generation) {
+        generation.setUpdateById(generation.getOperatorId());
+        generation.setUpdateTime(new Date());
+        generationMapper.updateById(generation);
+    }
+
+    private boolean isImage(String fileType) {
+        return IMAGE_EXTENSIONS.contains(StringUtils.lowerCase(StringUtils.trimToEmpty(fileType)));
+    }
+
+    @Data
+    private static class ImageItem {
+        private ProgramAuditAiGenerationFile file;
+        private byte[] bytes;
+
+        ImageItem(ProgramAuditAiGenerationFile file, byte[] bytes) {
+            this.file = file;
+            this.bytes = bytes;
+        }
+    }
+
+    @Data
+    public static class Segment {
+        private String key;
+        private String status;
+        private String content;
+    }
+
+    @Data
+    public static class ParsedResult {
+        private String rawJson;
+        private Segment detail;
+        private Segment report;
+        private Segment remarks;
+        private Segment work;
+        private String overallStatus;
+    }
+}

+ 436 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/service/ProgramAuditAiService.java

@@ -0,0 +1,436 @@
+package com.jeeplus.assess.programAuditAi.service;
+
+import cn.hutool.core.util.IdUtil;
+import cn.hutool.extra.spring.SpringUtil;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.jeeplus.assess.programAuditAi.config.WeKnoraAiAuditProperties;
+import com.jeeplus.assess.programAuditAi.domain.ProgramAuditAiGeneration;
+import com.jeeplus.assess.programAuditAi.domain.ProgramAuditAiGenerationFile;
+import com.jeeplus.assess.programAuditAi.mapper.ProgramAuditAiGenerationFileMapper;
+import com.jeeplus.assess.programAuditAi.mapper.ProgramAuditAiGenerationMapper;
+import com.jeeplus.assess.programAuditAi.service.dto.AiAttachmentDTO;
+import com.jeeplus.assess.programAuditAi.service.dto.AiGenerateReqDTO;
+import com.jeeplus.assess.programAuditAi.service.dto.AiGenerateRespDTO;
+import com.jeeplus.assess.programAuditAi.service.dto.AiGenerationStatusDTO;
+import com.jeeplus.assess.programAuditAi.support.ProgramAuditAiException;
+import com.jeeplus.assess.program.configuration.projectList.domain.ProgramAudit;
+import com.jeeplus.assess.program.configuration.projectList.domain.ProgramProjectListInfo;
+import com.jeeplus.assess.program.configuration.projectList.mapper.ProgramAuditMapper;
+import com.jeeplus.assess.program.configuration.projectList.mapper.ProjectListMapper;
+import com.jeeplus.common.SecurityUtils;
+import com.jeeplus.sys.feign.ITenantApi;
+import com.jeeplus.sys.service.dto.UserDTO;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.support.TransactionSynchronization;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+import javax.annotation.Resource;
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * 校审 AI 生成:同步校验、落任务、异步执行。
+ */
+@Slf4j
+@Service
+public class ProgramAuditAiService {
+
+    private static final Set<String> ALLOWED_EXTENSIONS = new HashSet<>(Arrays.asList(
+            "pdf", "doc", "docx", "xls", "xlsx", "txt",
+            "jpg", "jpeg", "png", "bmp", "gif", "tif", "tiff", "webp"
+    ));
+
+    private static final Set<String> ZIP_EXTENSIONS = new HashSet<>(Arrays.asList(
+            "zip", "rar", "7z", "tar", "gz", "bz2"
+    ));
+
+    private static final String[] SEGMENT_KEYS = new String[]{"detail", "report", "remarks", "work"};
+
+    @Resource
+    private WeKnoraAiAuditProperties properties;
+
+    @Resource
+    private ProgramAuditAiGenerationMapper generationMapper;
+
+    @Resource
+    private ProgramAuditAiGenerationFileMapper fileMapper;
+
+    @Resource
+    private ProjectListMapper projectListMapper;
+
+    @Resource
+    private ProgramAuditMapper programAuditMapper;
+
+    @Resource
+    private ProgramAuditAiAsyncService asyncService;
+
+    /**
+     * 创建一次生成任务。只做同步校验与落库,真正的 WeKnora 调用在异步线程里。
+     */
+    @Transactional(rollbackFor = Exception.class)
+    public synchronized AiGenerateRespDTO generate(AiGenerateReqDTO req) {
+        UserDTO user = currentUser();
+        String operatorId = user == null ? null : user.getId();
+        String operatorName = user == null ? null : user.getName();
+        String tenantId = currentTenantId();
+        if (StringUtils.isBlank(operatorId) || StringUtils.isBlank(tenantId)) {
+            throw new ProgramAuditAiException("NO_LOGIN", "取不到当前登录用户或租户", HttpStatus.UNAUTHORIZED);
+        }
+        if (req == null || StringUtils.isBlank(req.getProgramId())) {
+            throw new ProgramAuditAiException("PROGRAM_REQUIRED", "项目ID不能为空");
+        }
+        if (StringUtils.isBlank(req.getAuditLevel())) {
+            throw new ProgramAuditAiException("AUDIT_LEVEL_REQUIRED", "校审级别不能为空");
+        }
+
+        ProgramProjectListInfo project = projectListMapper.getById(req.getProgramId());
+        if (project == null) {
+            throw new ProgramAuditAiException("PROJECT_NOT_FOUND", "项目不存在或已删除", HttpStatus.NOT_FOUND);
+        }
+        String auditId = StringUtils.trimToNull(req.getAuditId());
+        if (auditId != null) {
+            ProgramAudit audit = programAuditMapper.selectById(auditId);
+            if (audit == null) {
+                throw new ProgramAuditAiException("AUDIT_NOT_FOUND", "当前校审记录不存在", HttpStatus.NOT_FOUND);
+            }
+            if (!StringUtils.equals(StringUtils.trimToEmpty(audit.getProgramId()), req.getProgramId())) {
+                throw new ProgramAuditAiException("AUDIT_PROGRAM_MISMATCH", "校审记录与项目不匹配");
+            }
+        }
+
+        List<AiAttachmentDTO> attachments = req.getWorkAttachmentDtoList();
+        if (attachments == null || attachments.isEmpty()) {
+            throw new ProgramAuditAiException("NO_ATTACHMENT", "该项目登记时未上传附件,请先上传附件再生成校审意见。");
+        }
+        if (attachments.size() > maxFiles()) {
+            throw new ProgramAuditAiException("TOO_MANY_FILES", "本次附件超过 " + maxFiles() + " 个,请保留核心资料后再生成");
+        }
+
+        List<FileSnapshot> snapshots = new ArrayList<>();
+        List<FileSnapshot> skippedSnapshots = new ArrayList<>();
+        Set<String> unsupportedTypes = new LinkedHashSet<>();
+        long totalSize = 0L;
+        for (AiAttachmentDTO attachment : attachments) {
+            if (attachment == null) {
+                continue;
+            }
+            String fileName = StringUtils.defaultIfBlank(attachment.getName(), attachment.getFileName());
+            String url = StringUtils.trimToNull(attachment.getUrl());
+            if (StringUtils.isBlank(fileName)) {
+                throw new ProgramAuditAiException("FILE_NAME_REQUIRED", "附件文件名不能为空");
+            }
+            if (url == null) {
+                throw new ProgramAuditAiException("FILE_URL_REQUIRED", "附件地址不能为空:" + fileName);
+            }
+            String ext = extension(fileName, attachment.getType());
+            if (ZIP_EXTENSIONS.contains(ext) || !ALLOWED_EXTENSIONS.contains(ext)) {
+                FileSnapshot skipped = new FileSnapshot();
+                skipped.attachment = attachment;
+                skipped.fileName = fileName;
+                skipped.fileType = StringUtils.isBlank(ext) ? "未知" : ext;
+                skipped.fileSize = 0L;
+                skipped.storagePath = normalizeOssKey(url);
+                skippedSnapshots.add(skipped);
+                unsupportedTypes.add(skipped.fileType);
+                continue;
+            }
+            long size = parseSize(attachment.getSize(), attachment.getFileSize());
+            if (size > maxFileBytes()) {
+                throw new ProgramAuditAiException("FILE_TOO_LARGE", "附件超过 AI 侧单文件上限:" + fileName);
+            }
+            totalSize += size;
+            if (totalSize > maxTotalBytes()) {
+                throw new ProgramAuditAiException("TOTAL_SIZE_TOO_LARGE", "附件总大小超过 AI 侧上限,请压缩或拆分后再生成");
+            }
+            FileSnapshot snapshot = new FileSnapshot();
+            snapshot.attachment = attachment;
+            snapshot.fileName = fileName;
+            snapshot.fileType = ext;
+            snapshot.fileSize = size;
+            snapshot.storagePath = normalizeOssKey(url);
+            snapshots.add(snapshot);
+        }
+        if (snapshots.isEmpty()) {
+            if (!skippedSnapshots.isEmpty()) {
+                throw new ProgramAuditAiException("NO_SUPPORTED_ATTACHMENT",
+                        "所有附件均为不支持的文件类型(" + typeText(unsupportedTypes) + "),无法生成校审意见。");
+            }
+            throw new ProgramAuditAiException("NO_ATTACHMENT", "该项目登记时未上传附件,请先上传附件再生成校审意见。");
+        }
+        String unsupportedWarning = unsupportedWarning(unsupportedTypes);
+
+        QueryWrapper<ProgramAuditAiGeneration> runningQuery = new QueryWrapper<>();
+        runningQuery.eq("program_id", req.getProgramId());
+        if (auditId == null) {
+            runningQuery.isNull("audit_id");
+        } else {
+            runningQuery.eq("audit_id", auditId);
+        }
+        runningQuery.eq("status", "running");
+        Integer running = generationMapper.selectCount(runningQuery);
+        if (running != null && running > 0) {
+            throw new ProgramAuditAiException("AI_GENERATION_RUNNING", "当前校审记录已有 AI 生成任务在执行,请稍后", HttpStatus.CONFLICT);
+        }
+
+        Date now = new Date();
+        ProgramAuditAiGeneration generation = new ProgramAuditAiGeneration();
+        generation.setId(IdUtil.simpleUUID());
+        generation.setProgramId(req.getProgramId());
+        generation.setAuditId(auditId);
+        generation.setAuditLevel(req.getAuditLevel());
+        generation.setOperatorId(operatorId);
+        generation.setOperatorName(operatorName);
+        generation.setStatus("running");
+        generation.setWeknoraAgentId(properties.getAgentId());
+        generation.setFileCount(snapshots.size() + skippedSnapshots.size());
+        generation.setStartedAt(now);
+        generation.setCreateById(operatorId);
+        generation.setCreateTime(now);
+        generation.setUpdateById(operatorId);
+        generation.setUpdateTime(now);
+        generation.setDelFlag(0);
+        generation.setTenantId(tenantId);
+        generationMapper.insert(generation);
+
+        for (int i = 0; i < snapshots.size(); i++) {
+            FileSnapshot snapshot = snapshots.get(i);
+            insertGenerationFile(generation.getId(), snapshot, "processing", null, i, operatorId, tenantId, now);
+        }
+        for (int i = 0; i < skippedSnapshots.size(); i++) {
+            FileSnapshot snapshot = skippedSnapshots.get(i);
+            insertGenerationFile(generation.getId(), snapshot, "skipped",
+                    "不支持的文件类型:" + snapshot.fileType, snapshots.size() + i, operatorId, tenantId, now);
+        }
+
+        submitAfterCommit(generation.getId());
+        return new AiGenerateRespDTO(generation.getId(), "running", unsupportedWarning);
+    }
+
+    private void insertGenerationFile(String generationId, FileSnapshot snapshot, String parseStatus,
+                                      String parseError, int sortNo, String operatorId, String tenantId, Date now) {
+        ProgramAuditAiGenerationFile file = new ProgramAuditAiGenerationFile();
+        file.setId(IdUtil.simpleUUID());
+        file.setGenerationId(generationId);
+        file.setAttachmentId(StringUtils.left(snapshot.attachment.getId(), 64));
+        file.setFileName(StringUtils.left(snapshot.fileName, 255));
+        file.setFileType(StringUtils.left(snapshot.fileType, 32));
+        file.setFileSize(snapshot.fileSize);
+        file.setStoragePath(StringUtils.left(snapshot.storagePath, 2000));
+        file.setParseStatus(parseStatus);
+        file.setParseError(parseError);
+        file.setSortNo(sortNo);
+        file.setCreateById(operatorId);
+        file.setCreateTime(now);
+        file.setUpdateById(operatorId);
+        file.setUpdateTime(now);
+        file.setDelFlag(0);
+        file.setTenantId(tenantId);
+        fileMapper.insert(file);
+    }
+
+    private void submitAfterCommit(final String generationId) {
+        Runnable task = new Runnable() {
+            @Override
+            public void run() {
+                asyncService.execute(generationId);
+            }
+        };
+        if (TransactionSynchronizationManager.isSynchronizationActive()) {
+            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
+                @Override
+                public void afterCommit() {
+                    task.run();
+                }
+            });
+        } else {
+            task.run();
+        }
+    }
+
+    /**
+     * 查询生成状态与四段结果,只返回同租户记录。
+     */
+    public AiGenerationStatusDTO status(String generationId) {
+        if (StringUtils.isBlank(generationId)) {
+            throw new ProgramAuditAiException("GENERATION_ID_REQUIRED", "生成记录ID不能为空");
+        }
+        ProgramAuditAiGeneration generation = generationMapper.selectById(generationId);
+        if (generation == null) {
+            throw new ProgramAuditAiException("GENERATION_NOT_FOUND", "生成记录不存在", HttpStatus.NOT_FOUND);
+        }
+        String tenantId = currentTenantId();
+        if (StringUtils.isBlank(tenantId) || !StringUtils.equals(tenantId, generation.getTenantId())) {
+            throw new ProgramAuditAiException("TENANT_MISMATCH", "无权查看该生成记录", HttpStatus.FORBIDDEN);
+        }
+
+        AiGenerationStatusDTO dto = new AiGenerationStatusDTO();
+        dto.setGenerationId(generation.getId());
+        dto.setStatus(generation.getStatus());
+        dto.setDetailContent(ensureSegmentContent(generation.getDetailContent(), generation.getDetailStatus(), "明细表", generation.getErrorMessage()));
+        dto.setReportContent(ensureSegmentContent(generation.getReportContent(), generation.getReportStatus(), "评估报告", generation.getErrorMessage()));
+        dto.setRemarksContent(ensureSegmentContent(generation.getRemarksContent(), generation.getRemarksStatus(), "技术说明", generation.getErrorMessage()));
+        dto.setWorkContent(ensureSegmentContent(generation.getWorkContent(), generation.getWorkStatus(), "工作底稿", generation.getErrorMessage()));
+        dto.setDetailStatus(generation.getDetailStatus());
+        dto.setReportStatus(generation.getReportStatus());
+        dto.setRemarksStatus(generation.getRemarksStatus());
+        dto.setWorkStatus(generation.getWorkStatus());
+        dto.setErrorCode(generation.getErrorCode());
+        dto.setErrorMessage(generation.getErrorMessage());
+        dto.setStartedAt(generation.getStartedAt());
+        dto.setFinishedAt(generation.getFinishedAt());
+        dto.setDurationMs(generation.getDurationMs());
+
+        List<String> warnings = new ArrayList<>();
+        String[] labels = new String[]{"明细表", "评估报告", "技术说明", "工作底稿"};
+        String[] statuses = new String[]{generation.getDetailStatus(), generation.getReportStatus(),
+                generation.getRemarksStatus(), generation.getWorkStatus()};
+        QueryWrapper<ProgramAuditAiGenerationFile> skippedQuery = new QueryWrapper<>();
+        skippedQuery.eq("generation_id", generation.getId()).eq("parse_status", "skipped");
+        List<ProgramAuditAiGenerationFile> skippedFiles = fileMapper.selectList(skippedQuery);
+        Set<String> unsupportedTypes = new LinkedHashSet<>();
+        for (ProgramAuditAiGenerationFile skippedFile : skippedFiles) {
+            unsupportedTypes.add(StringUtils.defaultIfBlank(skippedFile.getFileType(), "未知"));
+        }
+        String unsupportedWarning = unsupportedWarning(unsupportedTypes);
+        if (unsupportedWarning != null) {
+            warnings.add(unsupportedWarning);
+        }
+        for (int i = 0; i < SEGMENT_KEYS.length; i++) {
+            if (!"generated".equals(statuses[i])) {
+                warnings.add(labels[i] + "未生成,原因已回填");
+            }
+        }
+        dto.setWarning(warnings.isEmpty() ? null : StringUtils.join(warnings, ";").replace("。;", ";"));
+        return dto;
+    }
+
+    private String typeText(Set<String> types) {
+        List<String> names = new ArrayList<>();
+        for (String type : types) {
+            names.add("未知".equals(type) ? type : "." + type);
+        }
+        return String.join("、", names);
+    }
+
+    private String unsupportedWarning(Set<String> types) {
+        if (types == null || types.isEmpty()) {
+            return null;
+        }
+        return "不支持" + types.size() + "种类型的文件(" + typeText(types) + ")。使用其他文件生成校审意见。";
+    }
+
+    private String ensureSegmentContent(String content, String status, String label, String errorMessage) {
+        if (StringUtils.isNotBlank(content)) {
+            return content;
+        }
+        if ("skipped".equals(status)) {
+            return label + "缺少可用资料,未生成校审意见:AI 未返回具体缺失资料说明。";
+        }
+        if ("failed".equals(status)) {
+            return label + "生成失败,未生成校审意见:"
+                    + (StringUtils.isBlank(errorMessage) ? "AI 未返回具体错误原因。" : errorMessage);
+        }
+        return content;
+    }
+
+    private UserDTO currentUser() {
+        try {
+            return SecurityUtils.getCurrentUserDTO();
+        } catch (Exception e) {
+            log.warn("校审AI取当前用户失败: {}", e.getMessage());
+            return null;
+        }
+    }
+
+    private String currentTenantId() {
+        UserDTO user = currentUser();
+        if (user != null && user.getTenantDTO() != null && StringUtils.isNotBlank(user.getTenantDTO().getId())) {
+            return user.getTenantDTO().getId();
+        }
+        try {
+            return SpringUtil.getBean(ITenantApi.class).getCurrentTenantId();
+        } catch (Exception e) {
+            log.warn("校审AI取当前租户失败: {}", e.getMessage());
+            return null;
+        }
+    }
+
+    private int maxFiles() {
+        return properties.getMaxFiles() == null ? 20 : Math.max(1, properties.getMaxFiles());
+    }
+
+    private long maxFileBytes() {
+        int mb = properties.getMaxFileSizeMb() == null ? 50 : Math.max(1, properties.getMaxFileSizeMb());
+        return (long) mb * 1024L * 1024L;
+    }
+
+    private long maxTotalBytes() {
+        int mb = properties.getMaxTotalSizeMb() == null ? 200 : Math.max(1, properties.getMaxTotalSizeMb());
+        return (long) mb * 1024L * 1024L;
+    }
+
+    private String extension(String fileName, String type) {
+        String ext = StringUtils.lowerCase(StringUtils.trimToEmpty(type));
+        ext = ext.replace(".", "");
+        if (StringUtils.isBlank(ext) || ext.contains("/")) {
+            int pos = fileName.lastIndexOf('.');
+            ext = pos >= 0 ? fileName.substring(pos + 1) : "";
+        }
+        return StringUtils.lowerCase(ext);
+    }
+
+    private long parseSize(String size, String fileSize) {
+        String text = StringUtils.defaultIfBlank(size, fileSize);
+        if (StringUtils.isBlank(text)) {
+            return 0L;
+        }
+        String value = text.trim().toUpperCase();
+        BigDecimal multiplier = BigDecimal.ONE;
+        if (value.endsWith("GB")) {
+            multiplier = BigDecimal.valueOf(1024L * 1024L * 1024L);
+            value = value.substring(0, value.length() - 2).trim();
+        } else if (value.endsWith("MB")) {
+            multiplier = BigDecimal.valueOf(1024L * 1024L);
+            value = value.substring(0, value.length() - 2).trim();
+        } else if (value.endsWith("KB")) {
+            multiplier = BigDecimal.valueOf(1024L);
+            value = value.substring(0, value.length() - 2).trim();
+        } else if (value.endsWith("B")) {
+            value = value.substring(0, value.length() - 1).trim();
+        }
+        try {
+            return new BigDecimal(value).multiply(multiplier).setScale(0, RoundingMode.HALF_UP).longValue();
+        } catch (Exception e) {
+            return 0L;
+        }
+    }
+
+    private String normalizeOssKey(String url) {
+        String key = StringUtils.removeStart(url.trim(), "/");
+        int query = key.indexOf('?');
+        if (query >= 0) {
+            key = key.substring(0, query);
+        }
+        return key;
+    }
+
+    private static class FileSnapshot {
+        private AiAttachmentDTO attachment;
+        private String fileName;
+        private String fileType;
+        private long fileSize;
+        private String storagePath;
+    }
+}

+ 26 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/service/dto/AiAttachmentDTO.java

@@ -0,0 +1,26 @@
+package com.jeeplus.assess.programAuditAi.service.dto;
+
+import lombok.Data;
+
+/**
+ * 前端传入的项目登记附件。直接使用项目登记时已有的附件列表。
+ */
+@Data
+public class AiAttachmentDTO {
+
+    private String id;
+
+    private String name;
+
+    /** 兼容前端 fileName */
+    private String fileName;
+
+    private String url;
+
+    /** 字节数字符串,兼容前端上传组件的 size/fileSize */
+    private String size;
+
+    private String type;
+
+    private String fileSize;
+}

+ 23 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/service/dto/AiGenerateReqDTO.java

@@ -0,0 +1,23 @@
+package com.jeeplus.assess.programAuditAi.service.dto;
+
+import lombok.Data;
+
+import java.util.List;
+
+/**
+ * 发起校审 AI 生成请求。
+ */
+@Data
+public class AiGenerateReqDTO {
+
+    private String programId;
+
+    /** 当前校审记录 ID,可为空(例如新建校审尚未落库) */
+    private String auditId;
+
+    /** 一级/二级/三级 */
+    private String auditLevel;
+
+    /** 当前表单已有附件 */
+    private List<AiAttachmentDTO> workAttachmentDtoList;
+}

+ 21 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/service/dto/AiGenerateRespDTO.java

@@ -0,0 +1,21 @@
+package com.jeeplus.assess.programAuditAi.service.dto;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+/**
+ * 生成任务创建结果。
+ */
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+public class AiGenerateRespDTO {
+
+    private String generationId;
+
+    private String status;
+
+    /** 部分附件不支持时给前端展示的提示 */
+    private String warning;
+}

+ 49 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/service/dto/AiGenerationStatusDTO.java

@@ -0,0 +1,49 @@
+package com.jeeplus.assess.programAuditAi.service.dto;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+import lombok.Data;
+
+import java.util.Date;
+
+/**
+ * 生成任务状态与四段草稿。
+ */
+@Data
+public class AiGenerationStatusDTO {
+
+    private String generationId;
+
+    /** running/success/partial/failed/cancelled */
+    private String status;
+
+    private String detailContent;
+
+    private String reportContent;
+
+    private String remarksContent;
+
+    private String workContent;
+
+    private String detailStatus;
+
+    private String reportStatus;
+
+    private String remarksStatus;
+
+    private String workStatus;
+
+    /** 给前端显示的提示,例如“技术说明未生成,原因已回填” */
+    private String warning;
+
+    private String errorCode;
+
+    private String errorMessage;
+
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
+    private Date startedAt;
+
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
+    private Date finishedAt;
+
+    private Long durationMs;
+}

+ 31 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/programAuditAi/support/ProgramAuditAiException.java

@@ -0,0 +1,31 @@
+package com.jeeplus.assess.programAuditAi.support;
+
+import org.springframework.http.HttpStatus;
+
+/**
+ * 校审 AI 业务异常。
+ */
+public class ProgramAuditAiException extends RuntimeException {
+
+    private final String code;
+
+    private final HttpStatus httpStatus;
+
+    public ProgramAuditAiException(String code, String message) {
+        this(code, message, HttpStatus.BAD_REQUEST);
+    }
+
+    public ProgramAuditAiException(String code, String message, HttpStatus httpStatus) {
+        super(message);
+        this.code = code;
+        this.httpStatus = httpStatus;
+    }
+
+    public String getCode() {
+        return code;
+    }
+
+    public HttpStatus getHttpStatus() {
+        return httpStatus;
+    }
+}

+ 1 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/workContract/mapper/xml/WorkContractInfoMapper.xml

@@ -156,6 +156,7 @@
 			url,
 			attachment_name AS `name`,
 			create_by_id AS `by`,
+			file_size AS `fileSize`,
 			create_time
 		FROM
 			work_attachment

+ 34 - 2
jeeplus-modules/jeeplus-assess/src/main/resources/application-assess-development.yml

@@ -68,11 +68,43 @@ INQUIRE_STATUS: ccpm
 
 CAS_PATH: http://www.casserver.com:8443
 
-# ==================== 价格抓取服务(物料 + 电力共用同一个 Python 服务) ====================
+
+# ==================== 知识助手(WeKnora Embed) ====================
+weknora:
+  base-url: http://192.168.8.136
+  allowed-origin: http://localhost:2800
+  channels:
+    - code: assessKb
+      name: 评估知识助手
+      channel-id: 8a27d49d-afd6-451a-a017-69fc689172fb
+      agent-id: dcab2ac0-f673-45d3-919c-85eb6bcd725e
+      publish-token: em_1HlsFX4ueozXkbTSgRY0k_SPJp3RIUakiw7WglxRJ5A
+      sort: 10
+      is-default: true
+      page-title: 评估知识助手
+  access-retention-days: 180
+
+  ai:
+    audit:
+      base-url: http://192.168.8.136
+      api-key: 'sk-0faUn6g_rDmVC3DKWYcDQm-goiV3U0SN64D2XdlLMi8'
+      agent-id: 20ddb957-0d4d-4cce-8a84-e6d3487e6b58
+      image-agent-id: 8833c860-5a9b-4e32-a092-48196ab8158b
+      max-files: 20
+      max-file-size-mb: 50
+      max-total-size-mb: 200
+      image-text-max-chars: 4000
+      image-text-total-max-chars: 30000
+      generation-timeout-seconds: 300
+      connect-timeout-seconds: 5
+      scan-fallback-enabled: false
+
+
+# ====================  Python 服务====================
 scraper:
   # 抓取服务地址
   base-url: http://127.0.0.1:8100
   # 与 Python 的 SCRAPER_API_KEY 保持一致
-  api-key: dev-key-change-me
+  api-key: xg-34gt-09ji-32ms-j3o2
   # 电力价格下载中转目录:只放 download.tmp 与当前入库文件,处理完即清空
   local-dir: ${java.io.tmpdir}/bowei-scraperdata

+ 34 - 2
jeeplus-modules/jeeplus-assess/src/main/resources/application-assess-production.yml

@@ -56,10 +56,42 @@ signature_daily_office_work: 3206161416121062057
 #评估-报告签章流程id
 signature_report_caregory_id: 3206161481749336766
 
-# ==================== 价格抓取服务(物料 + 电力共用同一个 Python 服务) ====================
+
+# ==================== 知识助手(WeKnora Embed) ====================
+weknora:
+  base-url: http://192.168.8.136
+  allowed-origin: http://localhost:2800
+  channels:
+    - code: assessKb
+      name: 评估知识助手
+      channel-id: 8a27d49d-afd6-451a-a017-69fc689172fb
+      agent-id: dcab2ac0-f673-45d3-919c-85eb6bcd725e
+      publish-token: em_1HlsFX4ueozXkbTSgRY0k_SPJp3RIUakiw7WglxRJ5A
+      sort: 10
+      is-default: true
+      page-title: 评估知识助手
+  access-retention-days: 180
+
+  ai:
+    audit:
+      base-url: http://192.168.8.136
+      api-key: 'sk-0faUn6g_rDmVC3DKWYcDQm-goiV3U0SN64D2XdlLMi8'
+      agent-id: 20ddb957-0d4d-4cce-8a84-e6d3487e6b58
+      image-agent-id: 8833c860-5a9b-4e32-a092-48196ab8158b
+      max-files: 20
+      max-file-size-mb: 50
+      max-total-size-mb: 200
+      image-text-max-chars: 4000
+      image-text-total-max-chars: 30000
+      generation-timeout-seconds: 300
+      connect-timeout-seconds: 5
+      scan-fallback-enabled: false
+
+
+# ====================  Python 服务====================
 scraper:
   # 抓取服务地址
-  base-url: http://183.212.233.18:8100
+  base-url: http://127.0.0.1:8100
   # 与 Python 的 SCRAPER_API_KEY 保持一致
   api-key: xg-34gt-09ji-32ms-j3o2
   # 电力价格下载中转目录:只放 download.tmp 与当前入库文件,处理完即清空