Merge branch 'dev' into hugo-shipping-notice

This commit is contained in:
hugo committed 2026-08-11 14:33:56 +08:00
commit 472b530be3
397 files changed
+46450 -34171

No files matched your search

+3 -1
View File
@@ -13,6 +13,8 @@ backend/local_test.db
deploy
docs/*
!docs/
!docs/(表+字段).md
!docs/integrations/
!docs/integrations/erp/
!docs/integrations/erp/text2sql_schema.md
tmp_restore
tests
+67 -86
View File
@@ -3,31 +3,25 @@
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
# - .env.dev / .env.test / .env.prod for deployment environments
# =============================================================================
# --- 1. 环境与应用标识 ---
ENV_NAME=dev
FLASK_ENV=development
DATABASE_URL=postgresql://hxops:1qaz%40WSX@127.0.0.1/hxops
ORACLE_CLIENT_MOUNT_DIR=/home/lisq/ai/platform/hxops/oracle_client
ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_19_31
LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client
# --- 2. 应用运行与进程 ---
TASK_EXECUTION_MODE=sync
# Gunicorn配置
GUNICORN_WORKERS=10
# --- 3. 公共地址与网络入口 ---
# 知识库 Dify 对接
PUBLIC_BASE_URL=http://192.168.100.192:8890
# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠)
HXOPS_PUBLIC_BASE_URL=http://192.168.100.192:8890
# --- 4. 安全、认证与身份源 ---
# 如果需要用户密码登录,修改该值为password
#AUTH_LOGIN_MODE=casdoor
AUTH_LOGIN_MODE=password
# 是否启用 JWT 认证
AUTH_JWT_REQUIRED=true
AUTH_JWT_ISSUER=http://ait.well-trust.com:8872
# AUTH_LOGIN_MODE=password
# 如果需要用户密码登录,修改该值为password
AUTH_LOGIN_MODE=casdoor
# 必须与 CASDOOR_BASE_URL discovery 返回的 issuer 完全一致,不能填写 HXOPS 地址。
AUTH_JWT_ISSUER=https://autht.well-trust.com
AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
AUTH_JWT_JWKS_URL=http://192.168.100.192:8870/.well-known/jwks
# Casdoor
CASDOOR_BASE_URL=http://192.168.100.192:8870
# 以下为 hxops-dev 应用在 Casdoor 控制台里的 Client ID / Secret(勿与 prod 混用)
@@ -39,14 +33,28 @@ CASDOOR_SCOPE=openid profile email
CASDOOR_ORGANIZATION=organization_HX
# Casdoor Providers → wecom(Name=wecom,与 prod 共用同一 Provider 即可)
CASDOOR_WECOM_PROVIDER_HINT=wecom
# 知识库 Dify 对接
PUBLIC_BASE_URL=http://192.168.100.192:8890
DIFY_API_BASE=http://192.168.100.192:8882/v1
DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF
DEFAULT_ADMIN_USERNAME=admin
DEFAULT_ADMIN_PASSWORD=admin123456
TASK_EXECUTION_MODE=sync
# 采购合同全面审核 Dify Chatflow:开发环境已绑定 HXOPS Agent #17。
# Agent 内保存 API Key,勿在本文件重复写入;修改 Agent 后需重启后端和 hxops-kb-worker。
PROCUREMENT_CONTRACT_LLM_ENABLED=true
# 先复用现有采购合同审查 Chatflow;不受 HXOPS Agent 页面 Dify 应用类型字段影响。
PROCUREMENT_CONTRACT_LLM_PROVIDER=chatflow
PROCUREMENT_CONTRACT_LLM_AGENT_ID=17
PROCUREMENT_CONTRACT_LLM_DIFY_APP_ID=
PROCUREMENT_CONTRACT_LLM_DIFY_API_KEY=
PROCUREMENT_CONTRACT_LLM_DIFY_BASE=http://192.168.100.192:8882/v1
# Gunicorn配置
GUNICORN_WORKERS=10
# --- 5. 数据库与基础设施 ---
DATABASE_URL=postgresql://hxops:1qaz%40WSX@127.0.0.1/hxops
ORACLE_CLIENT_MOUNT_DIR=/home/lisq/ai/platform/hxops/oracle_client
ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_19_31
LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client
# MinIO(知识库文档清洗图片托管;dev 与测试机同机时用测试 MinIO)
# 本地非 Docker 跑 worker 时可改为 127.0.0.1:9000 或 192.168.100.192:9000
# 账号与 minio-app 的 MINIO_ROOT_USER / MINIO_ROOT_PASSWORD 保持一致
@@ -56,94 +64,67 @@ MINIO_SECRET_KEY=M3CLE928P8GavJBFZPhJO3RIHVZSRYlDouOMabasojfAGBlx
MINIO_SECURE=false
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
# --- 6. AI 平台、模型与内部工具 ---
DIFY_API_BASE=http://192.168.100.192:8882/v1
DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF
# 货代发货通知 Agent(见 docs/features/shipping-notice/technical.md §1.2;Tool 基地址见 HXOPS_TOOLS_API_BASE)
# RoHS / 货代等 Dify Tool API 基地址(Dify 服务端内网调用,无尾斜杠)
HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
# --- 9. 业务模块 ---
# XFA 试点门禁覆盖(默认见 .env.shared;自动建单走 Schema 总开关;空客户/checksum 白名单 fail-closed)
# SHIPPING_NOTICE_XFA_SHADOW_MODE=false
# SHIPPING_NOTICE_XFA_CUSTOMER_ALLOWLIST=
# SHIPPING_NOTICE_XFA_PROFILE_CHECKSUM_ALLOWLIST=
# SHIPPING_NOTICE_XFA_SCENARIO_ALLOWLIST=shipping_notice_order
# 自动推进(auto_progress)
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
# 进度细化灰度(阶段 5):新进度 UI / Run-Unit 取消 / 管理员审计导出;回滚只关开关,不删审计
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
# 复核工作台字段级 AI 建议;仅开发环境启用,建议仍须证据校验与人工裁决
SHIPPING_NOTICE_LLM_REVIEW_ENABLED=true
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
# Dify Chatflow(seed_shipping_notice_agents.py)
SHIPPING_NOTICE_CHAT_DIFY_APP_ID=
SHIPPING_NOTICE_CHAT_DIFY_API_KEY=
# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠)
HXOPS_PUBLIC_BASE_URL=http://192.168.100.192:8890
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
SHIPPING_NOTICE_TOOL_API_KEY=MymLe1StfTCuMOl0IYTp-BRYKln_TnywEDxJ0X0mraYjhFtGeL8mRqoiVPlP9Er8
# 文件存储(相对 backend/ 根目录)
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
# 解析与文本上限
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
# MinerU 订单附件表格结构化(服务地址由环境/Secret 注入,未配置时保持关闭)
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=false
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL=
SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS=10
SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS=300
SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE=10
SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY=2
SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS=1000000
SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES=2000000
SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS=3
SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
# 字段对齐确认(生产建议 true;测试可设 false)
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true
# 自动推进(auto_progress)
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=true
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
# RPA 目录(相对 backend/ 根目录)
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
FREIGHT_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers
FREIGHT_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers
FREIGHT_RPA_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
# 发货 Excel 模板(可选)
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
# AWS 库存列映射(可选 JSON 字符串)
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
# Dify Chatflow(seed_shipping_notice_agents.py)
SHIPPING_NOTICE_CHAT_DIFY_APP_ID=
SHIPPING_NOTICE_CHAT_DIFY_API_KEY=
SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
# 本地 RPA(scripts/rpa/freight_rpa_worker.py)
SHIPPING_NOTICE_RPA_WORKER_MOCK=false
# 本机无 Redis 时允许进程内存记录心跳;有 Redis 时优先写 Redis
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK=true
# 企微心跳告警总开关(默认关闭;需要时改为 true)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false
# SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3
# SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY=
# --- 10. 运维、告警与维护工具 ---
FREIGHT_RPA_MOCK=false
# FREIGHT_RPA_POLL_SECONDS=3
# FREIGHT_RPA_SAMPLE_INVENTORY=
# 设备维保助手后端工具调用密钥
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
+43 -68
View File
@@ -3,31 +3,24 @@
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
# - .env.dev / .env.test / .env.prod for deployment environments
# =============================================================================
# --- 1. 环境与应用标识 ---
ENV_NAME=prod
FLASK_ENV=production
DATABASE_URL=postgresql://postgres:difyai123456@192.168.100.230:5432/hxops_db
ORACLE_CLIENT_MOUNT_DIR=/data/ai-platform/hxops/oracle_client
ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_19_31
LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client
# --- 2. 应用运行与进程 ---
TASK_EXECUTION_MODE=rq
# Gunicorn配置
GUNICORN_WORKERS=20
# 是否启用 JWT 认证
AUTH_JWT_REQUIRED=true
# --- 3. 公共地址与网络入口 ---
# 知识库 Dify 对接
PUBLIC_BASE_URL=http://192.168.100.230:8891
# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠)
HXOPS_PUBLIC_BASE_URL=https://ai.well-trust.com
# --- 4. 安全、认证与身份源 ---
# AUTH_LOGIN_MODE=casdoor
# 如果需要用户密码登录,修改该值为password
AUTH_LOGIN_MODE=password
# 是否启用 JWT 认证
AUTH_JWT_REQUIRED=true
AUTH_JWT_ISSUER=http://ai.well-trust.com:8870
AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
AUTH_JWT_JWKS_URL=http://192.168.100.230:8870/.well-known/jwks
# Casdoor
CASDOOR_BASE_URL=https://auth.well-trust.com
# 与 Casdoor 里 Application「hxops-prod」(或你当前生产应用)的 Client ID 一致
@@ -41,14 +34,32 @@ CASDOOR_SCOPE=openid profile email
CASDOOR_ORGANIZATION=organization_HX
# Casdoor Providers → wecom:Name 字段(截图即为 wecom);Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo
CASDOOR_WECOM_PROVIDER_HINT=wecom
# 知识库 Dify 对接
PUBLIC_BASE_URL=http://192.168.100.230:8891
DIFY_API_BASE=http://192.168.100.230:8882/v1
DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF
DEFAULT_ADMIN_USERNAME=admin
DEFAULT_ADMIN_PASSWORD=admin123456
TASK_EXECUTION_MODE=rq
# 采购合同全面审核 Dify Chatflow:正式密钥仅填在本机/Jenkins密文变量,勿写入共享文件。
# 先在 test 验证输出质量后再把 ENABLED 改为 true。
PROCUREMENT_CONTRACT_LLM_ENABLED=false
PROCUREMENT_CONTRACT_LLM_PROVIDER=chatflow
PROCUREMENT_CONTRACT_LLM_AGENT_ID=
PROCUREMENT_CONTRACT_LLM_DIFY_APP_ID=
PROCUREMENT_CONTRACT_LLM_DIFY_API_KEY=
PROCUREMENT_CONTRACT_LLM_DIFY_BASE=http://192.168.100.230:8882/v1
# Gunicorn配置
GUNICORN_WORKERS=20
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com
# --- 5. 数据库与基础设施 ---
DATABASE_URL=postgresql://postgres:difyai123456@192.168.100.230:5432/hxops_db
ORACLE_CLIENT_MOUNT_DIR=/data/ai-platform/hxops/oracle_client
ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_19_31
LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client
# MinIO(知识库文档清洗图片托管,容器 minio-app)
# MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1)
MINIO_ENDPOINT=host.docker.internal:9000
@@ -58,73 +69,37 @@ MINIO_SECURE=false
# MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问
MINIO_PUBLIC_BASE_URL=http://ai.well-trust.com:9000
# --- 6. AI 平台、模型与内部工具 ---
DIFY_API_BASE=http://192.168.100.230:8882/v1
DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF
# RoHS / 货代 / 设备维保等 Dify Tool API 基地址(Dify 服务端内网调用,无尾斜杠)
HXOPS_TOOLS_API_BASE=http://192.168.100.230:8890
# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠)
HXOPS_PUBLIC_BASE_URL=https://ai.well-trust.com
# --- 7. 企业系统集成 ---
WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
# --- 9. 业务模块 ---
# XFA 试点门禁覆盖(默认见 .env.shared;自动建单走 Schema 总开关;空客户/checksum 白名单 fail-closed)
# SHIPPING_NOTICE_XFA_SHADOW_MODE=false
# SHIPPING_NOTICE_XFA_CUSTOMER_ALLOWLIST=
# SHIPPING_NOTICE_XFA_PROFILE_CHECKSUM_ALLOWLIST=
# SHIPPING_NOTICE_XFA_SCENARIO_ALLOWLIST=shipping_notice_order
# 进度细化灰度(阶段 5;生产默认开启,回滚时按需关闭,禁止删除审计事实)
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
# 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥)
SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh
# 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享)
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
# 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥)
SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
# MinerU 订单附件表格结构化(服务地址由 Jenkins/系统环境注入,未配置时保持关闭)
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=false
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL=
SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS=10
SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS=300
SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE=10
SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY=2
SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS=1000000
SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES=2000000
SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS=3
SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=false
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=false
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=false
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
FREIGHT_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/inventory_drop
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/inventory_triggers
FREIGHT_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/upload_queue
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/upload_triggers
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致)
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
# 企微心跳告警总开关(默认关闭;需要时改为 true)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false
# 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/inventory_drop
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/inventory_triggers
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/upload_queue
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/upload_triggers
# 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
# --- 10. 运维、告警与维护工具 ---
# 设备维保助手后端工具调用密钥
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
+83 -151
View File
@@ -1,38 +1,11 @@
# Shared environment variables for all environments (dev/test/prod)
# Keep only values that are truly identical across all environments.
# --- 1. 环境与应用标识 ---
# Runtime selector fallback (actual deployment still sets ENV_NAME explicitly)
ENV_NAME=dev
# Common runtime defaults
FLASK_APP=run.py
# --- 3. 公共地址与网络入口 ---
# HXOPS 浏览器可访问根地址(Excel 签名下载等用户可见链接;无尾斜杠;各环境 .env.* 覆盖)
HXOPS_PUBLIC_BASE_URL=
# --- 4. 安全、认证与身份源 ---
SECRET_KEY=hxops-dify
AUTH_JWT_REQUIRED=true
# 是否保留本地密码登录/本地TWT兼容
AUTH_ALLOW_LOCAL_PASSWORD_LOGIN=true
AUTH_ALLOW_LOCAL_JWT=true
AUTH_LOCAL_JWT_ISSUER=hxops-backend
AUTH_LOCAL_JWT_AUDIENCE=hxops-frontend
AUTH_LOCAL_JWT_EXPIRES_HOURS=12
# Common auth defaults
AUTH_LEGACY_HEADER_ENABLED=true
# --- 5. 数据库与基础设施 ---
# MinIO:按环境配置见 .env.dev / .env.test / .env.prod
# MINIO_KB_IMAGE_BUCKET — 知识库文档清洗图片托管(kb-worker / export)
# MINIO_AGENT_GUIDES_BUCKET — Agent 指南文件上传(Flask minio_service)
MINIO_KB_IMAGE_BUCKET=image-hosting-service
MINIO_AGENT_GUIDES_BUCKET=agent-guides
# --- 6. AI 平台、模型与内部工具 ---
# Common integration defaults
INTEGRATION_API_MODE=local
# 知识库管理(后续需要修改此地址)
# 查「Dify 文档对应原始源文件下载地址」时,要连的那台 Integration API 的根 URL
INTEGRATION_API_BASE=http://192.168.100.230:8891
@@ -40,17 +13,53 @@ INTEGRATION_API_BASE=http://192.168.100.230:8891
INTEGRATION_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
# 文件检核 Tool API Key;未单独配置时建议与 INTEGRATION_API_KEY 保持一致
FILE_CHECK_TOOL_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
DIFY_API_BASE=https://api.dify.ai/v1
# HXOPS Tool API 对外基地址(RoHS / 货代等 Dify Chatflow 服务端调用;无尾斜杠;各环境 .env.* 覆盖)
HXOPS_TOOLS_API_BASE=
GJL_API_BASE=https://api.siliconflow.cn/v1
# 硅基流动相关
GJL_API_KEY=sk-umfzicwjcvwampzblqczckkqojiscyybtaljzbsvpdwdvxlu
GJL_MODEL=deepseek-ai/DeepSeek-V3
# 硅基流动 ASR:FunAudioLLM/SenseVoiceSmall 或 TeleAI/TeleSpeechASR
ASR_MODEL=FunAudioLLM/SenseVoiceSmall
# --- 7. 企业系统集成 ---
SECRET_KEY=hxops-dify
# Knowledge base runtime
# KB_STORAGE_ROOT=backend/data/kb
KB_TASK_EXECUTION_MODE=worker
KB_WORKER_POLL_SECONDS=2
KB_WORKER_CONCURRENCY=3
# Linux 容器内 LibreOffice 路径(避免探测 Windows 安装路径)
EDKB_SOFFICE=/usr/bin/soffice
# LibreOffice 单次格式转换超时(秒);复杂 .doc 在容器内可能需 10 分钟左右
EDKB_SOFFICE_TIMEOUT_SEC=600
# Windows Word COM / word_bridge 单次转换超时(秒);复杂 .doc 可适当放宽
EDKB_WORD_TIMEOUT_SEC=300
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免单条任务长期卡住整个 worker
EDKB_FILE_TIMEOUT_SEC=300
EDKB_PDF_FILE_TIMEOUT_SEC=900
# Word 文档(.doc/.docx)单文件清洗总超时(秒);优先于 EDKB_FILE_TIMEOUT_SEC
EDKB_WORD_FILE_TIMEOUT_SEC=420
# running 任务回收阈值,须大于 EDKB_SOFFICE_TIMEOUT_SEC 及整条清洗链路耗时
KB_JOB_RUNNING_TIMEOUT_SECONDS=1200
# 采购合同全面审核:三环境一致的异步任务与输入保护参数
# 清洗产物目录由各环境相对 backend/ 根目录解析;容器部署可由 Compose 覆盖为 /app/data/procurement_contract
PROCUREMENT_CONTRACT_STORAGE_ROOT=data/procurement_contract
# 须覆盖清洗、条款结构化和一次 Dify Chatflow 调用;超时后任务可自动重试
PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS=600
PROCUREMENT_CONTRACT_LLM_CONNECT_TIMEOUT_SECONDS=5
PROCUREMENT_CONTRACT_LLM_READ_TIMEOUT_SECONDS=120
# 中短合同的单次全面审核上限;达到上限时后端标记 bounded_contract,不宣称全文覆盖
PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS=120000
PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES=160
# chat回答的评分与评论
FEEDBACK_ENABLED=true
# Common auth defaults
AUTH_LEGACY_HEADER_ENABLED=true
AUTH_JWT_REQUIRED=true
# 是否保留本地密码登录/本地TWT兼容
AUTH_ALLOW_LOCAL_PASSWORD_LOGIN=true
AUTH_ALLOW_LOCAL_JWT=true
AUTH_LOCAL_JWT_ISSUER=hxops-backend
AUTH_LOCAL_JWT_AUDIENCE=hxops-frontend
AUTH_LOCAL_JWT_EXPIRES_HOURS=12
# WeCom
WECOM_ENABLED=true
WECOM_CORP_ID=ww1ada6c11b684783e
@@ -78,6 +87,29 @@ WECOM_FEEDBACK_NOTIFY_ENABLED=true
WECOM_FEEDBACK_NOTIFY_BASE_URL=http://ai.well-trust.com:8881
# 企业微信群机器人 webhook,按环境写入 .env.<env> 或部署平台变量;不要提交真实 URL。
WECOM_FEEDBACK_BOT_WEBHOOK=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=bdb65cf6-e537-44b2-a10b-d826b15f4498
# Common integration defaults
INTEGRATION_API_MODE=local
DIFY_API_BASE=https://api.dify.ai/v1
# HXOPS Tool API 对外基地址(RoHS / 货代等 Dify Chatflow 服务端调用;无尾斜杠;各环境 .env.* 覆盖)
HXOPS_TOOLS_API_BASE=
# HXOPS 浏览器可访问根地址(Excel 签名下载等用户可见链接;无尾斜杠;各环境 .env.* 覆盖)
HXOPS_PUBLIC_BASE_URL=
# MinIO:按环境配置见 .env.dev / .env.test / .env.prod
# MINIO_KB_IMAGE_BUCKET — 知识库文档清洗图片托管(kb-worker / export)
# MINIO_AGENT_GUIDES_BUCKET — Agent 指南文件上传(Flask minio_service)
MINIO_KB_IMAGE_BUCKET=image-hosting-service
MINIO_AGENT_GUIDES_BUCKET=agent-guides
# 硅基流动相关
GJL_API_KEY=sk-umfzicwjcvwampzblqczckkqojiscyybtaljzbsvpdwdvxlu
GJL_API_BASE=https://api.siliconflow.cn/v1
GJL_MODEL=deepseek-ai/DeepSeek-V3
# 硅基流动 ASR:FunAudioLLM/SenseVoiceSmall 或 TeleAI/TeleSpeechASR
ASR_MODEL=FunAudioLLM/SenseVoiceSmall
# HR SQL Server Configuration
HR_SQLSERVER_HOST=192.168.100.191
HR_SQLSERVER_PORT=1433
@@ -88,12 +120,14 @@ HR_SQLSERVER_DRIVER=ODBC Driver 18 for SQL Server
HR_SQLSERVER_ENCRYPT=no
HR_SQLSERVER_TRUST_CERT=yes
HR_SQLSERVER_TIMEOUT=10
# PLM Oracle
PLM_ORACLE_HOST=192.168.0.11
PLM_ORACLE_PORT=1521
PLM_ORACLE_SID=orcl
PLM_ORACLE_USERNAME=PLM
PLM_ORACLE_PASSWORD=PLM
# SRM SQL Server Configuration
SRM_SQLSERVER_HOST=192.168.55.106
SRM_SQLSERVER_PORT=1433
@@ -104,33 +138,23 @@ SRM_SQLSERVER_DRIVER=ODBC Driver 18 for SQL Server
SRM_SQLSERVER_ENCRYPT=no
SRM_SQLSERVER_TRUST_CERT=yes
SRM_SQLSERVER_TIMEOUT=10
# ERP
ERP_DB_DSN=192.168.8.24:1521/topprod
TEXT2SQL_SCHEMA_PATH=
# --- 8. 知识库与文件处理 ---
# Knowledge base runtime
# KB_STORAGE_ROOT=backend/data/kb
KB_TASK_EXECUTION_MODE=worker
KB_WORKER_POLL_SECONDS=2
KB_WORKER_CONCURRENCY=3
# running 任务回收阈值,须大于 EDKB_SOFFICE_TIMEOUT_SEC 及整条清洗链路耗时
KB_JOB_RUNNING_TIMEOUT_SECONDS=900
# Linux 容器内 LibreOffice 路径(避免探测 Windows 安装路径)
EDKB_SOFFICE=/usr/bin/soffice
# LibreOffice 单次格式转换超时(秒);复杂 .doc 在容器内可能需 10 分钟左右
EDKB_SOFFICE_TIMEOUT_SEC=600
# Windows Word COM / word_bridge 单次转换超时(秒);复杂 .doc 可适当放宽
EDKB_WORD_TIMEOUT_SEC=300
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免单条任务长期卡住整个 worker
EDKB_FILE_TIMEOUT_SEC=300
# Word 文档(.doc/.docx)单文件清洗总超时(秒);优先于 EDKB_FILE_TIMEOUT_SEC
EDKB_WORD_FILE_TIMEOUT_SEC=420
# 固资履历共享盘
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
# --- 9. 业务模块 ---
# 固资图片文档库
FIXED_ASSET_IMAGE_BASE_URL=http://192.168.8.158:8071/Web/#/login
FIXED_ASSET_IMAGE_USERNAME=26040006
FIXED_ASSET_IMAGE_PASSWORD=26040006
FIXED_ASSET_IMAGE_LIBRARY_ID=8d61bd96-ff2d-489b-86fc-ca0b8c6bbcf8
FIXED_ASSET_IMAGE_FOLDER_ID=3aea6c19-d9ac-40fa-ab16-9cb06c0db3e3
# chat回答的评分与评论
FEEDBACK_ENABLED=true
# 热点 FAQ 离线聚合(ChatLog -> PostgreSQL faq_hot_candidates 表)
# 管理端「常用问题 > 热点发现」刷新聚合时读取以下配置
FAQ_HOT_ENABLED=true # 是否启用热点聚合(false 时刷新/CLI 直接跳过)
@@ -146,97 +170,5 @@ FAQ_HOT_ANSWER_SIMILARITY=0.95 # (聚类已关闭)答案聚类相
FAQ_HOT_ANSWER_DOMINANCE=0.6 # (聚类已关闭)最大答案簇占比下限,恢复聚类时生效
FAQ_HOT_GOOD_SCORE=4 # 选代表答案时「好评」反馈分阈值(≥此分优先)
FAQ_HOT_BAD_SCORE=2 # 选代表答案时「差评」反馈分阈值(≤此分排除)
# 货代客户自动确认默认关闭;仅 approved + auto_match_allowed 强规则唯一命中时可开启。
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED=true
# OT 后行级自动履约(默认关):关闭时只上线匹配事实契约/明细库存列;禁止自动决定与 wave。
SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED=false
# 发货通知专用 Worker 进程数;版面解析为长任务,默认并发处理同批两份文档。
SHIPPING_NOTICE_WORKER_CONCURRENCY=2
# Layout Job 内整页 OCR 结果复用(PR-1);共享默认关,dev/test 环境文件覆盖为 true,prod 保持 false 灰度。
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=false
# PDFium 字符预读复用与按需补图(PR-2);共享默认关,dev/test 开启,prod 灰度。
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=false
# 表格裁剪 OCR(PR-3);共享默认关;裁剪边距默认 3%。
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=false
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
# 通用 Job 回收阈值须高于版面 Worker 360 秒上限,避免并发 Worker 误回收正常长任务。
SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS=420
# 资格达标后 waiting_to_start 且无 STP 入队记录的超时(秒);超时投影 manual_fallback。
SHIPPING_NOTICE_STP_WAITING_TIMEOUT_SECONDS=120
# 门禁 Attempt 租约 / 心跳 / 接管 / 技术重试(与 process_gate_job_service 默认一致)。
SHIPPING_PROCESS_GATE_LEASE_SECONDS=60
SHIPPING_PROCESS_GATE_HEARTBEAT_SECONDS=15
SHIPPING_PROCESS_GATE_TAKEOVER_SECONDS=120
SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES=3
SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS=30
SHIPPING_PROCESS_GATE_EXTERNAL_WAIT_TIMEOUT_SECONDS=1800
# 订单行双写/切读:dual 写 + shadow 观察;全量 verify 零差异且观察窗口通过后切 table。
# 回滚:将 READ_MODE 改回 json(或 shadow)即可,本期不删 lines_json。
SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE=dual
SHIPPING_NOTICE_ORDER_LINES_READ_MODE=shadow
# RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。
# 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=
# 点击发送后的完整订单识别超时;超时 Intake 在状态读取时收口为 failed。
SHIPPING_NOTICE_ORDER_EXTRACTION_TIMEOUT_SECONDS=300
# 订单解析主链灰度(默认关闭高风险路径;主链不依赖 Dify)。
# L7 验收完成前禁止开启通用解析与通用自动冻结。
# 通用确定性解析:仅 no_special_profile_feature / 无漂移 no_match 可进入。
SHIPPING_NOTICE_GENERIC_EXTRACTION_ENABLED=false
# 通用路径自动冻结:须 generic 门禁通过且 STP=straight_through。
SHIPPING_NOTICE_GENERIC_AUTO_FREEZE_ENABLED=false
# 模板多维评分自动采用(Top1 决胜);关闭后评分命中仍须人工确认。
SHIPPING_NOTICE_PROFILE_AUTO_SELECTION_ENABLED=true
# 阶段四全量切换:全部模板重签并重新发布后改为 true
SHIPPING_NOTICE_PROFILE_LAYOUT_SIGNATURE_REQUIRED=true
# XFA 数据路径 Profile(识别到 xfa_hybrid 即正式提取)
SHIPPING_NOTICE_XFA_ENABLED=true
# 独立自动建单总闸(阶段 5+);默认关。开启前须合成预览门禁 / CQ / 盲测 / 审计补偿就绪。
SHIPPING_NOTICE_XFA_AUTO_CREATE_ENABLED=false
# 离线完整 flatten 引擎是否已交付;默认 false(禁 overlay/壳图充当图源)。
SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY=false
# 自动建单硬前置:审计写失败补偿能力就绪前禁止开自动建单。
SHIPPING_NOTICE_XFA_AUDIT_COMPENSATION_REQUIRED_FOR_AUTO_CREATE=true
# shadow=true:完整解析与资格评估,但阻断真实自动建单(仅记录 would_auto_create)
SHIPPING_NOTICE_XFA_SHADOW_MODE=false
# 自动建单硬门禁白名单:客户或 Profile checksum 为空 → fail-closed
SHIPPING_NOTICE_XFA_CUSTOMER_ALLOWLIST=
SHIPPING_NOTICE_XFA_PROFILE_CHECKSUM_ALLOWLIST=
SHIPPING_NOTICE_XFA_SCENARIO_ALLOWLIST=shipping_notice_order
SHIPPING_NOTICE_XFA_MAX_PDF_BYTES=20971520
SHIPPING_NOTICE_XFA_MAX_PACKET_BYTES=10485760
SHIPPING_NOTICE_XFA_MAX_XML_DEPTH=64
SHIPPING_NOTICE_XFA_MAX_XML_NODES=100000
SHIPPING_NOTICE_XFA_MAX_LINE_ROWS=2000
SHIPPING_NOTICE_XFA_PARSE_TIMEOUT_SECONDS=30
SHIPPING_NOTICE_XFA_MAX_RETRIES=2
# XFA 字段拆分规则资源上限(统一方案阶段 1;与 settings.XFA_SPLIT_* 对齐)
XFA_SPLIT_MAX_RULES_PER_SET=32
XFA_SPLIT_MAX_RULE_SETS=64
XFA_SPLIT_MAX_REGEX_PATTERN_LENGTH=128
XFA_SPLIT_MAX_REGEX_GROUPS=5
XFA_SPLIT_MAX_PREFIX_LENGTH=64
XFA_SPLIT_MAX_INPUT_LENGTH=32768
XFA_SPLIT_REGEX_TIMEOUT_MS=50
# 复核台 Dify 最小证据建议;永不自动冻结。
SHIPPING_NOTICE_LLM_REVIEW_ENABLED=true
# 全局紧急停止:新 Run 自动冻结立即为 0(进程配置;多 worker 需逐进程/重启生效)。
SHIPPING_NOTICE_EXTRACTION_EMERGENCY_STOP=false
# 货代统一审计默认保留天数(三年);到期由 shipping-audit-retention Job 清理。
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
# 货代上传 RPA:默认关闭;具备 Worker/凭据/共享目录与隔离校验后再在环境文件显式设 true。
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
# Freight RPA defaults to real browser automation. Set to true only for local mock/debug runs.
SHIPPING_NOTICE_RPA_WORKER_MOCK=false
# 企微心跳告警总开关(默认关闭;需要时在环境文件改为 true)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false
# 固资履历共享盘
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
# 固资图片文档库
FIXED_ASSET_IMAGE_BASE_URL=http://192.168.8.158:8071/Web/#/login
FIXED_ASSET_IMAGE_USERNAME=26040006
FIXED_ASSET_IMAGE_PASSWORD=26040006
FIXED_ASSET_IMAGE_LIBRARY_ID=8d61bd96-ff2d-489b-86fc-ca0b8c6bbcf8
FIXED_ASSET_IMAGE_FOLDER_ID=3aea6c19-d9ac-40fa-ab16-9cb06c0db3e3
FREIGHT_RPA_MOCK=false
+87 -95
View File
@@ -3,30 +3,25 @@
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
# - .env.dev / .env.test / .env.prod for deployment environments
# =============================================================================
# --- 1. 环境与应用标识 ---
ENV_NAME=test
FLASK_ENV=test
DATABASE_URL=postgresql://postgres:8je2olWwHj28fCfVTgRWmankoTQORjqyBn6iIK3dG2q10vAq@192.168.100.192:5432/hxops_testing
ORACLE_CLIENT_MOUNT_DIR=/home/lisq/ai/platform/hxops/oracle_client
ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_23_26
LD_LIBRARY_PATH=/app/oracle_client/instantclient_23_26:/app/oracle_client
# --- 2. 应用运行与进程 ---
TASK_EXECUTION_MODE=rq
# Gunicorn配置
GUNICORN_WORKERS=6
# --- 3. 公共地址与网络入口 ---
# 知识库 Dify 对接
PUBLIC_BASE_URL=http://192.168.100.192:8891
HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
# --- 4. 安全、认证与身份源 ---
# 如果需要用户密码登录,修改该值为password
#AUTH_LOGIN_MODE=casdoor
AUTH_LOGIN_MODE=casdoor
# 是否启用 JWT 认证
AUTH_JWT_REQUIRED=true
AUTH_JWT_ISSUER=http://ait.well-trust.com:8872
AUTH_LOGIN_MODE=casdoor
# 如果需要用户密码登录,修改该值为password
#AUTH_LOGIN_MODE=casdoor
# 必须与 CASDOOR_BASE_URL discovery 返回的 issuer 完全一致,不能填写 HXOPS 地址。
AUTH_JWT_ISSUER=https://autht.well-trust.com
AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
AUTH_JWT_JWKS_URL=http://192.168.100.192:8870/.well-known/jwks
# Casdoor
CASDOOR_BASE_URL=https://autht.well-trust.com
# 与 Casdoor 里 Application「hxops-prod」(或你当前生产应用)的 Client ID 一致
@@ -40,14 +35,42 @@ CASDOOR_SCOPE=openid profile email
CASDOOR_ORGANIZATION=organization_HX
# Casdoor Providers → wecom:Name 字段;Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo
CASDOOR_WECOM_PROVIDER_HINT=wecom
# 知识库 Dify 对接
PUBLIC_BASE_URL=http://192.168.100.192:8891
DIFY_API_BASE=http://192.168.100.192:8882/v1
DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF
DEFAULT_ADMIN_USERNAME=admin
DEFAULT_ADMIN_PASSWORD=admin123456
TASK_EXECUTION_MODE=rq
# 采购合同全面审核 Dify Chatflow:填入测试 Agent 后再开启。
PROCUREMENT_CONTRACT_LLM_ENABLED=false
PROCUREMENT_CONTRACT_LLM_PROVIDER=chatflow
PROCUREMENT_CONTRACT_LLM_AGENT_ID=
PROCUREMENT_CONTRACT_LLM_DIFY_APP_ID=
PROCUREMENT_CONTRACT_LLM_DIFY_API_KEY=
PROCUREMENT_CONTRACT_LLM_DIFY_BASE=http://192.168.100.192:8882/v1
# 测试服务器本机 MinerU API;后端和 Worker 容器经 host-gateway 访问宿主机 8100。
PROCUREMENT_CONTRACT_MINERU_API_URL=http://host.docker.internal:8100
PROCUREMENT_CONTRACT_MINERU_BACKEND=pipeline
PROCUREMENT_CONTRACT_MINERU_PARSE_METHOD=auto
PROCUREMENT_CONTRACT_MINERU_CONNECT_TIMEOUT_SECONDS=5
PROCUREMENT_CONTRACT_MINERU_READ_TIMEOUT_SECONDS=300
# 合同产物(源文件副本、MinerU 结果、清洗正文、条款和报告)归档至独立私有桶;成功后删除本地缓存。
PROCUREMENT_CONTRACT_ARCHIVE_ENABLED=true
PROCUREMENT_CONTRACT_ARCHIVE_BUCKET=procurement-contract
PROCUREMENT_CONTRACT_ARCHIVE_CLEANUP_LOCAL=true
# Gunicorn配置
GUNICORN_WORKERS=6
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
WECOM_PUBLIC_BASE_URL=https://ait.well-trust.com
HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
# --- 5. 数据库与基础设施 ---
DATABASE_URL=postgresql://postgres:8je2olWwHj28fCfVTgRWmankoTQORjqyBn6iIK3dG2q10vAq@192.168.100.192:5432/hxops_testing
ORACLE_CLIENT_MOUNT_DIR=/home/lisq/ai/platform/hxops/oracle_client
ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_23_26
LD_LIBRARY_PATH=/app/oracle_client/instantclient_23_26:/app/oracle_client
# MinIO(知识库文档清洗图片托管,容器 minio-app)
# MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1)
# 账号与 minio-app 的 MINIO_ROOT_USER / MINIO_ROOT_PASSWORD(及 DIFY_S3_ACCESS_KEY)保持一致
@@ -58,112 +81,81 @@ MINIO_SECURE=false
# MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
# --- 6. AI 平台、模型与内部工具 ---
DIFY_API_BASE=http://192.168.100.192:8882/v1
DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF
# 货代发货通知 Agent(见 docs/features/shipping-notice/technical.md §1.2;Tool 基地址见 HXOPS_TOOLS_API_BASE)
# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
HXOPS_TOOLS_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
# 货代专用 Tool API Key(RPA 回调优先读取;真实值请在服务器本地配置,禁止提交真实密钥)
SHIPPING_NOTICE_TOOL_API_KEY=GOnGt04o0-Ev4wEw6a6C4NOmm4XF7dxsLPP6fPtTC2vV341l1QKVASV75ONj72er
# --- 7. 企业系统集成 ---
WECOM_PUBLIC_BASE_URL=https://ait.well-trust.com
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
# 文件存储(相对 backend/ 根目录)
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
# --- 9. 业务模块 ---
# 解析与文本上限
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
# XFA 试点门禁覆盖(默认见 .env.shared;自动建单走 Schema 总开关;空客户/checksum 白名单 fail-closed)
# SHIPPING_NOTICE_XFA_SHADOW_MODE=false
# SHIPPING_NOTICE_XFA_CUSTOMER_ALLOWLIST=
# SHIPPING_NOTICE_XFA_PROFILE_CHECKSUM_ALLOWLIST=
# SHIPPING_NOTICE_XFA_SCENARIO_ALLOWLIST=shipping_notice_order
# 字段对齐确认(生产建议 true;测试可设 false)
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true
# 自动推进(auto_progress)
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
# 进度细化灰度(阶段 5):新进度 UI / Run-Unit 取消 / 管理员审计导出;回滚只关开关,不删审计
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
# Dify Chatflow(seed_shipping_notice_agents.py)
SHIPPING_NOTICE_CHAT_DIFY_APP_ID=
SHIPPING_NOTICE_CHAT_DIFY_API_KEY=
# 货代专用 Tool API Key(RPA 回调优先读取;真实值请在服务器本地配置,禁止提交真实密钥)
SHIPPING_NOTICE_TOOL_API_KEY=GOnGt04o0-Ev4wEw6a6C4NOmm4XF7dxsLPP6fPtTC2vV341l1QKVASV75ONj72er
# 文件存储(相对 backend/ 根目录)
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
# 解析与文本上限
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
# MinerU 订单附件表格结构化(服务地址由环境/Secret 注入,未配置时保持关闭)
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=true
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL=http://192.168.100.192:8100/
SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS=10
SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS=300
SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE=10
SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY=2
SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS=1000000
SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES=2000000
SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS=3
SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
# 字段对齐确认(生产建议 true;测试可设 false)
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐)
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享)
FREIGHT_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers
FREIGHT_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐)
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
# 企微心跳告警总开关(默认关闭;需要时改为 true)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false
# 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微
# 两者皆无则告警只写日志、不会发企微
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
# 企微发送中短锁秒数(发送失败过期后可重试,默认 120)
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns=
# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享)
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers
# 发货 Excel 模板(可选)
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
# AWS 库存列映射(可选 JSON 字符串)
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
# 本地 Mock RPA(scripts/rpa/freight_rpa_worker.py,可选)
# SHIPPING_NOTICE_RPA_WORKER_MOCK=true
# SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3
# SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY=
# 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
# --- 10. 运维、告警与维护工具 ---
# AWS 库存列映射(可选 JSON 字符串)
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
# Dify Chatflow(seed_shipping_notice_agents.py)
SHIPPING_NOTICE_CHAT_DIFY_APP_ID=
SHIPPING_NOTICE_CHAT_DIFY_API_KEY=
SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
# 本地 Mock RPA(scripts/rpa/freight_rpa_worker.py,可选)
# FREIGHT_RPA_MOCK=true
# FREIGHT_RPA_POLL_SECONDS=3
# FREIGHT_RPA_SAMPLE_INVENTORY=
# 设备维保助手后端工具调用密钥
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
+2
View File
@@ -70,6 +70,8 @@ Thumbs.db
# tmp
.tmp/
.tmp2/
.sso-pytest-temp/
.pytest-sso-run*/
.npm-cache
.npm-cache2
+7 -4
View File
@@ -54,7 +54,7 @@ frontend/src/
locales/ # i18n 四语言 JSON(zh-CN / zh-TW / en / th),按域拆分
scripts/ # 部署与运维脚本(deploy_compose.sh、healthcheck.sh ...)
docs/ # 权威文档(规范、上下文、流程、发布说明)
# features/ 业务域手册 · platform/ 平台设计 · prototype/ 产品原型
# features/ 业务域手册(含域内原型)· platform/ 平台设计(含跨域原型)
# convention/ · openapi/ · dify/ · refactor/
```
@@ -149,7 +149,7 @@ docker compose logs -f hxops-backend
- 🔒 **严禁提交任何密钥/密码/生产地址等敏感信息**。`.env.local` / `.env.*` 不进仓库的部分不得硬编码进代码或提交。
- 🧬 **修改数据库表结构必须配套迁移**:任何对 `models.py` / 数据表结构的新增、删除、字段或约束变更,都必须生成并提交对应的 Alembic 迁移脚本(`flask db migrate -m "..."` → `flask db upgrade`),禁止只改模型不出迁移。
- 🌐 **环境变量分层**:`.env.shared` + `.env.<env>`(dev/test/prod),不要在代码里写死环境值。规则见 **[docs/convention/env_loading_priority.md](docs/convention/env_loading_priority.md)** 与 **[docs/convention/环境变量规则.md](docs/convention/环境变量规则.md)**。
- 🌍 **i18n 四语言**:前端新增文案必须同时补齐 `zh-CN / zh-TW / en-US / th-TH`,禁止硬编码中文。
- 🌍 **i18n 四语言**:前端新增文案必须同时补齐 `zh-CN / zh-TW / en / th`,禁止硬编码中文。Agent 流程见项目 Skill `add-i18n-keys` 与 [docs/skills/add-i18n-keys-skill.md](docs/skills/add-i18n-keys-skill.md)。
- 📡 **SSE 流式约束**:对话链路依赖 Gevent 异步 worker + Nginx `proxy_buffering off`;对话接口(`chat.py`)使用原生 Fetch/SSE 而非 Axios,改动需保持流式不被破坏。
- 🔌 **外部集成依赖**:Oracle Instant Client 19.30 / `pyodbc` / `zeep`(OA、PLM、HR)等本地未必可运行,涉及这些 service 时谨慎并说明。
- ➕ **新增依赖需克制**:不擅自引入未经评审的第三方依赖;如需新增,在提交说明中给出理由。
@@ -198,9 +198,9 @@ docker compose logs -f hxops-backend
| 技术架构文档 | [docs/tec.md](docs/tec.md) |
| 功能清单 | [docs/funclist.md](docs/funclist.md) |
| 新人环境搭建 / 分支原则 | [docs/新人环境搭建与配置文档.md](docs/新人环境搭建与配置文档.md) |
| 发布流程(dev→test→prod) | [docs/release_workflow.md](docs/release_workflow.md) · [docs/convention/开发标准流程.md](docs/convention/开发标准流程.md) |
| 发布流程(dev→test→prod) | [docs/convention/release_workflow.md](docs/convention/release_workflow.md) · [docs/convention/开发标准流程.md](docs/convention/开发标准流程.md) |
| 提交规范 | [docs/convention/COMMIT_CONVENTION.md](docs/convention/COMMIT_CONVENTION.md) |
| Git Hooks | [docs/GIT_HOOKS.md](docs/GIT_HOOKS.md) |
| Git Hooks | [docs/convention/GIT_HOOKS.md](docs/convention/GIT_HOOKS.md) |
| 环境变量 | [docs/convention/env_loading_priority.md](docs/convention/env_loading_priority.md) · [docs/convention/环境变量规则.md](docs/convention/环境变量规则.md) |
| 知识库部署 | [docs/knowledge_base_runtime_deploy.md](docs/knowledge_base_runtime_deploy.md) |
| Excel/CSV 切块与 Dify 分段 | [docs/kb-excel-dify-chunking.md](docs/kb-excel-dify-chunking.md) |
@@ -208,6 +208,9 @@ docker compose logs -f hxops-backend
| 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.md) |
| 前端架构规范 | [docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md) |
| 错误处理规范 | [docs/convention/error_handling.md](docs/convention/error_handling.md) |
| Cursor Skills 索引 | [docs/skills/README.md](docs/skills/README.md) |
| 前端四语言 i18n Skill | [docs/skills/add-i18n-keys-skill.md](docs/skills/add-i18n-keys-skill.md) |
| 发布说明 Skill | [docs/skills/release-notes-skill.md](docs/skills/release-notes-skill.md) |
| **业务域文档索引** | [docs/features/README.md](docs/features/README.md) |
| 货代发货通知 | [docs/features/shipping-notice/technical.md](docs/features/shipping-notice/technical.md) |
| 文件检核 | [docs/features/file-check/technical.md](docs/features/file-check/technical.md) |
Vendored
+1 -1
View File
@@ -288,7 +288,7 @@ pipeline {
// 目录级变更识别:用于前后端增量构建 / Directory-level change detection for incremental builds
def frontendChanged = changedFiles.any { it.startsWith('frontend/') }
def backendChanged = changedFiles.any {
it.startsWith('backend/') || it == 'docs/(表+字段).md'
it.startsWith('backend/') || it == 'docs/integrations/erp/text2sql_schema.md'
}
def deployConfigChanged = changedFiles.any {
it == 'docker-compose.yml' ||
+3 -3
View File
@@ -62,10 +62,10 @@ RUN --mount=type=cache,target=/root/.cache/pip \
pyclipper Shapely six onnxruntime && \
python -c "import cv2; from rapidocr_onnxruntime import RapidOCR; import networkx, openpyxl"
# Copy backend code and the Text2SQL schema required at runtime
# Copy backend code and the ERP schema required by Text2SQL at runtime.
COPY backend/ .
RUN mkdir -p /app/docs
COPY docs/(表+字段).md /app/docs/(表+字段).md
RUN mkdir -p /app/docs/integrations/erp
COPY docs/integrations/erp/text2sql_schema.md /app/docs/integrations/erp/text2sql_schema.md
# Expose port 5000
+10 -3
View File
@@ -64,8 +64,6 @@ def create_app(config_name='default'):
load_handlers()
from app.services.chat.intent_route_registry import ensure_intent_routes_loaded
ensure_intent_routes_loaded()
from app.services.schedule.scheduler_service import start_scheduler
start_scheduler(app)
# 空库先迁移后建用户:启动补建 + User commit 钩子即时补建,消除无排程窗口
try:
from app.services.file_assets.cleanup_schedule import (
@@ -80,6 +78,15 @@ def create_app(config_name='default'):
ensure_default_order_extraction_progress_cleanup_schedule()
except Exception as exc: # pragma: no cover - 表未就绪时容忍
logger.warning('Failed to ensure file-asset-cleanup schedule: %s', exc)
try:
from app.services.voucher_check.schedule_seed import (
ensure_default_voucher_check_schedule,
register_voucher_check_schedule_hooks,
)
register_voucher_check_schedule_hooks()
ensure_default_voucher_check_schedule()
except Exception as exc: # pragma: no cover - 表未就绪时容忍
logger.warning('Failed to ensure accounting-voucher-check schedule: %s', exc)
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
FixedAssetsSnapshotService.start_worker(app)
# AUTO_UPLOAD 显式开启时启动级校验货代上传 RPA(仅告警,不阻断启动)。
@@ -131,7 +138,7 @@ def create_app(config_name='default'):
return wrapped_resp
def _should_return_json_error() -> bool:
if request.path.startswith('/api/'):
if request.path.startswith('/api/') or request.path == '/.well-known/jwks.json':
return True
accepted = request.headers.get('Accept', '')
return 'application/json' in accepted.lower()
+13 -2
View File
@@ -21,11 +21,13 @@ def register_blueprints(app: Flask) -> None:
from app.api.chat import chat_bp
from app.api.admin import admin_bp
from app.api.agents import agents_bp
from app.api.user import user_bp
from app.api.user import auth_bp, user_bp
from app.api.integration import integration_bp
from app.api.internal_jobs import internal_jobs_bp
from app.api.maintenance import maintenance_bp
from app.api.speech import speech_bp
from app.api.sso import sso_bp, sso_well_known_bp
from app.api.linked_services import linked_services_bp
from app.api.training import training_admin_bp, training_user_bp
from app.api.agent_runtime_context_tools import agent_runtime_context_bp
@@ -37,14 +39,17 @@ def register_blueprints(app: Flask) -> None:
workspace_file_check_bp,
workspace_schedule_bp,
workspace_shipping_notice_bp,
workspace_voucher_check_bp,
)
from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp
from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp, voucher_check_tools_bp
from app.api.files import files_bp
from app.api.procurement_contract_tools import procurement_contract_bp
app.register_blueprint(chat_bp, url_prefix='/api/chat')
app.register_blueprint(admin_bp, url_prefix='/api/admin')
app.register_blueprint(agents_bp, url_prefix='/api/agents')
app.register_blueprint(user_bp, url_prefix='/api/user')
app.register_blueprint(auth_bp, url_prefix='/api/user')
app.register_blueprint(training_user_bp, url_prefix='/api/user')
app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb')
app.register_blueprint(integration_bp, url_prefix='/api/integration')
@@ -53,12 +58,18 @@ def register_blueprints(app: Flask) -> None:
app.register_blueprint(workspace_announcements_bp, url_prefix='/api/workspace')
app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace')
app.register_blueprint(workspace_file_check_bp, url_prefix='/api/workspace')
app.register_blueprint(workspace_voucher_check_bp, url_prefix='/api/workspace')
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
app.register_blueprint(maintenance_bp, url_prefix='/api/maintenance')
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
app.register_blueprint(voucher_check_tools_bp, url_prefix='/api/accounting-voucher-check')
app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context')
app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance')
app.register_blueprint(speech_bp, url_prefix='/api/speech')
app.register_blueprint(sso_bp, url_prefix='/api/sso')
app.register_blueprint(linked_services_bp, url_prefix='/api')
app.register_blueprint(sso_well_known_bp)
app.register_blueprint(training_admin_bp, url_prefix='/api/admin')
app.register_blueprint(files_bp, url_prefix='/api/files')
app.register_blueprint(procurement_contract_bp, url_prefix='/api/procurement-contract')
+2 -10
View File
@@ -18,16 +18,8 @@ import app.api.admin.database # noqa: F401
import app.api.admin.permissions # noqa: F401
import app.api.admin.users # noqa: F401
import app.api.admin.wecom # noqa: F401
import app.api.admin.shipping_order_extraction # noqa: F401
import app.api.admin.announcements # noqa: F401
import app.api.admin.shipping_customers # noqa: F401
import app.api.admin.shipping_identity_rules # noqa: F401
import app.api.admin.shipping_inventory # noqa: F401
import app.api.admin.shipping_order_schema # noqa: F401
import app.api.admin.shipping_field_assets # noqa: F401
import app.api.admin.shipping_order_document_profiles # noqa: F401
import app.api.admin.shipping_document_layouts # noqa: F401
import app.api.admin.shipping_process_gate # noqa: F401
import app.api.admin.shipping_legacy_stp_jobs # noqa: F401
import app.api.admin.linked_services # noqa: F401
import app.api.admin.procurement_contract # noqa: F401
__all__ = ['admin_bp']
+44
View File
@@ -0,0 +1,44 @@
"""
backend/app/api/admin/linked_services.py
用途:管理后台关联服务 CRUD API(薄路由层)。
依赖:admin.blueprint、services/admin/linked_service_service。
逻辑:/linked-services* 路由;侧栏只读见 api/linked_services.py。
"""
from flask import jsonify, request
from app.api.admin.blueprint import admin_bp
from app.core.decorators import require_admin
from app.services.admin import linked_service_service
@admin_bp.route('/linked-services', methods=['GET'])
@require_admin
def list_linked_services():
"""列出全部关联服务(含停用)。"""
return jsonify(linked_service_service.list_linked_services())
@admin_bp.route('/linked-services', methods=['POST'])
@require_admin
def create_linked_service():
"""创建关联服务。"""
data = request.get_json() or {}
payload = linked_service_service.create_linked_service(data)
return jsonify(payload), 201
@admin_bp.route('/linked-services/<int:id>', methods=['PUT'])
@require_admin
def update_linked_service(id: int):
"""更新关联服务。"""
data = request.get_json() or {}
return jsonify(linked_service_service.update_linked_service(id, data))
@admin_bp.route('/linked-services/<int:id>', methods=['DELETE'])
@require_admin
def delete_linked_service(id: int):
"""删除关联服务。"""
return jsonify(linked_service_service.delete_linked_service(id))
@@ -0,0 +1,264 @@
"""
backend/app/api/admin/procurement_contract.py
Purpose: Admin APIs for procurement contract templates, risk rules, and review history.
Dependencies: admin blueprint, procurement_contract services, file asset upload, unified response envelope.
Flow: Admin manages reusable templates/rules; review history remains read-only with export endpoints.
"""
from __future__ import annotations
import io
import json
from flask import g, request, send_file
from app.api.admin.blueprint import admin_bp
from app.core.auth.jwt import get_current_user
from app.core.decorators import require_admin
from app.core.errors import UnauthorizedError, ValidationError
from app.core.response import ok
from app.services.file_assets.service import upload_file_asset
from app.services.procurement_contract import review_service, rule_service, template_service
from app.services.procurement_contract.template_service import read_template_bytes
def _admin_user():
"""Return current admin user or raise UnauthorizedError."""
user = get_current_user()
if not user:
raise UnauthorizedError()
return user
def _int_arg(name: str, default: int) -> int:
"""Parse an integer query argument with a ValidationError on bad input."""
raw = request.args.get(name)
if raw in (None, ""):
return default
try:
return int(raw)
except (TypeError, ValueError) as exc:
raise ValidationError(f"{name} must be integer") from exc
def _optional_json_form(name: str):
"""Parse an optional multipart JSON field through the unified validation error contract."""
raw = request.form.get(name)
if not raw:
return None
try:
return json.loads(raw)
except (TypeError, ValueError) as exc:
raise ValidationError(
f"{name} must be valid JSON",
code="PROCUREMENT_CONTRACT.INVALID_COMPARISON_REGION_CONFIG",
details={"field": name},
) from exc
@admin_bp.route("/procurement-contract/templates", methods=["GET"])
@require_admin
def admin_list_contract_templates():
"""List all contract templates."""
status = request.args.get("status") or None
return ok(template_service.list_templates(status=status), request_id=getattr(g, "request_id", None))
@admin_bp.route("/procurement-contract/templates", methods=["POST"])
@require_admin
def admin_create_contract_template():
"""Upload and create a reusable procurement contract template."""
user = _admin_user()
if request.content_type and "multipart/form-data" in request.content_type:
upload = request.files.get("file")
if not upload or not upload.filename:
raise ValidationError("file is required")
asset = upload_file_asset(user_id=user.id, upload=upload)
row = template_service.create_template(
user_id=user.id,
name=(request.form.get("name") or "").strip(),
version=(request.form.get("version") or "").strip(),
file_asset_no=str(asset.get("asset_no") or ""),
remark=request.form.get("remark"),
is_default=str(request.form.get("is_default") or "").lower() in ("1", "true", "yes"),
status=(request.form.get("status") or "enabled").strip(),
contract_type=(request.form.get("contract_type") or "general_procurement").strip(),
applicable_scope=request.form.get("applicable_scope"),
change_note=request.form.get("change_note"),
comparison_region_config=_optional_json_form("comparison_region_config"),
)
else:
data = request.get_json() or {}
file_asset_no = (data.get("file_asset_no") or "").strip()
file_asset_id = int(data.get("file_asset_id") or 0) or None
if not file_asset_no and not file_asset_id:
raise ValidationError("file_asset_no is required")
row = template_service.create_template(
user_id=user.id,
name=(data.get("name") or "").strip(),
version=(data.get("version") or "").strip(),
file_asset_id=file_asset_id,
file_asset_no=file_asset_no or None,
remark=data.get("remark"),
is_default=bool(data.get("is_default")),
status=(data.get("status") or "enabled").strip(),
contract_type=(data.get("contract_type") or "general_procurement").strip(),
applicable_scope=data.get("applicable_scope"),
change_note=data.get("change_note"),
comparison_region_config=data.get("comparison_region_config"),
)
return ok(row, request_id=getattr(g, "request_id", None), status=201)
@admin_bp.route("/procurement-contract/templates/<int:template_id>", methods=["PATCH"])
@require_admin
def admin_update_contract_template(template_id: int):
"""
Update template metadata, status, default flag, or validated comparison-region configuration.
Args:
template_id: ContractTemplate primary key from the Admin route.
Returns:
Unified success envelope containing the updated template row.
"""
user = _admin_user()
row = template_service.update_template(template_id, user_id=user.id, data=request.get_json() or {})
return ok(row, request_id=getattr(g, "request_id", None))
@admin_bp.route("/procurement-contract/templates/<int:template_id>/comparison-region-preview", methods=["POST"])
@require_admin
def admin_preview_contract_template_regions(template_id: int):
"""
Preview unsaved comparison-region anchors against the stored template file.
Args:
template_id: ContractTemplate primary key; the stored file is used only for recognition preview.
Returns:
Unified success envelope with matched body, signature, and attachment anchors.
"""
data = request.get_json() or {}
result = template_service.preview_comparison_regions(
template_id,
data.get("comparison_region_config"),
)
return ok(result, request_id=getattr(g, "request_id", None))
@admin_bp.route("/procurement-contract/templates/<int:template_id>", methods=["DELETE"])
@require_admin
def admin_delete_contract_template(template_id: int):
"""Delete a non-default template."""
return ok(template_service.delete_template(template_id), request_id=getattr(g, "request_id", None))
@admin_bp.route("/procurement-contract/templates/<int:template_id>/file", methods=["GET"])
@require_admin
def admin_download_contract_template(template_id: int):
"""Download template file bytes."""
tpl = template_service.get_template_or_404(template_id)
filename, data = read_template_bytes(tpl)
return send_file(io.BytesIO(data), mimetype="application/octet-stream", as_attachment=True, download_name=filename)
@admin_bp.route("/procurement-contract/rules", methods=["GET"])
@require_admin
def admin_list_contract_risk_rules():
"""List configurable procurement contract risk rules."""
rows = rule_service.list_rules(
contract_type=request.args.get("contract_type") or None,
status=request.args.get("status") or None,
clause_category=request.args.get("clause_category") or None,
)
return ok(rows, request_id=getattr(g, "request_id", None))
@admin_bp.route("/procurement-contract/rules", methods=["POST"])
@require_admin
def admin_create_contract_risk_rule():
"""Create a procurement contract risk rule."""
user = _admin_user()
row = rule_service.create_rule(user_id=user.id, data=request.get_json() or {})
return ok(row, request_id=getattr(g, "request_id", None), status=201)
@admin_bp.route("/procurement-contract/rules/<int:rule_id>", methods=["PATCH"])
@require_admin
def admin_update_contract_risk_rule(rule_id: int):
"""Update a procurement contract risk rule."""
user = _admin_user()
row = rule_service.update_rule(rule_id, user_id=user.id, data=request.get_json() or {})
return ok(row, request_id=getattr(g, "request_id", None))
@admin_bp.route("/procurement-contract/rules/<int:rule_id>", methods=["DELETE"])
@require_admin
def admin_delete_contract_risk_rule(rule_id: int):
"""Delete a procurement contract risk rule."""
return ok(rule_service.delete_rule(rule_id), request_id=getattr(g, "request_id", None))
@admin_bp.route("/procurement-contract/reviews", methods=["GET"])
@require_admin
def admin_list_contract_reviews():
"""List review history with filters."""
data = review_service.list_reviews(
review_mode=request.args.get("review_mode") or None,
template_source=request.args.get("template_source") or None,
status=request.args.get("status") or None,
keyword=request.args.get("keyword") or None,
contract_type=request.args.get("contract_type") or None,
supplier_name=request.args.get("supplier_name") or None,
risk_level=request.args.get("risk_level") or None,
date_from=request.args.get("date_from") or None,
date_to=request.args.get("date_to") or None,
limit=_int_arg("limit", 100),
offset=_int_arg("offset", 0),
)
return ok(data, request_id=getattr(g, "request_id", None))
@admin_bp.route("/procurement-contract/reviews/<int:review_id>", methods=["GET"])
@require_admin
def admin_get_contract_review(review_id: int):
"""Get review details."""
return ok(review_service.get_review(review_id=review_id), request_id=getattr(g, "request_id", None))
@admin_bp.route("/procurement-contract/reviews/<int:review_id>/report", methods=["GET"])
@require_admin
def admin_download_contract_review_report(review_id: int):
"""Download review report as txt or docx."""
if (request.args.get("format") or "").lower() == "docx":
name, data, mimetype = review_service.read_review_report_docx_bytes(review_id=review_id)
else:
name, data = review_service.read_review_report_bytes(review_id=review_id)
mimetype = "text/plain; charset=utf-8"
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=name)
@admin_bp.route("/procurement-contract/reviews/<int:review_id>/contract", methods=["GET"])
@require_admin
def admin_download_contract_review_contract(review_id: int):
"""Download original contract file for a review."""
filename, data = review_service.read_review_contract_bytes(review_id=review_id)
return send_file(io.BytesIO(data), mimetype="application/octet-stream", as_attachment=True, download_name=filename)
@admin_bp.route("/procurement-contract/reviews/<int:review_id>/annotated-contract", methods=["GET"])
@require_admin
def admin_download_annotated_contract(review_id: int):
"""Download original PDF with anchored contract-review highlights."""
filename, data, mimetype = review_service.read_review_annotated_contract_bytes(review_id=review_id)
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=filename)
@admin_bp.route("/procurement-contract/reviews/<int:review_id>/template-file", methods=["GET"])
@require_admin
def admin_download_contract_review_template(review_id: int):
"""Download template file used by a review."""
filename, data = review_service.read_review_template_bytes(review_id=review_id)
return send_file(io.BytesIO(data), mimetype="application/octet-stream", as_attachment=True, download_name=filename)
+240 -22
View File
@@ -422,6 +422,7 @@ def _is_allowed_preview_url(target_url: str) -> bool:
def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 * 1024):
"""
从上游文件 URL 拉取二进制内容(供预览接口复用)。
核心逻辑:共享盘直读 / 固资图 / HTTP 拉取;integration kind=source 404 时回退 md → Dify 原文件 → 分段文本。
如果 file_url 是内部 integration API 下载链接且包含过期 token,则尝试重新获取最新链接。
返回: (content_bytes, content_type, error_tuple)
其中 error_tuple = (message, status_code);成功时为 None。
@@ -596,6 +597,10 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
file_url = refreshed_url
current_app.logger.warning(f"[file-preview] upstream returned status {upstream.status_code} for {file_url}")
if upstream.status_code == 404:
# [STEP] 源文件 404:先试 integration kind=md,再试 Dify 原文件/分段文本
fallback = _fetch_preview_bytes_after_source_404(file_url, max_size=max_size)
if fallback[0] is not None or fallback[2] is not None:
return fallback
return None, None, ('source file not found', 404)
return None, None, (f'upstream returned status {upstream.status_code}', 502)
@@ -609,6 +614,174 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
return (None, None, ('upstream returned invalid preview payload', 502))
return (content, content_type, None)
def _rewrite_integration_download_kind(file_url: str, kind: str) -> str:
"""
将 integration download URL 的 kind 查询参数改写为目标值。
@param file_url: 原始下载 URL
@param kind: 目标 kind(如 md)
@returns 改写后的 URL;无法识别时原样返回
"""
from urllib.parse import parse_qs, urlencode, urlunparse
raw = str(file_url or '').strip()
if not raw or '/api/integration/files/' not in raw:
return raw
parsed = urlparse(raw)
qs = parse_qs(parsed.query, keep_blank_values=True)
qs['kind'] = [str(kind)]
flat: dict = {}
for key, values in qs.items():
flat[key] = values[0] if len(values) == 1 else values
new_query = urlencode(flat, doseq=True)
return urlunparse((parsed.scheme, parsed.netloc, parsed.path, parsed.params, new_query, parsed.fragment))
def _extract_integration_token_ids(file_url: str) -> tuple[str, str]:
"""
从 integration 下载 URL 的 JWT token 中解析 dataset_id / remote_document_id。
@returns (dataset_id, remote_document_id),失败时为空字符串
"""
import base64
from urllib.parse import parse_qs
try:
parsed = urlparse(str(file_url or ''))
qs = parse_qs(parsed.query)
token = (qs.get('token') or [''])[0]
if not token:
return ('', '')
parts = token.split('.')
if len(parts) < 2:
return ('', '')
payload_b64 = parts[1] + '=' * (-len(parts[1]) % 4)
payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8'))
dataset_id = str(payload_data.get('dataset_id') or '').strip()
remote_document_id = str(payload_data.get('remote_document_id') or '').strip()
return (dataset_id, remote_document_id)
except Exception:
return ('', '')
def _fetch_dify_source_bytes(dataset_id: str, remote_document_id: str, max_size: int | None):
"""
从 Dify 拉取文档原始二进制(签名下载 URL)。
【AI 触发时机】本地 source 文件丢失、integration 404 时作为预览兜底。
@returns (content, content_type, error_tuple) 与 _fetch_preview_source_bytes 一致
"""
if not dataset_id or not remote_document_id:
return (None, None, None)
try:
info = IntegrationApiService._lookup_from_dify_document_api(dataset_id, remote_document_id)
source_url = str((info or {}).get('source_download_url') or '').strip()
if not source_url:
return (None, None, None)
upstream = requests.get(source_url, timeout=(5, 30))
if upstream.status_code != 200:
current_app.logger.warning(
'[file-preview] dify source download status=%s dataset=%s doc=%s',
upstream.status_code,
dataset_id,
remote_document_id,
)
return (None, None, None)
content = upstream.content or b''
if max_size is not None and len(content) > max_size:
return (None, None, ('file too large for online preview', 413))
content_type = (upstream.headers.get('content-type') or '').split(';')[0].strip().lower()
return (content, content_type or None, None)
except Exception as exc:
current_app.logger.warning(
'[file-preview] dify source download failed dataset=%s doc=%s err=%s',
dataset_id,
remote_document_id,
exc,
)
return (None, None, None)
def _looks_like_text_document(content: bytes) -> bool:
"""
判断内容是否可按文本/Markdown 预览,避免把 OLE/PDF 等二进制当文本导致乱码。
核心逻辑:识别常见二进制魔数;抽样解码后要求可打印字符占比足够高。
"""
if not content:
return False
# [STEP 1] 排除 PDF / ZIP(OOXML) / OLE(旧版 Office)
if content.startswith((b'%PDF-', b'PK\x03\x04', b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1')):
return False
sample = content[:4096]
if b'\x00' in sample:
return False
text = None
for enc in ('utf-8', 'utf-8-sig', 'gb18030'):
try:
text = sample.decode(enc)
break
except UnicodeDecodeError:
continue
if text is None:
return False
printable = sum(1 for ch in text if ch.isprintable() or ch in '\r\n\t')
return (printable / max(len(text), 1)) >= 0.85
def _fetch_preview_bytes_after_source_404(file_url: str, max_size: int | None):
"""
源文件 404 后的预览兜底链:integration md → Dify 原文件 → Dify 分段文本。
"""
# [STEP 1] kind=source → kind=md(清洗稿,必须是可读文本)
if 'kind=source' in str(file_url or '') and '/api/integration/files/' in str(file_url or ''):
md_url = _rewrite_integration_download_kind(file_url, 'md')
if md_url and md_url != file_url:
try:
api_key = IntegrationApiService.get_api_key()
headers = {'X-Integration-Key': api_key} if api_key else {}
upstream = requests.get(md_url, headers=headers, timeout=(5, 20))
if upstream.status_code == 200:
content = upstream.content or b''
if max_size is not None and len(content) > max_size:
return (None, None, ('file too large for online preview', 413))
content_type = (upstream.headers.get('content-type') or '').split(';')[0].strip().lower()
if content_type == 'application/json':
current_app.logger.warning('[file-preview] md fallback returned json url=%s', md_url)
elif not _looks_like_text_document(content):
current_app.logger.warning(
'[file-preview] md fallback ignored binary payload url=%s',
md_url,
)
else:
current_app.logger.info('[file-preview] source 404 fallback to markdown url=%s', md_url)
return (content, content_type or 'text/markdown', None)
except requests.RequestException as exc:
current_app.logger.warning('[file-preview] markdown fallback failed: %s', exc)
dataset_id, remote_document_id = _extract_integration_token_ids(file_url)
# [STEP 2] Dify 原始文件下载
dify_bytes = _fetch_dify_source_bytes(dataset_id, remote_document_id, max_size)
if dify_bytes[0] is not None:
current_app.logger.info(
'[file-preview] source 404 fallback to dify binary dataset=%s doc=%s',
dataset_id,
remote_document_id,
)
return dify_bytes
if dify_bytes[2] is not None:
return dify_bytes
# [STEP 3] Dify 分段文本(任意文档形态)
text = _fetch_dify_document_segments_text(dataset_id, remote_document_id)
if text:
current_app.logger.info(
'[file-preview] source 404 fallback to dify segments dataset=%s doc=%s',
dataset_id,
remote_document_id,
)
return (text.encode('utf-8'), 'text/plain; charset=utf-8', None)
return (None, None, None)
def _extract_placeholder_text(content: bytes) -> str:
sample = content[:2048]
for enc in ('utf-16le', 'utf-8', 'utf-8-sig', 'gb18030', 'latin-1'):
@@ -627,6 +800,46 @@ def _extract_placeholder_text(content: bytes) -> str:
return ''
def _fetch_dify_document_segments_text(dataset_id: str, remote_document_id: str) -> str | None:
"""
拼接 Dify 文档全部分段文本,不限制 doc_form(供源文件丢失时的预览兜底)。
"""
if not dataset_id or not remote_document_id:
return None
try:
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
service = KbDifySyncService()
segments_payload = service._request(
'GET',
f'/datasets/{dataset_id}/documents/{remote_document_id}/segments?limit=1000',
)
rows = []
if isinstance(segments_payload, dict):
rows = segments_payload.get('data') or []
elif isinstance(segments_payload, list):
rows = segments_payload
if not isinstance(rows, list) or not rows:
return None
ordered_rows = sorted(
[row for row in rows if isinstance(row, dict)],
key=lambda row: (int(row.get('position') or 0), str(row.get('id') or '')),
)
parts: list[str] = []
for row in ordered_rows:
text_part = str(row.get('content') or '').strip()
if text_part:
parts.append(text_part)
return '\n\n'.join(parts).strip() or None
except Exception as e:
current_app.logger.warning(
'[source-file-text] failed to fetch dify segments dataset=%s doc=%s err=%s',
dataset_id,
remote_document_id,
e,
)
return None
def _fetch_dify_text_document(dataset_id: str, remote_document_id: str) -> str | None:
"""
对于 Dify 中以 text_model / txt 形式存储的文档,
@@ -660,28 +873,7 @@ def _fetch_dify_text_document(dataset_id: str, remote_document_id: str) -> str |
if not is_text_doc:
return None
segments_payload = service._request(
'GET',
f'/datasets/{dataset_id}/documents/{remote_document_id}/segments?limit=1000',
)
rows = []
if isinstance(segments_payload, dict):
rows = segments_payload.get('data') or []
elif isinstance(segments_payload, list):
rows = segments_payload
if not isinstance(rows, list) or not rows:
return None
ordered_rows = sorted(
[row for row in rows if isinstance(row, dict)],
key=lambda row: (int(row.get('position') or 0), str(row.get('id') or '')),
)
parts: list[str] = []
for row in ordered_rows:
text = str(row.get('content') or '').strip()
if text:
parts.append(text)
return '\n\n'.join(parts).strip() or None
return _fetch_dify_document_segments_text(dataset_id, remote_document_id)
except Exception as e:
current_app.logger.warning(
'[source-file-text] failed to fetch dify text document dataset=%s doc=%s err=%s',
@@ -2210,6 +2402,20 @@ def preview_file_raw():
# 根据文件二进制头部纠正扩展名,防止文件本身是 docx 却被命名为 doc,导致转换或下载后乱码
real_ext = _guess_ext_from_content(content, ext)
# 仅当内容确实是文本时,才允许按 content_type 切到 md/txt(避免 .doc OLE 被当文本渲染乱码)
normalized_ct = (content_type or '').split(';')[0].strip().lower()
if _looks_like_text_document(content):
if 'markdown' in normalized_ct:
real_ext = 'md'
elif normalized_ct.startswith('text/') and original_ext in (
'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx',
):
real_ext = 'txt'
elif real_ext in ('md', 'markdown', 'txt') and original_ext in (
'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx',
):
# content_type/文件名声称是文本,但载荷是 Office 二进制:以魔数扩展名为准
real_ext = _guess_ext_from_content(content, original_ext or ext)
if real_ext != ext:
current_app.logger.info(f"[file-preview] corrected extension from {ext} to {real_ext}")
ext = real_ext
@@ -2217,6 +2423,18 @@ def preview_file_raw():
name = f"{name.rsplit('.', 1)[0]}.{ext}"
elif name:
name = f"{name}.{ext}"
# 回退文本预览时,避免仍带二进制 Content-Type 导致前端按 PDF 渲染
if ext in ('md', 'markdown', 'txt') and _looks_like_text_document(content):
if not str(content_type or '').lower().startswith('text/'):
content_type = {
'md': 'text/markdown; charset=utf-8',
'markdown': 'text/markdown; charset=utf-8',
'txt': 'text/plain; charset=utf-8',
}.get(ext)
elif ext in ('md', 'markdown', 'txt') and not _looks_like_text_document(content):
# 拒绝把二进制伪装成文本扩展名
ext = _guess_ext_from_content(content, original_ext or 'bin') or (original_ext or 'bin')
content_type = None
# 仅当文件真实格式仍然是旧版 Office/PPT 时才转 PDF。
# 如果原始文件名是 .doc 但内容实际是 .docx,则交给前端 Office 组件渲染,
+20
View File
@@ -0,0 +1,20 @@
"""
api/chat/__init__.py
用途:聊天域 Blueprint 的统一入口。
依赖:chat 各职责路由模块、app.api.chat_turns。
逻辑:创建唯一的 chat_bp,导入子模块完成路由注册,并挂载 Chat Turn 流式接口。
"""
from __future__ import annotations
from flask import Blueprint
chat_bp = Blueprint('chat', __name__)
# 子模块导入时在同一 Blueprint 上注册原有 URL。
from . import assets, completions, directory, feedback, previews, sessions, uploads # noqa: E402, F401
from app.api.chat_turns import register_chat_turn_routes # noqa: E402
register_chat_turn_routes(chat_bp)
__all__ = ['chat_bp']
+129
View File
@@ -0,0 +1,129 @@
"""
api/chat/assets.py
用途:提供查询结果预览和固定资产文件、图片解析接口。
依赖:chat.shared、Text2SQLService、FixedAssetHistoryService、FixedAssetImageService。
逻辑:校验当前用户与 Agent 上下文后调用领域服务,返回分页数据或安全的预览元数据。
"""
from __future__ import annotations
from .shared import * # noqa: F403
from . import chat_bp
@chat_bp.route('/query-preview/<int:chat_log_id>', methods=['GET'])
@require_agent_permission
def get_chat_query_preview(chat_log_id: int):
page = request.args.get('page', type=int) or 1
page_size = request.args.get('page_size', type=int) or 100
page = max(1, page)
page_size = max(1, min(200, page_size))
log = db.session.query(ChatLog).filter(
ChatLog.id == chat_log_id,
ChatLog.user_id == getattr(g.current_user, 'id', 0),
ChatLog.agent_id == getattr(g.current_agent, 'id', 0),
).first()
if not log:
raise NotFoundError('query preview not found')
payload = log.payload if isinstance(log.payload, dict) else {}
if payload.get('kind') != 'text2sql_result_preview':
raise ValidationError('current message does not support query preview')
sql = str(payload.get('sql') or '').strip()
query = str(payload.get('query') or log.query or '').strip()
if not sql:
raise ValidationError('query preview sql is missing')
from app.services.text2sql import Text2SQLService
total_count = payload.get('total_count')
try:
total_count = int(total_count) if total_count is not None else None
except (TypeError, ValueError):
total_count = None
columns, rows, resolved_total = Text2SQLService.get_preview_page(
sql=sql,
query=query,
page=page,
page_size=page_size,
agent=g.current_agent,
total_count=total_count,
user_context=Text2SQLService._normalize_user_context(g.current_user),
)
if columns == ["Error"]:
raise AppError(code='CHAT.QUERY_PREVIEW_FAILED', message=str(rows[0][0] if rows and rows[0] else 'query preview failed'), http_status=500)
total = resolved_total if resolved_total is not None else len(rows)
return jsonify({
'columns': columns,
'rows': [list(row) for row in rows],
'page': page,
'page_size': page_size,
'total': total,
'has_more': page * page_size < total,
'query': query,
})
@chat_bp.route('/asset-history/search', methods=['GET'])
@require_agent_permission
def search_asset_history_files():
"""
检索固定资产履历文件。
用途:聊天结果表格点击“资产编号”时,返回共享盘中的候选履历文件列表。
约束:至少提供资产编号或资产名称之一;不直接返回文件内容,只返回预览所需路径元数据。
"""
asset_id = (request.args.get('asset_id') or '').strip()
asset_name = (request.args.get('asset_name') or '').strip()
limit = request.args.get('limit', type=int) or 20
limit = max(1, min(limit, 50))
if not asset_id and not asset_name:
raise ValidationError('asset_id or asset_name is required')
from app.services.fixed_asset_history import FixedAssetHistoryService
if not FixedAssetHistoryService.is_enabled():
raise ServiceUnavailableError('asset history share is not configured')
items = FixedAssetHistoryService.search_history_files(
asset_id=asset_id,
asset_name=asset_name,
limit=limit,
)
return jsonify({
'asset_id': asset_id,
'asset_name': asset_name,
'total': len(items),
'items': items,
})
@chat_bp.route('/asset-image/resolve', methods=['GET'])
@require_agent_permission
def resolve_asset_image_preview():
"""
解析固定资产图片预览链接。
用途:聊天结果表格点击“图片 -> 查看”时,后端自动登录外部文档库并返回最佳图片的可预览元数据。
约束:至少提供资产编号或资产名称之一;只返回当前最佳命中的单张图片,不向前端暴露文档库登录态。
"""
asset_id = (request.args.get('asset_id') or '').strip()
asset_name = (request.args.get('asset_name') or '').strip()
if not asset_id and not asset_name:
raise ValidationError('asset_id or asset_name is required')
from app.services.fixed_asset_image import FixedAssetImageService
result = FixedAssetImageService.resolve_images(
asset_id=asset_id,
asset_name=asset_name,
)
return jsonify({
'asset_id': asset_id,
'asset_name': asset_name,
'item': result.get('item'),
'items': result.get('items', []),
'total': result.get('total', 0),
})
+331
View File
@@ -0,0 +1,331 @@
"""
api/chat/completions.py
用途:处理聊天 SSE completions 请求与上游事件转发。
依赖:chat.shared、chat.core、services.chat.router、DifyService。
逻辑:解析 HTTP 请求并建立本地会话,按 Chat Router 分流后保持原 SSE 契约输出。
"""
from __future__ import annotations
from .shared import * # noqa: F403
from . import chat_bp
from .core import (
_build_chat_adapter_hints,
_ensure_chat_session,
_get_chat_session,
_should_reset_provider_conversation_for_asset_query,
_update_chat_session,
)
@chat_bp.route('/completions', methods=['POST'])
@require_agent_permission
def chat_completions():
"""
SSE 流式聊天接口
用途:接收前端问题,调用 DifyService.stream_chat,并以 text/event-stream 形式返回
核心逻辑:
1. 从请求体中读取 query / agent_id / conversation_id
2. 通过装饰器已完成权限校验,并在 g 中注入 current_user / current_agent
3. 使用 Flask 的 stream_with_context 包裹生成器,实现流式推送
传入参数:
无(从 request.json 读取)
返回值:
Flask Response 对象,mimetype=text/event-stream
"""
data = request.get_json() or {}
query = data.get('query')
display_query = str(data.get('display_query') or query or '').strip()
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
conversation_id = data.get('conversation_id')
shipping_task_id = str(data.get('task_id') or '').strip()
shipping_batch_no = str(data.get('batch_no') or '').strip()
kb_type = data.get('kb_type', '企业知识库')
files = data.get('files')
request_id = uuid.uuid4().hex[:12]
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
current_app.logger.info('[chat-api] /completions request_id=%s user_id=%s agent_id=%s query_len=%s conversation_id=%s kb_type=%s', request_id, getattr(user, 'id', None), getattr(agent, 'id', None), len(query or ''), conversation_id, kb_type)
if user is None or agent is None:
current_app.logger.error("[chat-api] missing user/agent context user=%s agent=%s", bool(user), bool(agent))
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
from app.services.agent_registry.resolver import resolve_runtime_provider
if resolve_runtime_provider(agent) == 'iframe':
raise ValidationError('Embedded iframe agents do not support chat completions')
user_id = getattr(user, 'id', None)
agent_id = getattr(agent, 'id', None)
from types import SimpleNamespace
from app.services.agent_directory import serialize_directory_members
is_aggregate = bool(getattr(agent, 'is_aggregate', False))
directory_members = serialize_directory_members(agent_id, active_only=True) if is_aggregate else []
agent_proxy = SimpleNamespace(
id=agent_id,
name=getattr(agent, 'name', None),
type=getattr(agent, 'type', None),
dify_api_key=getattr(agent, 'dify_api_key', None),
api_base_url=getattr(agent, 'api_base_url', None),
extra_config=getattr(agent, 'extra_config', None) or {},
agent_code=getattr(agent, 'agent_code', None),
runtime_provider=getattr(agent, 'runtime_provider', None),
conversation_mode=getattr(agent, 'conversation_mode', None),
dify_app_type=getattr(agent, 'dify_app_type', None),
capabilities=getattr(agent, 'capabilities', None),
bound_schedule_task_id=getattr(agent, 'bound_schedule_task_id', None),
handler_config=getattr(agent, 'handler_config', None),
is_aggregate=is_aggregate,
directory_members=directory_members,
)
user_proxy = SimpleNamespace(
id=user_id,
username=getattr(user, 'username', None),
employee_id=getattr(user, 'employee_id', None),
real_name=getattr(user, 'real_name', None),
role=getattr(user, 'role', None),
)
from app.services.dify import DifyService
external_conversation_id = None
if conversation_id:
existing_session = _get_chat_session(user_id, agent_id, conversation_id)
if existing_session:
session = _ensure_chat_session(
user_id,
agent_id,
existing_session.session_id,
title=display_query,
status='running',
)
external_conversation_id = session.external_conversation_id
if external_conversation_id and _should_reset_provider_conversation_for_asset_query(query, agent_proxy):
current_app.logger.info(
'[chat-api] reset provider conversation for asset query request_id=%s session_id=%s old_provider_conversation_id=%s query=%s',
request_id,
session.session_id,
external_conversation_id,
query,
)
session.external_conversation_id = None
session.updated_at = datetime.utcnow()
session.last_active_at = datetime.utcnow()
db.session.commit()
external_conversation_id = None
else:
session = _ensure_chat_session(
user_id,
agent_id,
conversation_id,
title=display_query,
status='running',
external_conversation_id=conversation_id,
)
external_conversation_id = session.external_conversation_id
else:
session = _ensure_chat_session(user_id, agent_id, None, title=display_query, status='running')
normalized_files: list[dict] | None = None
if files is not None:
if not isinstance(files, list):
raise ValidationError('files must be a list')
normalized_files = []
for item in files:
if not isinstance(item, dict):
continue
transfer_method = str(item.get('transfer_method') or '').strip()
ftype = str(item.get('type') or '').strip()
if transfer_method not in ('local_file', 'remote_url'):
continue
if ftype not in ('image', 'document', 'audio', 'video', 'custom'):
continue
if transfer_method == 'local_file':
upload_file_id = str(item.get('upload_file_id') or '').strip()
if not upload_file_id:
continue
normalized_files.append({'type': ftype, 'transfer_method': 'local_file', 'upload_file_id': upload_file_id})
else:
url = str(item.get('url') or '').strip()
if not url:
continue
normalized_files.append({'type': ftype, 'transfer_method': 'remote_url', 'url': url})
if not normalized_files:
normalized_files = None
from app.services.agent_registry.handlers.base import ChatStreamContext
relay_stream_ctx = ChatStreamContext(
query=query,
display_query=display_query,
user=user_proxy,
agent=agent_proxy,
session=session,
external_conversation_id=external_conversation_id,
request_id=request_id,
normalized_files=normalized_files,
adapter_hints=_build_chat_adapter_hints(
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
),
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
kb_type=kb_type,
)
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
from app.services.chat.router import try_fast_route
leave_supported = HRLeaveSQLServerService.supports(query)
fast_route = try_fast_route(
user=user_proxy,
agent=agent_proxy,
query=query,
agent_id=agent_id,
session_id=session.session_id,
external_conversation_id=external_conversation_id,
normalized_files=normalized_files,
kb_type=kb_type,
leave_supported=leave_supported,
)
if fast_route is not None:
generator = fast_route.generator
elif leave_supported:
generator = DifyService.stream_chat(
query,
user_proxy.id,
agent_proxy,
external_conversation_id,
request_id=request_id,
session_id=session.session_id,
files=normalized_files,
inputs=build_chat_dify_inputs(
agent_proxy,
session_id=session.session_id,
request_id=request_id,
trigger_source="frontend_chat",
user_role=user_proxy.role,
adapter_hints=_build_chat_adapter_hints(
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
),
),
)
else:
from app.services.chat.executors import stream_chat_via_executor
generator = stream_chat_via_executor(relay_stream_ctx)
def relay_stream():
from app.services.chat_perf import chat_perf_enabled
relay_started = time.perf_counter()
relay_first_chunk_at: float | None = None
created_event = {
'event': 'session_created',
'conversation_id': session.session_id,
'provider_conversation_id': session.external_conversation_id,
'session_status': session.status,
}
yield f"data: {json.dumps(created_event, ensure_ascii=False)}\n\n"
known_provider_conversation_id = session.external_conversation_id
known_status = session.status
emitted_handler_state_keys: set[str] = set()
from app.services.chat.stream_relay import (
iter_handler_preface_sse,
iter_handler_terminal_sse,
)
for preface_line in iter_handler_preface_sse(relay_stream_ctx, emitted_keys=emitted_handler_state_keys):
yield preface_line
try:
for chunk in generator:
if relay_first_chunk_at is None:
relay_first_chunk_at = time.perf_counter()
if not isinstance(chunk, str) or not chunk.startswith('data: '):
yield chunk
continue
raw_payload = chunk[6:].strip()
try:
event_data = json.loads(raw_payload)
except Exception:
yield chunk
continue
provider_conversation_id = str(event_data.get('conversation_id') or known_provider_conversation_id or '').strip() or None
event_name = event_data.get('event')
should_touch = False
if provider_conversation_id and provider_conversation_id != known_provider_conversation_id:
known_provider_conversation_id = provider_conversation_id
should_touch = True
if event_name in ('message_end', 'workflow_finished'):
known_status = 'done'
should_touch = True
elif event_name == 'error':
known_status = 'error'
should_touch = True
if should_touch:
updated_session = _update_chat_session(
user_id,
agent_id,
session.session_id,
status=known_status,
external_conversation_id=known_provider_conversation_id,
touch=True,
)
if updated_session:
known_status = updated_session.status
event_data['provider_conversation_id'] = provider_conversation_id
event_data['conversation_id'] = session.session_id
event_data['session_status'] = known_status
if chat_perf_enabled() and event_name in ('message_end', 'workflow_finished'):
relay_first_ms = int((relay_first_chunk_at - relay_started) * 1000) if relay_first_chunk_at else None
relay_total_ms = int((time.perf_counter() - relay_started) * 1000)
current_app.logger.info(
'[chat-perf] relay request_id=%s session_id=%s first_chunk_ms=%s total_relay_ms=%s event=%s',
request_id,
session.session_id,
relay_first_ms,
relay_total_ms,
event_name,
)
event_data['hxops_relay'] = {
'first_chunk_ms': relay_first_ms,
'total_relay_ms': relay_total_ms,
}
yield f"data: {json.dumps(event_data, ensure_ascii=False)}\n\n"
if event_name in ('message_end', 'workflow_finished'):
for terminal_line in iter_handler_terminal_sse(
relay_stream_ctx,
event_data,
emitted_keys=emitted_handler_state_keys,
):
yield terminal_line
except Exception as exc:
current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, session.session_id)
payload = {'event': 'error', 'message': str(exc), 'conversation_id': session.session_id, 'session_status': 'error'}
yield f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
# 返回 SSE 响应,mimetype 设为 text/event-stream
return Response(
stream_with_context(
relay_stream()
),
mimetype='text/event-stream',
headers={
'Cache-Control': 'no-cache',
'Content-Type': 'text/event-stream; charset=utf-8',
'Connection': 'keep-alive',
# 对于 Nginx 反向代理,需要关闭缓冲以支持实时流式传输
'X-Accel-Buffering': 'no'
}
)
+218
View File
@@ -0,0 +1,218 @@
"""
api/chat/core.py
用途:提供聊天 API 内部共享的会话、标题和日志辅助操作。
依赖:chat.shared、ChatSession、ChatLog、services.chat.session_service。
逻辑:供 completions 与 sessions 路由复用,集中维护本地会话和上游 conversation_id 的映射。
"""
from __future__ import annotations
from .shared import * # noqa: F403
def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_batch_no: str | None = None) -> dict | None:
"""
构建聊天入口分发给领域 adapter 的提示字典。
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示,
统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。
"""
task_id = str(shipping_task_id or '').strip()
batch_no = str(shipping_batch_no or '').strip()
if not task_id and not batch_no:
return None
return {
'shipping_notice': {
'task_id': task_id or None,
'batch_no': batch_no or None,
}
}
def _should_reset_provider_conversation_for_asset_query(query: str, agent_proxy) -> bool:
"""
判断固资管理里的当前问题是否应当切断上游 Dify 会话上下文。
核心逻辑:
- 仅对“固资管理”Agent 生效;
- 仅当用户本轮问题可脱离上一轮上下文独立完成时触发;
- 这样可以保留本地同一历史会话,又避免把上一轮超大结果继续带给上游模型,导致 context length 爆掉。
"""
from app.services.text2sql import Text2SQLService
return Text2SQLService._should_reset_provider_conversation(query, agent_proxy)
def _session_title_from_text(text: str) -> str:
value = str(text or '').strip()
if not value:
return ''
return value[:30] + ('...' if len(value) > 30 else '')
def _looks_like_review_auto_title(title: str) -> bool:
"""
判断会话标题是否为审查结果 headline(误用作历史标题)。
Args:
title: ChatSession.title。
Returns:
True 表示标题像「模板比对完成…」这类自动摘要,而非用户提问。
"""
value = str(title or '').strip()
return value.startswith(('模板比对完成', '单份审核完成', '采购合同审查结果'))
def _fallback_title_from_contract_review_log(log: ChatLog | None) -> str:
"""
从合同审查日志推导可读会话标题(优先 query,其次合同文件名)。
Args:
log: procurement-contract-review 类型的 ChatLog。
Returns:
截断后的标题;无法推导时返回空串。
"""
if not log:
return ''
query = str(log.query or '').strip()
if query:
return _session_title_from_text(query)
payload = log.payload if isinstance(log.payload, dict) else {}
file_name = str(payload.get('contract_file_name') or '').strip()
if file_name:
return _session_title_from_text(f'请对《{file_name}》进行审查')
return ''
def _user_facing_chat_query(text: str, *, agent_code: str | None = None) -> str:
"""
将内部 Agent 编排提示转换成业务用户可见话术。
Args:
text: chat_logs.query 中保存的用户侧文本。
agent_code: 当前 Agent 应用类型;仅 shipping_notice 做工具名净化。
Returns:
可直接展示在聊天历史里的用户问题。
"""
value = str(text or '').strip()
if not value or str(agent_code or '').strip() != SHIPPING_NOTICE_AGENT_CODE:
return value
import re
task_match = re.search(r'(SN-\d{8}-[A-Z0-9]+)', value, re.I)
task_no = task_match.group(1).upper() if task_match else ''
if 'create_task' in value or 'get_task_status' in value or 'parse_notice' in value:
return f'继续处理当前发货任务 {task_no}'.strip()
return value
def _serialize_session(session: ChatSession) -> dict:
last_active = session.last_active_at or session.created_at
return {
'id': session.id,
'conversation_id': session.session_id,
'title': session.title or '',
'created_at': last_active.isoformat() if last_active else '',
'status': session.status,
}
def _get_chat_session(user_id: int, agent_id: int, session_id: str | None):
session_key = str(session_id or '').strip()
if not session_key:
return None
return db.session.query(ChatSession).filter_by(
user_id=user_id,
agent_id=agent_id,
session_id=session_key,
).first()
def _chat_logs_for_session(user_id: int, agent_id: int, session: ChatSession):
match_ids = {session.session_id}
external_id = str(session.external_conversation_id or '').strip()
if external_id:
match_ids.add(external_id)
return db.session.query(ChatLog).filter(
ChatLog.user_id == user_id,
ChatLog.agent_id == agent_id,
or_(
ChatLog.session_id.in_(match_ids),
ChatLog.conversation_id.in_(match_ids),
),
).order_by(ChatLog.created_at.asc()).all()
def _ensure_chat_session(
user_id: int,
agent_id: int,
session_id: str | None,
title: str = '',
status: str = 'running',
external_conversation_id: str | None = None,
):
session_key = str(session_id or '').strip()
external_id = str(external_conversation_id or '').strip() or None
session = _get_chat_session(user_id, agent_id, session_key)
changed = False
if not session:
session = ChatSession(
session_id=session_key or uuid.uuid4().hex,
user_id=user_id,
agent_id=agent_id,
title=_session_title_from_text(title),
status=status,
external_conversation_id=external_id,
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
last_active_at=datetime.utcnow(),
)
db.session.add(session)
db.session.commit()
return session
if not session.title and title:
session.title = _session_title_from_text(title)
changed = True
if status and session.status != status:
session.status = status
changed = True
if external_id and session.external_conversation_id != external_id:
session.external_conversation_id = external_id
changed = True
session.last_active_at = datetime.utcnow()
session.updated_at = datetime.utcnow()
changed = True
if changed:
db.session.commit()
return session
def _update_chat_session(
user_id: int,
agent_id: int,
session_id: str,
*,
status: str | None = None,
external_conversation_id: str | None = None,
title: str | None = None,
touch: bool = False,
):
session = _get_chat_session(user_id, agent_id, session_id)
if not session:
return None
changed = False
if title and not session.title:
session.title = _session_title_from_text(title)
changed = True
external_id = str(external_conversation_id or '').strip() or None
if external_id and session.external_conversation_id != external_id:
session.external_conversation_id = external_id
changed = True
if status and session.status != status:
session.status = status
changed = True
if touch or changed:
session.last_active_at = datetime.utcnow()
session.updated_at = datetime.utcnow()
changed = True
if changed:
db.session.commit()
return session
+55
View File
@@ -0,0 +1,55 @@
"""
api/chat/directory.py
用途:提供聊天表单所需的 OA 员工、部门和分部名称查询接口。
依赖:chat.shared、OASQLServerService、chat_bp。
逻辑:解析分页或 ID 参数后调用 OA 集成服务,并保持原 `/api/chat/oa/*` 响应格式。
"""
from __future__ import annotations
from .shared import * # noqa: F403
from . import chat_bp
@chat_bp.route('/oa/employees', methods=['GET'])
@require_agent_permission
def get_oa_employees():
"""
获取 OA 系统中的员工列表(分页/搜索)
"""
keyword = request.args.get('keyword', '').strip()
try:
page = int(request.args.get('page', 1))
page_size = int(request.args.get('page_size', 20))
except ValueError:
page = 1
page_size = 20
try:
from app.services.oa_sqlserver import OASQLServerService
result = OASQLServerService.search_employees(keyword, page, page_size)
return jsonify(result)
except Exception as e:
current_app.logger.error(f'[OA-Employees] Query failed: {e}')
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
@chat_bp.route('/oa/resolve-names', methods=['GET'])
@require_agent_permission
def resolve_oa_names():
dept_ids = request.args.get('department_ids', '').strip()
sub_ids = request.args.get('subcompany_ids', '').strip()
result = {}
try:
from app.services.oa_sqlserver import OASQLServerService
if dept_ids:
for did in dept_ids.split(','):
did = did.strip()
if did:
result[f'dept_{did}'] = OASQLServerService.get_department_name(did)
if sub_ids:
for sid in sub_ids.split(','):
sid = sid.strip()
if sid:
result[f'sub_{sid}'] = OASQLServerService.get_subcompany_name(sid)
except Exception as e:
current_app.logger.error(f'[OA-ResolveNames] Query failed: {e}')
return jsonify(result)
+60
View File
@@ -0,0 +1,60 @@
"""
api/chat/feedback.py
用途:处理用户对聊天回答的评分与文字反馈。
依赖:chat.shared、ChatLog、Feedback、chat_bp。
逻辑:定位当前用户和 Agent 的最近一条会话日志,创建或更新对应反馈记录。
"""
from __future__ import annotations
from .shared import * # noqa: F403
from . import chat_bp
@chat_bp.route('/feedback', methods=['POST'])
@require_agent_permission
def submit_feedback():
"""
提交对回答的评分与评论
用途:在对话结束后,由前端发送评分(1~5)和文字意见
核心逻辑:
1. 从请求体中读取 score/comment/conversation_id
2. 根据当前 user/agent 与 conversation_id 查找最近一条 ChatLog
3. 为该 ChatLog 创建或更新 Feedback 记录
"""
data = request.get_json() or {}
score = data.get('score')
comment = data.get('comment') or ''
conversation_id = data.get('conversation_id')
if not current_app.config.get('FEEDBACK_ENABLED', True):
raise ForbiddenError('feedback is disabled')
if score is None:
raise ValidationError('score is required')
try:
score_value = int(score)
except (TypeError, ValueError):
raise ValidationError('score must be an integer')
if score_value < 1 or score_value > 5:
raise ValidationError('score must be between 1 and 5')
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
if user is None or agent is None:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
chat_logs_query = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id)
if conversation_id:
chat_logs_query = chat_logs_query.filter(
or_(ChatLog.session_id == conversation_id, ChatLog.conversation_id == conversation_id)
)
# 取最新一条对话日志
chat_log = chat_logs_query.order_by(ChatLog.created_at.desc()).first()
if not chat_log:
raise NotFoundError('ChatLog not found')
if chat_log.feedback:
chat_log.feedback.score = score_value
chat_log.feedback.comment = comment
else:
fb = Feedback(chat_log_id=chat_log.id, score=score_value, comment=comment)
db.session.add(fb)
db.session.commit()
return jsonify({'status': 'ok'})
+611
View File
@@ -0,0 +1,611 @@
"""
api/chat/preview_support.py
用途:提供聊天文件预览所需的来源校验、文件获取和格式转换操作。
依赖:chat.shared、requests、LibreOffice、openpyxl、共享盘配置。
逻辑:由 previews 路由调用,限制可访问路径与 URL,并将 Office/Excel 内容转换为可预览格式。
"""
from __future__ import annotations
from .shared import * # noqa: F403
def _normalize_allowed_share_path(path_value: str) -> tuple[str, str]:
"""
统一归一化 Windows UNC / Windows 本地盘符 / Linux 挂载目录路径。
Returns:
(path_kind, normalized_path)
- path_kind: 'windows' | 'posix' | ''
- normalized_path: 归一化后的绝对路径文本
"""
raw_value = str(path_value or '').strip().strip('"')
if not raw_value:
return ('', '')
if raw_value.startswith('\\\\'):
normalized = raw_value.replace('/', '\\')
normalized = '\\\\' + normalized[2:].rstrip('\\')
return ('windows', normalized)
if len(raw_value) >= 3 and raw_value[1] == ':' and raw_value[2] in ('\\', '/'):
normalized = ntpath.normpath(raw_value.replace('/', '\\')).rstrip('\\')
return ('windows', normalized)
if raw_value.startswith('/'):
normalized = posixpath.normpath(raw_value.replace('\\', '/'))
return ('posix', normalized.rstrip('/'))
return ('', '')
def _is_path_within_allowed_root(target_path: str, root_path: str) -> bool:
target_kind, normalized_target = _normalize_allowed_share_path(target_path)
root_kind, normalized_root = _normalize_allowed_share_path(root_path)
if not normalized_target or not normalized_root or target_kind != root_kind:
return False
if target_kind == 'windows':
target_lower = normalized_target.lower()
root_lower = normalized_root.lower()
return target_lower == root_lower or target_lower.startswith(root_lower.rstrip('\\') + '\\')
return normalized_target == normalized_root or normalized_target.startswith(normalized_root.rstrip('/') + '/')
def _is_allowed_share_path(target_url: str) -> bool:
target_kind, normalized_target = _normalize_allowed_share_path(target_url)
if not normalized_target:
return False
history_share_root = ''
history_local_root = ''
if has_request_context():
history_share_root = str(current_app.config.get('FIXED_ASSET_HISTORY_SHARE_ROOT') or '').strip()
history_local_root = str(current_app.config.get('FIXED_ASSET_HISTORY_LOCAL_ROOT') or '').strip()
if not history_share_root:
history_share_root = str(Config.FIXED_ASSET_HISTORY_SHARE_ROOT or '').strip()
if not history_local_root:
history_local_root = str(Config.FIXED_ASSET_HISTORY_LOCAL_ROOT or '').strip()
roots = [
PLM_PREVIEW_SHARE_ROOT,
history_share_root,
history_local_root,
]
return any(root and _is_path_within_allowed_root(normalized_target, root) for root in roots)
def _is_allowed_preview_url(target_url: str) -> bool:
"""
预览代理 URL 白名单校验。
仅允许:
1) 配置中的集成服务主机;
2) 本机地址;
3) 私网 IP 或常见内网域名(.local/.lan)。
"""
try:
if _is_allowed_share_path(target_url):
return True
parsed = urlparse(target_url)
if parsed.scheme not in ('http', 'https'):
return False
host = (parsed.hostname or '').strip().lower()
if not host:
return False
integration_base = (IntegrationApiService.get_base_url() or '').strip()
if integration_base:
integration_host = (urlparse(integration_base).hostname or '').strip().lower()
if integration_host and host == integration_host:
return True
# 放行当前请求的 Host (前端能够访问本接口说明 Host 是受信任的自身域名/IP)
if has_request_context():
req_host = (request.host.split(':')[0] or "").strip().lower()
if host == req_host:
return True
if host in ("localhost", "127.0.0.1", "::1"):
return True
try:
ip = ipaddress.ip_address(host)
return ip.is_private or ip.is_loopback
except ValueError:
# 非 IP 主机:仅放行内网风格本地域名。
return host.endswith(".local") or host.endswith(".lan") or host.endswith(".well-trust.com")
except Exception:
return False
def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 * 1024):
"""
从上游文件 URL 拉取二进制内容(供预览接口复用)。
如果 file_url 是内部 integration API 下载链接且包含过期 token,则尝试重新获取最新链接。
返回: (content_bytes, content_type, error_tuple)
其中 error_tuple = (message, status_code);成功时为 None。
"""
import base64
import json
import time
import sqlalchemy as sa
from urllib.parse import parse_qs
if _is_allowed_share_path(file_url):
_path_kind, normalized_path = _normalize_allowed_share_path(file_url)
try:
if not os.path.isfile(normalized_path):
return (None, None, ('source file not found', 404))
file_size = os.path.getsize(normalized_path)
if max_size is not None and file_size > max_size:
return (None, None, ('file too large for online preview', 413))
with open(normalized_path, 'rb') as fh:
content = fh.read()
except OSError as exc:
current_app.logger.warning('[file-preview] failed to read share path %s: %s', normalized_path, exc)
return (None, None, ('failed to read source file', 502))
guessed_type = (mimetypes.guess_type(normalized_path)[0] or '').strip().lower()
if _extract_placeholder_text(content):
guessed_type = 'text/plain; charset=utf-8'
return (content, guessed_type, None)
try:
from app.services.fixed_asset_image import FixedAssetImageService
content, content_type, asset_image_err = FixedAssetImageService.fetch_preview_bytes(
file_url,
max_size=max_size,
)
if content is not None or asset_image_err is not None:
return (content, content_type, asset_image_err)
except Exception as exc:
current_app.logger.warning('[file-preview] fixed asset image fetch failed url=%s err=%s', file_url, exc)
headers = {}
base_url = IntegrationApiService.get_base_url()
api_key = IntegrationApiService.get_api_key()
def _resolve_latest_integration_url(raw_url: str):
dataset_id = ''
remote_document_id = ''
try:
parsed = urlparse(raw_url)
qs = parse_qs(parsed.query)
token = (qs.get('token') or [''])[0]
if token:
parts = token.split('.')
if len(parts) >= 2:
payload_b64 = parts[1]
payload_b64 += '=' * (-len(payload_b64) % 4)
payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8'))
dataset_id = str(payload_data.get('dataset_id') or '').strip()
remote_document_id = str(payload_data.get('remote_document_id') or '').strip()
except Exception:
pass
if not dataset_id or not remote_document_id:
try:
stmt = sa.text('CAST(retriever_resources AS TEXT) LIKE :url')
log = db.session.query(ChatLog).filter(stmt).params(url=f'%{raw_url}%').order_by(ChatLog.created_at.desc()).first()
if log and log.retriever_resources:
for r in log.retriever_resources:
if not isinstance(r, dict):
continue
source_url = str(r.get('source_download_url') or '')
if source_url == raw_url or (source_url and source_url.split('&token=')[0] == raw_url.split('&token=')[0]):
resolved_dataset_id, resolved_remote_document_id = DifyService._extract_dify_ids(r)
dataset_id = dataset_id or str(resolved_dataset_id or '').strip()
remote_document_id = remote_document_id or str(resolved_remote_document_id or '').strip()
if dataset_id and remote_document_id:
break
except Exception as e:
current_app.logger.warning('[file-preview] failed to find IDs in ChatLog: %s', e)
if dataset_id and remote_document_id:
new_info = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
if new_info and new_info.get('source_download_url'):
current_app.logger.info('[file-preview] refreshed integration url for dataset=%s doc=%s', dataset_id, remote_document_id)
return new_info['source_download_url']
return raw_url
def _build_headers(raw_url: str):
next_headers = {}
is_trusted = False
if base_url and raw_url.startswith(base_url):
is_trusted = True
elif _is_allowed_preview_url(raw_url):
is_trusted = True
else:
try:
parsed = urlparse(raw_url)
host = (parsed.hostname or "").strip().lower()
if has_request_context():
req_host = (request.host.split(':')[0] or "").strip().lower()
if host == req_host:
is_trusted = True
if host in ("localhost", "127.0.0.1", "::1"):
is_trusted = True
except Exception:
pass
current_app.logger.info(f"[_build_headers] raw_url={raw_url}, is_trusted={is_trusted}")
if is_trusted:
if api_key:
next_headers['X-Integration-Key'] = api_key
if has_request_context():
auth_header = (request.headers.get('Authorization') or '').strip()
cookie_header = (request.headers.get('Cookie') or '').strip()
if auth_header:
next_headers['Authorization'] = auth_header
if cookie_header:
next_headers['Cookie'] = cookie_header
return next_headers
def _should_refresh_from_response(resp) -> bool:
ctype = (resp.headers.get('content-type') or '').split(';')[0].strip().lower()
if resp.status_code == 401:
return True
if resp.status_code in (403, 404) and 'token=' in file_url:
return True
if ctype == 'application/json':
body = (resp.content or b'')[:512].decode('utf-8', errors='ignore').lower()
if 'unauthorized' in body or '"error"' in body:
return True
return False
def _retry_with_refreshed_url(raw_url: str):
refreshed_url = _resolve_latest_integration_url(raw_url)
if not refreshed_url or refreshed_url == raw_url:
return None, raw_url
retry_headers = _build_headers(refreshed_url)
try:
return requests.get(refreshed_url, headers=retry_headers, timeout=(5, 20)), refreshed_url
except requests.RequestException as e:
current_app.logger.warning('[file-preview] refreshed upstream request failed: %s', e)
return None, refreshed_url
if 'token=' in file_url:
try:
parsed = urlparse(file_url)
qs = parse_qs(parsed.query)
token = (qs.get('token') or [''])[0]
if token:
parts = token.split('.')
if len(parts) >= 2:
payload_b64 = parts[1]
payload_b64 += '=' * (-len(payload_b64) % 4)
payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8'))
exp = payload_data.get('exp', 0)
if exp and exp < time.time() + 300:
file_url = _resolve_latest_integration_url(file_url)
except Exception as e:
current_app.logger.warning('[file-preview] failed to refresh expired integration token: %s', e)
headers = _build_headers(file_url)
try:
upstream = requests.get(file_url, headers=headers, timeout=(5, 20))
except requests.RequestException as e:
current_app.logger.warning('[file-preview] upstream request failed: %s', e)
return (None, None, ('failed to fetch source file', 502))
if 'token=' in file_url and _should_refresh_from_response(upstream):
refreshed_upstream, refreshed_url = _retry_with_refreshed_url(file_url)
if refreshed_upstream is not None:
upstream = refreshed_upstream
file_url = refreshed_url
if upstream.status_code != 200:
if 'token=' in file_url:
refreshed_upstream, refreshed_url = _retry_with_refreshed_url(file_url)
if refreshed_upstream is not None:
upstream = refreshed_upstream
file_url = refreshed_url
current_app.logger.warning(f"[file-preview] upstream returned status {upstream.status_code} for {file_url}")
if upstream.status_code == 404:
return None, None, ('source file not found', 404)
return None, None, (f'upstream returned status {upstream.status_code}', 502)
content = upstream.content or b''
if max_size is not None and len(content) > max_size:
return (None, None, ('file too large for online preview', 413))
content_type = (upstream.headers.get('content-type') or '').split(';')[0].strip().lower()
if content_type == 'application/json':
body = content[:512].decode('utf-8', errors='ignore')
current_app.logger.warning('[file-preview] upstream returned json instead of binary url=%s body=%s', file_url, body)
return (None, None, ('upstream returned invalid preview payload', 502))
return (content, content_type, None)
def _extract_placeholder_text(content: bytes) -> str:
sample = content[:2048]
for enc in ('utf-16le', 'utf-8', 'utf-8-sig', 'gb18030', 'latin-1'):
try:
text = sample.decode(enc).replace('\x00', '').strip()
except Exception:
continue
if not text:
continue
lines = [line.strip() for line in text.splitlines() if line.strip()]
if not lines:
continue
first_line = lines[0][:160]
if any((token in first_line for token in ('该文件', '机密文件', '未经允许', '法律风险', '禁止', '保密'))):
return first_line
return ''
def _fetch_dify_text_document(dataset_id: str, remote_document_id: str) -> str | None:
"""
对于 Dify 中以 text_model / txt 形式存储的文档,
直接拼接 segments 内容,避免依赖可能失效的 file-preview 签名链接。
"""
if not dataset_id or not remote_document_id:
return None
try:
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
service = KbDifySyncService()
document_payload = service.get_document(
dataset_id=str(dataset_id),
document_id=str(remote_document_id),
)
if not isinstance(document_payload, dict):
return None
upload_info = (
((document_payload.get('data_source_info') or {}).get('upload_file'))
if isinstance(document_payload.get('data_source_info'), dict)
else {}
) or {}
source_ext = str(upload_info.get('extension') or '').strip().lower()
doc_form = str(document_payload.get('doc_form') or '').strip().lower()
mime_type = str(upload_info.get('mime_type') or '').strip().lower()
is_text_doc = (
source_ext in ('txt', 'md', 'markdown', 'csv', 'html', 'htm', 'properties', 'vtt')
or doc_form == 'text_model'
or mime_type.startswith('text/')
)
if not is_text_doc:
return None
segments_payload = service._request(
'GET',
f'/datasets/{dataset_id}/documents/{remote_document_id}/segments?limit=1000',
)
rows = []
if isinstance(segments_payload, dict):
rows = segments_payload.get('data') or []
elif isinstance(segments_payload, list):
rows = segments_payload
if not isinstance(rows, list) or not rows:
return None
ordered_rows = sorted(
[row for row in rows if isinstance(row, dict)],
key=lambda row: (int(row.get('position') or 0), str(row.get('id') or '')),
)
parts: list[str] = []
for row in ordered_rows:
text = str(row.get('content') or '').strip()
if text:
parts.append(text)
return '\n\n'.join(parts).strip() or None
except Exception as e:
current_app.logger.warning(
'[source-file-text] failed to fetch dify text document dataset=%s doc=%s err=%s',
dataset_id,
remote_document_id,
e,
)
return None
def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
"""
使用 LibreOffice 或 WPS/MS Office 将 office 文件转为 PDF
"""
import shutil
temp_dir = tempfile.mkdtemp()
try:
input_path = os.path.join(temp_dir, f"input.{ext}")
with open(input_path, 'wb') as f:
f.write(content)
commands = ['soffice', 'libreoffice', 'C:\\Program Files\\LibreOffice\\program\\soffice.exe', 'C:\\Program Files (x86)\\LibreOffice\\program\\soffice.exe']
success = False
for cmd in commands:
try:
process = subprocess.run([cmd, '--headless', '--convert-to', 'pdf', '--outdir', temp_dir, input_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=60)
if process.returncode == 0:
success = True
break
else:
current_app.logger.warning(f"LibreOffice command {cmd} failed: {process.stderr.decode('utf-8', errors='ignore')}")
except (FileNotFoundError, subprocess.TimeoutExpired):
continue
if not success and os.name == 'nt':
app = None
doc_obj = None
pythoncom = None
try:
import win32com.client
import pythoncom
pythoncom.CoInitialize()
output_path = os.path.join(temp_dir, 'input.pdf')
if ext in ('doc', 'docx'):
try:
from pathlib import Path
from edkb_system.skills.word_bridge import convert_with_word
convert_with_word(Path(input_path), Path(output_path), 17)
success = True
except Exception as word_bridge_exc:
current_app.logger.warning("Word bridge conversion failed: %s", word_bridge_exc)
if not success and ext in ('doc', 'docx'):
try:
# 对旧版 .doc,MS Word 的 PDF 导出兼容性通常优于 WPS
app = win32com.client.Dispatch("Word.Application")
except Exception:
app = win32com.client.Dispatch("KWPS.Application")
app.Visible = False
app.DisplayAlerts = False
input_abs = os.path.abspath(input_path)
output_abs = os.path.abspath(output_path)
try:
doc_obj = app.Documents.Open(
FileName=input_abs,
ConfirmConversions=False,
ReadOnly=True,
AddToRecentFiles=False,
Visible=False,
NoEncodingDialog=True,
OpenAndRepair=True,
)
except TypeError:
doc_obj = app.Documents.Open(input_abs, ReadOnly=True)
try:
# 旧版 WPS/Word 对 ExportAsFixedFormat 的兼容通常优于 SaveAs(FileFormat=17)
doc_obj.ExportAsFixedFormat(output_abs, 17) # 17 = wdExportFormatPDF
except Exception:
doc_obj.SaveAs(output_abs, 17) # 17 = wdFormatPDF
success = True
elif ext in ('ppt', 'pptx'):
try:
app = win32com.client.Dispatch('KWPP.Application')
except Exception:
app = win32com.client.Dispatch('PowerPoint.Application')
app.Visible = False
try:
app.DisplayAlerts = False
except Exception:
pass
doc_obj = app.Presentations.Open(os.path.abspath(input_path), ReadOnly=True, WithWindow=False)
doc_obj.SaveAs(os.path.abspath(output_path), 32) # 32 = ppSaveAsPDF
success = True
elif ext in ('xls', 'xlsx'):
try:
app = win32com.client.Dispatch('KET.Application')
except Exception:
app = win32com.client.Dispatch('Excel.Application')
app.Visible = False
app.DisplayAlerts = False
doc_obj = app.Workbooks.Open(os.path.abspath(input_path), ReadOnly=True)
doc_obj.ExportAsFixedFormat(0, os.path.abspath(output_path)) # 0 = xlTypePDF
success = True
except ImportError:
current_app.logger.warning('pywin32 not installed, cannot fallback to WPS/MS Office COM API.')
except Exception as e:
current_app.logger.warning(f"WPS/MS Office COM conversion failed: {e}")
finally:
if doc_obj is not None:
try:
doc_obj.Close(False)
except Exception:
pass
if app is not None:
try:
app.Quit()
except Exception:
pass
if pythoncom is not None:
try:
pythoncom.CoUninitialize()
except Exception:
pass
if not success:
raise Exception('Failed to convert document to PDF using LibreOffice or WPS/MS Office')
output_path = os.path.join(temp_dir, 'input.pdf')
if os.path.exists(output_path):
with open(output_path, 'rb') as f:
return f.read()
else:
raise Exception("PDF output not found after conversion")
finally:
shutil.rmtree(temp_dir, ignore_errors=True)
def _convert_excel_to_xlsx(content: bytes, ext: str) -> bytes:
"""
使用 LibreOffice 将老式 `.xls` 转为 `.xlsx`,供在线预览解析。
"""
normalized_ext = (ext or '').strip().lower()
if normalized_ext != 'xls':
return content
with tempfile.TemporaryDirectory() as temp_dir:
input_path = os.path.join(temp_dir, 'input.xls')
output_path = os.path.join(temp_dir, 'input.xlsx')
with open(input_path, 'wb') as f:
f.write(content)
commands = ['soffice', 'libreoffice', 'C:\\Program Files\\LibreOffice\\program\\soffice.exe', 'C:\\Program Files (x86)\\LibreOffice\\program\\soffice.exe']
errors = []
for cmd in commands:
try:
process = subprocess.run([cmd, '--headless', '--convert-to', 'xlsx', '--outdir', temp_dir, input_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=60)
except (FileNotFoundError, subprocess.TimeoutExpired) as e:
errors.append(f'{cmd}: {e}')
continue
if process.returncode == 0 and os.path.exists(output_path):
with open(output_path, 'rb') as f:
return f.read()
stderr = process.stderr.decode('utf-8', errors='ignore').strip()
errors.append(f"{cmd}: {stderr or f'code={process.returncode}'}")
allow_windows_excel_preview = (
os.getenv('ENABLE_WINDOWS_EXCEL_PREVIEW_CONVERSION', '').strip().lower() in ('1', 'true', 'yes', 'on')
)
if allow_windows_excel_preview:
if _convert_excel_via_windows_office(input_path, output_path):
with open(output_path, 'rb') as f:
return f.read()
errors.append("windows-office: failed to convert xls via WPS/MS Excel")
else:
errors.append("windows-office: disabled for preview to avoid interactive Office dialogs")
joined = "; ".join(errors) if errors else "no converter attempted"
raise RuntimeError(f"failed to convert xls to xlsx: {joined}")
def _convert_excel_via_windows_office(input_path: str, output_path: str) -> bool:
"""
在 Windows 环境下使用 WPS/MS Excel 将 `.xls` 转为 `.xlsx`。
LibreOffice 不存在时,给在线预览提供兜底转换能力。
"""
if os.name != 'nt':
return False
try:
import pythoncom
import win32com.client
except ImportError:
current_app.logger.warning('pywin32 not installed, cannot fallback to WPS/MS Excel for xls preview.')
return False
app = None
workbook = None
pythoncom.CoInitialize()
try:
try:
app = win32com.client.Dispatch('KET.Application')
except Exception:
app = win32com.client.Dispatch('Excel.Application')
app.Visible = False
app.DisplayAlerts = False
workbook = app.Workbooks.Open(os.path.abspath(input_path))
workbook.SaveAs(os.path.abspath(output_path), FileFormat=51)
workbook.Close(False)
workbook = None
app.Quit()
app = None
return os.path.exists(output_path)
except Exception as exc:
current_app.logger.warning('WPS/MS Excel conversion failed for xls preview: %s', exc)
return False
finally:
try:
if workbook is not None:
workbook.Close(False)
except Exception:
pass
try:
if app is not None:
app.Quit()
except Exception:
pass
try:
pythoncom.CoUninitialize()
except Exception:
pass
def _detect_excel_format(content: bytes, ext: str) -> str:
"""
根据文件头兜底判断 Excel 实际格式,避免只依赖 URL/文件名扩展名。
- OLE 复合文档头: 老式 `.xls`
- ZIP 头: `.xlsx`
"""
normalized_ext = (ext or '').strip().lower()
head = content[:8] if content else b''
if head.startswith(b'PK\x03\x04'):
return 'xlsx'
if head.startswith(b'\xd0\xcf\x11\xe0'):
return 'xls'
return normalized_ext
def _load_excel_workbook(content: bytes, ext: str):
normalized_ext = _detect_excel_format(content, ext)
if normalized_ext == 'xls':
content = _convert_excel_to_xlsx(content, 'xls')
return load_workbook(filename=io.BytesIO(content), data_only=True, read_only=True)
+330
View File
@@ -0,0 +1,330 @@
"""
api/chat/previews.py
用途:处理聊天来源文件、Excel、文本及原始文件预览路由。
依赖:chat.shared、chat.preview_support、Dify 与共享盘数据源。
逻辑:校验预览来源后获取文件内容,按格式转换并返回安全的预览响应。
"""
from __future__ import annotations
from .shared import * # noqa: F403
from . import chat_bp
from .preview_support import (
_convert_office_to_pdf,
_detect_excel_format,
_extract_placeholder_text,
_fetch_dify_text_document,
_fetch_preview_source_bytes,
_is_allowed_preview_url,
_load_excel_workbook,
)
@chat_bp.route('/source-file', methods=['GET'])
@require_agent_permission
def resolve_source_file():
"""
Resolve original source download URL by Dify dataset/document IDs.
"""
dataset_id = (request.args.get('dataset_id') or '').strip()
remote_document_id = (request.args.get('remote_document_id') or '').strip()
if not dataset_id or not remote_document_id:
current_app.logger.warning('[source-file] missing required params: dataset_id=%r remote_document_id_present=%s remote_document_id_preview=%r query_args=%s', dataset_id, bool(remote_document_id), remote_document_id[:8] + '...' if remote_document_id else '', dict(request.args))
raise ValidationError('dataset_id and remote_document_id are required')
payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
if not payload:
raise NotFoundError('source file mapping not found')
source_ext = str(payload.get('source_ext') or '').strip().lower()
source_download_url = payload.get('source_download_url')
return jsonify({
'dataset_id': dataset_id,
'remote_document_id': remote_document_id,
'source_filename': payload.get('source_filename'),
'source_ext': source_ext,
'source_download_url': source_download_url,
'download_url_expires_at': payload.get('download_url_expires_at'),
})
@chat_bp.route('/source-file-text', methods=['GET'])
@require_agent_permission
def source_file_text():
dataset_id = (request.args.get('dataset_id') or '').strip()
remote_document_id = (request.args.get('remote_document_id') or '').strip()
if not dataset_id or not remote_document_id:
raise ValidationError('dataset_id and remote_document_id are required')
text = _fetch_dify_text_document(dataset_id, remote_document_id)
if not text:
raise NotFoundError('failed to resolve text source file')
filename = f'{remote_document_id}.txt'
return Response(
text,
status=200,
mimetype='text/plain; charset=utf-8',
headers={
'Content-Disposition': f'inline; filename="{filename}"',
'Cache-Control': 'no-store',
},
)
@chat_bp.route('/preview-excel', methods=['GET'])
@require_agent_permission
def preview_excel():
"""
内网 Excel 预览接口(简版可上线)。
说明:
- xlsx 直接解析;
- xls 先转为 xlsx 后再解析。
"""
file_url = (request.args.get('url') or '').strip()
if not file_url:
raise ValidationError('url is required')
if not _is_allowed_preview_url(file_url):
raise ForbiddenError('url is not allowed for preview')
parsed = urlparse(file_url)
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
name = (request.args.get('name') or '').strip()
name_ext = (name.split('.')[-1] if '.' in name else '').lower()
ext = url_path_ext or name_ext
if ext and ext not in ('xlsx', 'xls'):
raise_for_status(f'unsupported file extension: {ext}', 415)
try:
limit = int(request.args.get('limit', 100))
except ValueError:
limit = 100
limit = max(1, min(limit, 300))
content, _, err = _fetch_preview_source_bytes(file_url, max_size=50 * 1024 * 1024)
if err:
msg, code = err
raise_for_status(msg, code)
detected_ext = _detect_excel_format(content or b'', ext)
if detected_ext not in ('xlsx', 'xls'):
raise_for_status(f'unsupported file extension: {ext or detected_ext or "unknown"}', 415)
try:
wb = _load_excel_workbook(content, detected_ext)
except Exception as e:
current_app.logger.warning(
"[excel-preview] parse workbook failed ext=%s detected_ext=%s size=%s name=%s url=%s err=%r",
ext,
detected_ext,
len(content or b''),
name,
file_url,
e,
)
details: dict = {}
if current_app.config.get('DEBUG') or os.getenv('ENV_NAME', 'dev').strip().lower() == 'dev':
details = {'detail': str(e), 'ext': ext, 'detected_ext': detected_ext, 'size': len(content or b'')}
raise AppError(code='VALIDATION.UNPROCESSABLE', message='failed to parse excel file', http_status=422, details=details)
if not wb.sheetnames:
raise_for_status('workbook has no sheets', 422)
requested_sheet = (request.args.get('sheet') or '').strip()
sheet_name = requested_sheet if requested_sheet in wb.sheetnames else wb.sheetnames[0]
ws = wb[sheet_name]
rows = []
for row in ws.iter_rows(values_only=True):
normalized = []
for cell in row:
if cell is None:
normalized.append('')
elif isinstance(cell, (int, float, bool)):
normalized.append(cell)
else:
normalized.append(str(cell))
rows.append(normalized)
if len(rows) >= limit:
break
max_cols = max((len(r) for r in rows), default=0)
for r in rows:
if len(r) < max_cols:
r.extend([''] * (max_cols - len(r)))
columns = [f'COL_{i + 1}' for i in range(max_cols)]
return jsonify({'sheet_name': sheet_name, 'sheets': wb.sheetnames, 'columns': columns, 'rows': rows, 'limit': limit, 'truncated': len(rows) >= limit})
@chat_bp.route('/preview-text', methods=['GET'])
@require_agent_permission
def preview_text():
"""
文本类文件预览接口(内网代理)。
支持:md/markdown/txt/csv/vtt/properties/html/htm
"""
file_url = (request.args.get('url') or '').strip()
if not file_url:
raise ValidationError('url is required')
if not _is_allowed_preview_url(file_url):
raise ForbiddenError('url is not allowed for preview')
parsed = urlparse(file_url)
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
name = (request.args.get('name') or '').strip()
name_ext = (name.split('.')[-1] if '.' in name else '').lower()
explicit_ext = (request.args.get('ext') or '').strip().lower()
ext = explicit_ext or url_path_ext or name_ext
allowed = {'md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'}
if ext and ext not in allowed:
raise_for_status(f'unsupported text extension: {ext}', 415)
max_size = 100 * 1024 * 1024 if request.args.get('download') == '1' else 15 * 1024 * 1024
content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size)
if err:
msg, code = err
raise_for_status(msg, code)
text = None
for enc in ('utf-8', 'utf-8-sig', 'gb18030', 'latin-1'):
try:
text = content.decode(enc)
break
except Exception:
continue
if text is None:
raise_for_status('failed to decode text file', 422)
return jsonify({'content': text, 'content_type': content_type or 'text/plain', 'ext': ext})
def _guess_ext_from_content(content: bytes, default_ext: str) -> str:
"""
根据文件内容(Magic Bytes)纠正可能的错误扩展名
"""
import io
import zipfile
if not content:
return default_ext
if content.startswith(b'%PDF-'):
return 'pdf'
if content.startswith(b'PK\x03\x04'):
# ZIP 归档,进一步检查内部目录判断是 docx/xlsx/pptx。
try:
with zipfile.ZipFile(io.BytesIO(content)) as zf:
names = {name.lower() for name in zf.namelist()}
if any(name.startswith('word/') for name in names):
return 'docx'
if any(name.startswith('xl/') for name in names):
return 'xlsx'
if any(name.startswith('ppt/') for name in names):
return 'pptx'
except Exception:
pass
if default_ext == 'doc':
return 'docx'
if default_ext == 'xls':
return 'xlsx'
if default_ext == 'ppt':
return 'pptx'
if default_ext in ('docx', 'xlsx', 'pptx'):
return default_ext
return 'docx'
if content.startswith(b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1'):
# OLE 复合文件,通常是 doc, xls, ppt 等。
if default_ext == 'docx': return 'doc'
if default_ext == 'xlsx': return 'xls'
if default_ext == 'pptx': return 'ppt'
if default_ext in ('doc', 'xls', 'ppt'): return default_ext
return 'doc'
return default_ext
@chat_bp.route('/preview-file-raw', methods=['GET'])
@require_agent_permission
def preview_file_raw():
"""
二进制文件内网代理预览接口。
用途:
- 为 pdf/doc/docx 生成可被前端 iframe 访问的同源地址;
- 尽量使用 inline 响应头,避免强制下载。
"""
file_url = (request.args.get('url') or '').strip()
if not file_url:
raise ValidationError('url is required')
if not _is_allowed_preview_url(file_url):
raise ForbiddenError('url is not allowed for preview')
parsed = urlparse(file_url)
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
name = (request.args.get('name') or '').strip()
name_ext = (name.split('.')[-1] if '.' in name else '').lower()
original_ext = url_path_ext or name_ext
ext = original_ext
is_download = request.args.get('download') == '1'
max_size = None if is_download else 15 * 1024 * 1024
content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size)
if err:
msg, code = err
raise_for_status(msg, code)
# 根据文件二进制头部纠正扩展名,防止文件本身是 docx 却被命名为 doc,导致转换或下载后乱码
real_ext = _guess_ext_from_content(content, ext)
if real_ext != ext:
current_app.logger.info(f"[file-preview] corrected extension from {ext} to {real_ext}")
ext = real_ext
if name and '.' in name:
name = f"{name.rsplit('.', 1)[0]}.{ext}"
elif name:
name = f"{name}.{ext}"
# 仅当文件真实格式仍然是旧版 Office/PPT 时才转 PDF。
# 如果原始文件名是 .doc 但内容实际是 .docx,则交给前端 Office 组件渲染,
# 避免在服务端走旧版转换链路导致长时间卡住。
needs_pdf_conversion = (
request.args.get('download') != '1'
and ext in ('doc', 'ppt', 'pptx')
)
if needs_pdf_conversion:
try:
content = _convert_office_to_pdf(content, ext)
ext = 'pdf'
content_type = 'application/pdf'
if name and '.' in name:
name = f"{name.rsplit('.', 1)[0]}.pdf"
elif name:
name = f"{name}.pdf"
except Exception as e:
current_app.logger.error("[file-preview] LibreOffice conversion failed: %s", e)
placeholder_text = _extract_placeholder_text(content)
if placeholder_text:
content = placeholder_text.encode('utf-8')
ext = 'txt'
content_type = 'text/plain; charset=utf-8'
if name and '.' in name:
name = f"{name.rsplit('.', 1)[0]}.txt"
elif name:
name = f"{name}.txt"
current_app.logger.info('[file-preview] office preview degraded to text placeholder for %s', file_url)
else:
raise AppError(
code='VALIDATION.UNPROCESSABLE',
message='failed to convert office file for preview',
http_status=422,
)
fallback_types = {
'pdf': 'application/pdf',
'doc': 'application/msword',
'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'xls': 'application/vnd.ms-excel',
'csv': 'text/csv',
'txt': 'text/plain',
'md': 'text/markdown',
'markdown': 'text/markdown',
'html': 'text/html',
'htm': 'text/html',
}
if ext == 'pdf' and not content.startswith(b'%PDF-'):
placeholder_text = _extract_placeholder_text(content)
if placeholder_text:
content = placeholder_text.encode('utf-8')
content_type = 'text/plain; charset=utf-8'
current_app.logger.info('[file-preview] pdf preview degraded to text placeholder for %s', file_url)
mime = content_type or fallback_types.get(ext) or 'application/octet-stream'
from urllib.parse import quote
filename = (request.args.get('name') or '').strip() or f"preview.{ext or 'bin'}"
encoded_filename = quote(filename)
ascii_filename = filename.encode('ascii', 'ignore').decode('ascii') or f"preview.{ext or 'bin'}"
disposition_type = 'attachment' if is_download else 'inline'
resp = Response(content, status=200, mimetype=mime)
resp.headers['Content-Disposition'] = f"""{disposition_type}; filename="{ascii_filename}"; filename*=UTF-8''{encoded_filename}"""
resp.headers['Cache-Control'] = 'no-store'
resp.headers['X-Preview-Actual-Ext'] = ext or ''
resp.headers['X-Preview-Original-Ext'] = original_ext or ''
return resp
+315
View File
@@ -0,0 +1,315 @@
"""
api/chat/sessions.py
用途:处理聊天会话、历史消息与本地结构化消息路由。
依赖:chat.shared、chat.core、ChatSession、ChatLog。
逻辑:校验当前用户和 Agent 后读写会话及日志,保持历史数据兼容查询。
"""
from __future__ import annotations
from .shared import * # noqa: F403
from . import chat_bp
from .core import (
_chat_logs_for_session,
_ensure_chat_session,
_fallback_title_from_contract_review_log,
_get_chat_session,
_looks_like_review_auto_title,
_serialize_session,
_session_title_from_text,
_user_facing_chat_query,
)
@chat_bp.route('/sessions', methods=['GET'])
@require_agent_permission
def get_chat_sessions():
"""
获取当前用户与当前 Agent 的历史会话列表
"""
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
if user is None or agent is None:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
session_rows = db.session.query(ChatSession).filter(
ChatSession.user_id == user.id,
ChatSession.agent_id == agent.id,
or_(
ChatSession.status == 'running',
exists().where(
and_(
ChatLog.session_id == ChatSession.session_id,
ChatLog.user_id == user.id,
ChatLog.agent_id == agent.id,
)
),
),
).order_by(desc(ChatSession.last_active_at), desc(ChatSession.id)).limit(20).all()
# 纠偏历史:审查结果卡曾把 headline 写成标题时,改用合同文件名展示
title_repaired = False
for item in session_rows:
if not _looks_like_review_auto_title(item.title or ''):
continue
review_log = (
db.session.query(ChatLog)
.filter(
ChatLog.user_id == user.id,
ChatLog.agent_id == agent.id,
ChatLog.message_type == 'procurement-contract-review',
or_(
ChatLog.session_id == item.session_id,
ChatLog.conversation_id == item.session_id,
),
)
.order_by(desc(ChatLog.created_at), desc(ChatLog.id))
.first()
)
better = _fallback_title_from_contract_review_log(review_log)
if better:
item.title = better
title_repaired = True
if title_repaired:
db.session.commit()
sessions = [_serialize_session(item) for item in session_rows]
session_ids = {item['conversation_id'] for item in sessions}
# 兼容旧数据:未迁移到 chat_sessions 的历史记录继续从 chat_logs 聚合出来。
subquery = db.session.query(
ChatLog.conversation_id,
func.max(ChatLog.created_at).label('last_active')
).filter(
ChatLog.user_id == user.id,
ChatLog.agent_id == agent.id,
ChatLog.session_id.is_(None),
ChatLog.conversation_id.isnot(None),
ChatLog.conversation_id != '',
).group_by(ChatLog.conversation_id).subquery()
legacy_rows = db.session.query(
subquery.c.conversation_id,
subquery.c.last_active,
).order_by(desc(subquery.c.last_active)).limit(20).all()
for row in legacy_rows:
if not row.conversation_id or row.conversation_id in session_ids:
continue
latest_query_row = db.session.query(ChatLog.query).filter(ChatLog.user_id == user.id, ChatLog.agent_id == agent.id, ChatLog.conversation_id == row.conversation_id, ChatLog.query.isnot(None), ChatLog.query != '').order_by(desc(ChatLog.created_at), desc(ChatLog.id)).first()
title = (latest_query_row[0] if latest_query_row and latest_query_row[0] else '').strip()
sessions.append({
'id': 0,
'conversation_id': row.conversation_id,
'title': title[:30] + ('...' if len(title) > 30 else '') if title else '',
'created_at': row.last_active.isoformat(),
'status': 'done',
})
sessions.sort(key=lambda item: item.get('created_at') or '', reverse=True)
return jsonify(sessions[:20])
@chat_bp.route('/sessions', methods=['DELETE'])
@require_agent_permission
def delete_all_chat_sessions():
"""
删除当前用户与当前 Agent 的所有历史会话
"""
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
if user is None or agent is None:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
chat_logs = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id).all()
chat_log_ids = [log.id for log in chat_logs]
if chat_log_ids:
from app.models import GeneralFeedback
db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
db.session.query(GeneralFeedback).filter(GeneralFeedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False)
db.session.query(ChatSession).filter_by(user_id=user.id, agent_id=agent.id).delete(synchronize_session=False)
db.session.commit()
return jsonify({'status': 'ok'})
@chat_bp.route('/sessions/<conversation_id>', methods=['DELETE'])
@require_agent_permission
def delete_chat_session(conversation_id):
"""
删除指定的会话记录
"""
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
if user is None or agent is None:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
session = _get_chat_session(user.id, agent.id, conversation_id)
if session:
chat_logs = db.session.query(ChatLog).filter(
ChatLog.user_id == user.id,
ChatLog.agent_id == agent.id,
or_(
ChatLog.session_id == session.session_id,
ChatLog.conversation_id == session.external_conversation_id,
)
).all()
else:
chat_logs = db.session.query(ChatLog).filter_by(
user_id=user.id,
agent_id=agent.id,
conversation_id=conversation_id
).all()
chat_log_ids = [log.id for log in chat_logs]
if chat_log_ids:
from app.models import GeneralFeedback
db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
db.session.query(GeneralFeedback).filter(GeneralFeedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False)
if session:
db.session.delete(session)
db.session.commit()
return jsonify({'status': 'ok'})
@chat_bp.route('/messages', methods=['GET'])
@require_agent_permission
def get_chat_messages():
"""
获取指定会话的消息记录
"""
conversation_id = request.args.get('conversation_id')
if not conversation_id:
return jsonify([])
session = _get_chat_session(getattr(g.current_user, 'id', 0), getattr(g.current_agent, 'id', 0), conversation_id)
if session:
logs = _chat_logs_for_session(g.current_user.id, g.current_agent.id, session)
else:
logs = db.session.query(ChatLog).filter(
ChatLog.user_id == g.current_user.id,
ChatLog.agent_id == g.current_agent.id,
ChatLog.conversation_id == conversation_id,
).order_by(ChatLog.created_at.asc()).all()
messages = []
agent_code = str(getattr(g.current_agent, 'agent_code', '') or '').strip() or 'generic'
for log in logs:
if log.query:
messages.append({'role': 'user', 'content': _user_facing_chat_query(log.query, agent_code=agent_code)})
if (
not log.answer
and not log.message_type
and not log.payload
):
continue
if (
log.query
and log.answer == log.query
and (not log.message_type or log.message_type == 'text')
and not log.payload
):
continue
assistant_msg = {
'role': 'assistant',
'content': DifyService._dedupe_exact_doubled_text(log.answer or ''),
'chat_log_id': log.id,
'retriever_resources': log.retriever_resources or [],
'attribution_parts': log.attribution_parts or [],
}
if log.run_id:
assistant_msg['run_id'] = log.run_id
if log.message_type:
assistant_msg['type'] = log.message_type
if log.payload:
assistant_msg['payload'] = log.payload
messages.append(assistant_msg)
return jsonify(messages)
@chat_bp.route('/messages/local', methods=['POST'])
@require_agent_permission
def save_local_message():
"""
保存前端本地生成的聊天记录(如表单、确认弹窗、合同审查结果卡等)。
核心逻辑:user 角色用 content/query 落库;纯文本 assistant 忽略 query 防重复气泡;
结构化 typed 消息(leave-form / procurement-contract-review 等)保留 query,供历史回放与会话标题。
"""
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
if user is None or agent is None:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
data = request.get_json() or {}
conversation_id = (data.get('conversation_id') or '').strip()
role = (data.get('role') or 'assistant').strip()
message_type = data.get('type')
content = data.get('content', '')
payload = data.get('payload')
user_query = data.get('query', '')
if role == 'user':
user_query = user_query or content
content = ''
else:
# [STEP] 纯文本助手消息忽略误传的 query,避免与已落库用户气泡重复(见回归测试)
# 结构化结果卡必须保留 query,否则刷新后用户提问与历史标题都会丢失
if not message_type or message_type == 'text':
user_query = ''
if not message_type:
raise ValidationError('type is required')
title = user_query or content
external_conversation_id = conversation_id if conversation_id and _get_chat_session(user.id, agent.id, conversation_id) is None else None
session = _ensure_chat_session(
user.id,
agent.id,
conversation_id or None,
title=title,
status='done',
external_conversation_id=external_conversation_id,
)
conversation_id = session.session_id
# 纠偏:已有会话若误用审查 headline 作标题,有用户提问时改回提问摘要
if user_query and _looks_like_review_auto_title(session.title or ''):
session.title = _session_title_from_text(user_query)
# 如果 payload 里面包含 formId,且该 formId 已经被保存过,可以直接更新该记录
# 这样能保证前端表单状态(例如已确认)被持久化
local_id = payload.get('formId') if payload and isinstance(payload, dict) else None
chat_log = None
if local_id:
# 在 payload 中查找是否已存在相同 formId 的同类型消息
# SQLite / Postgres 对 JSON 过滤有差异,为了简单,我们可以取出当前会话的所有该类型消息并在内存中匹配
logs = db.session.query(ChatLog).filter_by(
user_id=user.id,
agent_id=agent.id,
session_id=conversation_id,
message_type=message_type
).order_by(ChatLog.created_at.desc()).limit(20).all()
for log in logs:
if log.payload and isinstance(log.payload, dict) and (log.payload.get('formId') == local_id):
chat_log = log
break
if chat_log:
chat_log.content = content
chat_log.answer = content
chat_log.payload = payload
if user_query and (not chat_log.query):
chat_log.query = user_query
else:
chat_log = ChatLog(
user_id=user.id,
agent_id=agent.id,
conversation_id=session.external_conversation_id or conversation_id,
session_id=conversation_id,
query=user_query,
answer=content,
message_type=message_type,
payload=payload
)
db.session.add(chat_log)
session.status = 'done'
session.last_active_at = datetime.utcnow()
session.updated_at = datetime.utcnow()
db.session.commit()
return jsonify({'status': 'ok', 'chat_log_id': chat_log.id, 'conversation_id': conversation_id})
+47
View File
@@ -0,0 +1,47 @@
"""
api/chat/shared.py
用途:汇总聊天 API 子模块共同使用的框架对象、模型、服务和常量。
依赖:Flask、SQLAlchemy、DifyService、IntegrationApiService、聊天数据模型。
逻辑:各 chat 路由模块从本文件复用基础依赖;Blueprint 仅由 api/chat/__init__.py 创建,避免重复注册。
"""
import io
import ipaddress
import mimetypes
import ntpath
import posixpath
import tempfile
import os
import subprocess
import uuid
import json
import time
from datetime import datetime
from urllib.parse import urlparse
import requests
from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app, has_request_context
from sqlalchemy import func, desc, or_, exists, and_
from openpyxl import load_workbook
from app.services.agent_runtime_context.dify_inputs import build_chat_dify_inputs
from app.services.dify import DifyService
from app.core.config.settings import Config
from app.services.integration_api import IntegrationApiService
from app.core.decorators import require_agent_permission
from app.models import Agent, ChatLog, ChatSession, Feedback
from app import db
from app.core.errors import (
AppError,
ConflictError,
ForbiddenError,
NotFoundError,
ServiceUnavailableError,
UnauthorizedError,
ValidationError,
raise_for_status,
)
SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice'
PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip()
+223
View File
@@ -0,0 +1,223 @@
"""
api/chat/uploads.py
用途:处理聊天附件上传并转发至当前 Agent 对应的 Dify 应用。
依赖:chat.shared、DifyService、Config、requests、chat_bp。
逻辑:校验文件类型、上传方式和大小限制后调用 Dify 文件接口,返回标准化文件元数据。
"""
from __future__ import annotations
from .shared import * # noqa: F403
from . import chat_bp
@chat_bp.route('/files/upload', methods=['POST'])
@require_agent_permission
def upload_chat_file():
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
if user is None or agent is None:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
if str(getattr(agent, 'type', '') or '').strip().lower() != 'api':
raise ValidationError('This agent does not support file upload')
if not getattr(agent, 'dify_api_key', None):
raise ValidationError('This agent does not support file upload')
upload = request.files.get('file')
if not upload:
raise ValidationError('file is required')
from app.services.dify import DifyService
from app.core.config.settings import Config
params = DifyService.get_app_parameters(agent, force_refresh=True)
file_upload_cfg = (params or {}).get('file_upload') if isinstance(params, dict) else {}
system_params = (params or {}).get('system_parameters') if isinstance(params, dict) else {}
filename = str(getattr(upload, 'filename', '') or '').strip()
mimetype = str(getattr(upload, 'mimetype', '') or '').lower().strip()
detected_type, ext = DifyService.detect_file_type(filename, mimetype)
file_type = None
normalized_allowed_types = None
normalized_allowed_methods = None
normalized_allowed_exts = None
is_new_schema = False
if isinstance(file_upload_cfg, dict) and file_upload_cfg.get('enabled') is True and isinstance(file_upload_cfg.get('allowed_file_types'), list):
is_new_schema = True
normalized_allowed_types = set(
(
str(v or '').strip().lower()
for v in (file_upload_cfg.get('allowed_file_types') or [])
if str(v or '').strip()
)
)
normalized_allowed_methods = set(
(
str(v or '').strip().lower()
for v in (file_upload_cfg.get('allowed_file_upload_methods') or [])
if str(v or '').strip()
)
)
exts = []
for v in (file_upload_cfg.get('allowed_file_extensions') or []):
s = str(v or '').strip()
if not s:
continue
if s.startswith('.'):
s = s[1:]
s = s.lower().strip()
if s:
exts.append(s)
normalized_allowed_exts = set(exts) if exts else None
if detected_type:
file_type = detected_type
else:
if is_new_schema and normalized_allowed_types and 'custom' in normalized_allowed_types and (not DifyService.is_known_file_extension(ext)):
file_type = 'custom'
else:
custom_cfg = file_upload_cfg.get('custom') if isinstance(file_upload_cfg, dict) else None
if isinstance(custom_cfg, dict) and custom_cfg.get('enabled') and (not DifyService.is_known_file_extension(ext)):
file_type = 'custom'
else:
raise ValidationError(f'Unsupported file type (ext={ext or ""}, mime={mimetype or ""})')
def _effective_type_methods(target_type: str) -> set[str]:
if not isinstance(file_upload_cfg, dict):
return set(normalized_allowed_methods or set())
cfg = file_upload_cfg.get(target_type)
transfer_methods = []
if isinstance(cfg, dict):
transfer_methods = cfg.get('transfer_methods') or cfg.get('transfer_methods'.replace('_', '-')) or []
if isinstance(transfer_methods, str):
transfer_methods = [transfer_methods]
if isinstance(transfer_methods, list) and len(transfer_methods) > 0:
return set(str(m or '').strip().lower() for m in transfer_methods if str(m or '').strip())
return set(normalized_allowed_methods or set())
def _is_type_enabled_in_new_schema(target_type: str) -> bool:
if not (is_new_schema and normalized_allowed_types):
return False
if not isinstance(file_upload_cfg, dict):
return target_type in normalized_allowed_types
cfg = file_upload_cfg.get(target_type)
if isinstance(cfg, dict) and isinstance(cfg.get('enabled'), bool):
if cfg.get('enabled') is False:
return False
if cfg.get('enabled') is True:
return True
return target_type in normalized_allowed_types
if is_new_schema and normalized_allowed_types:
if not _is_type_enabled_in_new_schema(file_type):
raise ValidationError(f'File type not enabled: {file_type}')
type_methods = _effective_type_methods(file_type)
if 'local_file' not in type_methods:
raise ValidationError('local_file upload is not enabled')
if normalized_allowed_exts:
allowed_for_type = set()
for e in normalized_allowed_exts:
t, _ = DifyService.detect_file_type(f'file.{e}', None)
if t is None:
if _is_type_enabled_in_new_schema('custom') and (not DifyService.is_known_file_extension(e)):
allowed_for_type.add(e)
continue
if t == file_type:
allowed_for_type.add(e)
if allowed_for_type and (not ext or ext not in allowed_for_type):
raise ValidationError(f'Unsupported file extension: .{ext or ""}')
else:
# legacy schema checks
type_cfg = file_upload_cfg.get(file_type) if isinstance(file_upload_cfg, dict) else None
if not isinstance(type_cfg, dict) or not type_cfg.get('enabled'):
raise ValidationError(f'File type not enabled: {file_type}')
transfer_methods = type_cfg.get('transfer_methods') or type_cfg.get('transfer_methods'.replace('_', '-')) or []
if isinstance(transfer_methods, str):
transfer_methods = [transfer_methods]
if 'local_file' not in set((str(m).strip() for m in transfer_methods if m is not None)):
raise ValidationError('local_file upload is not enabled')
def _mb_limit_for_type() -> float | None:
merged = {}
if isinstance(system_params, dict):
merged.update(system_params)
if isinstance(file_upload_cfg, dict) and isinstance(file_upload_cfg.get('fileUploadConfig'), dict):
merged.update(file_upload_cfg.get('fileUploadConfig') or {})
if file_type == 'image':
return merged.get('image_file_size_limit') or merged.get('file_size_limit')
if file_type == 'audio':
return merged.get('audio_file_size_limit') or merged.get('file_size_limit')
if file_type == 'video':
return merged.get('video_file_size_limit') or merged.get('file_size_limit')
return merged.get('file_size_limit')
size_limit_mb = _mb_limit_for_type()
if size_limit_mb is not None:
try:
import os
stream = getattr(upload, 'stream', None)
if stream and hasattr(stream, 'tell') and hasattr(stream, 'seek'):
cur = stream.tell()
stream.seek(0, os.SEEK_END)
size_bytes = stream.tell()
stream.seek(cur)
limit_bytes = int(float(size_limit_mb) * 1024 * 1024)
if size_bytes > limit_bytes:
raise ValidationError(f'File too large (limit {size_limit_mb}MB)')
except ValidationError:
raise
except Exception:
pass
base_url = agent.api_base_url if getattr(agent, 'api_base_url', None) else Config.DIFY_API_BASE
dify_url = DifyService._build_files_upload_url(base_url)
headers = {'Authorization': f'Bearer {agent.dify_api_key}'}
try:
try:
upload.stream.seek(0)
except Exception:
pass
resp = requests.post(
dify_url,
headers=headers,
files={'file': (filename or 'upload', upload.stream, mimetype or 'application/octet-stream')},
data={'user': str(getattr(user, 'id', 'system'))},
timeout=(5, 300),
)
except requests.RequestException as exc:
raise ServiceUnavailableError(f'Upload failed: {exc}')
if not resp.ok:
body = (resp.text or '')[:1500]
header_snapshot = {}
try:
for k in ('x-request-id', 'x-requestid', 'request-id', 'trace-id', 'cf-ray', 'server', 'date'):
v = resp.headers.get(k) or resp.headers.get(k.title())
if v:
header_snapshot[k] = v
except Exception:
header_snapshot = {}
current_app.logger.warning(
'[chat-upload] dify upload failed status=%s url=%s headers=%s body=%s',
resp.status_code,
dify_url,
header_snapshot,
body,
)
raise AppError(
code='DIFY.UPLOAD_FAILED',
message='Upload failed',
http_status=502,
details={'status': resp.status_code, 'body': body, 'url': dify_url, 'headers': header_snapshot},
)
data = resp.json() if resp.content else {}
return jsonify({
'id': data.get('id'),
'name': data.get('name') or filename,
'size': data.get('size'),
'extension': data.get('extension') or ext,
'mime_type': data.get('mime_type') or mimetype,
'type': file_type,
})
+38 -27
View File
@@ -1,9 +1,9 @@
"""
backend/app/api/file_check_tools.py
用途:文件检核 Chatflow 显式 HTTP Tool API。
用途:文件检核 / 立账凭证检核 Chatflow 显式 HTTP Tool API(启动检核复用本蓝图)。
依赖:workspace_file_check、file_check_tools、schedule.scheduler_service。
逻辑:Dify Chatflow 调用本蓝图发起检核、查询批次、下载 Excel。
逻辑:发起检核时可透传顶层 mode/invoice_no(或嵌套 run_options)写入 ScheduleRun.api_request_json。
"""
from __future__ import annotations
@@ -74,7 +74,7 @@ def _require_tool_auth() -> None:
"""
校验 Tool API 访问权限。
核心逻辑:Excel 下载仅校验 query token(浏览器场景);其余端点校验 Dify/RPA 的 Tool API Key。
核心逻辑:Excel 下载仅校验 query token(浏览器场景);其余端点走共用 integration_tool_auth。
"""
# [STEP 1] 浏览器 Excel 下载:JWT token 独立于 Tool API Key
if request.path.endswith("/excel"):
@@ -84,26 +84,10 @@ def _require_tool_auth() -> None:
return
raise UnauthorizedError("invalid_auth")
# [STEP 2] Dify / RPA 服务端调用
configured = str(
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
or current_app.config.get("INTEGRATION_API_KEY")
or ""
).strip()
if not configured:
raise ServiceUnavailableError(
"FILE_CHECK_TOOL_API_KEY or INTEGRATION_API_KEY is not configured",
code="missing_auth",
)
# [STEP 2] Dify / RPA 服务端调用(与立账凭证检核等 Tool 共用密钥)
from app.services.integration_tool_auth import require_integration_tool_auth
bearer = str(request.headers.get("Authorization") or "").strip()
api_token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
if configured in {api_token, integration_key}:
return
if not api_token and not integration_key:
raise UnauthorizedError("missing_auth")
raise UnauthorizedError("invalid_auth")
require_integration_tool_auth()
def _tool_error_code(exc: AppError) -> str:
@@ -382,7 +366,17 @@ def _precheck_no_data(task: ScheduleTask) -> dict | None:
@file_check_bp.route("/tools/tasks/run", methods=["POST"])
def run_file_check():
"""立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。"""
"""
立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。
核心逻辑:解析 task → 防并发锁 → 可选透传 mode/invoice_no(或 run_options)到
ScheduleRun.api_request_json → 异步启动平台 Job。Dify 推荐填顶层 mode/invoice_no。
Body 关键字段(立账凭证检核):
mode: incremental | force_all | single
invoice_no: mode=single 时发票号
run_options: 可选嵌套对象,与顶层字段合并(顶层优先)
"""
perf_started = time.perf_counter()
data = _prepare_bind_payload(request.get_json(silent=True) or {})
task = _resolve_check_task(data)
@@ -428,16 +422,33 @@ def run_file_check():
)
return jsonify(no_data_response)
# [STEP] 解析运行选项:优先顶层 mode/invoice_no(Dify Tool 表单对嵌套 object 常不展示),
# 再与 run_options 对象合并;立账凭证检核读取,普通文件检核忽略。
raw_options = data.get("run_options") if isinstance(data.get("run_options"), dict) else {}
run_options = {}
mode = str(data.get("mode") or raw_options.get("mode") or "").strip().lower()
if mode in {"incremental", "force_all", "single"}:
run_options["mode"] = mode
invoice_no = data.get("invoice_no")
if invoice_no is None or not str(invoice_no).strip():
invoice_no = raw_options.get("invoice_no")
if invoice_no is not None and str(invoice_no).strip():
run_options["invoice_no"] = str(invoice_no).strip()
api_request_json = {
"trigger_source": data.get("trigger_source") or "dify_chatflow",
"conversation_id": data.get("conversation_id"),
}
if run_options:
api_request_json["run_options"] = run_options
run = ScheduleRun(
run_no=_generate_run_no(),
schedule_task_id=task.id,
trigger_type="dify_chatflow",
started_at=datetime.utcnow(),
status="running",
api_request_json={
"trigger_source": data.get("trigger_source") or "dify_chatflow",
"conversation_id": data.get("conversation_id"),
},
api_request_json=api_request_json,
)
db.session.add(run)
db.session.commit()
+110 -11
View File
@@ -1,6 +1,9 @@
"""
backend/app/api/integration.py
文件用途:知识库外部集成查询接口
用途:知识库外部集成查询/下载接口(供 Dify Tool 与聊天源文件预览解析)。
依赖:Flask Blueprint、SQLAlchemy、IntegrationApiService、Kb* 模型。
逻辑:聊天预览经 /api/chat/preview-* 代理到本模块 download;dify-file 供 IntegrationApiService 反查本地映射。
"""
from __future__ import annotations
from pathlib import Path
@@ -144,6 +147,12 @@ def _kb_storage_root() -> Path:
return root
def _resolve_storage_path(path_value: str | None) -> Path | None:
"""
解析知识库存储相对/绝对路径,并校验落在 KB_STORAGE_ROOT 内。
核心逻辑:相对路径拼到存储根;绝对路径直接 resolve 后做越界校验。
@param path_value: 数据库中的路径字符串
@returns 合法绝对 Path,越界或空则 None
"""
if not path_value:
return None
raw_path = Path(str(path_value))
@@ -155,6 +164,45 @@ def _resolve_storage_path(path_value: str | None) -> Path | None:
return None
return candidate
def _existing_storage_path(path_value: str | None) -> Path | None:
"""
解析存储路径且要求文件真实存在。
核心逻辑:先 _resolve_storage_path,再校验 is_file。
@returns 存在的 Path,否则 None
"""
path = _resolve_storage_path(path_value)
if path is None or not path.exists() or not path.is_file():
return None
return path
def _markdown_storage_path(version: KbDocumentVersion) -> Path | None:
"""
取版本可用的清洗 Markdown 文件路径(优先 cleaned_file,其次 preview)。
核心逻辑:路径存在且内容像文本时才返回,避免误把 OLE 二进制当 md。
"""
for path_value in (version.cleaned_file_path, version.cleaned_preview_path):
path = _existing_storage_path(path_value)
if path is None:
continue
try:
head = path.read_bytes()[:4096]
except OSError:
continue
if head.startswith((b'%PDF-', b'PK\x03\x04', b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1')):
current_app.logger.warning(
'[integration] skip binary cleaned path version_id=%s path=%s',
version.id,
path,
)
continue
if b'\x00' in head:
continue
return path
return None
def _current_version(document: KbDocument) -> KbDocumentVersion | None:
versions = list(getattr(document, 'versions', []) or [])
if not versions:
@@ -165,13 +213,40 @@ def _document_query():
return db.session.query(KbDocument).options(joinedload(KbDocument.group), joinedload(KbDocument.versions).joinedload(KbDocumentVersion.sync_records)).filter(KbDocument.is_deleted.is_(False))
def _serialize_integration_document(document: KbDocument, *, version: KbDocumentVersion | None=None, sync_record: KbDifySyncRecord | None=None):
"""
序列化集成侧文档元数据与可下载 URL。
核心逻辑:源文件在磁盘存在时返回 kind=source;否则回退到清洗 Markdown(kind=md),
避免聊天预览拿到“库有映射、盘无文件”的死链。
"""
version = version or _current_version(document)
if not version:
abort(404, description='No current version found.')
sync_record = sync_record or (next((item for item in getattr(version, 'sync_records', []) if item.status == 'synced'), None) or (version.sync_records[0] if getattr(version, 'sync_records', None) else None))
source_download_url = _build_download_url(document.id, kind='source', version_id=version.id)
markdown_download_url = _build_download_url(document.id, kind='md', version_id=version.id) if version.cleaned_file_path or version.cleaned_preview_path else None
return {'document_id': document.id, 'knowledge_base': {'id': document.group.id if document.group else None, 'name': document.group.name if document.group else None, 'department_id': document.group.department_id if document.group else None, 'dify_dataset_id': document.group.dify_dataset_id if document.group else None}, 'title': document.title, 'source_filename': version.source_file_name, 'source_ext': version.source_file_ext, 'file_name': version.source_file_name, 'version_id': version.id, 'version_no': version.version_no, 'convert_status': version.status, 'sync_status': sync_record.status if sync_record else None, 'uploaded_at': version.created_at.isoformat() if version.created_at else None, 'converted_at': version.converted_at.isoformat() if version.converted_at else None, 'download_url_expires_at': None, 'source_download_url': source_download_url, 'markdown_download_url': markdown_download_url, 'markdown_download_url_expires_at': None, 'markdown_public_url': markdown_download_url, 'dify': {'dataset_id': sync_record.dataset_id if sync_record else document.group.dify_dataset_id if document.group else None, 'remote_document_id': sync_record.remote_document_id if sync_record else None, 'status': sync_record.status if sync_record else None, 'last_synced_at': sync_record.synced_at.isoformat() if sync_record and sync_record.synced_at else None}}
source_path = _existing_storage_path(version.source_file_path)
markdown_path = _markdown_storage_path(version)
markdown_download_url = (
_build_download_url(document.id, kind='md', version_id=version.id) if markdown_path else None
)
if source_path is not None:
source_download_url = _build_download_url(document.id, kind='source', version_id=version.id)
source_filename = version.source_file_name
source_ext = version.source_file_ext
elif markdown_path is not None:
# [STEP] 源文件缺失时用清洗稿顶替预览入口,扩展名改为 md 以便前端走文本预览
source_download_url = markdown_download_url
stem = Path(str(version.source_file_name or document.title or f'document-{document.id}')).stem
source_filename = f'{stem}.md'
source_ext = 'md'
current_app.logger.info(
'[integration] source missing, serialize fallback to markdown document_id=%s version_id=%s',
document.id,
version.id,
)
else:
source_download_url = _build_download_url(document.id, kind='source', version_id=version.id)
source_filename = version.source_file_name
source_ext = version.source_file_ext
return {'document_id': document.id, 'knowledge_base': {'id': document.group.id if document.group else None, 'name': document.group.name if document.group else None, 'department_id': document.group.department_id if document.group else None, 'dify_dataset_id': document.group.dify_dataset_id if document.group else None}, 'title': document.title, 'source_filename': source_filename, 'source_ext': source_ext, 'file_name': source_filename, 'version_id': version.id, 'version_no': version.version_no, 'convert_status': version.status, 'sync_status': sync_record.status if sync_record else None, 'uploaded_at': version.created_at.isoformat() if version.created_at else None, 'converted_at': version.converted_at.isoformat() if version.converted_at else None, 'download_url_expires_at': None, 'source_download_url': source_download_url, 'markdown_download_url': markdown_download_url, 'markdown_download_url_expires_at': None, 'markdown_public_url': markdown_download_url, 'dify': {'dataset_id': sync_record.dataset_id if sync_record else document.group.dify_dataset_id if document.group else None, 'remote_document_id': sync_record.remote_document_id if sync_record else None, 'status': sync_record.status if sync_record else None, 'last_synced_at': sync_record.synced_at.isoformat() if sync_record and sync_record.synced_at else None}}
def _serialize_knowledge_base(group: KbGroup, *, document_count: int) -> dict:
return {'id': group.id, 'knowledge_base_id': group.id, 'name': group.name, 'description': group.description, 'department_id': group.department_id, 'dify_dataset_id': group.dify_dataset_id, 'document_count': int(document_count or 0), 'created_at': group.created_at.isoformat() if group.created_at else None, 'updated_at': group.updated_at.isoformat() if group.updated_at else None}
@@ -196,13 +271,31 @@ def _list_files_payload(*, knowledge_base_id: int | None=None, department_id: in
return payload
def _resolve_download_path(version: KbDocumentVersion, kind: str) -> tuple[Path, str]:
"""
解析下载目标路径与文件名。
核心逻辑:kind=source 优先原始文件;缺失时回退清洗 Markdown,避免预览 404。
@param version: 文档版本
@param kind: source | md
@returns (绝对路径, 下载文件名)
@raises NotFoundError: 源文件与清洗稿均不存在
"""
if kind == 'source':
path = _resolve_storage_path(version.source_file_path)
if path is None:
raise NotFoundError('File not found on disk.')
filename = version.source_file_name or f'document-{version.document_id}'
return (path, filename)
preferred = _resolve_storage_path(version.cleaned_file_path) or _resolve_storage_path(version.cleaned_preview_path)
path = _existing_storage_path(version.source_file_path)
if path is not None:
filename = version.source_file_name or f'document-{version.document_id}'
return (path, filename)
preferred = _markdown_storage_path(version)
if preferred is not None:
current_app.logger.warning(
'[integration] source file missing, fallback to markdown document_id=%s version_id=%s path=%s',
version.document_id,
version.id,
preferred,
)
filename = f'document-{version.document_id}-v{version.version_no}.md'
return (preferred, filename)
raise NotFoundError('File not found on disk.')
preferred = _markdown_storage_path(version)
if not preferred:
abort(409, description='Markdown not ready.')
filename = f'document-{version.document_id}-v{version.version_no}.md'
@@ -248,6 +341,10 @@ def list_files_for_knowledge_base(knowledge_base_id: int):
@integration_bp.route('/dify-file', methods=['GET'])
def get_file_detail_by_dify():
"""
按 Dify dataset/document 反查本地知识库文件元数据。
核心逻辑:查 KbDifySyncRecord;若源文件与清洗稿均不在磁盘,返回 404 以便上层改走 Dify 下载。
"""
remote_document_id = str(request.args.get('remote_document_id') or '').strip()
dataset_id = str(request.args.get('dataset_id') or '').strip() or None
if not remote_document_id:
@@ -258,8 +355,10 @@ def get_file_detail_by_dify():
record = record_query.first()
version = record.document_version if record else None
document = version.document if version else None
if not document:
if not document or not version:
raise NotFoundError('No local file mapping found for the given Dify document.')
if _existing_storage_path(version.source_file_path) is None and _markdown_storage_path(version) is None:
raise NotFoundError('No readable local file for the given Dify document.')
return jsonify(_serialize_integration_document(document, version=version, sync_record=record))
@integration_bp.route('/dify-files/resolve', methods=['POST'])
+39
View File
@@ -0,0 +1,39 @@
"""
backend/app/api/linked_services.py
用途:已登录用户读取启用中的关联服务,供 Chat/工作台侧栏入口展示。
依赖:JWT current-user、linked_service_service。
逻辑:仅返回 is_enabled=true;目录失败时由前端静默隐藏入口。
"""
from __future__ import annotations
from flask import Blueprint, jsonify, request
from app.core.auth.jwt import get_current_user
from app.core.errors import AppError, UnauthorizedError
from app.services.admin import linked_service_service
linked_services_bp = Blueprint('linked_services', __name__)
def _require_active_user():
"""解析 Bearer 登录用户;未登录或停用账号时拒绝。"""
authorization = str(request.headers.get('Authorization') or '').strip()
scheme, _, token = authorization.partition(' ')
if scheme.lower() != 'bearer' or not token.strip():
raise UnauthorizedError('Bearer token is required')
user = get_current_user()
if user is None:
raise UnauthorizedError('Unauthorized')
if user.status != 'active':
raise AppError(code='AUTH.ACCOUNT_DISABLED', message='Account is disabled', http_status=403)
return user
@linked_services_bp.route('/linked-services', methods=['GET'])
def list_enabled_linked_services():
"""返回当前用户可见的已启用关联服务。"""
_require_active_user()
return jsonify({'items': linked_service_service.list_enabled_linked_services()})
@@ -0,0 +1,111 @@
"""
backend/app/api/procurement_contract_tools.py
Purpose: Chat/tool-facing procurement contract review APIs.
Dependencies: procurement_contract services, JWT current user, unified response envelope.
Flow: Authenticated users upload comparison files, start reviews, query own history, and download own reports.
"""
from __future__ import annotations
import io
from flask import Blueprint, g, request, send_file
from app.core.auth.jwt import get_current_user
from app.core.errors import UnauthorizedError, ValidationError
from app.core.response import ok
from app.services.procurement_contract import review_service, template_service
procurement_contract_bp = Blueprint("procurement_contract", __name__)
def _require_user():
"""Return current authenticated user."""
user = get_current_user()
if not user:
raise UnauthorizedError()
return user
def _optional_int(value, field: str) -> int | None:
"""Parse optional int payload fields with a ValidationError on bad input."""
if value in (None, ""):
return None
try:
return int(value)
except (TypeError, ValueError) as exc:
raise ValidationError(f"{field} must be integer") from exc
@procurement_contract_bp.route("/templates", methods=["GET"])
def list_enabled_templates():
"""List enabled templates for chat dropdown."""
_require_user()
return ok(template_service.list_enabled_for_chat(), request_id=getattr(g, "request_id", None))
@procurement_contract_bp.route("/reviews", methods=["POST"])
def start_contract_review():
"""Start a review; compare mode requires a user-uploaded original contract baseline."""
user = _require_user()
data = request.get_json() or {}
contract_asset_no = (data.get("contract_asset_no") or "").strip()
if not contract_asset_no:
raise ValidationError("contract_asset_no is required")
result = review_service.start_review(
user_id=user.id,
review_mode=str(data.get("review_mode") or "compare"),
contract_asset_no=contract_asset_no,
original_contract_asset_no=(data.get("original_contract_asset_no") or None),
contract_type=(data.get("contract_type") or None),
supplier_name=(data.get("supplier_name") or None),
agent_id=_optional_int(data.get("agent_id"), "agent_id"),
chat_log_id=_optional_int(data.get("chat_log_id"), "chat_log_id"),
)
return ok(result, request_id=getattr(g, "request_id", None), status=202)
@procurement_contract_bp.route("/reviews/<review_no>", methods=["GET"])
def get_contract_review(review_no: str):
"""Get a current user's review by review number."""
user = _require_user()
return ok(review_service.get_review_for_owner(review_no=review_no, user_id=user.id), request_id=getattr(g, "request_id", None))
@procurement_contract_bp.route("/reviews/<review_no>/report", methods=["GET"])
def download_my_contract_review_report(review_no: str):
"""Download current user's review report as txt or docx."""
user = _require_user()
review_service.get_review_for_owner(review_no=review_no, user_id=user.id)
if (request.args.get("format") or "").lower() == "docx":
name, data, mimetype = review_service.read_review_report_docx_bytes(review_no=review_no)
else:
name, data = review_service.read_review_report_bytes(review_no=review_no)
mimetype = "text/plain; charset=utf-8"
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=name)
@procurement_contract_bp.route("/reviews/<review_no>/annotated-contract", methods=["GET"])
def download_my_annotated_contract(review_no: str):
"""Download current user's original PDF with anchored risk highlights."""
user = _require_user()
review_service.get_review_for_owner(review_no=review_no, user_id=user.id)
name, data, mimetype = review_service.read_review_annotated_contract_bytes(review_no=review_no)
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=name)
@procurement_contract_bp.route("/reviews", methods=["GET"])
def list_my_contract_reviews():
"""List current user's recent procurement contract reviews."""
user = _require_user()
data = review_service.list_reviews(
user_id=user.id,
review_mode=request.args.get("review_mode") or None,
status=request.args.get("status") or None,
keyword=request.args.get("keyword") or None,
risk_level=request.args.get("risk_level") or None,
limit=_optional_int(request.args.get("limit"), "limit") or 20,
offset=_optional_int(request.args.get("offset"), "offset") or 0,
)
return ok(data, request_id=getattr(g, "request_id", None))
+11 -50
View File
@@ -2,16 +2,15 @@
backend/app/api/schedule/runs.py
用途:排程运行触发与运行记录查询 API。
依赖:schedule.blueprint、services/schedule/query_service、scheduler_service。
逻辑:/schedules/<id>/run、/schedules/<id>/runs、/schedule-runs/* 路由。
依赖:schedule.blueprint、services/schedule/query_service、queue_service。
逻辑:手动执行仅创建 queued run/job;独立 schedule worker 承担实际运行。
"""
from __future__ import annotations
import threading
from datetime import datetime
from io import BytesIO
from flask import current_app, jsonify, request, send_file
from flask import jsonify, request, send_file
from app import db
from app.api.schedule.blueprint import schedule_admin_bp
@@ -20,66 +19,28 @@ from app.core.decorators import require_admin
from app.core.errors import ConflictError, NotFoundError
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule.query_service import get_run, list_runs, serialize_run
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
from app.services.schedule.queue_service import enqueue_manual_schedule_run
from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download
from app.services.schedule.shipping_inventory_rpa_finalize import recover_stale_awaiting_rpa_schedule_runs
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
@require_admin
def run_schedule(task_id: int):
"""
手动触发排程后台执行。
核心逻辑:创建 running ScheduleRun → 守护线程内 run_task_now。
手动触发排程并立即返回 queued 运行记录。
核心逻辑:queue_service 同事务创建 ScheduleRun + Job;独立 worker 后台执行。
"""
task = db.session.get(ScheduleTask, task_id)
if not task:
raise NotFoundError('Not found')
recover_stale_awaiting_rpa_schedule_runs(task)
user = get_current_user()
existing = (
db.session.query(ScheduleRun)
.filter(ScheduleRun.schedule_task_id == task.id, ScheduleRun.status == 'running')
.first()
)
if existing:
raise ConflictError('该排程正在执行中,请等待完成后再试', details={'run_id': existing.id})
run = ScheduleRun(
run_no=_generate_run_no(),
schedule_task_id=task.id,
trigger_type='manual',
run, _job_id, created = enqueue_manual_schedule_run(
task.id,
triggered_by_user_id=getattr(user, 'id', None),
started_at=datetime.utcnow(),
status='running',
)
db.session.add(run)
db.session.commit()
app = current_app._get_current_object()
run_id = run.id
def _background():
with app.app_context():
t = db.session.get(ScheduleTask, task_id)
r = db.session.get(ScheduleRun, run_id)
if not t or not r:
return
try:
run_task_now(t, trigger_type='manual', triggered_by_user_id=r.triggered_by_user_id, run=r)
except Exception as exc:
try:
r = db.session.get(ScheduleRun, run_id)
if r and r.status == 'running':
r.status = 'failed'
r.error_message = str(exc)
r.finished_at = datetime.utcnow()
db.session.commit()
except Exception:
db.session.rollback()
current_app.logger.error('[schedule-run] run_id=%s failed: %s', run_id, exc, exc_info=True)
t = threading.Thread(target=_background, daemon=True, name=f'schedule-run-{run_id}')
t.start()
fresh = db.session.get(ScheduleRun, run_id)
if not created:
raise ConflictError('该排程正在等待或执行中,请等待完成后再试', details={'run_id': run.id})
fresh = db.session.get(ScheduleRun, run.id)
return jsonify(serialize_run(fresh))
+4 -4
View File
@@ -231,17 +231,17 @@ def delete_schedule(task_id: int):
raise NotFoundError('Not found')
from app.services.schedule.scheduler_service import request_cancel_run
running_runs = (
active_runs = (
db.session.query(ScheduleRun)
.filter(ScheduleRun.schedule_task_id == task_id, ScheduleRun.status == 'running')
.filter(ScheduleRun.schedule_task_id == task_id, ScheduleRun.status.in_(('queued', 'running')))
.all()
)
for rr in running_runs:
for rr in active_runs:
request_cancel_run(rr.id)
rr.status = 'failed'
rr.error_message = '排程已被删除,执行中断'
rr.finished_at = datetime.utcnow()
if running_runs:
if active_runs:
db.session.commit()
db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False)
db.session.delete(task)
+66
View File
@@ -0,0 +1,66 @@
"""
backend/app/api/sso.py
Purpose: Expose peer-service discovery, short-lived assertion issuance, and public JWKS APIs.
Dependencies: JWT current-user resolver, SSO services, and Flask Blueprint.
Flow: Authenticated browsers request audience-bound assertions; peer-service backends verify them using JWKS.
"""
from __future__ import annotations
from flask import Blueprint, g, jsonify, request
from app.core.auth.jwt import get_current_user
from app.core.errors import AppError, UnauthorizedError, ValidationError
from app.services.auth.sso import build_jwks, issue_assertion, list_applications
sso_bp = Blueprint('sso', __name__)
sso_well_known_bp = Blueprint('sso_well_known', __name__)
def _require_active_user():
"""Resolve an active Bearer-authenticated user and retain verified JWT claims."""
authorization = str(request.headers.get('Authorization') or '').strip()
scheme, _, token = authorization.partition(' ')
if scheme.lower() != 'bearer' or not token.strip():
raise UnauthorizedError('Bearer token is required')
user = get_current_user()
if user is None:
raise UnauthorizedError('Unauthorized')
claims = dict(getattr(g, 'jwt_claims', None) or {})
if not claims:
raise UnauthorizedError('Verified Bearer token is required')
if user.status != 'active':
raise AppError(code='AUTH.ACCOUNT_DISABLED', message='Account is disabled', http_status=403)
return user, claims
@sso_bp.route('/apps', methods=['GET'])
def list_sso_apps():
"""Return enabled application navigation metadata to authenticated HXOPS users."""
_require_active_user()
return jsonify({'items': [application.public_payload() for application in list_applications()]})
@sso_bp.route('/apps/<string:app_key>/assertions', methods=['POST'])
def create_sso_assertion(app_key: str):
"""Issue a short-lived RS256 assertion and return the registered peer callback URL."""
user, claims = _require_active_user()
data = request.get_json(silent=True) or {}
if not isinstance(data, dict):
raise ValidationError('JSON body is required')
return jsonify(issue_assertion(
app_key=app_key,
user=user,
claims=claims,
state=data.get('state'),
))
@sso_well_known_bp.route('/.well-known/jwks.json', methods=['GET'])
def sso_jwks():
"""Publish active and rotation-window product SSO public keys for offline peer verification."""
response = jsonify(build_jwks())
response.headers['Cache-Control'] = 'public, max-age=300'
return response
+3 -2
View File
@@ -2,10 +2,11 @@
backend/app/api/tools/__init__.py
用途:Dify HTTP Tool API Blueprint 聚合。
逻辑:Wave 1 前 re-export shipping_notice_tools、file_check_tools。
逻辑:re-export shipping_notice、file_check、maintenance、voucher_check tools。
"""
from app.api.tools.shipping_notice import shipping_notice_bp # noqa: F401
from app.api.tools.file_check import file_check_bp # noqa: F401
from app.api.tools.maintenance import maintenance_tool_bp # noqa: F401
from app.api.tools.voucher_check import voucher_check_tools_bp # noqa: F401
__all__ = ['shipping_notice_bp', 'file_check_bp']
__all__ = ['shipping_notice_bp', 'file_check_bp', 'maintenance_tool_bp', 'voucher_check_tools_bp']
+105
View File
@@ -0,0 +1,105 @@
"""
backend/app/api/tools/voucher_check.py
用途:立账凭证检核 Dify Tool API(缺资料/批次明细/单票最新状态查询 + OpenAPI)。
依赖:voucher_check.query_service、openapi_spec、integration_tool_auth;启动检核复用 file-check。
逻辑:非 envelope 契约(ok/error_code);与 file-check 共用 Tool API Key;register_blueprints 挂到 /api/accounting-voucher-check。
"""
from __future__ import annotations
from flask import Blueprint, jsonify, request
from app.core.errors import AppError
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
from app.services.integration_tool_auth import require_integration_tool_auth
from app.services.voucher_check import query_service
from app.services.voucher_check.openapi_spec import build_voucher_check_openapi_spec
voucher_check_tools_bp = Blueprint("voucher_check_tools", __name__)
@voucher_check_tools_bp.before_request
def _verify_tool_access():
"""openapi.json 免鉴权,其余端点校验 Tool API Key。"""
if request.path.endswith("/openapi.json"):
return None
require_integration_tool_auth()
return None
def _tool_error(exc: AppError):
"""将 AppError 映射为 Tool 非 envelope 错误体。"""
code = str(exc.code or "").lower().replace(".", "_")
message = str(exc.message or "").strip()
# 与 file-check 对齐:鉴权类错误码用 message 短码,便于 Dify 分支
if message in {"missing_auth", "invalid_auth"}:
code = message
return jsonify({
"ok": False,
"error_code": code,
"message": message or code,
"details": exc.details or {},
}), exc.http_status
@voucher_check_tools_bp.route("/tools/openapi.json", methods=["GET"])
def voucher_check_openapi_spec():
"""
返回 Dify 可 URL 导入的 OpenAPI(无需鉴权)。
【AI 触发时机】:不由对话调用;运维/Dify 导入工具时访问。
"""
return jsonify(build_voucher_check_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
@voucher_check_tools_bp.route("/tools/tasks/<int:task_id>/missing", methods=["GET"])
def tool_list_missing(task_id: int):
"""
查询当前月或指定月缺资料票。
【AI 触发时机】:用户说「查询缺资料发票」时调用。
"""
try:
data = query_service.list_missing_states(
task_id=task_id,
scope_code=str(request.args.get("scope_code") or "HXJM"),
period=request.args.get("period"),
limit=request.args.get("limit", default=200, type=int) or 200,
)
return jsonify({"ok": True, **data})
except AppError as exc:
return _tool_error(exc)
@voucher_check_tools_bp.route("/tools/runs/<int:run_id>/items", methods=["GET"])
def tool_list_run_items(run_id: int):
"""
查询批次明细,可按 result 过滤。
【AI 触发时机】:用户查询某批次结果明细时调用。
"""
try:
data = query_service.list_run_items(
run_id=run_id,
result=request.args.get("result"),
page=request.args.get("page", default=1, type=int) or 1,
page_size=request.args.get("page_size", default=50, type=int) or 50,
)
return jsonify({"ok": True, **data})
except AppError as exc:
return _tool_error(exc)
@voucher_check_tools_bp.route("/tools/invoices/<path:invoice_no>/latest", methods=["GET"])
def tool_invoice_latest(invoice_no: str):
"""
查询指定发票最新状态。
【AI 触发时机】:用户询问某张发票检核结论时调用。
"""
try:
data = query_service.get_invoice_latest(
invoice_no=invoice_no,
scope_code=str(request.args.get("scope_code") or "HXJM"),
period=request.args.get("period"),
)
return jsonify({"ok": True, **data})
except AppError as exc:
return _tool_error(exc)
File diff suppressed because it is too large. Load diff
+46
View File
@@ -0,0 +1,46 @@
"""
api/user/__init__.py
用途:导出用户域与认证域 Blueprint,并维护历史测试替身兼容入口。
依赖:handlers、auth 及其共享认证操作。
逻辑:register_blueprints 将两个 Blueprint 挂载到 `/api/user`;兼容代理确保迁包前的替身点仍然生效。
"""
from __future__ import annotations
import sys
from types import ModuleType
from . import handlers
from . import auth
from .auth import auth_bp
user_bp = handlers.user_bp
# The documented Wave 3 compatibility export supports existing tests and callers.
_get_current_user = handlers._get_current_user
class _UserApiCompatModule(ModuleType):
"""Forward historic private test replacement points to the canonical handlers."""
def __setattr__(self, name: str, value: object) -> None:
super().__setattr__(name, value)
if hasattr(handlers, name):
setattr(handlers, name, value)
if hasattr(auth, name):
setattr(auth, name, value)
sys.modules[__name__].__class__ = _UserApiCompatModule
def __getattr__(name: str):
"""Expose historic test symbols from their formal auth or user module."""
if hasattr(auth, name):
return getattr(auth, name)
return getattr(handlers, name)
__all__ = ['auth_bp', 'user_bp']
+40
View File
@@ -0,0 +1,40 @@
"""
api/user/auth.py
用途:用户认证 Blueprint 的兼容门面与路由装配入口。
依赖:auth_local、auth_casdoor、auth_wecom、auth_password_reset、auth_support。
逻辑:api/user/__init__.py 从此模块导出 auth_bp;各职责路由在独立模块注册,历史测试仍可替换本模块私有符号。
"""
from __future__ import annotations
import sys
from types import ModuleType
from flask import Blueprint
from . import auth_support as _support
auth_bp = Blueprint('user_auth', __name__)
class _AuthCompatModule(ModuleType):
"""将历史 monkeypatch 同步到共享认证操作,保持测试替身入口稳定。"""
def __setattr__(self, name: str, value: object) -> None:
super().__setattr__(name, value)
if hasattr(_support, name):
setattr(_support, name, value)
sys.modules[__name__].__class__ = _AuthCompatModule
def __getattr__(name: str):
"""兼容导出共享认证操作与历史测试替身点。"""
return getattr(_support, name)
# Importing modules registers their narrow route groups on the shared Blueprint.
from . import auth_casdoor, auth_local, auth_password_reset, auth_wecom # noqa: E402, F401
__all__ = ['auth_bp']
+125
View File
@@ -0,0 +1,125 @@
"""
api/user/auth_casdoor.py
用途:Casdoor 密码、授权码与刷新令牌认证路由。
依赖:auth.auth_bp、auth_support 兼容操作、services/auth/hxops。
逻辑:HTTP 参数与公开 URL 在本模块分组;登录编排仍复用已有 Casdoor 服务适配器。
"""
from __future__ import annotations
from flask import current_app, jsonify, request
from app import db
from app.core.errors import AppError, UnauthorizedError, ValidationError
from app.services.auth.hxops.casdoor_authorize import CasdoorAuthorizeOptions
from . import auth as _compat
from .auth import auth_bp
@auth_bp.post('/casdoor/password-login', endpoint='casdoor_password_login')
def password_login():
"""使用 Casdoor password grant 登录,并返回 HXOPS 本地 API 会话。"""
if (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() != 'casdoor':
raise AppError(
code='AUTH.CASDOOR_PASSWORD_LOGIN_DISABLED',
message='Casdoor password login is disabled by AUTH_LOGIN_MODE',
http_status=403,
)
data = request.get_json() or {}
username = _compat._clean_str(data.get('username'))
password = data.get('password') or ''
if not username or not password:
raise ValidationError('Username and password are required')
try:
result = _compat._hxops_login_service().password(username, password)
db.session.commit()
return jsonify(result.login_payload())
except _compat.WeComLoginError:
db.session.rollback()
raise
except AppError:
db.session.rollback()
raise
except Exception as exc:
db.session.rollback()
_compat._raise_casdoor_auth_error(exc, context='password')
@auth_bp.get('/casdoor/authorize-url', endpoint='casdoor_authorize_url')
def authorize_url():
"""生成包含状态参数的 Casdoor 授权码登录地址。"""
try:
options = CasdoorAuthorizeOptions(
redirect_uri=request.args.get('redirect_uri'),
provider_hint=request.args.get('provider_hint'),
default_provider=request.args.get('default_provider'),
silent_signin=request.args.get('silent_signin'),
)
return jsonify(_compat._build_casdoor_authorize_payload(options))
except Exception as exc:
raise AppError(
code='SYSTEM.INTERNAL_ERROR',
message=f'Failed to build Casdoor authorize url: {exc}',
http_status=500,
) from exc
@auth_bp.post('/casdoor/login', endpoint='casdoor_login')
def authorization_code_login():
"""交换授权码、映射本地用户并签发 HXOPS API 会话。"""
data = request.get_json() or {}
code = _compat._clean_str(data.get('code'))
state = _compat._clean_str(data.get('state'))
if not code:
raise ValidationError('code is required')
current_app.logger.info('[casdoor_login] start code_len=%s state=%s', len(code), state[:24] if state else '')
redirect_uri = _compat._consume_casdoor_state(state)
if not redirect_uri:
current_app.logger.warning('[casdoor_login] invalid_state state=%s', state[:24] if state else '')
raise ValidationError('Invalid or expired Casdoor state')
try:
result = _compat._hxops_login_service().authorization_code(code, redirect_uri)
current_app.logger.info('[casdoor_login] user_resolved username=%s id=%s', result.user.username, result.user.id)
db.session.commit()
return jsonify(result.login_payload())
except _compat.WeComLoginError:
db.session.rollback()
current_app.logger.warning('[casdoor_login] business_reject')
raise
except AppError:
db.session.rollback()
raise
except Exception as exc:
db.session.rollback()
current_app.logger.exception('[casdoor_login] failed state=%s redirect_uri=%s', state[:24] if state else '', redirect_uri)
_compat._raise_casdoor_auth_error(exc, context='code')
@auth_bp.post('/casdoor/refresh', endpoint='casdoor_refresh')
def refresh():
"""以 Casdoor refresh token 换取新的 HXOPS API 会话。"""
data = request.get_json() or {}
refresh_token = _compat._clean_str(data.get('refresh_token'))
if not refresh_token:
raise ValidationError('refresh_token is required')
current_app.logger.info('[casdoor_refresh] start refresh=%s', _compat._token_brief(refresh_token))
try:
result = _compat._hxops_login_service().refresh(refresh_token)
current_app.logger.info(
'[casdoor_refresh] token_refresh_ok next_refresh=%s user_id=%s',
_compat._token_brief(result.refresh_token), result.user.id,
)
return jsonify(result.refresh_payload())
except AppError:
raise
except Exception as exc:
message = str(exc)
if 'unsupported_grant_type' in message or 'refresh_token is not supported' in message:
raise AppError(
code='AUTH.CASDOOR_REFRESH_UNSUPPORTED',
message='Casdoor refresh token is not supported by current application config',
http_status=400,
) from exc
current_app.logger.exception('[casdoor_refresh] failed refresh=%s', _compat._token_brief(refresh_token))
raise UnauthorizedError(f'Casdoor refresh failed: {exc}') from exc
+128
View File
@@ -0,0 +1,128 @@
"""
api/user/auth_local.py
用途:注册、传统密码登录与改密 HTTP 路由。
依赖:auth.auth_bp、auth_support 的共享认证操作。
逻辑:本模块仅装配本地密码职责;业务处理暂由兼容实现承接,后续迁移不改变公开 URL。
"""
from __future__ import annotations
from flask import current_app, jsonify, request
from sqlalchemy.exc import DatabaseError, OperationalError
from app import db
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError, ValidationError
from . import auth as _compat
from .auth import auth_bp
@auth_bp.post('/register', endpoint='register')
def register():
"""校验必填和唯一字段后创建本地用户,保持原有注册响应。"""
data = request.get_json() or {}
required_fields = ['username', 'password', 'email', 'real_name', 'employee_id', 'phone_number']
for field in required_fields:
if not data.get(field):
raise ValidationError(f'{field} is required')
if db.session.query(_compat.User).filter_by(username=data['username']).first():
raise ValidationError('Username already exists')
if db.session.query(_compat.User).filter_by(email=data['email']).first():
raise ValidationError('Email already exists')
if db.session.query(_compat.User).filter_by(employee_id=data['employee_id']).first():
raise ValidationError('Employee ID already exists')
try:
user = _compat.User(
username=data['username'], email=data['email'], real_name=data['real_name'],
employee_id=data['employee_id'], phone_number=data['phone_number'],
department=data.get('department'), role='user', status='active',
)
user.set_password(data['password'])
db.session.add(user)
db.session.commit()
return jsonify({'message': 'Registration successful', 'id': user.id}), 201
except Exception as exc:
db.session.rollback()
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(exc), http_status=500) from exc
@auth_bp.post('/login', endpoint='login')
def login():
"""处理兼容的本地用户名密码登录;委托原有审计与重试逻辑。"""
if not bool(current_app.config.get('AUTH_ALLOW_LOCAL_PASSWORD_LOGIN', True)):
raise AppError(
code='AUTH.PASSWORD_LOGIN_DISABLED',
message='Password login is disabled. Please use Casdoor login.',
http_status=403,
)
def attempt_login():
"""校验本地密码并写入登录审计;用于可恢复数据库失败的一次重试。"""
data = request.get_json() or {}
username = data.get('username')
password = data.get('password')
if not username or not password:
_compat._write_login_audit('password', 'failed', username=username, reason='missing_credentials')
raise ValidationError('Username and password are required')
user = db.session.query(_compat.User).filter_by(username=username).first()
if not user:
_compat._write_login_audit('password', 'failed', username=username, reason='user_not_found')
db.session.commit()
raise AppError(code='AUTH.USER_NOT_FOUND', message='User not found', http_status=404)
if not user.check_password(password):
_compat._write_login_audit('password', 'failed', user=user, reason='incorrect_password')
db.session.commit()
raise AppError(code='AUTH.INCORRECT_PASSWORD', message='Incorrect password', http_status=401)
if user.status != 'active':
_compat._write_login_audit('password', 'failed', user=user, reason='account_disabled')
db.session.commit()
raise AppError(code='AUTH.ACCOUNT_DISABLED', message='Account is disabled', http_status=403)
_compat._write_login_audit('password', 'success', user=user)
db.session.commit()
return jsonify(_compat._build_login_payload(user, 'password'))
try:
return attempt_login()
except (OperationalError, DatabaseError):
db.session.rollback()
db.session.remove()
try:
return attempt_login()
except (OperationalError, DatabaseError) as retry_exc:
current_app.logger.warning('Password login retry failed: %s', retry_exc)
raise ServiceUnavailableError('Database connection failed') from retry_exc
except AppError:
raise
except Exception as exc:
db.session.rollback()
current_app.logger.exception('Login error: %s', exc)
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Internal server error', http_status=500) from exc
@auth_bp.post('/change-password', endpoint='change_password')
def change_password():
"""校验当前身份并同步更新本地与 Casdoor 密码。"""
user = _compat._get_current_user()
if not user:
raise UnauthorizedError('Unauthorized')
data = request.get_json() or {}
current_password = data.get('current_password')
new_password = data.get('new_password')
if not current_password or not new_password:
raise ValidationError('Current and new password are required')
try:
_compat._verify_current_password_for_change(user, current_password)
_compat._sync_casdoor_password(user.username, current_password, new_password)
user.set_password(new_password)
db.session.commit()
return jsonify({'message': 'Password changed successfully'})
except AppError:
raise
except RuntimeError as exc:
db.session.rollback()
if _compat._is_casdoor_password_error(str(exc)):
_compat._raise_incorrect_current_password()
_compat._raise_casdoor_set_password_error(exc)
except Exception as exc:
db.session.rollback()
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(exc), http_status=500) from exc
+147
View File
@@ -0,0 +1,147 @@
"""
api/user/auth_password_reset.py
用途:密码找回与确认重置 HTTP 路由。
依赖:auth.auth_bp、auth_support 的企微配置与 Casdoor 密码同步操作。
逻辑:密码重置从常规登录路由分离;保留原有 URL、通用提示语和令牌有效期语义。
"""
from __future__ import annotations
from datetime import datetime, timedelta
import uuid
from flask import current_app, jsonify, request
from app import db
from app.core.errors import AppError, ValidationError
from app.services.wecom_notify import send_wecom_event_message
from . import auth as _compat
from .auth import auth_bp
_RATE_CACHE: dict[str, datetime] = {}
_GENERIC_MESSAGE = 'If the account exists and WeCom is bound, a reset link has been sent to your WeCom.'
def _base_url() -> str:
"""读取密码重置的公网基地址,避免将内部服务地址发给企业微信用户。"""
for key in ('WECOM_PUBLIC_BASE_URL', 'PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'):
base = _compat._clean_str(current_app.config.get(key))
if base:
return base.rstrip('/')
return ''
def _rate_limit(employee_id: str, *, window_seconds: int = 300) -> tuple[bool, int]:
"""按工号和来源 IP 限制找回请求,返回是否允许及剩余等待秒数。"""
client_ip = request.headers.get('X-Forwarded-For', request.remote_addr) or 'unknown'
key = f'{employee_id}:{client_ip}'
now = datetime.utcnow()
last = _RATE_CACHE.get(key)
if last:
elapsed = (now - last).total_seconds()
if elapsed < window_seconds:
return False, max(1, int(window_seconds - elapsed))
_RATE_CACHE[key] = now
return True, 0
def _sync_casdoor_password(user, new_password: str) -> None:
"""令牌重置无需旧密码;Casdoor 启用时仍须同步 IdP 密码。"""
if not _compat._is_casdoor_configured():
return
try:
_compat._casdoor_set_password(_compat._casdoor_user_owner(), user.username, '', new_password)
except RuntimeError as exc:
if _compat._is_casdoor_user_missing_error(str(exc)):
_compat._raise_casdoor_user_not_in_idp(exc)
_compat._raise_casdoor_set_password_error(exc)
@auth_bp.post('/reset-password-by-wecom', endpoint='reset_password_by_wecom')
def request_by_wecom():
"""向已绑定企业微信的用户发送限时重置链接。"""
if not _compat._is_wecom_configured():
raise AppError(code='WECOM.RESET_NOT_CONFIGURED', message='WeCom password reset is not configured', http_status=503, details={'missing': _compat._get_wecom_config_missing_fields()})
if not bool(current_app.config.get('WECOM_NOTIFY_ENABLED', True)):
raise AppError(code='WECOM.NOTIFY_DISABLED', message='WeCom notification is disabled', http_status=503)
base_url = _base_url()
if not base_url:
raise AppError(code='WECOM.RESET_URL_NOT_CONFIGURED', message='Password reset public base URL is not configured', http_status=503)
data = request.get_json() or {}
employee_id = _compat._clean_str(data.get('employee_id'))
username = _compat._clean_str(data.get('username'))
if not employee_id:
raise ValidationError('Employee ID is required')
if not username:
raise ValidationError('Username is required')
allowed, retry_after_seconds = _rate_limit(employee_id)
if not allowed:
raise AppError(code='AUTH.PASSWORD_RESET_RATE_LIMITED', message='Password reset requests are too frequent', http_status=429, details={'retry_after_seconds': retry_after_seconds, 'retry_after_minutes': max(1, (retry_after_seconds + 59) // 60)}, retryable=True)
user = db.session.query(_compat.User).filter(_compat.User.employee_id == employee_id).first()
if not user or user.username != username or user.status != 'active' or not user.wecom_userid:
return jsonify({'message': _GENERIC_MESSAGE})
token = str(uuid.uuid4())
user.reset_token = token
user.reset_token_expiry = datetime.utcnow() + timedelta(hours=1)
db.session.flush()
try:
result = send_wecom_event_message(event_type='password_reset', user=user, title='和信AI智能工作台 密码重置', content='您发起了和信AI智能工作台密码重置请求。\n请在 1 小时内点击下方按钮设置新密码。\n如非本人操作,请忽略本消息。', jump_url=f'{base_url}/reset-password?token={token}')
if not result.get('ok'):
db.session.rollback()
return jsonify({'message': _GENERIC_MESSAGE})
db.session.commit()
return jsonify({'message': _GENERIC_MESSAGE})
except Exception as exc:
db.session.rollback()
current_app.logger.exception('[password_reset] unexpected failure user_id=%s: %s', user.id, exc)
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Failed to request password reset', http_status=500) from exc
@auth_bp.post('/reset-password-by-email', endpoint='reset_password_request')
def request_by_email():
"""保留邮件找回兼容接口及其既有响应格式。"""
data = request.get_json() or {}
email = data.get('email')
if not email:
raise ValidationError('Email is required')
user = db.session.query(_compat.User).filter_by(email=email).first()
if not user:
return jsonify({'message': 'If the email exists, a reset link has been sent.'})
user.reset_token = str(uuid.uuid4())
user.reset_token_expiry = datetime.utcnow() + timedelta(hours=1)
db.session.commit()
# Legacy development contract: the email channel is mocked by logging its reset link.
reset_link = f'http://localhost:5173/reset-password?token={user.reset_token}'
print('============================================')
print(f'MOCK EMAIL TO: {email}')
print('SUBJECT: Password Reset Request')
print(f'LINK: {reset_link}')
print('============================================')
return jsonify({'message': 'If the email exists, a reset link has been sent.'})
@auth_bp.post('/reset-password-confirm', endpoint='reset_password_confirm')
def confirm():
"""校验重置令牌后同步更新本地与 Casdoor 密码。"""
data = request.get_json() or {}
token = _compat._clean_str(data.get('token'))
new_password = data.get('new_password')
if not token or not new_password:
raise ValidationError('Token and new password are required')
user = db.session.query(_compat.User).filter_by(reset_token=token).first()
if not user or not user.reset_token_expiry or user.reset_token_expiry < datetime.utcnow():
raise AppError(code='AUTH.RESET_TOKEN_INVALID', message='Invalid or expired token', http_status=400)
try:
_sync_casdoor_password(user, new_password)
user.set_password(new_password)
user.reset_token = None
user.reset_token_expiry = None
db.session.commit()
return jsonify({'message': 'Password has been reset successfully'})
except AppError:
db.session.rollback()
raise
except Exception as exc:
db.session.rollback()
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(exc), http_status=500) from exc
+628
View File
@@ -0,0 +1,628 @@
"""
api/user/auth_support.py
用途:承载用户认证域的共享操作,包括 Casdoor 兼容适配、企微身份匹配、登录审计和短时状态。
依赖:services/auth、services/wecom_auth_service、models.User/LoginAudit/WecomCallbackAudit。
逻辑:auth_* 路由模块调用本文件完成领域协作;auth.py 兼容门面转发历史测试替身,不再保留路由实现。
"""
from __future__ import annotations
from flask import request, jsonify, current_app
from app import db
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog
from app.services.feedback_notify import send_feedback_group_notification
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
from app.services.agent_registry.serialization import serialize_registry_fields
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
from app.core.auth.jwt import get_current_user as _auth_current_user
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
from sqlalchemy import and_, or_, inspect, insert
from datetime import datetime, timedelta
import uuid
import requests
from urllib.parse import quote
import re
import ast
from app.core.errors import (
AppError,
ConflictError,
ForbiddenError,
NotFoundError,
ServiceUnavailableError,
UnauthorizedError,
ValidationError,
raise_for_status,
)
from app.services.auth import casdoor_service as _casdoor_svc
from app.services.auth.hxops.casdoor_authorize import CasdoorAuthorizeOptions
from app.services.auth.hxops.login_service import HxopsLoginService
from app.services.auth.hxops import casdoor_route_adapter as _casdoor_route_adapter
from app.services.auth import wecom_auth_service as _wecom_svc
_WECOM_ACCESS_TOKEN_CACHE = _wecom_svc.ACCESS_TOKEN_CACHE
_WECOM_STATE_CACHE = _wecom_svc.STATE_CACHE
_WECOM_BIND_SESSION_CACHE = _wecom_svc.BIND_SESSION_CACHE
_PASSWORD_RESET_RATE_CACHE = {}
_PASSWORD_RESET_GENERIC_MESSAGE = 'If the account exists and WeCom is bound, a reset link has been sent to your WeCom.'
_ALLOWED_WECOM_MATCH_FIELDS = {'employee_id', 'mobile', 'email'}
_LOGIN_AUDIT_COLUMNS_CACHE = None
def _token_brief(token: str) -> str:
if not token:
return 'empty'
text = str(token)
if len(text) <= 16:
return f'len={len(text)}:{text}'
return f'len={len(text)}:{text[:8]}...{text[-8:]}'
def _is_users_pk_sequence_error(exc: Exception) -> bool:
message = str(exc)
return 'null value in column "id"' in message and 'relation "users"' in message
class WeComLoginError(AppError):
def __init__(self, error: str, error_code: str, status_code: int, reason: str = None, extra: dict = None):
details = dict(extra or {})
if reason:
details['reason'] = reason
super().__init__(code=error_code, message=error, http_status=status_code, details=details)
self.error = error
self.error_code = error_code
self.status_code = status_code
self.reason = reason
self.extra = extra or {}
def _write_login_audit(source: str, status: str, user: User=None, username: str=None, reason: str=None, wecom_userid: str=None, error_code: str=None, match_rules: list=None, match_operator: str=None, match_result: str=None):
payload = {'user_id': user.id if user else None, 'username': username or (user.username if user else None), 'source': source, 'status': status, 'reason': reason, 'error_code': error_code, 'match_rules': ','.join(match_rules) if isinstance(match_rules, list) else match_rules, 'match_operator': match_operator, 'match_result': match_result, 'wecom_userid': wecom_userid, 'ip': request.headers.get('X-Forwarded-For', request.remote_addr), 'user_agent': (request.user_agent.string or '')[:255], 'created_at': datetime.utcnow()}
try:
supported_columns = _get_login_audit_supported_columns()
if not supported_columns:
return
filtered_payload = {key: value for key, value in payload.items() if key in supported_columns}
if not filtered_payload:
return
_execute_login_audit_insert(filtered_payload)
except Exception:
pass
def _get_login_audit_supported_columns():
global _LOGIN_AUDIT_COLUMNS_CACHE
if _LOGIN_AUDIT_COLUMNS_CACHE is not None:
return _LOGIN_AUDIT_COLUMNS_CACHE
try:
columns = {column['name'] for column in inspect(db.engine).get_columns(LoginAudit.__tablename__)}
except Exception:
columns = set()
_LOGIN_AUDIT_COLUMNS_CACHE = columns
return columns
def _execute_login_audit_insert(payload: dict):
nested = db.session.begin_nested()
try:
db.session.execute(insert(LoginAudit.__table__).values(**payload))
db.session.flush()
nested.commit()
except Exception:
nested.rollback()
raise
def _get_current_user():
"""
Resolve current authenticated user for API handlers.
Behavior:
1) Prefer JWT Bearer token validation (Casdoor JWKS).
2) Optional legacy header fallback depends on AUTH_LEGACY_HEADER_ENABLED.
3) Returns None when authentication cannot be established.
"""
return _auth_current_user()
def _run_db_with_retry(operation, *, label: str):
try:
return operation()
except (OperationalError, DatabaseError) as exc:
current_app.logger.warning('%s failed on first attempt: %s', label, exc)
db.session.rollback()
db.session.remove()
try:
db.engine.dispose()
except Exception as dispose_exc:
current_app.logger.warning('%s dispose engine failed: %s', label, dispose_exc)
return operation()
def _get_wecom_config_missing_fields() -> list[str]:
return _wecom_svc.get_config_missing_fields()
def _is_wecom_configured() -> bool:
return _wecom_svc.is_configured()
def _issue_casdoor_state(redirect_uri: str):
"""兼容旧调用点:签发格式不变的 Casdoor state。"""
return _casdoor_route_adapter.issue_casdoor_state(redirect_uri)
def _consume_casdoor_state(state: str):
"""兼容旧调用点:校验 Casdoor state 并恢复签名绑定的 redirect_uri。"""
return _casdoor_route_adapter.consume_casdoor_state(state)
def _get_casdoor_oidc_metadata():
"""兼容旧调用点:委托公共 CasdoorClient 获取 discovery 文档。"""
return _casdoor_route_adapter.get_oidc_metadata()
def _build_casdoor_authorize_payload(options: CasdoorAuthorizeOptions) -> dict[str, str]:
"""兼容入口:使用旧 discovery/state 替换点构造 Casdoor 授权响应。"""
return _casdoor_route_adapter.build_authorize_payload(
options,
oidc_metadata=_get_casdoor_oidc_metadata,
issue_state=_issue_casdoor_state,
)
def _resolve_user_from_casdoor_claims(claims: dict):
"""兼容旧调用点:通过公共身份对象映射 HXOPS 用户。"""
from app.services.auth.casdoor.identity import identity_from_claims
from app.services.auth.common import IdentityValidationError
from app.services.auth.hxops.user_resolver import HxopsIdentityMappingError, resolve_hxops_user
try:
identity = identity_from_claims(
claims,
expected_issuer=str(current_app.config.get('AUTH_JWT_ISSUER') or ''),
)
return resolve_hxops_user(identity)
except IdentityValidationError as exc:
raise AppError(
code='AUTH.CASDOOR_IDENTITY_INVALID',
message='Casdoor identity is missing issuer or subject',
http_status=401,
) from exc
except HxopsIdentityMappingError as exc:
raise WeComLoginError(error=str(exc), error_code=exc.code, status_code=exc.status) from exc
def _issue_casdoor_api_token(user: User, claims: dict) -> str:
"""
为已通过 Casdoor 认证的用户签发 HXOPS API 会话 JWT。
Args:
user: 已映射成功的 HXOPS 本地用户。
claims: Casdoor ID token 或 userinfo 返回的可信身份声明。
Returns:
HXOPS 本地签名 JWT,其中保留 Casdoor issuer/subject 供跨系统 SSO 使用。
Raises:
AppError: Casdoor 未返回稳定 subject,不能建立可复用身份。
"""
from app.services.auth.casdoor.identity import identity_from_claims
from app.services.auth.common import IdentityValidationError
from app.services.auth.hxops.session_token import issue_hxops_access_token
try:
identity = identity_from_claims(
claims,
expected_issuer=str(current_app.config.get('AUTH_JWT_ISSUER') or claims.get('iss') or ''),
)
except IdentityValidationError as exc:
raise AppError(
code='AUTH.CASDOOR_IDENTITY_INVALID',
message='Casdoor identity is missing issuer or subject',
http_status=401,
) from exc
return issue_hxops_access_token(user, identity)
def _casdoor_exchange_code(code: str, redirect_uri: str):
"""兼容旧测试替换点:委托公共客户端执行 authorization code grant。"""
return _casdoor_route_adapter.authorization_code_login(code, redirect_uri)
def _casdoor_refresh_token(refresh_token: str):
"""兼容旧测试替换点:委托公共客户端执行 refresh grant。"""
return _casdoor_route_adapter.refresh_token(refresh_token)
def _casdoor_userinfo(access_token: str):
"""兼容旧测试替换点:委托公共客户端读取 userinfo。"""
return _casdoor_route_adapter.userinfo(access_token)
def _casdoor_password_login(username: str, password: str):
"""
Resource-owner password login against Casdoor token endpoint.
Requires the Casdoor application to enable password grant.
"""
return _casdoor_route_adapter.password_login(username, password)
def _hxops_login_service() -> HxopsLoginService:
"""创建使用当前兼容代理的登录服务,使既有 monkeypatch 测试和调用方式保持有效。"""
return _casdoor_route_adapter.create_login_service(
write_login_audit=_write_login_audit,
password_operation=_casdoor_password_login,
code_operation=_casdoor_exchange_code,
refresh_operation=_casdoor_refresh_token,
userinfo_operation=_casdoor_userinfo,
)
def _is_casdoor_login_mode() -> bool:
return (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() == 'casdoor'
def _is_casdoor_configured() -> bool:
return _casdoor_svc.is_casdoor_configured()
def _casdoor_user_owner() -> str:
return _casdoor_svc.casdoor_user_owner()
def _verify_casdoor_password(username: str, password: str):
_casdoor_password_login(username, password)
def _casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str):
return _casdoor_svc.casdoor_set_password(user_owner, user_name, old_password, new_password)
def _is_casdoor_user_exists_error(message: str) -> bool:
return _casdoor_svc.is_user_exists_error(message)
def _raise_casdoor_add_user_error(source) -> None:
_casdoor_svc.raise_add_user_error(source)
def _casdoor_add_user(user_payload: dict):
return _casdoor_svc.casdoor_add_user(user_payload)
def _sync_casdoor_create_user(*, username: str, password: str, email: str, employee_id: str | None = None, real_name=None, phone_number=None, status='active', department=None):
"""兼容入口:同步创建 Casdoor 用户,并传递认证主映射工号。"""
return _casdoor_svc.sync_create_user(username=username, password=password, employee_id=employee_id, email=email, real_name=real_name, phone_number=phone_number, status=status, department=department)
def _raise_casdoor_update_user_error(source) -> None:
_casdoor_svc.raise_update_user_error(source)
def _casdoor_update_user(user_payload: dict):
return _casdoor_svc.casdoor_update_user(user_payload)
def _sync_casdoor_admin_set_password(user: User, new_password: str):
return _casdoor_svc.sync_admin_set_password(user, new_password)
def _sync_casdoor_update_user(user: User, *, new_password: str | None = None):
return _casdoor_svc.sync_update_user(user, new_password=new_password)
def _is_casdoor_password_error(message: str) -> bool:
return _casdoor_svc.is_password_error(message)
def _is_casdoor_user_missing_error(message: str) -> bool:
return _casdoor_svc.is_user_missing_error(message)
def _raise_casdoor_user_not_in_idp(source=None) -> None:
_casdoor_svc.raise_user_not_in_idp(source)
def _extract_casdoor_error_payload(source) -> dict:
return _casdoor_svc.extract_error_payload(source)
def _raise_casdoor_auth_error(source, *, context: str, status_code: int = 401) -> None:
_casdoor_svc.raise_auth_error(source, context=context, status_code=status_code)
def _raise_casdoor_set_password_error(source) -> None:
_casdoor_svc.raise_set_password_error(source)
def _raise_incorrect_current_password():
raise AppError(
code='AUTH.INCORRECT_CURRENT_PASSWORD',
message='Incorrect current password',
http_status=403,
)
def _verify_current_password_for_change(user, current_password: str):
if user.check_password(current_password):
return
if not _is_casdoor_configured():
_raise_incorrect_current_password()
try:
_verify_casdoor_password(user.username, current_password)
except AppError as e:
if e.code == 'CASDOOR_INVALID_CREDENTIALS':
_raise_incorrect_current_password()
raise
except RuntimeError as e:
if _is_casdoor_password_error(str(e)):
_raise_incorrect_current_password()
raise
def _sync_casdoor_password(username: str, current_password: str, new_password: str):
if not _is_casdoor_configured():
return
user_owner = _casdoor_user_owner()
try:
_casdoor_set_password(user_owner, username, current_password, new_password)
except AppError as first_error:
if first_error.code in ('CASDOOR_INVALID_CREDENTIALS', 'AUTH.INCORRECT_CURRENT_PASSWORD'):
_raise_incorrect_current_password()
raise
except RuntimeError as first_error:
if _is_casdoor_user_missing_error(str(first_error)):
_raise_casdoor_user_not_in_idp(first_error)
if _is_casdoor_password_error(str(first_error)):
_raise_incorrect_current_password()
try:
_casdoor_set_password(user_owner, username, '', new_password)
except RuntimeError:
raise first_error
def _cleanup_wecom_state_cache():
now = datetime.utcnow()
expired = [k for k, v in _WECOM_STATE_CACHE.items() if not v or v < now]
for k in expired:
_WECOM_STATE_CACHE.pop(k, None)
def _issue_wecom_state():
_cleanup_wecom_state_cache()
state = f'hxops_wecom_{uuid.uuid4().hex}'
_WECOM_STATE_CACHE[state] = datetime.utcnow() + timedelta(minutes=10)
return state
def _consume_wecom_state(state: str):
if not state:
return False
_cleanup_wecom_state_cache()
exp = _WECOM_STATE_CACHE.pop(state, None)
return bool(exp and exp > datetime.utcnow())
def _cleanup_wecom_bind_session_cache():
now = datetime.utcnow()
expired = [key for key, item in _WECOM_BIND_SESSION_CACHE.items() if not isinstance(item, dict) or not item.get('expires_at') or item['expires_at'] < now]
for key in expired:
_WECOM_BIND_SESSION_CACHE.pop(key, None)
def _issue_wecom_bind_session(identity: dict):
_cleanup_wecom_bind_session_cache()
token = f'hxops_wecom_bind_{uuid.uuid4().hex}'
_WECOM_BIND_SESSION_CACHE[token] = {'expires_at': datetime.utcnow() + timedelta(minutes=10), 'identity': dict(identity or {})}
return token
def _get_wecom_bind_session(token: str):
if not token:
return None
_cleanup_wecom_bind_session_cache()
item = _WECOM_BIND_SESSION_CACHE.get(token)
if not isinstance(item, dict):
return None
expires_at = item.get('expires_at')
if not expires_at or expires_at < datetime.utcnow():
_WECOM_BIND_SESSION_CACHE.pop(token, None)
return None
identity = item.get('identity')
return identity if isinstance(identity, dict) else None
def _consume_wecom_bind_session(token: str):
identity = _get_wecom_bind_session(token)
if identity is None:
return None
_WECOM_BIND_SESSION_CACHE.pop(token, None)
return identity
def _parse_wecom_field_list(raw_value, default_fields: list[str]):
return _wecom_svc.parse_field_list(raw_value, default_fields)
def _verify_wecom_msg_signature(msg_signature: str, token: str, timestamp: str, nonce: str, encrypt: str) -> bool:
if not msg_signature or not token or (not encrypt):
return False
expected = sha1_hex([token, str(timestamp or ''), str(nonce or ''), encrypt])
return expected == msg_signature
def _extract_xml_field(xml_text: str, tag: str):
if not xml_text:
return None
m = re.search(f'<{tag}><!\\[CDATA\\[(.*?)\\]\\]></{tag}>', xml_text, re.DOTALL)
if m:
return m.group(1).strip()
m2 = re.search(f'<{tag}>(.*?)</{tag}>', xml_text, re.DOTALL)
if m2:
return m2.group(1).strip()
return None
def _persist_wecom_callback_audit(*, msg_signature, timestamp, nonce, encrypt_raw, decrypted_xml=None, msg_type=None, event=None, from_user=None, agent_id=None, msg_id=None, error_message=None):
try:
row = WecomCallbackAudit(msg_signature=msg_signature, timestamp=timestamp, nonce=nonce, encrypt_raw=encrypt_raw, decrypted_xml=decrypted_xml, msg_type=msg_type, event=event, from_user=from_user, agent_id=agent_id, msg_id=msg_id, error_message=error_message)
db.session.add(row)
db.session.commit()
except Exception:
db.session.rollback()
def _get_wecom_access_token():
return _wecom_svc.get_access_token()
def _build_login_payload(user: User, source: str='password', bind_status: str=None):
payload = {
'id': user.id,
'username': user.username,
'role': user.role,
'default_agent_id': user.default_agent_id,
'feature_permissions': user.get_feature_permissions(),
'source': source,
'access_token': issue_local_access_token(user),
'token_type': 'Bearer',
}
if bind_status:
payload['bind_status'] = bind_status
return payload
def _clean_str(value):
if value is None:
return None
if isinstance(value, str):
value = value.strip()
return value or None
return str(value).strip() or None
def _parse_leave_int_flag(value, field_label: str):
if value in (0, 1):
return int(value)
text = _clean_str(value)
if text in ('0', '1'):
return int(text)
raise OALeaveWorkflowError(f'{field_label} 取值无效,应为 0 或 1。')
def _normalize_mobile(mobile: str):
mobile = _clean_str(mobile)
if not mobile:
return None
digits = re.sub('\\D', '', mobile)
if not digits:
return mobile
if digits.startswith('0086'):
digits = digits[4:]
elif digits.startswith('86') and len(digits) > 11:
digits = digits[2:]
return digits
def _extract_wecom_extattr_value(wecom_user: dict, key: str):
extattr = wecom_user.get('extattr') or {}
attrs = extattr.get('attrs') if isinstance(extattr, dict) else None
if not isinstance(attrs, list):
return None
for attr in attrs:
if not isinstance(attr, dict):
continue
if _clean_str(attr.get('name')) != key:
continue
raw = attr.get('value')
if isinstance(raw, dict):
raw = raw.get('text') or raw.get('web') or raw.get('value')
return _clean_str(raw)
return None
def _get_wecom_match_config():
return _wecom_svc.get_match_config()
def _get_wecom_first_login_bind_mode():
return _wecom_svc.get_first_login_bind_mode()
def _get_wecom_first_login_input_fields():
return _wecom_svc.get_first_login_input_fields()
def _extract_wecom_identity(wecom_user: dict):
return _wecom_svc.extract_identity(wecom_user)
def _mobile_candidates(identity: dict):
values = []
for item in [identity.get('mobile'), identity.get('mobile_raw')]:
item = _clean_str(item)
if item and item not in values:
values.append(item)
return values
def _find_users_by_input_field(field: str, value):
field = _clean_str(field)
if field not in _ALLOWED_WECOM_MATCH_FIELDS:
return ([], 'invalid_field')
if field == 'employee_id':
needle = _clean_str(value)
if not needle:
return ([], 'employee_id')
return (db.session.query(User).filter(User.employee_id == needle).all(), None)
if field == 'email':
needle = _clean_str(value)
if not needle:
return ([], 'email')
return (db.session.query(User).filter(User.email == needle).all(), None)
if field == 'mobile':
raw_mobile = _clean_str(value)
normalized_mobile = _normalize_mobile(raw_mobile)
candidates = []
for item in [normalized_mobile, raw_mobile]:
item = _clean_str(item)
if item and item not in candidates:
candidates.append(item)
if not candidates:
return ([], 'mobile')
return (db.session.query(User).filter(User.phone_number.in_(candidates)).all(), None)
return ([], 'invalid_field')
def _find_users_by_match_rules(identity: dict, rules: list, operator: str):
return _wecom_svc.find_users_by_match_rules(identity, rules, operator)
def _assert_wecom_binding_not_occupied(user: User, identity: dict):
wecom_userid = identity.get('wecom_userid')
wecom_unionid = identity.get('wecom_unionid')
if wecom_userid:
dup = db.session.query(User).filter(User.wecom_userid == wecom_userid, User.id != user.id).first()
if dup:
raise WeComLoginError(error=f'Current WeCom account has been bound to user: {dup.username}', error_code='WECOM_BIND_CONFLICT', status_code=409, reason='bind_conflict')
if wecom_unionid:
dup_union = db.session.query(User).filter(User.wecom_unionid == wecom_unionid, User.id != user.id).first()
if dup_union:
raise WeComLoginError(error=f'Current WeCom unionid has been bound to user: {dup_union.username}', error_code='WECOM_BIND_CONFLICT', status_code=409, reason='bind_conflict')
def _sync_user_from_wecom_identity(user: User, identity: dict):
_assert_wecom_binding_not_occupied(user, identity)
if identity.get('wecom_userid'):
user.wecom_userid = identity['wecom_userid']
if identity.get('wecom_unionid') and (not user.wecom_unionid):
user.wecom_unionid = identity['wecom_unionid']
if identity.get('name') and (not user.real_name):
user.real_name = identity['name']
if identity.get('email') and (not user.email):
dup_email = db.session.query(User).filter(User.email == identity['email'], User.id != user.id).first()
if not dup_email:
user.email = identity['email']
if identity.get('mobile') and (not user.phone_number):
candidates = _mobile_candidates(identity)
dup_mobile = db.session.query(User).filter(User.phone_number.in_(candidates), User.id != user.id).first()
if not dup_mobile:
user.phone_number = identity['mobile']
if identity.get('employee_id') and (not user.employee_id):
dup_employee = db.session.query(User).filter(User.employee_id == identity['employee_id'], User.id != user.id).first()
if not dup_employee:
user.employee_id = identity['employee_id']
def _create_user_from_wecom_identity(identity: dict) -> User:
base_username = (identity.get('wecom_userid') or identity.get('email') or identity.get('mobile') or f'wecom_{uuid.uuid4().hex[:8]}').replace('@', '_')
candidate = base_username
suffix = 1
while db.session.query(User).filter_by(username=candidate).first():
candidate = f'{base_username}_{suffix}'
suffix += 1
safe_email = identity.get('email') or f'{candidate}@wecom.local'
if db.session.query(User).filter_by(email=safe_email).first():
safe_email = f'{candidate}_{uuid.uuid4().hex[:6]}@wecom.local'
employee_id = identity.get('employee_id')
if employee_id and db.session.query(User).filter_by(employee_id=employee_id).first():
employee_id = None
phone_number = identity.get('mobile')
if phone_number:
candidates = _mobile_candidates(identity)
dup_mobile = db.session.query(User).filter(User.phone_number.in_(candidates)).first()
if dup_mobile:
phone_number = None
user = User(username=candidate, email=safe_email, role='user', status='active', real_name=identity.get('name'), employee_id=employee_id, phone_number=phone_number, wecom_userid=identity.get('wecom_userid'), wecom_unionid=identity.get('wecom_unionid'))
user.set_password(uuid.uuid4().hex)
db.session.add(user)
return user
def _issue_wecom_input_bind_prompt(identity: dict):
allowed_fields = _get_wecom_first_login_input_fields()
binding_token = _issue_wecom_bind_session(identity)
raise WeComLoginError(error='First WeCom login requires verification input to bind a local account.', error_code='WECOM_BIND_INPUT_REQUIRED', status_code=409, reason='input_bind_required', extra={'binding_token': binding_token, 'allowed_fields': allowed_fields, 'wecom_name': identity.get('name'), 'wecom_userid': identity.get('wecom_userid')})
def _sync_or_create_user_from_wecom(wecom_user: dict):
identity = _extract_wecom_identity(wecom_user)
rules, operator = _get_wecom_match_config()
rule_info = {'operator': operator, 'fields': rules}
bind_mode = _get_wecom_first_login_bind_mode()
user = None
if identity.get('wecom_userid'):
user = db.session.query(User).filter_by(wecom_userid=identity['wecom_userid']).first()
if user:
_sync_user_from_wecom_identity(user, identity)
return (user, 'already_bound', rule_info)
if bind_mode == 'input_verify':
_issue_wecom_input_bind_prompt(identity)
matched_users, missing_fields = _find_users_by_match_rules(identity, rules, operator)
if missing_fields:
missing_field = missing_fields[0]
raise WeComLoginError(error=f'Required match attribute missing: {missing_field}', error_code='WECOM_MATCH_ATTR_MISSING', status_code=422, reason=f'missing_attr:{missing_field}', extra={'missing_field': missing_field, 'match_rules': rule_info})
if len(matched_users) == 1:
user = matched_users[0]
_sync_user_from_wecom_identity(user, identity)
return (user, 'matched_and_bound', rule_info)
if len(matched_users) > 1:
raise WeComLoginError(error='Multiple local users matched', error_code='WECOM_MATCH_AMBIGUOUS', status_code=409, reason='ambiguous_match', extra={'candidate_count': len(matched_users), 'match_rules': rule_info})
if not current_app.config.get('WECOM_AUTO_CREATE_USER', True):
raise WeComLoginError(error='No linked account found. Contact admin to bind WeCom account.', error_code='WECOM_BIND_REQUIRED', status_code=403, reason='bind_required', extra={'match_rules': rule_info})
user = _create_user_from_wecom_identity(identity)
return (user, 'auto_created', rule_info)
+196
View File
@@ -0,0 +1,196 @@
"""
api/user/auth_wecom.py
用途:企业微信 OAuth、绑定与回调 HTTP 路由。
依赖:auth.auth_bp、auth_support 的企微签名、身份匹配和审计操作。
逻辑:将企微认证入口同本地/Casdoor 路由隔离,保持企业微信回调 URL 不变。
"""
from __future__ import annotations
from urllib.parse import quote
import requests
from flask import current_app, jsonify, request
from app import db
from app.core.errors import AppError, ConflictError, ForbiddenError, UnauthorizedError, ValidationError
from app.services.wecom_crypto import decrypt_wecom_aes, extract_encrypt_field
from . import auth as _compat
from .auth import auth_bp
@auth_bp.get('/wecom/authorize-url', endpoint='wecom_authorize_url')
def authorize_url():
"""生成企业微信 OAuth 授权地址。"""
if not _compat._is_wecom_configured():
raise ValidationError('WeCom login is not configured')
redirect_uri = request.args.get('redirect_uri') or current_app.config.get('WECOM_REDIRECT_URI')
if not redirect_uri:
raise ValidationError('redirect_uri is required')
state = _compat._issue_wecom_state()
corp_id = current_app.config.get('WECOM_CORP_ID')
agent_id = current_app.config.get('WECOM_AGENT_ID')
url = f"https://open.weixin.qq.com/connect/oauth2/authorize?appid={corp_id}&redirect_uri={quote(redirect_uri, safe='')}&response_type=code&scope=snsapi_base&state={quote(state, safe='')}&agentid={agent_id}#wechat_redirect"
return jsonify({'url': url, 'state': state})
@auth_bp.post('/wecom/login', endpoint='wecom_login')
def login():
"""完成企业微信 OAuth 登录并映射或绑定本地用户。"""
if not _compat._is_wecom_configured():
raise ValidationError('WeCom login is not configured')
data = request.get_json() or {}
code, state = data.get('code'), data.get('state')
if not code:
_compat._write_login_audit('wecom', 'failed', reason='missing_code')
db.session.commit()
raise ValidationError('code is required')
if not _compat._consume_wecom_state(state):
_compat._write_login_audit('wecom', 'failed', reason='invalid_state')
db.session.commit()
raise ValidationError('Invalid or expired WeCom state')
wecom_userid = None
try:
access_token = _compat._get_wecom_access_token()
info = requests.get('https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo', params={'access_token': access_token, 'code': code}, timeout=8).json()
wecom_userid = info.get('userid') or info.get('UserId')
if info.get('errcode') != 0:
raise UnauthorizedError(f"WeCom auth failed: {info.get('errmsg', 'unknown error')}")
if not wecom_userid:
raise AppError(code='WECOM_NOT_IN_AGENT_SCOPE', message='当前企业微信账号未授权登录该应用:账号不在自建应用的可见范围内,或不是本企业成员。请管理员到「企业微信后台 → 应用管理 → 该应用 → 可见范围」中加入该成员所在的部门或个人。', http_status=401)
wecom_user = requests.get('https://qyapi.weixin.qq.com/cgi-bin/user/get', params={'access_token': access_token, 'userid': wecom_userid}, timeout=8).json()
if wecom_user.get('errcode') != 0:
raise UnauthorizedError(f"WeCom user fetch failed: {wecom_user.get('errmsg', 'unknown error')}")
user, bind_status, rule_info = _compat._sync_or_create_user_from_wecom(wecom_user)
if user.status != 'active':
raise ForbiddenError('Account is disabled')
_compat._write_login_audit('wecom', 'success', user=user, wecom_userid=wecom_userid, match_rules=rule_info.get('fields'), match_operator=rule_info.get('operator'), match_result=bind_status)
db.session.commit()
return jsonify(_compat._build_login_payload(user, 'wecom', bind_status=bind_status))
except _compat.WeComLoginError as exc:
db.session.rollback()
_compat._write_login_audit('wecom', 'failed', reason=exc.reason or 'wecom_login_error', wecom_userid=wecom_userid, error_code=exc.error_code)
db.session.commit()
raise
except AppError as exc:
db.session.rollback()
_compat._write_login_audit('wecom', 'failed', reason=str(exc)[:160], wecom_userid=wecom_userid, error_code=exc.code)
db.session.commit()
raise
except Exception as exc:
db.session.rollback()
if _compat._is_users_pk_sequence_error(exc):
_compat._write_login_audit('wecom', 'failed', reason='db_sequence_misconfig', wecom_userid=wecom_userid, error_code='DB_SEQUENCE_MISCONFIG')
db.session.commit()
raise AppError(code='SYSTEM.DB_SEQUENCE_MISCONFIG', message='数据库主键自增配置异常,当前环境缺少 users.id 的自动序列。请执行数据库迁移后重试。', http_status=500) from exc
_compat._write_login_audit('wecom', 'failed', reason=f'exception:{str(exc)[:160]}', wecom_userid=wecom_userid)
db.session.commit()
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'WeCom login failed: {exc}', http_status=500) from exc
@auth_bp.post('/wecom/complete-bind', endpoint='wecom_complete_bind')
def complete_bind():
"""提交首登人工绑定信息并完成企业微信账号绑定。"""
if not _compat._is_wecom_configured():
raise ValidationError('WeCom login is not configured')
data = request.get_json() or {}
token, field, value = _compat._clean_str(data.get('binding_token')), _compat._clean_str(data.get('field')), data.get('value')
identity = _compat._get_wecom_bind_session(token)
if not identity:
raise AppError(code='WECOM_BIND_SESSION_EXPIRED', message='WeCom binding session expired. Please restart WeCom login.', http_status=400)
allowed_fields = _compat._get_wecom_first_login_input_fields()
if field not in allowed_fields:
raise AppError(code='WECOM_BIND_FIELD_NOT_ALLOWED', message='Selected bind field is not allowed', http_status=400, details={'allowed_fields': allowed_fields})
matched_users, missing_field = _compat._find_users_by_input_field(field, value)
if missing_field:
raise AppError(code='WECOM_BIND_INPUT_VALUE_REQUIRED', message=f'{field} is required', http_status=400, details={'field': field})
if not matched_users:
raise AppError(code='WECOM_BIND_INPUT_NOT_FOUND', message='No local account matched the verification value.', http_status=404, details={'field': field})
if len(matched_users) > 1:
raise ConflictError('Multiple local accounts matched the verification value.', code='WECOM_BIND_INPUT_AMBIGUOUS', details={'field': field, 'candidate_count': len(matched_users)})
user = matched_users[0]
if user.status != 'active':
raise ForbiddenError('Account is disabled')
try:
_compat._sync_user_from_wecom_identity(user, identity)
_compat._write_login_audit('wecom', 'success', user=user, wecom_userid=identity.get('wecom_userid'), match_rules=[field], match_operator='AND', match_result='input_verified_and_bound')
db.session.commit()
_compat._WECOM_BIND_SESSION_CACHE.pop(token, None)
return jsonify(_compat._build_login_payload(user, 'wecom', bind_status='input_verified_and_bound'))
except _compat.WeComLoginError as exc:
db.session.rollback()
_compat._write_login_audit('wecom', 'failed', user=user, reason=exc.reason or 'wecom_input_bind_error', wecom_userid=identity.get('wecom_userid'), error_code=exc.error_code, match_rules=[field], match_operator='AND')
db.session.commit()
raise
except Exception as exc:
db.session.rollback()
_compat._write_login_audit('wecom', 'failed', user=user, reason=f'exception:{str(exc)[:160]}', wecom_userid=identity.get('wecom_userid'), error_code='WECOM_BIND_INPUT_EXCEPTION', match_rules=[field], match_operator='AND')
db.session.commit()
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'WeCom bind failed: {exc}', http_status=500) from exc
@auth_bp.route('/wecom/callback', methods=['GET', 'POST'], endpoint='wecom_callback')
def callback():
"""处理企业微信 URL 验证及加密事件回调。"""
signature = request.args.get('msg_signature') or request.args.get('signature')
timestamp, nonce = request.args.get('timestamp', ''), request.args.get('nonce', '')
token = current_app.config.get('WECOM_CALLBACK_TOKEN') or ''
aes_key, corp_id = current_app.config.get('WECOM_ENCODING_AES_KEY') or '', current_app.config.get('WECOM_CORP_ID') or ''
if not token:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='callback token not configured', http_status=500)
if request.method == 'GET':
echostr = request.args.get('echostr', '') or ''
if not _compat._verify_wecom_msg_signature(signature, token, timestamp, nonce, echostr):
raise ForbiddenError('invalid callback signature')
try:
plain = decrypt_wecom_aes(echostr, aes_key, corp_id) if aes_key else echostr
except Exception as exc:
_compat._persist_wecom_callback_audit(msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=echostr, error_message=f'decrypt_failed:{str(exc)[:200]}')
raise ValidationError('decrypt failed') from exc
_compat._persist_wecom_callback_audit(msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=echostr, decrypted_xml=plain, msg_type='url_verify' if aes_key else 'url_verify_plain')
return plain, 200, {'Content-Type': 'text/plain; charset=utf-8'}
payload = request.get_data(as_text=True) or ''
encrypt_field = extract_encrypt_field(payload) or ''
if not encrypt_field:
raise ValidationError('missing Encrypt field')
if not _compat._verify_wecom_msg_signature(signature, token, timestamp, nonce, encrypt_field):
_compat._persist_wecom_callback_audit(msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=encrypt_field, error_message='invalid_msg_signature')
raise ForbiddenError('invalid callback signature')
decrypted = None
if aes_key:
try:
decrypted = decrypt_wecom_aes(encrypt_field, aes_key, corp_id)
except Exception as exc:
_compat._persist_wecom_callback_audit(msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=encrypt_field, error_message=f'decrypt_failed:{str(exc)[:200]}')
raise ValidationError('decrypt failed') from exc
_compat._persist_wecom_callback_audit(
msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=encrypt_field,
decrypted_xml=decrypted, msg_type=_compat._extract_xml_field(decrypted, 'MsgType') if decrypted else None,
event=_compat._extract_xml_field(decrypted, 'Event') if decrypted else None,
from_user=_compat._extract_xml_field(decrypted, 'FromUserName') if decrypted else None,
agent_id=_compat._extract_xml_field(decrypted, 'AgentID') if decrypted else None,
msg_id=_compat._extract_xml_field(decrypted, 'MsgId') if decrypted else None,
)
return 'success', 200, {'Content-Type': 'text/plain; charset=utf-8'}
@auth_bp.get('/wecom/binding', endpoint='get_wecom_binding')
def binding():
"""返回当前用户的企业微信绑定状态。"""
user = _compat._get_current_user()
if not user:
raise UnauthorizedError('Unauthorized')
return jsonify({'bound': bool(user.wecom_userid), 'wecom_userid': user.wecom_userid, 'wecom_unionid': user.wecom_unionid})
@auth_bp.post('/wecom/unbind', endpoint='unbind_wecom_self')
def unbind():
"""解除当前用户与企业微信账号的绑定。"""
user = _compat._get_current_user()
if not user:
raise UnauthorizedError('Unauthorized')
user.wecom_userid = None
user.wecom_unionid = None
db.session.commit()
return jsonify({'status': 'ok', 'message': 'WeCom account unbound'})
+383
View File
@@ -0,0 +1,383 @@
"""
backend/app/api/user/handlers.py
用途:当前用户域 API(Casdoor 登录、企微 OAuth、首页、FAQ、反馈等)。
依赖:sqlalchemy(and_/or_、exc)、app.core.errors、models、wecom/dify 相关 services。
逻辑:薄路由层鉴权与参数校验;Casdoor/企微 OAuth 委托 services/auth/*。
"""
from flask import Blueprint, request, jsonify, current_app
from sqlalchemy import and_, or_
from sqlalchemy.exc import DatabaseError, OperationalError
from app import db
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, GeneralFeedback, ChatLog
from app.services.feedback_notify import send_feedback_group_notification
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
from app.services.agent_registry.serialization import serialize_registry_fields
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
import re
import ast
from app.core.errors import (
AppError,
ForbiddenError,
NotFoundError,
ServiceUnavailableError,
UnauthorizedError,
ValidationError,
)
from .auth import (
_clean_str,
_get_current_user,
_parse_leave_int_flag,
_run_db_with_retry,
)
user_bp = Blueprint('user', __name__)
@user_bp.route('/wecom/deeplink-opened', methods=['POST'])
def mark_wecom_deeplink_opened():
user = _get_current_user()
if not user:
raise UnauthorizedError('Unauthorized')
data = request.get_json() or {}
trace_id = _clean_str(data.get('trace_id'))
if not trace_id:
raise ValidationError('trace_id is required')
ok = mark_wecom_message_opened(trace_id)
if not ok:
raise NotFoundError('trace_id not found')
db.session.commit()
return jsonify({'status': 'ok'})
@user_bp.route('/wecom/task-complete', methods=['POST'])
def wecom_task_complete():
"""
Lightweight endpoint for sending task completion WeCom message.
Can be called by frontend after long-running task is done.
"""
user = _get_current_user()
if not user:
raise UnauthorizedError('Unauthorized')
data = request.get_json() or {}
title = _clean_str(data.get('title')) or 'AI 任务已完成'
content = _clean_str(data.get('content')) or '你发起的 AI 任务已完成,点击查看详情。'
agent_id = data.get('agent_id')
jump_path = '/workspace'
jump_params = {}
if agent_id:
jump_path = f'/chat/{int(agent_id)}'
result = send_wecom_event_message(event_type='task_completed', user=user, title=title, content=content, jump_path=jump_path, jump_params=jump_params)
db.session.commit()
return (jsonify(result), 200 if result.get('ok') else 202)
@user_bp.route('/leave-balance', methods=['GET'])
def get_leave_balance():
user = _get_current_user()
if not user:
raise UnauthorizedError('Unauthorized')
leave_type_code = _clean_str(request.args.get('leave_type'))
if leave_type_code not in ('010', '408'):
raise ValidationError('仅支持查询年假(010)和育儿假(408)的余额')
try:
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
employee_code = HRLeaveSQLServerService._get_employee_code(user)
now_year = datetime.now().year
if leave_type_code == '010':
_, record = HRLeaveSQLServerService._query_one(view_name='VIEW_D044', year_column='D044001', total_column='D044005', used_column='D044006', remaining_column='D044007', employee_code=employee_code, year=now_year)
label = '年假'
else:
_, record = HRLeaveSQLServerService._query_one(view_name='VIEW_D072', year_column='d072001', total_column='d072002', used_column='d072003', remaining_column='d072004', employee_code=employee_code, year=now_year)
label = '育儿假'
remaining = record.get('remaining_hours') if record else None
try:
has_balance = remaining is not None and float(remaining) > 0
except (TypeError, ValueError):
has_balance = False
return jsonify({'leave_type_code': leave_type_code, 'leave_type_label': label, 'year': record.get('leave_year', now_year) if record else now_year, 'total_hours': record.get('total_hours') if record else None, 'used_hours': record.get('used_hours') if record else None, 'remaining_hours': remaining, 'has_balance': has_balance})
except Exception as exc:
current_app.logger.exception('[leave-balance] query failed user_id=%s', getattr(user, 'id', None))
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'假期余额查询失败:{exc}', http_status=500)
@user_bp.route('/leave-workflow/submit', methods=['POST'])
def submit_leave_workflow():
user = _get_current_user()
if not user:
raise UnauthorizedError('Unauthorized')
data = request.get_json() or {}
form_data = {'applicantName': _clean_str(data.get('applicantName')) or _clean_str(getattr(user, 'real_name', None)) or _clean_str(getattr(user, 'username', None)), 'employeeId': _clean_str(data.get('employeeId')) or _clean_str(getattr(user, 'employee_id', None)) or _clean_str(getattr(user, 'username', None)), 'applicantJobTitle': _clean_str(data.get('applicantJobTitle')), 'applicantDepartmentId': _clean_str(data.get('applicantDepartmentId')), 'applicantSubCompanyId1': _clean_str(data.get('applicantSubCompanyId1')), 'applyTime': _clean_str(data.get('applyTime')), 'fillerName': _clean_str(data.get('fillerName')) or _clean_str(getattr(user, 'real_name', None)) or _clean_str(getattr(user, 'username', None)), 'agentUid': _clean_str(data.get('agentUid')), 'agentEmployeeId': _clean_str(data.get('agentEmployeeId')), 'agentName': _clean_str(data.get('agentName')), 'agentJobTitle': _clean_str(data.get('agentJobTitle')), 'agentDepartmentId': _clean_str(data.get('agentDepartmentId')), 'agentSubCompanyId1': _clean_str(data.get('agentSubCompanyId1')), 'leaveType': _clean_str(data.get('leaveType')), 'startTime': _clean_str(data.get('startTime')), 'endTime': _clean_str(data.get('endTime')), 'durationHours': data.get('durationHours'), 'isOutOfOffice': _parse_leave_int_flag(data.get('isOutOfOffice'), '是否外出'), 'isWorkInjury': _parse_leave_int_flag(data.get('isWorkInjury'), '是否为工伤'), 'remark': _clean_str(data.get('remark')) or ''}
required_fields = {'applicantName': '请假人', 'employeeId': '工号', 'fillerName': '填单人', 'agentUid': '代理人UID', 'agentEmployeeId': '代理人工号', 'agentName': '代理人姓名', 'leaveType': '假别', 'startTime': '开始时间', 'endTime': '结束时间'}
for key, label in required_fields.items():
if not form_data.get(key):
raise ValidationError(f'{label}不能为空。')
try:
from app.services.oa_leave_workflow import OALeaveWorkflowService, OALeaveWorkflowError
result = OALeaveWorkflowService.submit_leave_request(form_data, user)
except OALeaveWorkflowError as exc:
current_app.logger.warning('[oa-leave] submit failed user_id=%s employee_id=%s err=%s', getattr(user, 'id', None), form_data.get('employeeId'), exc)
raise ValidationError(str(exc))
except Exception as exc:
current_app.logger.exception('[oa-leave] unexpected submit failure user_id=%s', getattr(user, 'id', None))
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'OA 请假提交失败:{exc}', http_status=500)
current_app.logger.info('[oa-leave] submit success user_id=%s employee_id=%s request_id=%s workflow_id=%s', getattr(user, 'id', None), form_data.get('employeeId'), result.get('request_id'), result.get('workflow_id'))
return jsonify(result)
@user_bp.route('/feedback', methods=['POST'])
def submit_general_feedback():
"""
通用意见反馈接口(与 /api/chat/feedback 的对话评分接口不同
"""
user = _get_current_user()
if not user:
raise UnauthorizedError('Unauthorized')
data = request.get_json() or {}
feedback_type = _clean_str(data.get('feedback_type'))
feedback_module = _clean_str(data.get('feedback_module'))
content = _clean_str(data.get('content'))
source_page = _clean_str(data.get('source_page'))
raw_chat_log_id = data.get('chat_log_id')
chat_log_id = None
if raw_chat_log_id not in (None, ''):
try:
chat_log_id = int(raw_chat_log_id)
except (TypeError, ValueError):
raise ValidationError('chat_log_id must be an integer')
if chat_log_id <= 0:
raise ValidationError('chat_log_id must be a positive integer')
if not feedback_type:
raise ValidationError('feedback_type is required')
if not feedback_module:
raise ValidationError('feedback_module is required')
if len(feedback_type) > 32:
raise ValidationError('feedback_type is too long')
if len(feedback_module) > 32:
raise ValidationError('feedback_module is too long')
if not content:
raise ValidationError('content is required')
if len(content) > 2000:
raise ValidationError('content is too long')
if source_page != 'chat':
chat_log_id = None
if chat_log_id is not None:
chat_log = db.session.get(ChatLog, chat_log_id)
if not chat_log:
raise ValidationError('chat_log_id not found')
if chat_log.user_id != user.id:
raise ForbiddenError('chat_log_id is not owned by current user')
row = GeneralFeedback(user_id=user.id, username=user.username, feedback_type=feedback_type, feedback_module=feedback_module, content=content, source_page=source_page, chat_log_id=chat_log_id)
db.session.add(row)
db.session.commit()
notify_result = send_feedback_group_notification(row, user)
if notify_result.get('ok'):
current_app.logger.info('[feedback] group notification sent feedback_id=%s', row.id)
elif not notify_result.get('skipped'):
current_app.logger.warning(
'[feedback] group notification failed feedback_id=%s reason=%s',
row.id,
notify_result.get('reason'),
)
return jsonify({'status': 'ok', 'id': row.id})
@user_bp.route('/home', methods=['GET'])
def home():
"""
Get user homepage data
"""
user = _get_current_user()
if not user:
raise UnauthorizedError('Unauthorized')
def _load_home_payload():
if user.role == 'admin':
agent_rows = Agent.query.filter(Agent.is_active.is_(True)).all()
else:
agent_rows = [agent for agent in user.agents if agent.is_active]
agent_rows = sort_agent_rows(agent_rows)
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
favorite_ids = [f.agent_id for f in favorites]
qqs = db.session.query(QuickQuestion).filter(
or_(
QuickQuestion.user_id == user.id,
and_(QuickQuestion.user_id.is_(None), QuickQuestion.is_enabled.is_(True)),
)
).all()
layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
layout = layout_config.layout if layout_config else {}
embedded_rel = db.session.query(UserDefaultAgent).filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all()
embedded_agents = []
for rel in embedded_rel:
agent = db.session.get(Agent, rel.agent_id)
if agent:
registry = serialize_registry_fields(agent)
embedded_agents.append({
'id': agent.id,
'name': agent.name,
'iframe_url': registry.get('iframe_url'),
'runtime_provider': registry.get('runtime_provider'),
'conversation_mode': registry.get('conversation_mode'),
})
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
try:
return _run_db_with_retry(_load_home_payload, label='user.home')
except (OperationalError, DatabaseError) as exc:
current_app.logger.warning('user.home retry failed: %s', exc)
raise ServiceUnavailableError('Database connection failed')
@user_bp.route('/favorites/<int:agent_id>', methods=['POST', 'DELETE'])
def toggle_favorite(agent_id: int):
user = _get_current_user()
if not user:
raise UnauthorizedError('Unauthorized')
if request.method == 'POST':
exists = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id, agent_id=agent_id).first()
if not exists:
fav = UserFavoriteAgent(user_id=user.id, agent_id=agent_id)
db.session.add(fav)
else:
db.session.query(UserFavoriteAgent).filter_by(user_id=user.id, agent_id=agent_id).delete()
db.session.commit()
return jsonify({'status': 'ok'})
@user_bp.route('/quick-questions', methods=['POST'])
def add_quick_question():
user = _get_current_user()
if not user:
raise UnauthorizedError('Unauthorized')
data = request.get_json() or {}
if not data.get('title') or not data.get('question') or (not data.get('agent_id')):
raise ValidationError('Missing fields')
qq = QuickQuestion(user_id=user.id, title=data['title'], question=data['question'], agent_id=data['agent_id'])
db.session.add(qq)
db.session.commit()
return (jsonify({'message': 'Added', 'id': qq.id}), 201)
@user_bp.route('/quick-questions/<int:qq_id>', methods=['PUT', 'DELETE'])
def update_quick_question(qq_id: int):
user = _get_current_user()
if not user:
raise UnauthorizedError('Unauthorized')
qq = db.session.query(QuickQuestion).filter_by(id=qq_id, user_id=user.id).first()
if not qq:
raise NotFoundError('QuickQuestion not found or permission denied')
if request.method == 'DELETE':
db.session.delete(qq)
db.session.commit()
return jsonify({'status': 'ok'})
data = request.get_json() or {}
if 'title' in data:
qq.title = data['title']
if 'question' in data:
qq.question = data['question']
if 'agent_id' in data:
qq.agent_id = data['agent_id']
db.session.commit()
return jsonify({'status': 'ok'})
@user_bp.route('/homepage-layout', methods=['PUT'])
def update_layout():
user = _get_current_user()
if not user:
raise UnauthorizedError('Unauthorized')
data = request.get_json() or {}
layout = data.get('layout', {})
config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
if not config:
config = UserHomepageConfig(user_id=user.id, layout=layout)
db.session.add(config)
else:
config.layout = layout
db.session.commit()
return jsonify({'status': 'ok'})
@user_bp.route('/profile', methods=['GET', 'PUT'])
def user_profile():
"""
User profile management
GET: Get details
PUT: Update basic info
"""
user = _get_current_user()
if not user:
raise UnauthorizedError('Unauthorized')
if request.method == 'GET':
return jsonify({'id': user.id, 'username': user.username, 'real_name': user.real_name, 'email': user.email, 'phone_number': user.phone_number, 'employee_id': user.employee_id, 'department': user.department, 'role': user.role, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'})
data = request.get_json() or {}
def _update_profile():
if 'real_name' in data:
user.real_name = data['real_name']
if 'phone_number' in data:
user.phone_number = data['phone_number']
if 'language' in data:
user.language = data['language']
if 'theme_preference' in data:
if data['theme_preference'] not in ['light', 'dark', 'system']:
raise ValidationError('Invalid theme preference')
user.theme_preference = data['theme_preference']
if 'email' in data:
if data['email']:
existing = db.session.query(User).filter_by(email=data['email']).first()
if existing and existing.id != user.id:
raise ValidationError('Email already exists')
user.email = data['email']
if 'employee_id' in data:
if data['employee_id']:
existing = db.session.query(User).filter_by(employee_id=data['employee_id']).first()
if existing and existing.id != user.id:
raise ValidationError('Employee ID already exists')
user.employee_id = data['employee_id']
if 'department' in data:
user.department = data['department']
db.session.commit()
return jsonify({'message': 'Profile updated successfully'})
try:
return _run_db_with_retry(_update_profile, label='user.profile.update')
except (OperationalError, DatabaseError) as exc:
db.session.rollback()
current_app.logger.warning('user.profile.update retry failed: %s', exc)
raise ServiceUnavailableError('Database connection failed')
except Exception as e:
db.session.rollback()
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
@user_bp.route('/agents/<int:id>', methods=['GET'])
def get_agent_details(id):
"""
Get agent details with permission check
"""
user = _get_current_user()
if not user:
raise UnauthorizedError('Unauthorized')
agent = db.session.get(Agent, id)
if not agent:
raise NotFoundError('Not found')
if user.role != 'admin':
has_permission = agent in user.agents
if not has_permission:
raise ForbiddenError('Access denied')
from app.services.agent_registry.resolver import resolve_runtime_provider
from app.services.agent_registry.serialization import serialize_agent_for_user_detail
dify_parameters = None
if resolve_runtime_provider(agent) in {'dify', 'hybrid'} and getattr(agent, 'dify_api_key', None):
from app.services.dify import DifyService
try:
params = DifyService.get_app_parameters(agent)
if isinstance(params, dict):
dify_parameters = {
'file_upload': params.get('file_upload') if isinstance(params.get('file_upload'), dict) else {},
'system_parameters': params.get('system_parameters') if isinstance(params.get('system_parameters'), dict) else {},
}
except Exception as exc:
current_app.logger.warning('[user.agents] dify parameters fetch failed agent_id=%s err=%s', id, exc)
return jsonify(serialize_agent_for_user_detail(
agent,
dify_parameters=dify_parameters,
))
@user_bp.route('/db', methods=['GET'])
def get_db():
from app.models import User
from app import db
u = db.session.query(User).filter_by(username='26040006').first()
return jsonify({'db': current_app.config.get('SQLALCHEMY_DATABASE_URI'), 'user': u.username if u else None})
+4 -5
View File
@@ -1,21 +1,20 @@
"""
backend/app/api/workspace/__init__.py
用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check、announcements、process_gate 路由)。
用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check、voucher_check、announcements)。
依赖:workspace 各子模块 blueprint。
逻辑:import 子模块注册路由;register_blueprints 从本包导入各 bp;process_gate 路由挂载于 workspace_shipping_notice_bp。
逻辑:import 子模块注册路由;register_blueprints 从本包导入各 bp。
"""
from app.api.workspace.announcements import workspace_announcements_bp
from app.api.workspace.file_check import workspace_file_check_bp
from app.api.workspace.schedule import workspace_schedule_bp
from app.api.workspace.shipping_notice import workspace_shipping_notice_bp
import app.api.workspace.shipping_process_gate # noqa: F401
import app.api.workspace.shipping_inventory_candidates # noqa: F401
from app.api.workspace.voucher_check import workspace_voucher_check_bp
__all__ = [
'workspace_announcements_bp',
'workspace_file_check_bp',
'workspace_schedule_bp',
'workspace_shipping_notice_bp',
'workspace_voucher_check_bp',
]
+58 -1
View File
@@ -57,6 +57,31 @@ def serialize_current_step(payload: dict) -> dict | None:
return None
return {'step': str(current_step.get('step') or ''), 'label': str(current_step.get('label') or current_step.get('step') or ''), 'row_id': current_step.get('row_id'), 'started_at': current_step.get('started_at'), 'processed_count': int(current_step.get('processed_count') or 0), 'success_count': int(current_step.get('success_count') or 0), 'failed_count': int(current_step.get('failed_count') or 0), 'skipped_count': int(current_step.get('skipped_count') or 0)}
def serialize_progress_metrics(payload: dict) -> list[dict] | None:
"""
序列化领域自定义进度指标(如立账凭证检核的齐全/缺资料)。
核心逻辑:读取 response_summary_json.progress_metrics;非法则返回 None 以回退旧八格。
"""
response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {}
metrics = response_summary.get('progress_metrics')
if not isinstance(metrics, list) or not metrics:
return None
out: list[dict] = []
for item in metrics:
if not isinstance(item, dict):
continue
key = str(item.get('key') or '').strip()
if not key:
continue
out.append({
'key': key,
'label_key': str(item.get('label_key') or ''),
'label': str(item.get('label') or ''),
'value': int(item.get('value') or 0),
})
return out or None
def _serialize_progress_run(run: ScheduleRun) -> dict:
payload = serialize_run(run)
total = int(payload.get('total_count') or 0)
@@ -66,7 +91,39 @@ def _serialize_progress_run(run: ScheduleRun) -> dict:
processed = success + failed + skipped
percent = int(round(processed / total * 100)) if total > 0 else 0
percent = max(0, min(percent, 100))
return {'run_id': payload['id'], 'run_no': payload['run_no'], 'task_id': payload['schedule_task_id'], 'title': payload.get('schedule_name') or '', 'status': payload['status'], 'total_count': total, 'processed_count': processed, 'success_count': success, 'failed_count': failed, 'skipped_count': skipped, 'judgement': serialize_file_judgement(payload), 'current_step': serialize_current_step(payload), 'progress_percent': percent, 'started_at': payload.get('started_at'), 'finished_at': payload.get('finished_at'), 'duration_ms': payload.get('duration_ms'), 'error_message': payload.get('error_message'), 'excel': {'file_name': payload.get('excel_file_name'), 'file_size': payload.get('excel_file_size'), 'download_url': f'/api/workspace/file-check/runs/{run.id}/excel' if payload.get('excel_file_name') else None}, 'knowledge_base': {'sync_status': payload.get('kb_sync_status'), 'group_id': payload.get('kb_group_id'), 'document_id': payload.get('kb_document_id'), 'document_version_id': payload.get('kb_document_version_id'), 'sync_job_id': payload.get('kb_sync_job_id'), 'error_message': payload.get('kb_sync_error')}}
return {
'run_id': payload['id'],
'run_no': payload['run_no'],
'task_id': payload['schedule_task_id'],
'title': payload.get('schedule_name') or '',
'status': payload['status'],
'total_count': total,
'processed_count': processed,
'success_count': success,
'failed_count': failed,
'skipped_count': skipped,
'judgement': serialize_file_judgement(payload),
'progress_metrics': serialize_progress_metrics(payload),
'current_step': serialize_current_step(payload),
'progress_percent': percent,
'started_at': payload.get('started_at'),
'finished_at': payload.get('finished_at'),
'duration_ms': payload.get('duration_ms'),
'error_message': payload.get('error_message'),
'excel': {
'file_name': payload.get('excel_file_name'),
'file_size': payload.get('excel_file_size'),
'download_url': f'/api/workspace/file-check/runs/{run.id}/excel' if payload.get('excel_file_name') else None,
},
'knowledge_base': {
'sync_status': payload.get('kb_sync_status'),
'group_id': payload.get('kb_group_id'),
'document_id': payload.get('kb_document_id'),
'document_version_id': payload.get('kb_document_version_id'),
'sync_job_id': payload.get('kb_sync_job_id'),
'error_message': payload.get('kb_sync_error'),
},
}
@workspace_file_check_bp.route('/file-check/runs/for-log', methods=['GET'])
def workspace_file_check_run_for_log():
@@ -0,0 +1,70 @@
"""
backend/app/api/workspace/voucher_check.py
用途:工作台立账凭证检核记录查询 API(批次明细 / 最新状态)。
依赖:auth.jwt、response_utils envelope、voucher_check.query_service。
逻辑:对话与检核记录页共用;标准 {success,data|error,request_id} envelope。
"""
from __future__ import annotations
from flask import Blueprint, request
from app.core.auth.jwt import get_current_user
from app.core.errors import UnauthorizedError
from app.core.response import ok
from app.services.voucher_check import query_service
workspace_voucher_check_bp = Blueprint("workspace_voucher_check", __name__)
def _require_user():
user = get_current_user()
if not user:
raise UnauthorizedError()
return user
@workspace_voucher_check_bp.route("/accounting-voucher-check/runs/<int:run_id>/items", methods=["GET"])
def workspace_voucher_run_items(run_id: int):
"""
分页查看批次明细。
核心逻辑:委托 query_service.list_run_items,可按 result 过滤。
"""
_require_user()
data = query_service.list_run_items(
run_id=run_id,
result=request.args.get("result"),
page=request.args.get("page", default=1, type=int) or 1,
page_size=request.args.get("page_size", default=50, type=int) or 50,
)
return ok(data)
@workspace_voucher_check_bp.route("/accounting-voucher-check/states", methods=["GET"])
def workspace_voucher_states():
"""
按月份、状态、发票号筛选最新状态。
"""
_require_user()
data = query_service.list_states(
scope_code=str(request.args.get("scope_code") or "HXJM"),
period=request.args.get("period"),
status=request.args.get("status"),
invoice_no=request.args.get("invoice_no"),
page=request.args.get("page", default=1, type=int) or 1,
page_size=request.args.get("page_size", default=50, type=int) or 50,
)
return ok(data)
@workspace_voucher_check_bp.route("/accounting-voucher-check/states/<path:invoice_no>", methods=["GET"])
def workspace_voucher_state_detail(invoice_no: str):
"""查看单票最近状态和历史批次快照。"""
_require_user()
data = query_service.get_invoice_latest(
invoice_no=invoice_no,
scope_code=str(request.args.get("scope_code") or "HXJM"),
period=request.args.get("period"),
)
return ok(data)
+23 -2
View File
@@ -294,8 +294,23 @@ def get_current_user() -> Optional[User]:
return None
def issue_local_access_token(user: User) -> str:
"""签发本地 HS256 JWT(密码登录兼容)。"""
def issue_local_access_token(
user: User,
*,
casdoor_issuer: str | None = None,
casdoor_subject: str | None = None,
) -> str:
"""
签发 HXOPS API 会话 JWT。
Args:
user: 已完成认证并映射到 HXOPS 的本地用户。
casdoor_issuer: Casdoor 身份签发者;仅 Casdoor 登录成功后写入。
casdoor_subject: Casdoor 稳定用户 subject;必须与 issuer 同时提供。
Returns:
由 HXOPS SECRET_KEY 签名、供本站 API 使用的 HS256 JWT。
"""
now = datetime.now(timezone.utc)
exp_hours = int(current_app.config.get('AUTH_LOCAL_JWT_EXPIRES_HOURS') or 12)
payload = {
@@ -310,5 +325,11 @@ def issue_local_access_token(user: User) -> str:
'iss': (current_app.config.get('AUTH_LOCAL_JWT_ISSUER') or 'hxops-backend'),
'aud': (current_app.config.get('AUTH_LOCAL_JWT_AUDIENCE') or 'hxops-frontend'),
}
normalized_issuer = str(casdoor_issuer or '').strip()
normalized_subject = str(casdoor_subject or '').strip()
if normalized_issuer and normalized_subject:
# 标准 iss/sub 仍属于 HXOPS 会话;Casdoor 身份单独保存,避免混淆两个信任域。
payload['casdoor_iss'] = normalized_issuer
payload['casdoor_sub'] = normalized_subject
secret = current_app.config.get('SECRET_KEY')
return jwt.encode(payload, secret, algorithm='HS256')
+66 -1
View File
@@ -142,6 +142,7 @@ def _rpa_data_path(canonical_name: str, *parts: str) -> str:
class Config:
ENV_NAME = ACTIVE_ENV_NAME
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.getenv('SECRET_KEY')
# 配置最大上传文件大小(200MB)
@@ -170,6 +171,46 @@ class Config:
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
DIFY_CHAT_CONNECT_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_CONNECT_TIMEOUT_SECONDS', '5'))
DIFY_CHAT_READ_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_READ_TIMEOUT_SECONDS', '30'))
PROCUREMENT_CONTRACT_LLM_ENABLED = os.getenv('PROCUREMENT_CONTRACT_LLM_ENABLED', 'false').lower() == 'true'
# 合同审核可独立复用 Chatflow;未配置时按 Agent 的 dify_app_type 判断。
PROCUREMENT_CONTRACT_LLM_PROVIDER = os.getenv('PROCUREMENT_CONTRACT_LLM_PROVIDER', 'agent').strip().lower()
PROCUREMENT_CONTRACT_LLM_AGENT_ID = int(os.getenv('PROCUREMENT_CONTRACT_LLM_AGENT_ID') or '0')
PROCUREMENT_CONTRACT_LLM_DIFY_APP_ID = os.getenv('PROCUREMENT_CONTRACT_LLM_DIFY_APP_ID', '').strip()
PROCUREMENT_CONTRACT_LLM_DIFY_API_KEY = os.getenv('PROCUREMENT_CONTRACT_LLM_DIFY_API_KEY', '').strip()
PROCUREMENT_CONTRACT_LLM_DIFY_BASE = os.getenv('PROCUREMENT_CONTRACT_LLM_DIFY_BASE', '').strip()
PROCUREMENT_CONTRACT_LLM_CONNECT_TIMEOUT_SECONDS = int(
os.getenv('PROCUREMENT_CONTRACT_LLM_CONNECT_TIMEOUT_SECONDS') or '5'
)
PROCUREMENT_CONTRACT_LLM_READ_TIMEOUT_SECONDS = int(
os.getenv('PROCUREMENT_CONTRACT_LLM_READ_TIMEOUT_SECONDS') or '120'
)
# 合同审核清洗产物与异步任务配置;目录仅供 HXOPS 读写,不直接暴露给 Dify。
PROCUREMENT_CONTRACT_STORAGE_ROOT = _data_path('PROCUREMENT_CONTRACT_STORAGE_ROOT', 'procurement_contract')
PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS = float(
os.getenv('PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS') or '600'
)
PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS = int(
os.getenv('PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS') or '120000'
)
PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES = int(
os.getenv('PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES') or '160'
)
# MinerU 仅在显式配置服务地址后接管 PDF 解析;Word 与服务故障仍复用现有清洗链路。
PROCUREMENT_CONTRACT_MINERU_API_URL = os.getenv('PROCUREMENT_CONTRACT_MINERU_API_URL', '').strip().rstrip('/')
PROCUREMENT_CONTRACT_MINERU_BACKEND = os.getenv('PROCUREMENT_CONTRACT_MINERU_BACKEND', 'pipeline').strip()
PROCUREMENT_CONTRACT_MINERU_PARSE_METHOD = os.getenv('PROCUREMENT_CONTRACT_MINERU_PARSE_METHOD', 'auto').strip()
PROCUREMENT_CONTRACT_MINERU_CONNECT_TIMEOUT_SECONDS = int(
os.getenv('PROCUREMENT_CONTRACT_MINERU_CONNECT_TIMEOUT_SECONDS') or '5'
)
PROCUREMENT_CONTRACT_MINERU_READ_TIMEOUT_SECONDS = int(
os.getenv('PROCUREMENT_CONTRACT_MINERU_READ_TIMEOUT_SECONDS') or '300'
)
# 合同产物归档到独立私有 MinIO 桶;本地目录仅作为审核过程和按需恢复缓存。
PROCUREMENT_CONTRACT_ARCHIVE_ENABLED = os.getenv('PROCUREMENT_CONTRACT_ARCHIVE_ENABLED', 'true').lower() == 'true'
PROCUREMENT_CONTRACT_ARCHIVE_BUCKET = os.getenv('PROCUREMENT_CONTRACT_ARCHIVE_BUCKET', 'procurement-contract').strip()
PROCUREMENT_CONTRACT_ARCHIVE_CLEANUP_LOCAL = (
os.getenv('PROCUREMENT_CONTRACT_ARCHIVE_CLEANUP_LOCAL', 'true').lower() == 'true'
)
# Redis 连接配置,默认使用本地 Redis + 密码
REDIS_URL = os.getenv('REDIS_URL')
# 订单文档模板预览默认要求 Redis;仅开发单进程 run.py 可显式放开进程内一次性令牌兜底。
@@ -469,7 +510,7 @@ class Config:
# Login mode switch: "casdoor" (default) or "password".
# casdoor: login form credentials are sent to Casdoor token endpoint (no redirect page for users).
# password: keep legacy local username/password login.
AUTH_LOGIN_MODE = os.getenv('AUTH_LOGIN_MODE').strip().lower()
AUTH_LOGIN_MODE = (os.getenv('AUTH_LOGIN_MODE') or 'casdoor').strip().lower()
AUTH_ALLOW_LOCAL_JWT = os.getenv('AUTH_ALLOW_LOCAL_JWT', 'true').lower() == 'true'
# JWT 的签发者(iss)校验值,后端用它确认“这个 token 是谁发的”
AUTH_JWT_ISSUER = os.getenv('AUTH_JWT_ISSUER')
@@ -480,6 +521,7 @@ class Config:
CASDOOR_BASE_URL = os.getenv('CASDOOR_BASE_URL')
CASDOOR_CLIENT_ID = os.getenv('CASDOOR_CLIENT_ID')
CASDOOR_CLIENT_SECRET = os.getenv('CASDOOR_CLIENT_SECRET')
CASDOOR_HTTP_TIMEOUT_SECONDS = int(os.getenv('CASDOOR_HTTP_TIMEOUT_SECONDS', '8') or '8')
# Fallback when authorize-url request omits redirect_uri; OAuth flow sends browser origin + /casdoor-callback.
# Casdoor Application must whitelist every origin users hit, e.g. IP and domain on port 8881.
CASDOOR_REDIRECT_URI = os.getenv('CASDOOR_REDIRECT_URI')
@@ -489,10 +531,21 @@ class Config:
# WeCom as Casdoor IdP: provider Name from Casdoor Providers page (used with default_provider=wecom on authorize-url).
CASDOOR_WECOM_PROVIDER_HINT = os.getenv('CASDOOR_WECOM_PROVIDER_HINT').strip()
CASDOOR_WECOM_SILENT_SIGNIN = os.getenv('CASDOOR_WECOM_SILENT_SIGNIN', 'false').lower() == 'true'
# Product SSO: HXOPS signs short-lived, audience-bound RS256 assertions for registered peer services.
SSO_ENABLED = os.getenv('SSO_ENABLED', 'false').lower() == 'true'
SSO_APPS_JSON = os.getenv('SSO_APPS_JSON', '[]')
SSO_ASSERTION_TTL_SECONDS = int(os.getenv('SSO_ASSERTION_TTL_SECONDS', '60') or '60')
SSO_ISSUER = os.getenv('SSO_ISSUER', '').strip()
SSO_SIGNING_ALGORITHM = os.getenv('SSO_SIGNING_ALGORITHM', 'RS256').strip().upper()
SSO_SIGNING_KEY_ID = os.getenv('SSO_SIGNING_KEY_ID', '').strip()
SSO_PRIVATE_KEY_PATH = os.getenv('SSO_PRIVATE_KEY_PATH', '').strip()
SSO_ADDITIONAL_PUBLIC_KEYS_JSON = os.getenv('SSO_ADDITIONAL_PUBLIC_KEYS_JSON', '[]')
AUTH_LOCAL_JWT_ISSUER = os.getenv('AUTH_LOCAL_JWT_ISSUER')
AUTH_LOCAL_JWT_AUDIENCE = os.getenv('AUTH_LOCAL_JWT_AUDIENCE')
AUTH_LOCAL_JWT_EXPIRES_HOURS = int(os.getenv('AUTH_LOCAL_JWT_EXPIRES_HOURS', '12'))
SCHEDULE_WORKER_ENABLED = os.getenv('SCHEDULE_WORKER_ENABLED', 'true').lower() == 'true'
SCHEDULE_WORKER_POLL_SECONDS = float(os.getenv('SCHEDULE_WORKER_POLL_SECONDS', '30') or '30')
SCHEDULE_JOB_RUNNING_TIMEOUT_SECONDS = float(os.getenv('SCHEDULE_JOB_RUNNING_TIMEOUT_SECONDS', '7200') or '7200')
# Cron 表达式按此时区解读(如 0 12 * * * 表示该时区 12:00);入库 next_run_at 仍为 UTC。
SCHEDULE_TIMEZONE = (os.getenv('SCHEDULE_TIMEZONE') or 'Asia/Shanghai').strip()
SRM_SQLSERVER_HOST = os.getenv('SRM_SQLSERVER_HOST', '')
@@ -545,6 +598,18 @@ class Config:
FIXED_ASSETS_ERP_PASSWORD = os.getenv('FIXED_ASSETS_ERP_PASSWORD', 'extviewuser')
FIXED_ASSETS_ERP_DSN = os.getenv('FIXED_ASSETS_ERP_DSN') or os.getenv('ERP_DB_DSN', '192.168.8.24:1521/topprod')
# 立账凭证检核:共享盘只读根 + Oracle 只读账号(密码仅 env)
VOUCHER_CHECK_SHARE_UNC = os.getenv('VOUCHER_CHECK_SHARE_UNC', '').strip()
VOUCHER_CHECK_LOCAL_ROOT = os.getenv('VOUCHER_CHECK_LOCAL_ROOT', '').strip()
VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH = os.getenv(
'VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH',
'.hxops-share-ready',
).strip() or '.hxops-share-ready'
VOUCHER_CHECK_ERP_DSN = os.getenv('VOUCHER_CHECK_ERP_DSN') or os.getenv('ERP_DB_DSN', '')
VOUCHER_CHECK_ERP_USERNAME = os.getenv('VOUCHER_CHECK_ERP_USERNAME', '').strip()
VOUCHER_CHECK_ERP_PASSWORD = os.getenv('VOUCHER_CHECK_ERP_PASSWORD', '')
VOUCHER_CHECK_ERP_TIMEOUT_SECONDS = int(os.getenv('VOUCHER_CHECK_ERP_TIMEOUT_SECONDS', '30') or '30')
# MinIO 配置
MINIO_ENDPOINT = os.getenv('MINIO_ENDPOINT', '127.0.0.1:9000')
MINIO_ACCESS_KEY = os.getenv('MINIO_ACCESS_KEY', 'minioadmin')
+1 -18
View File
@@ -5,21 +5,4 @@ backend/app/jobs/handlers/__init__.py
逻辑:Wave 2 起在 worker 启动前 import 本包。
"""
from app.jobs.handlers import ( # noqa: F401
file_check_run,
kb_clean,
kb_dify_sync,
schedule_run,
shipping_document_layout,
shipping_notice_parse,
shipping_notice_run,
shipping_order_extraction,
shipping_process_gate,
shipping_auto_progress,
shipping_stp_auto_create,
shipping_line_auto_fulfill,
shipping_post_ot_wave_progress,
shipping_review_revalidate_progress,
shipping_xfa_ocr_automark,
wecom_directory_sync,
)
from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, procurement_contract_review, schedule_run, shipping_notice_parse, shipping_notice_run, wecom_directory_sync # noqa: F401
@@ -0,0 +1,48 @@
"""
backend/app/jobs/handlers/procurement_contract_review.py
用途:采购合同清洗、确定性分析与 Dify 全面审核的异步任务处理器。
依赖:jobs.registry、models.Job、procurement_contract.review_service。
逻辑:contract 队列领取任务后按 review_no 执行审核;仅在重试次数耗尽时把业务审核标记为 failed。
"""
from __future__ import annotations
from app import db
from app.jobs.context import JobContext
from app.jobs.queue import finish_job
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.models import Job
from app.services.procurement_contract import review_service
@register_handler(JobType.PROCUREMENT_CONTRACT_REVIEW)
def run_procurement_contract_review(ctx: JobContext, payload: dict) -> None:
"""
执行一份采购合同后台审核。
Args:
ctx: Worker 上下文,用于记录运行日志。
payload: 必须包含 review_no;job_id 由通用队列注入。
Raises:
RuntimeError: 审核失败时抛出,由通用队列决定重试或终态失败。
"""
review_no = str(payload.get("review_no") or "").strip()
job_id = int(payload.get("job_id") or 0)
if not review_no or not job_id:
raise RuntimeError("review_no and job_id are required")
try:
result = review_service.execute_review_job(review_no=review_no, job_id=job_id)
finish_job(job_id, result={"review_no": review_no, "status": "success"}, message="合同审核完成")
ctx.logger.info("contract review completed review_no=%s job_id=%s", review_no, job_id)
except Exception as exc:
db.session.rollback()
job = db.session.get(Job, job_id)
if job and int(job.attempts or 0) >= int(job.max_attempts or 1):
review_service.mark_review_failed(review_no=review_no, error=str(exc))
else:
review_service.mark_review_retrying(review_no=review_no, error=str(exc))
ctx.logger.exception("contract review failed review_no=%s job_id=%s", review_no, job_id)
raise
+18 -4
View File
@@ -2,17 +2,31 @@
backend/app/jobs/handlers/schedule_run.py
用途:排程任务执行 handler。
逻辑:Wave 4 从 scheduler_service in-process 执行体迁入。
依赖:schedule.queue_service、jobs registry/context。
逻辑:独立 schedule worker 领取 Job 后,委托 queue_service 执行并同步双层状态。
"""
from __future__ import annotations
from app.jobs.context import JobContext
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.services.schedule.queue_service import execute_schedule_job
@register_handler(JobType.SCHEDULE_RUN)
def run_schedule(ctx: JobContext, payload: dict) -> None:
"""执行单条 ScheduleTask。"""
ctx.logger.info('schedule_run handler skeleton invoked payload=%s', payload)
raise NotImplementedError('schedule_run handler pending Wave 4')
"""
执行单条已入队排程。
Args:
ctx: Worker 上下文,用于日志与运行配置。
payload: 必须包含 job_id 与 schedule_run_id。
Raises:
RuntimeError: payload 缺失或执行失败时抛出,由通用 Job 层负责重试。
"""
job_id = int(payload.get("job_id") or 0)
run_id = int(payload.get("schedule_run_id") or 0)
if not job_id or not run_id:
raise RuntimeError("job_id and schedule_run_id are required")
execute_schedule_job(job_id=job_id, run_id=run_id, logger=ctx.logger)
+2
View File
@@ -19,6 +19,8 @@ if TYPE_CHECKING:
def _resolve_poll_seconds(ctx: JobContext) -> float:
"""按队列配置读取轮询间隔。"""
queues = ctx.extras.get('queues') or ['kb']
if 'schedule' in queues and len(queues) == 1:
return float(ctx.config.get('SCHEDULE_WORKER_POLL_SECONDS', 30))
if 'shipping' in queues and 'kb' not in queues:
return float(ctx.config.get('SHIPPING_NOTICE_WORKER_POLL_SECONDS', 2))
return float(ctx.config.get('KB_WORKER_POLL_SECONDS', 2))
+33 -2
View File
@@ -1,9 +1,9 @@
"""
backend/app/jobs/store.py
用途:Job 认领与状态读写(Wave 2:KbJob 双轨 adapter,无新表)。
用途:Job 认领与状态读写(KbJob 双轨 adapter + 通用 Job)。
依赖:KbJob、各域 queue_service 的 claim/recover 逻辑。
逻辑:runner 通过 claim_next 获取待执行任务;返回归一化 dict 供 handler 分发。
逻辑:runner 通过 claim_next 获取 kb / shipping / contract / schedule 任务;返回归一化 dict 供 handler 分发。
"""
from __future__ import annotations
@@ -79,6 +79,17 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs
recover_stale_shipping_notice_jobs()
if JobType.PROCUREMENT_CONTRACT_REVIEW.value in allowed_types:
from app.jobs.queue import recover_stale_jobs
from flask import current_app
from app.services.procurement_contract.review_service import sync_review_after_job_recovery
recover_stale_jobs(
domain="procurement_contract",
timeout_seconds=float(current_app.config.get("PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS", 600)),
job_type=JobType.PROCUREMENT_CONTRACT_REVIEW,
on_recovered=sync_review_after_job_recovery,
)
# [STEP 2] 按队列优先级 claim
for name in queue_names:
@@ -94,6 +105,26 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
job = claim_next_shipping_notice_job()
if job:
return _normalize_generic_job(job)
elif name == 'contract':
from app.jobs.queue import claim_next_job
job = claim_next_job(
domain="procurement_contract",
job_types=[JobType.PROCUREMENT_CONTRACT_REVIEW],
)
if job:
return _normalize_generic_job(job)
elif name == 'schedule':
from app.jobs.queue import claim_next_job
from app.services.schedule.queue_service import prepare_schedule_queue
prepare_schedule_queue()
job = claim_next_job(
domain="schedule",
job_types=[JobType.SCHEDULE_RUN],
)
if job:
return _normalize_generic_job(job)
return None
+5 -24
View File
@@ -2,8 +2,7 @@
backend/app/jobs/types.py
用途:Job 类型与状态枚举;KbJob.job_type 与 handler JobType 的双向映射。
逻辑:handlers 与 queue 通过 JobType 注册;store 持久化仍走 KbJob 表(Wave 2 双轨);
shipping_process_gate 由 shipping worker 与发货通知任务同队列领取。
逻辑:handlers 与 queue 通过 JobType 注册;store 持久化仍走 KbJob 表(Wave 2 双轨)。
"""
from __future__ import annotations
@@ -17,24 +16,10 @@ class JobType(StrEnum):
KB_DIFY_SYNC = 'kb_dify_sync'
SHIPPING_NOTICE_RUN = 'shipping_notice_run'
SHIPPING_NOTICE_PARSE = 'shipping_notice_parse'
SHIPPING_ORDER_EXTRACTION = 'shipping_order_extraction'
SHIPPING_DOCUMENT_LAYOUT = 'shipping_document_layout'
SHIPPING_PROCESS_GATE = 'shipping_process_gate'
# 历史 APX 兼容:Worker 仅终态化,不再执行 Gate。
SHIPPING_AUTO_PROGRESS = 'shipping_auto_progress'
# XFA 合成预览就绪后的 OCR 自动标记(Job.job_type 为字符串列,无需 DB enum 迁移)
SHIPPING_XFA_OCR_AUTOMARK = 'shipping_xfa_ocr_automark'
# 资格达标后的 STP 自动建单入队(先 queued,再由 worker 执行 confirm)
SHIPPING_STP_AUTO_CREATE = 'shipping_stp_auto_create'
# OT 后行级自动履约协调(flag 关闭时不入队)
SHIPPING_LINE_AUTO_FULFILL = 'shipping_line_auto_fulfill'
# post-OT wave 专用 Excel/RPA 推进(禁止复用 confirm 后整单推进)
SHIPPING_POST_OT_WAVE_PROGRESS = 'shipping_post_ot_wave_progress'
# Case 字段变更后异步协调:刷新校验、重跑 STP 资格判定、推进自动入队
SHIPPING_REVIEW_REVALIDATE_PROGRESS = 'shipping_review_revalidate_progress'
SCHEDULE_RUN = 'schedule_run'
FILE_CHECK_RUN = 'file_check_run'
WECOM_DIRECTORY_SYNC = 'wecom_directory_sync'
PROCUREMENT_CONTRACT_REVIEW = 'procurement_contract_review'
class JobStatus(StrEnum):
@@ -65,13 +50,9 @@ _HANDLER_TO_KB_JOB_TYPE: dict[JobType, str] = {
# worker --queues 参数 → 可消费的 KbJob.job_type 集合
QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
'kb': frozenset({'clean', 'path_upload', 'sync_dify'}),
'shipping': frozenset({
'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction',
'shipping_document_layout', 'shipping_process_gate', 'shipping_xfa_ocr_automark',
'shipping_auto_progress',
'shipping_stp_auto_create', 'shipping_line_auto_fulfill',
'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress',
}),
'shipping': frozenset({'shipping_notice_run', 'shipping_notice_parse'}),
'contract': frozenset({'procurement_contract_review'}),
'schedule': frozenset({'schedule_run'}),
}
+22 -266
View File
@@ -2,7 +2,7 @@
backend/app/models/__init__.py
用途:按业务域拆分的 ORM 模型包入口;聚合导出以保持 `from app.models import User` 兼容。
依赖:models/* 子模块、app.extensions.db(经 base.Base)。
依赖:models/* 子模块(含 voucher_check)、app.extensions.db(经 base.Base)。
逻辑:Alembic / Flask-Migrate 通过本模块 import 注册全部表元数据;业务代码继续从此处导入模型类。
"""
@@ -11,171 +11,28 @@ from app.models.base import Base, user_agent_permissions
from app.models.chat import ChatLog, ChatSession, ChatToolRun, Feedback, GeneralFeedback
from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlLanguage
from app.models.department import Department
from app.models.linked_service import LinkedService
from app.models.job import Job
from app.jobs.types import JobType # noqa: F401 — 与 Job 配合读库,聚合在 models 一处导入
from app.models.kb import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup, KbJob
from app.models.maintenance import MaintenanceAuditLog, MaintenanceDevice, MaintenanceRecord
from app.models.schedule import ScheduleRun, ScheduleTask, ScheduleTaskConfig
from app.models.settings import AppSetting
from app.models.file_asset import FileAsset
from app.models.contract import ContractReview, ContractRiskRule, ContractTemplate
from app.models.shipping import (
ShippingBatch,
ShippingInventoryFile,
ShippingNotice,
ShippingOrderCandidate,
ShippingOrderDocument,
ShippingOrderIntake,
ShippingInventoryMapping,
ShippingNoticeCandidate,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingTask,
ShippingTaskEvent,
ShippingTaskPurgeAudit,
ShippingTaskInventoryLink,
)
from app.models.shipping_order_submission import ShippingOrderSubmission
from app.models.shipping_order_task import ShippingOrderTask
from app.models.shipping_order_candidate_evidence import ShippingOrderCandidateEvidence
from app.models.shipping_notice_line import ShippingNoticeLine
from app.models.shipping_order_document_version import ShippingOrderDocumentVersion
from app.models.shipping_task_line import ShippingTaskFieldConflict
# [BE-14] 已移除 ShippingTask=ShippingNotice 兼容别名;正式发货通知统一用 ShippingNotice,
# 建单前 OT 用 ShippingOrderTask,禁止再引入 ShippingTask 混淆二者。
from app.models.shipping_context_provider import ShippingContextProvider, ShippingContextProviderOption
from app.models.shipping_excel_template import ShippingExcelTemplate, ShippingExportArtifact
from app.models.shipping_fulfillment import (
ShippingExportArtifactLine,
ShippingInventoryVerification,
ShippingInventoryVerificationLine,
ShippingReservation,
ShippingUploadAttempt,
)
from app.models.shipping_process_gate import (
ShippingProcessExecution,
ShippingProcessGate,
ShippingProcessGateAttempt,
)
# 短期兼容别名:历史代码仍可 import ShippingNotice*;新代码优先用 ShippingOrder*。
ShippingNoticeIntake = ShippingOrderIntake
ShippingNoticeDocument = ShippingOrderDocument
ShippingNoticeCandidate = ShippingOrderCandidate
from app.models.shipping_order_schema import (
ShippingFieldAsset,
ShippingOrderExtraction,
ShippingOrderSchemaAuditEvent,
ShippingOrderField,
ShippingOrderFieldDecision,
ShippingOrderFieldObservation,
ShippingOrderFieldValue,
ShippingOrderLine,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingSchemaFamily,
)
from app.models.shipping_order_customer_match import ShippingOrderCustomerMatch
from app.models.shipping_order_snapshot import (
ShippingOrderReviewEvent,
ShippingOrderSnapshot,
ShippingOrderSnapshotLine,
)
from app.models.shipping_order_review import (
ShippingOrderReviewCase,
ShippingOrderReviewDraft,
ShippingOrderReviewCaseEvent,
ShippingOrderReviewConfirmedRevision,
)
from app.models.shipping_order_review_line_decision import ShippingOrderReviewLineDecision
from app.models.shipping_order_review_wave_line import ShippingOrderReviewWaveLine
from app.models.shipping_order_review_wave_idempotency import ShippingOrderReviewWaveIdempotency
from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch
from app.models.shipping_order_review_suggestion import ShippingOrderReviewSuggestion
from app.models.shipping_order_extraction_run import (
ShippingOrderExtractionDiagnosticAudit,
ShippingOrderExtractionProgressEvent,
ShippingOrderExtractionSubmission,
ShippingOrderProcessingPlan,
ShippingOrderProcessingRun,
ShippingOrderProcessingRunIntake,
ShippingOrderProcessingUnit,
ShippingOrderRouteDecision,
)
# 短期兼容别名:历史代码仍可 import ShippingOrderExtractionRun*;新代码优先用 Processing*。
ShippingOrderExtractionRun = ShippingOrderProcessingRun
ShippingOrderExtractionRunIntake = ShippingOrderProcessingRunIntake
ShippingOrderExtractionPlan = ShippingOrderProcessingPlan
ShippingOrderExtractionUnit = ShippingOrderProcessingUnit
ShippingOrderExtractionRouteDecision = ShippingOrderRouteDecision
from app.models.shipping_audit_event import ShippingAuditEvent
from app.models.shipping_order_document_profile import (
ShippingOrderDocumentProfile,
ShippingOrderDocumentProfileAudit,
ShippingOrderDocumentProfileDraftRevision,
ShippingOrderDocumentProfileEditLease,
ShippingOrderDocumentProfileSuggestionDecision,
ShippingOrderDocumentProfileValidationRun,
ShippingOrderDocumentProfilePublishCheckReport,
ShippingOrderDocumentProfileSample,
)
from app.models.shipping_document_profile_quality import (
ShippingDocumentProfileTestRun,
ShippingDocumentProfileTestSample,
ShippingDocumentProfileTestSuite,
)
from app.models.shipping_document_profile_auto_freeze import ShippingDocumentProfileAutoFreezeQualification
from app.models.shipping_order_candidate_qualification import ShippingOrderCandidateQualification
from app.models.shipping_freight_cancellation import ShippingFreightCancellation
from app.models.shipping_document_layout import ShippingDocumentLayoutVersion
from app.models.shipping_xfa_structure_analysis import ShippingXfaStructureAnalysis
from app.models.shipping_xfa_audit_snapshot import ShippingXfaAuditSnapshot
from app.models.shipping_inventory_config import (
ShippingInventoryField,
ShippingInventoryExternalMapping,
ShippingInventoryConfigurationTestRun,
ShippingInventoryValidationBatch,
ShippingInventorySourceParsingBindingAudit,
ShippingInventoryParsingProfile,
ShippingInventoryRoutingRule,
ShippingInventoryRoutingRuleCondition,
ShippingInventoryRoutingRuleVersion,
ShippingInventorySource,
ShippingInventoryStructureAnalysis,
ShippingRpaProfile,
)
from app.models.shipping_temporary_inventory import ShippingTemporaryInventorySession
from app.models.shipping_customer import (
ShippingBusinessSequence,
ShippingCase,
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
ShippingCustomerLifecycleEvent,
ShippingCustomerMerge,
ShippingCustomerSite,
ShippingCustomerSiteIdentifier,
)
from app.models.shipping_customer_import import ShippingCustomerImportBatch, ShippingCustomerImportRow
from app.models.shipping_customer_resolution import ShippingCustomerShadowMatch, ShippingCustomerShadowResolution
from app.models.shipping_order_extraction_quality import (
ShippingOrderExtractionQualityBatch,
ShippingOrderExtractionQualityLabel,
)
from app.models.shipping_identity_rule import (
ShippingIdentityDefinition,
ShippingIdentityEvidence,
ShippingIdentityRuleAuditEvent,
ShippingIdentityRuleSet,
)
from app.models.shipping_inventory_candidates import (
ShippingInventoryCandidateLine,
ShippingInventoryCandidateSet,
ShippingInventoryCandidateSource,
)
from app.models.shipping_task_inventory_rpa_attempts import ShippingTaskInventoryRpaAttempt
from app.models.shipping_process_recovery_plan import ShippingProcessRecoveryPlan
from app.models.shipping_inventory_preparation import (
ShippingInventoryPreparationAttempt,
ShippingInventoryPreparationSourceAttempt,
)
from app.models.shipping_inventory_mapping import ShippingInventoryMapping
from app.models.training import TrainingRecord
from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig
from app.models.voucher_check import VoucherCheckInvoiceState, VoucherCheckRunItem
from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit
__all__ = [
@@ -197,6 +54,7 @@ __all__ = [
'QuickQuestion',
'FaqHotCandidate',
'Announcement',
'LinkedService',
'LoginAudit',
'WecomNotifyAudit',
'AppSetting',
@@ -205,132 +63,30 @@ __all__ = [
'KbDocumentVersion',
'KbJob',
'Job',
'JobType',
'KbDifySyncRecord',
'WecomCallbackAudit',
'ScheduleTask',
'ScheduleTaskConfig',
'ScheduleRun',
'ShippingNotice',
'ShippingTaskFieldConflict',
'ShippingContextProvider',
'ShippingContextProviderOption',
'ShippingOrderSchema',
'ShippingSchemaFamily',
'ShippingOrderSchemaVersion',
'ShippingOrderSchemaAuditEvent',
'ShippingOrderField',
'ShippingFieldAsset',
'ShippingOrderExtraction',
'ShippingOrderLine',
'ShippingOrderFieldObservation',
'ShippingOrderFieldDecision',
'ShippingOrderFieldValue',
'ShippingOrderCustomerMatch',
'ShippingOrderSnapshot',
'ShippingOrderSnapshotLine',
'ShippingOrderReviewEvent',
'ShippingOrderReviewCase',
'ShippingOrderReviewDraft',
'ShippingOrderReviewCaseEvent',
'ShippingOrderReviewConfirmedRevision',
'ShippingOrderReviewLineDecision',
'ShippingOrderReviewWaveLine',
'ShippingOrderReviewWaveIdempotency',
'ShippingNoticeLineInventoryMatch',
'ShippingOrderReviewSuggestion',
'ShippingOrderProcessingRun',
'ShippingOrderProcessingRunIntake',
'ShippingOrderProcessingPlan',
'ShippingOrderProcessingUnit',
'ShippingOrderRouteDecision',
'ShippingOrderExtractionRun',
'ShippingOrderExtractionRunIntake',
'ShippingOrderExtractionSubmission',
'ShippingOrderExtractionPlan',
'ShippingOrderExtractionRouteDecision',
'ShippingOrderExtractionUnit',
'ShippingOrderExtractionProgressEvent',
'ShippingOrderExtractionDiagnosticAudit',
'ShippingAuditEvent',
'ShippingOrderExtractionQualityBatch',
'ShippingOrderExtractionQualityLabel',
'ShippingOrderDocumentProfile',
'ShippingOrderDocumentProfileAudit',
'ShippingOrderDocumentProfileSample',
'ShippingDocumentProfileTestSuite',
'ShippingDocumentProfileTestSample',
'ShippingDocumentProfileTestRun',
'ShippingDocumentProfileAutoFreezeQualification',
'ShippingOrderCandidateQualification',
'ShippingFreightCancellation',
'ShippingDocumentLayoutVersion',
'ShippingXfaStructureAnalysis',
'ShippingXfaAuditSnapshot',
'ShippingCustomer',
'ShippingCustomerIdentifier',
'ShippingCustomerExternalRef',
'ShippingCustomerLifecycleEvent',
'ShippingCustomerMerge',
'ShippingCustomerSite',
'ShippingCustomerSiteIdentifier',
'ShippingCustomerImportBatch',
'ShippingCustomerImportRow',
'ShippingCase',
'ShippingBusinessSequence',
'ShippingCustomerShadowResolution',
'ShippingCustomerShadowMatch',
'ShippingIdentityDefinition',
'ShippingIdentityEvidence',
'ShippingIdentityRuleSet',
'ShippingIdentityRuleAuditEvent',
'ShippingBatch',
'ShippingTask',
'ShippingTaskEvent',
'ShippingTaskPurgeAudit',
'ShippingInventoryFile',
'ShippingTaskInventoryLink',
'ShippingRpaProfile',
'ShippingInventorySource',
'ShippingInventoryField',
'ShippingInventoryStructureAnalysis',
'ShippingInventoryRoutingRule',
'ShippingInventoryRoutingRuleCondition',
'ShippingInventoryRoutingRuleVersion',
'ShippingInventoryExternalMapping',
'ShippingInventoryConfigurationTestRun',
'ShippingInventoryValidationBatch',
'ShippingInventorySourceParsingBindingAudit',
'ShippingInventoryParsingProfile',
'ShippingTemporaryInventorySession',
'ShippingExcelTemplate',
'ShippingExportArtifact',
'ShippingReservation',
'ShippingInventoryVerification',
'ShippingInventoryVerificationLine',
'ShippingExportArtifactLine',
'ShippingUploadAttempt',
'ShippingProcessExecution',
'ShippingProcessGate',
'ShippingProcessGateAttempt',
'ShippingOrderIntake',
'ShippingOrderDocument',
'ShippingOrderCandidate',
'ShippingNoticeIntake', # 兼容别名
'ShippingNoticeDocument', # 兼容别名
'ShippingNoticeCandidate', # 兼容别名
'ShippingOrderSubmission',
'ShippingOrderTask',
'ShippingOrderCandidateEvidence',
'ShippingNoticeLine',
'ShippingOrderDocumentVersion',
'ShippingInventoryMapping',
'ShippingNoticeIntake',
'ShippingNoticeDocument',
'ShippingNoticeCandidate',
'FileAsset',
'ContractTemplate',
'ContractReview',
'ContractRiskRule',
'AgentGuide',
'AgentDirectoryMember',
'TrainingRecord',
'MaintenanceDevice',
'MaintenanceRecord',
'MaintenanceAuditLog',
'ShippingInventoryCandidateSet',
'ShippingInventoryCandidateSource',
'ShippingInventoryCandidateLine',
'ShippingTaskInventoryRpaAttempt',
'VoucherCheckInvoiceState',
'VoucherCheckRunItem',
]
+119
View File
@@ -0,0 +1,119 @@
"""
backend/app/models/contract.py
用途:采购合同审查域模型——标准模板库与单次审查记录。
依赖:models.base.Base、users / agents / file_assets FK。
逻辑:Admin 模板库与历史页、Chat/Tool 发起审查均读写本表;不绑定 ScheduleRun。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import JSON, Boolean, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ContractTemplate(Base):
"""管理员维护的标准采购合同模板。"""
__tablename__ = "contract_templates"
__table_args__ = (
UniqueConstraint("name", "version", name="uq_contract_templates_name_version"),
)
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(128), nullable=False)
version: Mapped[str] = mapped_column(String(32), nullable=False)
file_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey("file_assets.id"), nullable=True)
file_name: Mapped[str] = mapped_column(String(255), nullable=False)
contract_type: Mapped[str] = mapped_column(String(64), default="general_procurement", nullable=False, index=True)
applicable_scope: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
change_note: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
comparison_region_config: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
status: Mapped[str] = mapped_column(String(16), default="enabled", nullable=False, index=True)
is_default: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
)
class ContractReview(Base):
"""一次单合同审查记录(模板比对或单份审核)。"""
__tablename__ = "contract_reviews"
id: Mapped[int] = mapped_column(primary_key=True)
review_no: Mapped[str] = mapped_column(String(64), unique=True, nullable=False, index=True)
agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey("agents.id"), nullable=True, index=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False, index=True)
chat_log_id: Mapped[Optional[int]] = mapped_column(ForeignKey("chat_logs.id"), nullable=True)
review_mode: Mapped[str] = mapped_column(String(16), nullable=False, index=True) # compare | solo
status: Mapped[str] = mapped_column(String(16), default="pending", nullable=False, index=True)
contract_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey("file_assets.id"), nullable=True)
contract_file_name: Mapped[str] = mapped_column(String(255), nullable=False)
supplier_name: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
# 从对方合同正文抽取的业务合同编号(非审查编号 review_no)
contract_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
contract_type: Mapped[str] = mapped_column(String(64), default="general_procurement", nullable=False, index=True)
template_id: Mapped[Optional[int]] = mapped_column(ForeignKey("contract_templates.id"), nullable=True)
template_source: Mapped[str] = mapped_column(String(16), nullable=False, default="none")
# library | user_upload | none
template_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey("file_assets.id"), nullable=True)
template_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
total_change_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
high_risk_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
medium_risk_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
low_risk_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
summary_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
clauses_json: Mapped[Optional[list[Any]]] = mapped_column(JSON, nullable=True)
report_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False, index=True)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
)
class ContractRiskRule(Base):
"""Configurable procurement contract risk rule used by solo and compare review."""
__tablename__ = "contract_risk_rules"
__table_args__ = (
UniqueConstraint("code", name="uq_contract_risk_rules_code"),
)
id: Mapped[int] = mapped_column(primary_key=True)
code: Mapped[str] = mapped_column(String(64), nullable=False)
contract_type: Mapped[str] = mapped_column(String(64), default="general_procurement", nullable=False, index=True)
clause_category: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
title: Mapped[str] = mapped_column(String(128), nullable=False)
keywords: Mapped[list[Any]] = mapped_column(JSON, nullable=False, default=list)
trigger_type: Mapped[str] = mapped_column(String(32), default="keyword_missing", nullable=False)
risk_level: Mapped[str] = mapped_column(String(16), nullable=False, index=True)
risk_hint: Mapped[str] = mapped_column(Text, nullable=False)
suggestion: Mapped[str] = mapped_column(Text, nullable=False)
negotiation_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
status: Mapped[str] = mapped_column(String(16), default="enabled", nullable=False, index=True)
sort_order: Mapped[int] = mapped_column(Integer, default=100, nullable=False)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
)
+35
View File
@@ -0,0 +1,35 @@
"""
backend/app/models/linked_service.py
用途:管理台可配置的关联服务(名称 + URL),供 Chat/工作台侧栏入口展示。
依赖:models.base.Base。
逻辑:admin CRUD 写入本表;已登录用户只读启用项,由 ExternalSystemLinks 渲染。
"""
from __future__ import annotations
from datetime import datetime
from sqlalchemy import Boolean, DateTime, Integer, String
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class LinkedService(Base):
"""
关联服务表
用途:存储产品内其它服务的显示名称与访问地址。
"""
__tablename__ = 'linked_services'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(100), nullable=False)
url: Mapped[str] = mapped_column(String(500), nullable=False)
is_enabled: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
sort_order: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
+114
View File
@@ -0,0 +1,114 @@
"""
backend/app/models/voucher_check.py
用途:立账凭证检核单票最新状态与批次明细 ORM。
依赖:models.base.Base、schedule_runs。
逻辑:runner/persistence 写入;query_service 与工作台 API 读取;增量跳过依赖 invoice_states。
"""
from __future__ import annotations
from datetime import date, datetime
from typing import Optional
from sqlalchemy import (
BigInteger,
Boolean,
Date,
DateTime,
ForeignKey,
Index,
JSON,
String,
Text,
UniqueConstraint,
)
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class VoucherCheckInvoiceState(Base):
"""账套+月份+发票号的最新材料齐全状态(增量跳过真相源)。"""
__tablename__ = "voucher_check_invoice_states"
__table_args__ = (
UniqueConstraint(
"scope_code",
"period_month",
"invoice_no",
name="uq_voucher_check_invoice_states_scope_period_invoice",
),
Index("ix_voucher_check_invoice_states_period_status", "period_month", "status"),
Index("ix_voucher_check_invoice_states_invoice_no", "invoice_no"),
Index("ix_voucher_check_invoice_states_notified_on", "last_missing_notified_on"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
scope_code: Mapped[str] = mapped_column(String(32), nullable=False)
period_month: Mapped[date] = mapped_column(Date, nullable=False)
invoice_no: Mapped[str] = mapped_column(String(128), nullable=False)
invoice_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
status: Mapped[str] = mapped_column(String(24), nullable=False)
folder_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
folder_exists: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
material_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
matched_files_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
missing_materials_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
last_actual_run_id: Mapped[Optional[int]] = mapped_column(
BigInteger,
ForeignKey("schedule_runs.id", ondelete="SET NULL"),
nullable=True,
)
last_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
last_seen_erp_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
last_missing_notified_on: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime,
default=datetime.utcnow,
onupdate=datetime.utcnow,
nullable=False,
)
class VoucherCheckRunItem(Base):
"""单次 ScheduleRun 的发票检核快照(含跳过项,供审计与 Excel)。"""
__tablename__ = "voucher_check_run_items"
__table_args__ = (
UniqueConstraint(
"schedule_run_id",
"invoice_no",
name="uq_voucher_check_run_items_run_invoice",
),
Index("ix_voucher_check_run_items_run_result", "schedule_run_id", "result"),
Index("ix_voucher_check_run_items_period_result", "period_month", "result"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
schedule_run_id: Mapped[int] = mapped_column(
BigInteger,
ForeignKey("schedule_runs.id", ondelete="CASCADE"),
nullable=False,
index=True,
)
invoice_state_id: Mapped[Optional[int]] = mapped_column(
BigInteger,
ForeignKey("voucher_check_invoice_states.id", ondelete="SET NULL"),
nullable=True,
)
scope_code: Mapped[str] = mapped_column(String(32), nullable=False)
period_month: Mapped[date] = mapped_column(Date, nullable=False)
invoice_no: Mapped[str] = mapped_column(String(128), nullable=False)
invoice_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
result: Mapped[str] = mapped_column(String(24), nullable=False)
folder_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
folder_exists: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
material_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
matched_files_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
missing_materials_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
+2
View File
@@ -12,6 +12,7 @@ from . import (
department_service,
faq_service,
guide_service,
linked_service_service,
permission_service,
report_service,
shipping_customer_import_service,
@@ -30,6 +31,7 @@ __all__ = [
'department_service',
'faq_service',
'guide_service',
'linked_service_service',
'permission_service',
'report_service',
'shipping_customer_import_service',
@@ -0,0 +1,130 @@
"""
backend/app/services/admin/linked_service_service.py
用途:关联服务 CRUD 与侧栏只读列表。
依赖:models.LinkedService、app.core.errors。
逻辑:api/admin/linked_services.py 管理 CRUD;api/linked_services.py 返回已启用项。
"""
from __future__ import annotations
from typing import Any
from urllib.parse import urlparse
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import LinkedService
def _normalize_name(value: Any) -> str:
"""校验并规范化显示名称。"""
name = str(value or '').strip()
if not name:
raise ValidationError('Name is required')
if len(name) > 100:
raise ValidationError('Name is too long')
return name
def _normalize_url(value: Any) -> str:
"""
校验并规范化访问地址。
核心逻辑:仅允许 http/https,且必须含主机;内网 IP 可用 http。
"""
url = str(value or '').strip()
if not url:
raise ValidationError('URL is required')
if len(url) > 500:
raise ValidationError('URL is too long')
parsed = urlparse(url)
if parsed.scheme not in {'http', 'https'} or not parsed.netloc:
raise ValidationError('URL must be an absolute http(s) address')
return url
def serialize_linked_service(row: LinkedService, *, include_admin_fields: bool = False) -> dict:
"""LinkedService ORM → API dict。"""
payload = {
'id': row.id,
'name': row.name,
'url': row.url,
}
if include_admin_fields:
payload.update({
'is_enabled': bool(row.is_enabled),
'sort_order': int(row.sort_order or 0),
'created_at': row.created_at.isoformat() if row.created_at else None,
'updated_at': row.updated_at.isoformat() if row.updated_at else None,
})
return payload
def list_enabled_linked_services() -> list[dict]:
"""返回已启用关联服务,供 Chat/工作台侧栏入口使用。"""
rows = (
db.session.query(LinkedService)
.filter(LinkedService.is_enabled.is_(True))
.order_by(LinkedService.sort_order.asc(), LinkedService.id.asc())
.all()
)
return [serialize_linked_service(row) for row in rows]
def list_linked_services() -> list[dict]:
"""管理端列表:含停用项与排序字段。"""
rows = (
db.session.query(LinkedService)
.order_by(LinkedService.sort_order.asc(), LinkedService.id.asc())
.all()
)
return [serialize_linked_service(row, include_admin_fields=True) for row in rows]
def create_linked_service(data: dict[str, Any]) -> dict:
"""
创建关联服务。
Args:
data: 含 name、url;可选 is_enabled、sort_order。
Returns:
{ id, message }
"""
row = LinkedService(
name=_normalize_name(data.get('name')),
url=_normalize_url(data.get('url')),
is_enabled=bool(data.get('is_enabled', True)),
sort_order=int(data.get('sort_order') or 0),
)
db.session.add(row)
db.session.commit()
return {'message': 'Created', 'id': row.id}
def update_linked_service(service_id: int, data: dict[str, Any]) -> dict:
"""
更新关联服务。
Raises:
NotFoundError: 记录不存在。
"""
row = db.session.get(LinkedService, service_id)
if not row:
raise NotFoundError('Not found')
row.name = _normalize_name(data.get('name'))
row.url = _normalize_url(data.get('url'))
if 'is_enabled' in data:
row.is_enabled = bool(data.get('is_enabled'))
if 'sort_order' in data:
row.sort_order = int(data.get('sort_order') or 0)
db.session.commit()
return {'message': 'Updated'}
def delete_linked_service(service_id: int) -> dict:
"""删除关联服务(不存在时静默成功)。"""
row = db.session.get(LinkedService, service_id)
if row:
db.session.delete(row)
db.session.commit()
return {'message': 'Deleted'}
@@ -214,6 +214,7 @@ def create_user(data: dict[str, Any]) -> dict:
casdoor_service.sync_create_user(
username=user.username,
password=data['password'],
employee_id=user.employee_id,
email=email,
real_name=user.real_name,
phone_number=user.phone_number,
@@ -115,3 +115,17 @@ agent_types:
lock_input_when_running:
type: boolean
default: true
procurement_contract_review:
label: 采购合同审查
conversation_mode_default: task_chat
runtime_provider_default: dify
models:
- ContractTemplate
- ContractReview
required_fields: []
default_capabilities:
file_upload: true
forced_capabilities:
file_upload: true
human_confirm: false
handler_config_schema: {}
@@ -0,0 +1,20 @@
"""
backend/app/services/auth/casdoor/__init__.py
用途:导出不依赖 HXOPS User 模型的 Casdoor 认证公共能力。
依赖:config、client、identity、errors。
逻辑:HXOPS 与平级服务可复制本目录,并用各自配置适配器创建 CasdoorClient。
"""
from .client import CasdoorClient, CasdoorTokenResult, get_casdoor_client
from .config import CasdoorConfig, casdoor_config_from_flask
from .identity import identity_from_claims
__all__ = [
'CasdoorClient',
'CasdoorConfig',
'CasdoorTokenResult',
'casdoor_config_from_flask',
'get_casdoor_client',
'identity_from_claims',
]
+170
View File
@@ -0,0 +1,170 @@
"""
backend/app/services/auth/casdoor/client.py
用途:封装 Casdoor OAuth/OIDC HTTP 通信,供 HXOPS 与平级服务复制复用。
依赖:requests、CasdoorConfig、Casdoor 错误映射。
逻辑:所有 grant 和 userinfo 请求集中在此;模块不依赖 HXOPS User、数据库或业务权限。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from threading import Lock
from typing import Any
import requests
from .config import CasdoorConfig, casdoor_config_from_flask
from .errors import raise_auth_error
_CLIENT_CACHE_LOCK = Lock()
_CLIENT_CACHE_CONFIG: CasdoorConfig | None = None
_CLIENT_CACHE_VALUE: CasdoorClient | None = None
@dataclass(frozen=True)
class CasdoorTokenResult:
"""Casdoor token endpoint 返回的标准字段和原始扩展字段。"""
access_token: str
refresh_token: str | None
id_token: str | None
token_type: str
expires_in: int
raw: dict[str, Any]
def as_dict(self) -> dict[str, Any]:
"""返回兼容现有 HXOPS 路由和测试的 token 字典。"""
return dict(self.raw)
class CasdoorClient:
"""无业务模型依赖的 Casdoor OAuth/OIDC 客户端。"""
def __init__(self, config: CasdoorConfig, *, http_session=requests):
"""
创建客户端并注入配置和 HTTP 实现。
Args:
config: 当前服务自己的 Casdoor Application 配置。
http_session: 兼容 requests 的 HTTP 对象,测试可注入替身。
"""
self.config = config
self._http = http_session
self._metadata: dict[str, Any] | None = None
self._metadata_expires_at: datetime | None = None
self._metadata_lock = Lock()
def oidc_metadata(self) -> dict[str, Any]:
"""读取并缓存 OIDC discovery 文档 10 分钟。"""
now = datetime.now(timezone.utc)
if self._metadata and self._metadata_expires_at and self._metadata_expires_at > now:
return dict(self._metadata)
with self._metadata_lock:
now = datetime.now(timezone.utc)
if self._metadata and self._metadata_expires_at and self._metadata_expires_at > now:
return dict(self._metadata)
response = self._http.get(
f'{self.config.base_url}/.well-known/openid-configuration',
timeout=self.config.timeout_seconds,
)
response.raise_for_status()
data = response.json() or {}
if not isinstance(data, dict):
raise RuntimeError('Casdoor OIDC metadata is invalid')
self._metadata = data
self._metadata_expires_at = now + timedelta(minutes=10)
return dict(data)
def _token_endpoint(self) -> str:
"""从 discovery 文档读取 token endpoint,缺失时安全失败。"""
endpoint = str(self.oidc_metadata().get('token_endpoint') or '').strip()
if not endpoint:
raise RuntimeError('Casdoor token endpoint missing')
return endpoint
def _token_request(self, payload: dict[str, Any], *, context: str) -> CasdoorTokenResult:
"""执行 token endpoint 请求并统一解析成功或失败结果。"""
response = self._http.post(
self._token_endpoint(),
data=payload,
timeout=self.config.timeout_seconds,
)
try:
data = response.json() or {}
except ValueError as exc:
raise RuntimeError(f'Casdoor token request failed: HTTP {response.status_code}') from exc
if not response.ok or not data.get('access_token'):
raise_auth_error(data, context=context)
return CasdoorTokenResult(
access_token=str(data['access_token']),
refresh_token=str(data['refresh_token']) if data.get('refresh_token') else None,
id_token=str(data['id_token']) if data.get('id_token') else None,
token_type=str(data.get('token_type') or 'Bearer'),
expires_in=int(data.get('expires_in') or 3600),
raw=dict(data),
)
def password_login(self, username: str, password: str) -> CasdoorTokenResult:
"""使用当前服务自己的 Casdoor Application 执行 password grant。"""
return self._token_request({
'grant_type': 'password',
'username': username,
'password': password,
'client_id': self.config.client_id,
'client_secret': self.config.client_secret,
'scope': self.config.scope,
}, context='password')
def authorization_code_login(self, code: str, redirect_uri: str) -> CasdoorTokenResult:
"""将浏览器返回的 authorization code 兑换为 Casdoor token。"""
return self._token_request({
'grant_type': 'authorization_code',
'code': code,
'client_id': self.config.client_id,
'client_secret': self.config.client_secret,
'redirect_uri': redirect_uri,
}, context='code')
def refresh(self, refresh_token: str) -> CasdoorTokenResult:
"""使用 Casdoor refresh token 获取新 token 集合。"""
return self._token_request({
'grant_type': 'refresh_token',
'refresh_token': refresh_token,
'client_id': self.config.client_id,
'client_secret': self.config.client_secret,
}, context='refresh')
def userinfo(self, access_token: str) -> dict[str, Any]:
"""使用 Casdoor access token 获取可信用户声明。"""
endpoint = str(self.oidc_metadata().get('userinfo_endpoint') or '').strip()
if not endpoint:
raise RuntimeError('Casdoor userinfo endpoint missing')
response = self._http.get(
endpoint,
headers={'Authorization': f'Bearer {access_token}'},
timeout=self.config.timeout_seconds,
)
try:
data = response.json() or {}
except ValueError as exc:
raise RuntimeError(f'Casdoor userinfo failed: HTTP {response.status_code}') from exc
if not response.ok or not isinstance(data, dict):
raise RuntimeError(f'Casdoor userinfo failed: HTTP {response.status_code}')
return data
def get_casdoor_client() -> CasdoorClient:
"""复用当前配置对应的进程内客户端,配置变化时自动替换缓存实例。"""
global _CLIENT_CACHE_CONFIG, _CLIENT_CACHE_VALUE
config = casdoor_config_from_flask()
if _CLIENT_CACHE_VALUE is not None and _CLIENT_CACHE_CONFIG == config:
return _CLIENT_CACHE_VALUE
with _CLIENT_CACHE_LOCK:
if _CLIENT_CACHE_VALUE is None or _CLIENT_CACHE_CONFIG != config:
_CLIENT_CACHE_CONFIG = config
_CLIENT_CACHE_VALUE = CasdoorClient(config)
return _CLIENT_CACHE_VALUE
@@ -0,0 +1,68 @@
"""
backend/app/services/auth/casdoor/config.py
用途:定义纯 Casdoor 客户端配置及 HXOPS Flask 配置适配器。
依赖:dataclasses、flask.current_app、app.core.errors。
逻辑:公共客户端只接收 CasdoorConfig;不同服务只需替换配置适配器。
"""
from __future__ import annotations
from dataclasses import dataclass
from flask import current_app
from app.core.errors import AppError
@dataclass(frozen=True)
class CasdoorConfig:
"""Casdoor OAuth/OIDC 客户端运行参数,secret 不参与 repr。"""
base_url: str
client_id: str
client_secret: str
issuer: str
scope: str = 'openid profile email'
timeout_seconds: int = 8
def __repr__(self) -> str:
"""输出可诊断但不包含 client_secret 的配置摘要。"""
return (
'CasdoorConfig('
f'base_url={self.base_url!r}, client_id={self.client_id!r}, '
f'issuer={self.issuer!r}, scope={self.scope!r}, '
f'timeout_seconds={self.timeout_seconds!r})'
)
def casdoor_config_from_flask() -> CasdoorConfig:
"""
从当前 Flask 应用读取并校验 Casdoor 客户端配置。
Returns:
可交给 CasdoorClient 的不可变配置。
Raises:
AppError: 基础地址、客户端凭据或 issuer 未配置。
"""
base_url = str(current_app.config.get('CASDOOR_BASE_URL') or '').strip().rstrip('/')
client_id = str(current_app.config.get('CASDOOR_CLIENT_ID') or '').strip()
client_secret = str(current_app.config.get('CASDOOR_CLIENT_SECRET') or '')
issuer = str(current_app.config.get('AUTH_JWT_ISSUER') or '').strip().rstrip('/')
scope = str(current_app.config.get('CASDOOR_SCOPE') or 'openid profile email').strip()
timeout_seconds = int(current_app.config.get('CASDOOR_HTTP_TIMEOUT_SECONDS') or 8)
if not base_url or not client_id or not client_secret or not issuer:
raise AppError(
code='CASDOOR_CONFIG_ERROR',
message='Authentication service is not configured. Please contact the administrator.',
http_status=503,
)
return CasdoorConfig(
base_url=base_url,
client_id=client_id,
client_secret=client_secret,
issuer=issuer,
scope=scope or 'openid profile email',
timeout_seconds=max(1, timeout_seconds),
)
+106
View File
@@ -0,0 +1,106 @@
"""
backend/app/services/auth/casdoor/errors.py
用途:把 Casdoor OAuth/OIDC 失败转换为稳定业务错误码。
依赖:标准库解析工具、flask.current_app、app.core.errors。
逻辑:CasdoorClient 将失败响应交给本模块,API 层只处理统一 AppError。
"""
from __future__ import annotations
import ast
import json
import re
from flask import current_app
from app.core.errors import AppError, ValidationError
def clean_str(value) -> str | None:
"""去除字符串首尾空白,空值统一返回 None。"""
if value is None:
return None
return str(value).strip() or None
def extract_error_payload(source) -> dict:
"""从 Casdoor 响应字典或异常文本中提取可识别错误字段。"""
if isinstance(source, dict):
return source
text = str(source or '')
match = re.search(r'\{.*\}', text, re.DOTALL)
if match:
try:
parsed = ast.literal_eval(match.group(0))
if isinstance(parsed, dict):
return parsed
except (SyntaxError, ValueError):
pass
try:
parsed = json.loads(text)
return parsed if isinstance(parsed, dict) else {}
except (json.JSONDecodeError, TypeError):
return {}
def is_password_error(message: str) -> bool:
"""判断 Casdoor 错误是否表示用户名或密码无效。"""
lowered = (message or '').lower()
return 'invalid_grant' in lowered or 'password login failed' in lowered or 'incorrect password' in lowered
def raise_auth_error(source, *, context: str, status_code: int = 401) -> None:
"""
将 Casdoor 登录、授权码和刷新失败映射为稳定错误。
Args:
source: Casdoor JSON 错误体或捕获的异常。
context: ``password``、``code``、``refresh`` 或 ``verify``。
status_code: 未识别错误的默认 HTTP 状态码。
Raises:
AppError: 所有失败均转换为统一认证错误,不返回原始 token 或 secret。
"""
data = extract_error_payload(source)
raw = str(source or '')
oauth_error = (clean_str(data.get('error')) or '').lower()
if not oauth_error and 'invalid_grant' in raw.lower():
oauth_error = 'invalid_grant'
if not oauth_error and 'invalid_client' in raw.lower():
oauth_error = 'invalid_client'
if oauth_error == 'invalid_grant' or is_password_error(raw):
if context in {'password', 'verify'}:
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect username or password', http_status=401)
raise AppError(code='CASDOOR_CODE_EXPIRED', message='Login session expired, please sign in again', http_status=401)
if oauth_error in {'invalid_client', 'unauthorized_client'}:
raise AppError(
code='CASDOOR_CONFIG_ERROR',
message='Authentication service is misconfigured. Please contact the administrator.',
http_status=503,
details={'casdoor_error': oauth_error},
)
if oauth_error == 'access_denied':
raise AppError(code='CASDOOR_ACCESS_DENIED', message='Login was cancelled or denied', http_status=403)
if oauth_error == 'unsupported_grant_type':
raise AppError(
code='AUTH.CASDOOR_REFRESH_UNSUPPORTED',
message='Casdoor refresh token is not supported by current application config',
http_status=400,
)
lowered_raw = raw.lower()
if 'token endpoint missing' in lowered_raw or 'casdoor_base_url is not configured' in lowered_raw:
raise AppError(
code='CASDOOR_CONFIG_ERROR',
message='Authentication service is not configured. Please contact the administrator.',
http_status=503,
)
if 'invalid or expired casdoor state' in lowered_raw:
raise ValidationError('Invalid or expired Casdoor state')
current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s', context, data)
raise AppError(
code='CASDOOR_AUTH_FAILED',
message='Authentication failed, please try again',
http_status=status_code,
details={'casdoor_error': oauth_error or None},
)
@@ -0,0 +1,70 @@
"""
backend/app/services/auth/casdoor/identity.py
用途:将 Casdoor ID token/userinfo claims 转换为统一 AuthIdentity。
依赖:hmac、typing、services.auth.common.identity。
逻辑:严格绑定预期 issuer,提取稳定 subject 与可变用户资料,不访问业务数据库。
"""
from __future__ import annotations
import hmac
from collections.abc import Mapping
from typing import Any
from app.services.auth.common import AuthIdentity, IdentityValidationError, require_stable_identity
def _claim_text(claims: Mapping[str, Any], *keys: str) -> str | None:
"""按优先级读取第一个非空 claim 并转换为去空白字符串。"""
for key in keys:
value = claims.get(key)
if value is not None and str(value).strip():
return str(value).strip()
return None
def _claim_or_property_text(claims: Mapping[str, Any], *keys: str) -> str | None:
"""优先读取顶层 claim,再兼容 Casdoor properties 中同名的用户自定义属性。"""
value = _claim_text(claims, *keys)
if value:
return value
properties = claims.get('properties')
if isinstance(properties, Mapping):
return _claim_text(properties, *keys)
return None
def identity_from_claims(
claims: Mapping[str, Any],
*,
expected_issuer: str,
) -> AuthIdentity:
"""
将可信 Casdoor claims 转换为跨服务统一身份。
Args:
claims: 已验证 ID token 或通过 HTTPS 从 userinfo 获取的声明。
expected_issuer: 当前服务配置的可信 Casdoor issuer。
Returns:
不包含角色和业务权限的 AuthIdentity。
Raises:
IdentityValidationError: issuer 不匹配或缺少稳定 subject/username。
"""
trusted_issuer = str(expected_issuer or '').strip().rstrip('/')
claim_issuer = str(claims.get('iss') or trusted_issuer).strip().rstrip('/')
if not trusted_issuer or not claim_issuer or not hmac.compare_digest(claim_issuer, trusted_issuer):
raise IdentityValidationError('Casdoor identity issuer does not match the trusted issuer')
identity = AuthIdentity(
issuer=trusted_issuer,
subject=_claim_text(claims, 'sub') or '',
username=_claim_text(claims, 'preferred_username', 'name') or '',
display_name=_claim_text(claims, 'display_name', 'displayName', 'real_name', 'realName', 'name'),
email=_claim_text(claims, 'email'),
phone_number=_claim_text(claims, 'phone_number', 'phone'),
employee_id=_claim_or_property_text(claims, 'employee_id', 'employeeId'),
department=_claim_text(claims, 'department', 'affiliation'),
)
return require_stable_identity(identity)
+53 -321
View File
@@ -1,373 +1,105 @@
"""
backend/app/services/auth/casdoor_service.py
用途:Casdoor IdP 用户同步与 OAuth 错误映射(管理端创建/改密、用户域登录共用)。
依赖:flask.current_app、requests、app.core.errors。
逻辑:由 services/admin/user_service、api/user 登录路由调用。
用途:为历史调用点保留 Casdoor 错误与 HXOPS 用户同步兼容门面。
依赖:公共 casdoor.errors、HXOPS casdoor_user_sync。
逻辑:新代码按职责导入分层模块;旧路由、管理端和测试可继续替换本文件函数。
"""
from __future__ import annotations
import ast
import json
import re
from typing import Any
import requests
from flask import current_app
from app.core.errors import AppError, ConflictError, ValidationError
from app.models import User
def clean_str(value) -> str | None:
"""Trim 字符串;空串返回 None。"""
if value is None:
return None
if isinstance(value, str):
value = value.strip()
return value or None
return str(value).strip() or None
from app.services.auth.casdoor.errors import (
clean_str,
extract_error_payload,
is_password_error,
raise_auth_error,
)
from app.services.auth.hxops import casdoor_user_sync as _sync
def is_casdoor_configured() -> bool:
"""Casdoor 基础配置是否齐全。"""
if not clean_str(current_app.config.get('CASDOOR_ORGANIZATION')):
return False
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
return bool(base and client_id and client_secret)
"""兼容入口:检查 Casdoor 用户同步配置。"""
return _sync.is_casdoor_configured()
def casdoor_user_owner() -> str:
"""返回 Casdoor organization owner。"""
owner = clean_str(current_app.config.get('CASDOOR_ORGANIZATION'))
if not owner:
raise RuntimeError('CASDOOR_ORGANIZATION is not configured')
return owner
def extract_error_payload(source) -> dict:
"""从 Casdoor 响应或异常文本解析 JSON 错误体。"""
if isinstance(source, dict):
return source
text = str(source or '')
match = re.search(r'\{.*\}', text, re.DOTALL)
if match:
try:
parsed = ast.literal_eval(match.group(0))
if isinstance(parsed, dict):
return parsed
except (SyntaxError, ValueError):
pass
try:
parsed = json.loads(text)
if isinstance(parsed, dict):
return parsed
except (json.JSONDecodeError, TypeError):
pass
return {}
"""兼容入口:返回 Casdoor organization owner。"""
return _sync.casdoor_user_owner()
def is_user_exists_error(message: str) -> bool:
lowered = (message or '').lower()
return 'already exist' in lowered or 'duplicate' in lowered or 'has existed' in lowered
def is_password_error(message: str) -> bool:
lowered = (message or '').lower()
return 'invalid_grant' in lowered or 'password login failed' in lowered or 'incorrect password' in lowered
"""兼容入口:判断 IdP 用户已存在错误。"""
return _sync.is_user_exists_error(message)
def is_user_missing_error(message: str) -> bool:
lowered = (message or '').lower()
return (
"doesn't exist" in lowered
or 'does not exist' in lowered
or 'user not found' in lowered
or 'no such user' in lowered
)
"""兼容入口:判断 IdP 用户不存在错误。"""
return _sync.is_user_missing_error(message)
def raise_user_not_in_idp(source=None) -> None:
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
raise AppError(
code='CASDOOR_USER_NOT_IN_IDP',
message='Your account has not been registered in the authentication system. Please contact the administrator.',
http_status=409,
details={'technical': msg_text or str(source or '')[:300]},
)
"""兼容入口:抛出 IdP 缺失用户业务错误。"""
_sync.raise_user_not_in_idp(source)
def raise_add_user_error(source) -> None:
"""将 Casdoor add-user 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_user_exists_error(lowered):
raise ConflictError(
'Username already exists in Casdoor',
code='USER.USERNAME_EXISTS',
details={'field': 'username', 'technical': msg_text},
)
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='Password does not meet security requirements', http_status=400)
raise AppError(
code='CASDOOR_ADD_USER_FAILED',
message='Failed to create user in authentication system. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source or '')[:300]},
)
"""兼容入口:映射 Casdoor 新增用户错误。"""
_sync.raise_add_user_error(source)
def raise_update_user_error(source) -> None:
"""将 Casdoor update-user 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_user_missing_error(lowered):
raise_user_not_in_idp(source)
if is_user_exists_error(lowered) or ('email' in lowered and 'already' in lowered):
raise ConflictError(
'Email already exists in Casdoor',
code='USER.EMAIL_EXISTS',
details={'field': 'email', 'technical': msg_text},
)
raise AppError(
code='CASDOOR_UPDATE_USER_FAILED',
message='Failed to update user in authentication system. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source or '')[:300]},
)
"""兼容入口:映射 Casdoor 更新用户错误。"""
_sync.raise_update_user_error(source)
def raise_set_password_error(source) -> None:
"""将 Casdoor set-password 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_password_error(lowered) or 'old password' in lowered or 'current password' in lowered:
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect current password', http_status=401)
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='New password does not meet security requirements', http_status=400)
if is_user_missing_error(lowered):
raise_user_not_in_idp(source)
raise AppError(
code='CASDOOR_SET_PASSWORD_FAILED',
message='Failed to change password. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source)[:300]},
)
"""兼容入口:映射 Casdoor 修改密码错误。"""
_sync.raise_set_password_error(source)
def raise_auth_error(source, *, context: str, status_code: int = 401) -> None:
"""Map Casdoor OAuth/API failures to stable business error codes."""
data = extract_error_payload(source)
raw = str(source or '')
oauth_error = clean_str(data.get('error')).lower()
if not oauth_error and 'invalid_grant' in raw.lower():
oauth_error = 'invalid_grant'
if not oauth_error and 'invalid_client' in raw.lower():
oauth_error = 'invalid_client'
if oauth_error == 'invalid_grant' or is_password_error(raw):
if context in ('password', 'verify'):
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect username or password', http_status=401)
raise AppError(code='CASDOOR_CODE_EXPIRED', message='Login session expired, please sign in again', http_status=401)
if oauth_error in ('invalid_client', 'unauthorized_client'):
raise AppError(
code='CASDOOR_CONFIG_ERROR',
message='Authentication service is misconfigured. Please contact the administrator.',
http_status=503,
details={'casdoor_error': oauth_error},
)
if oauth_error == 'access_denied':
raise AppError(code='CASDOOR_ACCESS_DENIED', message='Login was cancelled or denied', http_status=403)
if 'token endpoint missing' in raw.lower() or 'casdoor_base_url is not configured' in raw.lower() or 'casdoor is not configured' in raw.lower():
raise AppError(
code='CASDOOR_CONFIG_ERROR',
message='Authentication service is not configured. Please contact the administrator.',
http_status=503,
)
if 'invalid or expired casdoor state' in raw.lower():
raise ValidationError('Invalid or expired Casdoor state')
current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s raw=%s', context, data, raw[:500])
raise AppError(
code='CASDOOR_AUTH_FAILED',
message='Authentication failed, please try again',
http_status=status_code,
details={'casdoor_error': oauth_error or None, 'technical': raw[:300]},
)
def build_user_profile_payload(**kwargs) -> dict[str, Any]:
"""兼容入口:构造不含密码的 Casdoor 用户资料。"""
return _sync.build_user_profile_payload(**kwargs)
def build_user_profile_payload(
*,
username: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict:
"""组装 Casdoor 用户资料字段(不含 password)。"""
display_name = clean_str(real_name) or username
payload = {
'owner': casdoor_user_owner(),
'name': username,
'email': email or '',
'displayName': display_name,
'realName': clean_str(real_name) or '',
'phone': clean_str(phone_number) or '',
'isForbidden': clean_str(status) not in (None, 'active'),
}
department_value = clean_str(department)
if department_value:
payload['affiliation'] = department_value
return payload
def build_user_payload(**kwargs) -> dict[str, Any]:
"""兼容入口:构造 Casdoor 创建用户请求体。"""
return _sync.build_user_payload(**kwargs)
def build_user_payload(
*,
username: str,
password: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict:
"""组装 Casdoor add-user 请求体。"""
payload = build_user_profile_payload(
username=username,
email=email,
real_name=real_name,
phone_number=phone_number,
status=status,
department=department,
)
payload['password'] = password
return payload
def casdoor_add_user(user_payload: dict[str, Any]) -> None:
"""兼容入口:调用 Casdoor 创建用户。"""
_sync.casdoor_add_user(user_payload)
def casdoor_add_user(user_payload: dict) -> None:
"""调用 Casdoor /api/add-user 创建 IdP 用户。"""
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
if not base or not client_id or not client_secret:
raise RuntimeError('Casdoor is not configured')
url = f'{base}/api/add-user'
resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8)
try:
data = resp.json() or {}
except ValueError:
raise RuntimeError(f'Casdoor add-user failed: HTTP {resp.status_code} {resp.text[:200]}')
if data.get('status') != 'ok':
raise_add_user_error(data)
def casdoor_update_user(user_payload: dict) -> None:
"""调用 Casdoor /api/update-user 更新 IdP 用户资料。"""
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
if not base or not client_id or not client_secret:
raise RuntimeError('Casdoor is not configured')
url = f'{base}/api/update-user'
resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8)
try:
data = resp.json() or {}
except ValueError:
raise RuntimeError(f'Casdoor update-user failed: HTTP {resp.status_code} {resp.text[:200]}')
if data.get('status') != 'ok':
raise_update_user_error(data)
def casdoor_update_user(user_payload: dict[str, Any]) -> None:
"""兼容入口:调用 Casdoor 更新用户。"""
_sync.casdoor_update_user(user_payload)
def casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str) -> None:
"""调用 Casdoor /api/set-password。"""
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
if not base or not client_id or not client_secret:
raise RuntimeError('Casdoor is not configured')
url = f'{base}/api/set-password'
resp = requests.post(
url,
files={
'userOwner': (None, user_owner),
'userName': (None, user_name),
'oldPassword': (None, old_password),
'newPassword': (None, new_password),
},
auth=(client_id, client_secret),
timeout=8,
)
try:
data = resp.json() or {}
except ValueError:
raise RuntimeError(f'Casdoor set-password failed: HTTP {resp.status_code} {resp.text[:200]}')
if data.get('status') != 'ok':
raise_set_password_error(data)
"""兼容入口:调用 Casdoor 修改密码。"""
_sync.casdoor_set_password(user_owner, user_name, old_password, new_password)
def sync_create_user(
*,
username: str,
password: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> None:
"""管理端创建用户时同步至 Casdoor。"""
if not is_casdoor_configured():
return
payload = build_user_payload(
username=username,
password=password,
email=email,
real_name=real_name,
phone_number=phone_number,
status=status,
department=department,
)
casdoor_add_user(payload)
def sync_create_user(**kwargs) -> None:
"""兼容入口:同步创建用户,并保留旧模块 monkeypatch 替换点。"""
_sync.sync_create_user(**kwargs, add_user=casdoor_add_user)
def sync_admin_set_password(user: User, new_password: str) -> None:
"""管理端重设密码时同步 Casdoor(无旧密码)。"""
if not is_casdoor_configured():
return
user_owner = casdoor_user_owner()
try:
casdoor_set_password(user_owner, user.username, '', new_password)
except RuntimeError as exc:
if is_user_missing_error(str(exc)):
raise_user_not_in_idp(exc)
raise_set_password_error(exc)
"""兼容入口:同步管理员改密,并保留旧模块 monkeypatch 替换点。"""
_sync.sync_admin_set_password(user, new_password, set_password=casdoor_set_password)
def sync_update_user(user: User, *, new_password: str | None = None) -> None:
"""管理端编辑用户时同步 Casdoor:仅改密;IdP 无账号则 add-user 补建。"""
if not is_casdoor_configured() or not new_password:
return
def _provision_missing_user_in_casdoor():
sync_create_user(
username=user.username,
password=new_password,
email=user.email,
real_name=user.real_name,
phone_number=user.phone_number,
status=user.status,
department=user.department,
)
try:
sync_admin_set_password(user, new_password)
except AppError as exc:
if exc.code == 'CASDOOR_USER_NOT_IN_IDP':
_provision_missing_user_in_casdoor()
return
raise
"""兼容入口:同步用户改密或补建 IdP 账号,并保留测试替换点。"""
_sync.sync_update_user(
user,
new_password=new_password,
set_password=casdoor_set_password,
add_user=casdoor_add_user,
)
@@ -0,0 +1,16 @@
"""
backend/app/services/auth/common/__init__.py
用途:导出不依赖 HXOPS 数据模型的认证公共类型。
依赖:common.identity。
逻辑:Casdoor 客户端、HXOPS 登录和 SSO 模块通过本入口共享统一身份对象。
"""
from .identity import AuthIdentity, IdentityValidationError, identity_key, require_stable_identity
__all__ = [
'AuthIdentity',
'IdentityValidationError',
'identity_key',
'require_stable_identity',
]
@@ -0,0 +1,69 @@
"""
backend/app/services/auth/common/identity.py
用途:定义跨认证来源通用、可复制的稳定身份对象。
依赖:Python dataclasses;不依赖 Flask、SQLAlchemy 或 HXOPS User。
逻辑:Casdoor claims 先转换为 AuthIdentity,业务系统再按 issuer + subject 映射自己的用户。
"""
from __future__ import annotations
from dataclasses import dataclass
class IdentityValidationError(ValueError):
"""身份缺少跨服务稳定键时抛出,调用方负责映射为自身错误契约。"""
@dataclass(frozen=True)
class AuthIdentity:
"""认证系统返回的稳定身份和可变展示资料,不包含任何业务权限。"""
issuer: str
subject: str
username: str
display_name: str | None = None
email: str | None = None
phone_number: str | None = None
employee_id: str | None = None
department: str | None = None
def require_stable_identity(identity: AuthIdentity) -> AuthIdentity:
"""
校验跨服务身份必须具备 issuer、subject 和 username。
Args:
identity: 待校验的认证身份。
Returns:
去除稳定键首尾空白后的不可变身份对象。
Raises:
IdentityValidationError: 缺少稳定身份键或用户名。
"""
issuer = str(identity.issuer or '').strip()
subject = str(identity.subject or '').strip()
username = str(identity.username or '').strip()
if not issuer or not subject:
raise IdentityValidationError('Identity issuer and subject are required')
if not username:
raise IdentityValidationError('Identity username is required')
if issuer == identity.issuer and subject == identity.subject and username == identity.username:
return identity
return AuthIdentity(
issuer=issuer,
subject=subject,
username=username,
display_name=identity.display_name,
email=identity.email,
phone_number=identity.phone_number,
employee_id=identity.employee_id,
department=identity.department,
)
def identity_key(identity: AuthIdentity) -> tuple[str, str]:
"""返回业务系统建立外部身份映射时使用的唯一键 ``(issuer, subject)``。"""
stable = require_stable_identity(identity)
return stable.issuer, stable.subject
@@ -0,0 +1,28 @@
"""
backend/app/services/auth/hxops/__init__.py
用途:导出依赖 HXOPS User、数据库和会话契约的认证编排能力。
依赖:user_resolver、session_token、login_service、casdoor_route_adapter、casdoor_authorize、casdoor_state、casdoor_user_sync。
逻辑:API 路由调用本包;平级服务不复制本目录。
"""
from .login_service import HxopsLoginService, LoginResult
from .casdoor_authorize import CasdoorAuthorizeOptions, build_casdoor_authorize_payload
from . import casdoor_route_adapter
from .casdoor_state import consume_casdoor_state, issue_casdoor_state
from . import casdoor_user_sync
from .session_token import issue_hxops_access_token
from .user_resolver import resolve_hxops_user
__all__ = [
'HxopsLoginService',
'LoginResult',
'casdoor_user_sync',
'CasdoorAuthorizeOptions',
'build_casdoor_authorize_payload',
'casdoor_route_adapter',
'consume_casdoor_state',
'issue_hxops_access_token',
'issue_casdoor_state',
'resolve_hxops_user',
]
@@ -0,0 +1,105 @@
"""
backend/app/services/auth/hxops/casdoor_authorize.py
用途:组装 HXOPS 跳转 Casdoor 的 OAuth 授权地址及其 state 响应。
依赖:Flask 配置、Casdoor OIDC discovery、Casdoor state 服务。
逻辑:路由传入可选参数,本模块选择默认值、处理企微 provider 规则并返回原有响应字段。
"""
from __future__ import annotations
from collections.abc import Callable, Mapping
from dataclasses import dataclass
from typing import Any
from urllib.parse import quote
from flask import current_app
from app.core.errors import AppError
from .casdoor_state import issue_casdoor_state
MetadataOperation = Callable[[], Mapping[str, Any]]
StateOperation = Callable[[str], str]
@dataclass(frozen=True)
class CasdoorAuthorizeOptions:
"""授权地址构造所需的浏览器可选参数,不包含任何 client_secret。"""
redirect_uri: str | None = None
provider_hint: str | None = None
default_provider: str | None = None
silent_signin: str | None = None
def _clean_text(value: object) -> str | None:
"""将 query/config 值归一为去空白字符串,空值统一为 None。"""
text = str(value or '').strip()
return text or None
def _is_truthy(value: object) -> bool:
"""识别现有接口支持的 1/true/yes 静默登录显式开关。"""
return (_clean_text(value) or '').lower() in {'1', 'true', 'yes'}
def build_casdoor_authorize_payload(
options: CasdoorAuthorizeOptions,
*,
oidc_metadata: MetadataOperation | None = None,
issue_state: StateOperation = issue_casdoor_state,
) -> dict[str, str]:
"""
依据 Casdoor discovery 与 HXOPS 配置构造授权地址,保持现有 response 字段和参数规则。
Args:
options: redirect_uri、provider_hint、default_provider 与 silent_signin 的可选浏览器输入。
oidc_metadata: 可选 discovery 读取函数,路由和测试可注入既有兼容代理。
issue_state: 可选 state 签发函数,供路由兼容 monkeypatch 与单元测试注入。
Returns:
包含 ``url``、``state`` 与 ``redirect_uri`` 的原有扁平响应 payload。
Raises:
AppError: Casdoor 授权端点或 client/redirect 配置缺失时保持既有 500 错误契约。
"""
metadata = (oidc_metadata or _flask_oidc_metadata)()
authorize_endpoint = _clean_text(metadata.get('authorization_endpoint'))
if not authorize_endpoint:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Casdoor authorization endpoint missing', http_status=500)
client_id = _clean_text(current_app.config.get('CASDOOR_CLIENT_ID'))
redirect_uri = _clean_text(options.redirect_uri) or _clean_text(current_app.config.get('CASDOOR_REDIRECT_URI'))
scope = _clean_text(current_app.config.get('CASDOOR_SCOPE')) or 'openid profile email'
if not client_id or not redirect_uri:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Casdoor client config is incomplete', http_status=500)
default_provider = (_clean_text(options.default_provider) or '').lower()
provider_hint = _clean_text(options.provider_hint)
if not provider_hint and default_provider == 'wecom':
provider_hint = _clean_text(current_app.config.get('CASDOOR_WECOM_PROVIDER_HINT'))
silent_signin = _is_truthy(options.silent_signin)
if not silent_signin and default_provider == 'wecom':
silent_signin = bool(current_app.config.get('CASDOOR_WECOM_SILENT_SIGNIN'))
state = issue_state(redirect_uri)
url = (
f'{authorize_endpoint}?client_id={quote(client_id, safe="")}'
f'&response_type=code&redirect_uri={quote(redirect_uri, safe="")}'
f'&scope={quote(scope, safe="")}&state={quote(state, safe="")}'
)
if provider_hint:
url += f'&provider_hint={quote(provider_hint, safe="")}'
if silent_signin:
url += '&silentSignin=1'
return {'url': url, 'state': state, 'redirect_uri': redirect_uri}
def _flask_oidc_metadata() -> Mapping[str, Any]:
"""读取当前 Flask 配置对应的 Casdoor discovery 文档,供默认服务调用。"""
from app.services.auth.casdoor import get_casdoor_client
return get_casdoor_client().oidc_metadata()
@@ -0,0 +1,92 @@
"""
backend/app/services/auth/hxops/casdoor_route_adapter.py
用途:集中 HXOPS Casdoor 路由所需的默认操作与登录服务装配。
依赖:CasdoorClient、授权地址/state 服务、HxopsLoginService。
逻辑:api/user 保留历史私有替换点,本模块提供其默认实现及可注入的登录编排工厂。
"""
from __future__ import annotations
from collections.abc import Callable, Mapping
from typing import Any
from app.services.auth.casdoor import get_casdoor_client
from .casdoor_authorize import CasdoorAuthorizeOptions, build_casdoor_authorize_payload
from .casdoor_state import consume_casdoor_state, issue_casdoor_state
from .login_service import HxopsLoginService, TokenOperation, UserinfoOperation
AuditOperation = Callable[..., None]
MetadataOperation = Callable[[], Mapping[str, Any]]
StateOperation = Callable[[str], str]
def get_oidc_metadata() -> dict[str, Any]:
"""读取当前 HXOPS Casdoor Application 对应的 OIDC discovery 文档。"""
return get_casdoor_client().oidc_metadata()
def password_login(username: str, password: str) -> dict[str, Any]:
"""以 HXOPS 自己的 Casdoor Application 执行 password grant。"""
return get_casdoor_client().password_login(username, password).as_dict()
def authorization_code_login(code: str, redirect_uri: str) -> dict[str, Any]:
"""以 HXOPS 自己的 Casdoor Application 兑换 authorization code。"""
return get_casdoor_client().authorization_code_login(code, redirect_uri).as_dict()
def refresh_token(refresh_token_value: str) -> dict[str, Any]:
"""使用 Casdoor refresh token 获取新的 Casdoor token 集合。"""
return get_casdoor_client().refresh(refresh_token_value).as_dict()
def userinfo(access_token: str) -> dict[str, Any]:
"""读取 Casdoor userinfo,供登录编排在缺少可信 ID token 时回退。"""
return get_casdoor_client().userinfo(access_token)
def build_authorize_payload(
options: CasdoorAuthorizeOptions,
*,
oidc_metadata: MetadataOperation | None = None,
issue_state: StateOperation | None = None,
) -> dict[str, str]:
"""构造原有 Casdoor authorize-url 响应,并允许路由兼容层注入测试替身。"""
return build_casdoor_authorize_payload(
options,
oidc_metadata=oidc_metadata or get_oidc_metadata,
issue_state=issue_state or issue_casdoor_state,
)
def create_login_service(
*,
write_login_audit: AuditOperation | None,
password_operation: TokenOperation | None = None,
code_operation: TokenOperation | None = None,
refresh_operation: TokenOperation | None = None,
userinfo_operation: UserinfoOperation | None = None,
) -> HxopsLoginService:
"""
组装 HXOPS 登录服务;路由可注入旧私有替换点以维持测试和渐进迁移兼容。
Args:
write_login_audit: HXOPS 登录审计写入函数。
password_operation: 可选 password grant 实现,默认使用本模块操作。
code_operation: 可选 authorization code grant 实现,默认使用本模块操作。
refresh_operation: 可选 refresh grant 实现,默认使用本模块操作。
userinfo_operation: 可选 userinfo 实现,默认使用本模块操作。
Returns:
已配置 Casdoor 操作和审计回调的 HxopsLoginService。
"""
return HxopsLoginService(
password_login=password_operation or password_login,
authorization_code_login=code_operation or authorization_code_login,
refresh_token=refresh_operation or refresh_token,
userinfo=userinfo_operation or userinfo,
write_login_audit=write_login_audit,
)
@@ -0,0 +1,103 @@
"""
backend/app/services/auth/hxops/casdoor_state.py
用途:签发和校验 Casdoor 授权码登录的无状态 HMAC state。
依赖:标准库、Flask 配置;不依赖数据库和 HXOPS User。
逻辑:授权地址签发固定格式 state,回调校验签名和有效期后恢复已绑定的 redirect_uri。
"""
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import time
import uuid
from typing import Callable
from flask import current_app
_STATE_PREFIX = 'hxops_casdoor_v1'
_STATE_TTL_SECONDS = 600
def issue_casdoor_state(
redirect_uri: str,
*,
secret: str | None = None,
now_timestamp: int | None = None,
nonce_factory: Callable[[], str] | None = None,
) -> str:
"""
签发绑定 callback redirect_uri 的短时 HMAC state,保持现有 state 格式不变。
Args:
redirect_uri: 已由调用方选择的 Casdoor 回调地址,原样写入签名 payload。
secret: 可选 HMAC 密钥,仅供测试或非 Flask 调用注入;默认使用 SECRET_KEY。
now_timestamp: 可选当前 Unix 秒数,用于确定性测试;默认读取系统时钟。
nonce_factory: 可选随机 nonce 生成器;默认生成 UUID4 hex。
Returns:
格式为 ``hxops_casdoor_v1.<payload>.<signature>`` 的 URL-safe state。
"""
now = int(time.time()) if now_timestamp is None else int(now_timestamp)
payload = {
'v': 1,
'exp': now + _STATE_TTL_SECONDS,
'nonce': (nonce_factory or (lambda: uuid.uuid4().hex))(),
'redirect_uri': redirect_uri,
}
payload_json = json.dumps(payload, separators=(',', ':'))
payload_b64 = base64.urlsafe_b64encode(payload_json.encode('utf-8')).decode('ascii').rstrip('=')
signing_secret = str(secret if secret is not None else current_app.config.get('SECRET_KEY') or '')
signature = hmac.new(signing_secret.encode('utf-8'), payload_b64.encode('ascii'), hashlib.sha256).digest()
signature_b64 = base64.urlsafe_b64encode(signature).decode('ascii').rstrip('=')
return f'{_STATE_PREFIX}.{payload_b64}.{signature_b64}'
def consume_casdoor_state(
state: str | None,
*,
secret: str | None = None,
now_timestamp: int | None = None,
) -> str | None:
"""
校验 Casdoor state 的版本、HMAC 签名和有效期,成功时返回其绑定的 redirect_uri。
Args:
state: Casdoor 回调带回的 state。
secret: 可选 HMAC 密钥,仅供测试或非 Flask 调用注入;默认使用 SECRET_KEY。
now_timestamp: 可选当前 Unix 秒数,用于确定性测试;默认读取系统时钟。
Returns:
已签名且未过期的 redirect_uri;任一校验失败时返回 None,调用方映射为既有验证错误。
"""
if not state:
return None
try:
prefix, payload_b64, signature_b64 = state.split('.')
if prefix != _STATE_PREFIX:
return None
signing_secret = str(secret if secret is not None else current_app.config.get('SECRET_KEY') or '')
expected_signature = hmac.new(
signing_secret.encode('utf-8'),
payload_b64.encode('ascii'),
hashlib.sha256,
).digest()
expected_b64 = base64.urlsafe_b64encode(expected_signature).decode('ascii').rstrip('=')
if not hmac.compare_digest(expected_b64, signature_b64):
return None
padded_payload = payload_b64 + '=' * (-len(payload_b64) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded_payload.encode('ascii')).decode('utf-8'))
if not isinstance(payload, dict) or payload.get('v') != 1:
return None
expires_at = int(payload.get('exp') or 0)
except (TypeError, ValueError, UnicodeDecodeError, json.JSONDecodeError):
return None
now = int(time.time()) if now_timestamp is None else int(now_timestamp)
if expires_at <= now:
return None
redirect_uri = payload.get('redirect_uri')
return str(redirect_uri).strip() or None
@@ -0,0 +1,325 @@
"""
backend/app/services/auth/hxops/casdoor_user_sync.py
用途:集中实现 HXOPS 用户创建和改密到 Casdoor 的管理端同步。
依赖:Flask 配置、requests、HXOPS User 模型、公共 Casdoor 错误解析。
逻辑:管理端事务调用本模块;HTTP 失败映射为稳定 AppError,由上层决定回滚。
"""
from __future__ import annotations
from typing import Any, Callable
import requests
from flask import current_app
from app.core.errors import AppError, ConflictError
from app.models import User
from app.services.auth.casdoor.errors import clean_str, extract_error_payload, is_password_error
AddUserOperation = Callable[[dict[str, Any]], None]
SetPasswordOperation = Callable[[str, str, str, str], None]
def is_casdoor_configured() -> bool:
"""检查用户同步所需的 organization、地址和客户端凭据是否齐全。"""
if not clean_str(current_app.config.get('CASDOOR_ORGANIZATION')):
return False
base = str(current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
return bool(base and client_id and client_secret)
def casdoor_user_owner() -> str:
"""返回 Casdoor organization owner,缺失时阻止构造无效用户请求。"""
owner = clean_str(current_app.config.get('CASDOOR_ORGANIZATION'))
if not owner:
raise RuntimeError('CASDOOR_ORGANIZATION is not configured')
return owner
def is_user_exists_error(message: str) -> bool:
"""判断 Casdoor 错误文本是否表示用户名或用户记录已存在。"""
lowered = (message or '').lower()
return 'already exist' in lowered or 'duplicate' in lowered or 'has existed' in lowered
def is_user_missing_error(message: str) -> bool:
"""判断 Casdoor 错误文本是否表示 IdP 中不存在目标用户。"""
lowered = (message or '').lower()
return (
"doesn't exist" in lowered
or 'does not exist' in lowered
or 'user not found' in lowered
or 'no such user' in lowered
)
def raise_user_not_in_idp(source=None) -> None:
"""将 IdP 缺失用户转换为稳定业务错误,避免上层解析供应商文本。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
raise AppError(
code='CASDOOR_USER_NOT_IN_IDP',
message='Your account has not been registered in the authentication system. Please contact the administrator.',
http_status=409,
details={'technical': msg_text or str(source or '')[:300]},
)
def raise_add_user_error(source) -> None:
"""将 Casdoor add-user 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_user_exists_error(lowered):
raise ConflictError(
'Username already exists in Casdoor',
code='USER.USERNAME_EXISTS',
details={'field': 'username', 'technical': msg_text},
)
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='Password does not meet security requirements', http_status=400)
raise AppError(
code='CASDOOR_ADD_USER_FAILED',
message='Failed to create user in authentication system. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source or '')[:300]},
)
def raise_update_user_error(source) -> None:
"""将 Casdoor update-user 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_user_missing_error(lowered):
raise_user_not_in_idp(source)
if is_user_exists_error(lowered) or ('email' in lowered and 'already' in lowered):
raise ConflictError(
'Email already exists in Casdoor',
code='USER.EMAIL_EXISTS',
details={'field': 'email', 'technical': msg_text},
)
raise AppError(
code='CASDOOR_UPDATE_USER_FAILED',
message='Failed to update user in authentication system. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source or '')[:300]},
)
def raise_set_password_error(source) -> None:
"""将 Casdoor set-password 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_password_error(lowered) or 'old password' in lowered or 'current password' in lowered:
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect current password', http_status=401)
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='New password does not meet security requirements', http_status=400)
if is_user_missing_error(lowered):
raise_user_not_in_idp(source)
raise AppError(
code='CASDOOR_SET_PASSWORD_FAILED',
message='Failed to change password. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source)[:300]},
)
def build_user_profile_payload(
*,
username: str,
email: str,
employee_id: str | None = None,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict[str, Any]:
"""组装 Casdoor 用户资料字段,并将 HXOPS 工号写入 Casdoor 自定义属性。"""
payload: dict[str, Any] = {
'owner': casdoor_user_owner(),
'name': username,
'email': email or '',
'displayName': clean_str(real_name) or username,
'realName': clean_str(real_name) or '',
'phone': clean_str(phone_number) or '',
'isForbidden': clean_str(status) not in (None, 'active'),
}
department_value = clean_str(department)
if department_value:
payload['affiliation'] = department_value
employee_id_value = clean_str(employee_id)
if employee_id_value:
# Casdoor 将扩展资料放入 properties;应用需将 employee_id 配置为 userinfo/ID token 可见。
payload['properties'] = {'employee_id': employee_id_value}
return payload
def build_user_payload(
*,
username: str,
password: str,
email: str,
employee_id: str | None = None,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict[str, Any]:
"""组装 Casdoor add-user 请求体,并只在创建场景附加明文密码。"""
payload = build_user_profile_payload(
username=username,
employee_id=employee_id,
email=email,
real_name=real_name,
phone_number=phone_number,
status=status,
department=department,
)
payload['password'] = password
return payload
def _management_config() -> tuple[str, str, str, int]:
"""读取 Casdoor 管理 API 配置,返回地址、凭据和 HTTP 超时。"""
base = str(current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = str(current_app.config.get('CASDOOR_CLIENT_ID') or '')
client_secret = str(current_app.config.get('CASDOOR_CLIENT_SECRET') or '')
timeout = max(1, int(current_app.config.get('CASDOOR_HTTP_TIMEOUT_SECONDS') or 8))
if not base or not client_id or not client_secret:
raise RuntimeError('Casdoor is not configured')
return base, client_id, client_secret, timeout
def casdoor_add_user(user_payload: dict[str, Any]) -> None:
"""调用 Casdoor `/api/add-user` 创建 IdP 用户。"""
base, client_id, client_secret, timeout = _management_config()
response = requests.post(
f'{base}/api/add-user',
json=user_payload,
auth=(client_id, client_secret),
timeout=timeout,
)
try:
data = response.json() or {}
except ValueError as exc:
raise RuntimeError(f'Casdoor add-user failed: HTTP {response.status_code} {response.text[:200]}') from exc
if data.get('status') != 'ok':
raise_add_user_error(data)
def casdoor_update_user(user_payload: dict[str, Any]) -> None:
"""调用 Casdoor `/api/update-user` 更新 IdP 用户资料。"""
base, client_id, client_secret, timeout = _management_config()
response = requests.post(
f'{base}/api/update-user',
json=user_payload,
auth=(client_id, client_secret),
timeout=timeout,
)
try:
data = response.json() or {}
except ValueError as exc:
raise RuntimeError(f'Casdoor update-user failed: HTTP {response.status_code} {response.text[:200]}') from exc
if data.get('status') != 'ok':
raise_update_user_error(data)
def casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str) -> None:
"""调用 Casdoor `/api/set-password` 修改或由管理员覆盖用户密码。"""
base, client_id, client_secret, timeout = _management_config()
response = requests.post(
f'{base}/api/set-password',
files={
'userOwner': (None, user_owner),
'userName': (None, user_name),
'oldPassword': (None, old_password),
'newPassword': (None, new_password),
},
auth=(client_id, client_secret),
timeout=timeout,
)
try:
data = response.json() or {}
except ValueError as exc:
raise RuntimeError(f'Casdoor set-password failed: HTTP {response.status_code} {response.text[:200]}') from exc
if data.get('status') != 'ok':
raise_set_password_error(data)
def sync_create_user(
*,
username: str,
password: str,
email: str,
employee_id: str | None = None,
real_name=None,
phone_number=None,
status='active',
department=None,
add_user: AddUserOperation | None = None,
) -> None:
"""管理端创建 HXOPS 用户时同步 Casdoor;未配置 IdP 时保持原有跳过行为。"""
if not is_casdoor_configured():
return
payload = build_user_payload(
username=username,
password=password,
employee_id=employee_id,
email=email,
real_name=real_name,
phone_number=phone_number,
status=status,
department=department,
)
(add_user or casdoor_add_user)(payload)
def sync_admin_set_password(
user: User,
new_password: str,
*,
set_password: SetPasswordOperation | None = None,
) -> None:
"""管理端无旧密码重设 Casdoor 密码,并将缺失用户转换为稳定错误。"""
if not is_casdoor_configured():
return
try:
(set_password or casdoor_set_password)(casdoor_user_owner(), user.username, '', new_password)
except RuntimeError as exc:
if is_user_missing_error(str(exc)):
raise_user_not_in_idp(exc)
raise_set_password_error(exc)
def sync_update_user(
user: User,
*,
new_password: str | None = None,
set_password: SetPasswordOperation | None = None,
add_user: AddUserOperation | None = None,
) -> None:
"""同步管理端改密;IdP 缺失账号时用新密码补建,资料编辑仍不主动同步。"""
if not is_casdoor_configured() or not new_password:
return
try:
sync_admin_set_password(user, new_password, set_password=set_password)
except AppError as exc:
if exc.code != 'CASDOOR_USER_NOT_IN_IDP':
raise
sync_create_user(
username=user.username,
password=new_password,
employee_id=user.employee_id,
email=user.email,
real_name=user.real_name,
phone_number=user.phone_number,
status=user.status,
department=user.department,
add_user=add_user,
)
@@ -0,0 +1,196 @@
"""
backend/app/services/auth/hxops/login_service.py
用途:统一编排 HXOPS 的 Casdoor 密码登录、授权码登录和刷新流程。
依赖:Casdoor token/identity 公共模块、HXOPS 用户映射、HXOPS API Token。
逻辑:Casdoor token -> claims -> AuthIdentity -> HXOPS User -> 本地 API JWT;路由仅负责参数和事务边界。
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Callable
from flask import current_app
from app.core.auth.jwt import _decode_jwt
from app.core.errors import AppError
from app.models import User
from app.services.auth.casdoor.client import CasdoorTokenResult
from app.services.auth.casdoor.identity import identity_from_claims
from app.services.auth.common import AuthIdentity, IdentityValidationError
from .session_token import issue_hxops_access_token
from .user_resolver import HxopsIdentityMappingError, resolve_hxops_user
TokenOperation = Callable[..., CasdoorTokenResult | dict[str, Any]]
UserinfoOperation = Callable[[str], dict[str, Any]]
AuditOperation = Callable[..., None]
@dataclass(frozen=True)
class LoginResult:
"""HXOPS 登录接口所需的用户、Token 和原响应有效期数据。"""
user: User
identity: AuthIdentity
access_token: str
refresh_token: str | None
id_token: str | None
token_type: str
expires_in: int
def login_payload(self) -> dict[str, Any]:
"""生成与现有 password/code 登录接口完全一致的扁平响应。"""
return {
'id': self.user.id,
'username': self.user.username,
'role': self.user.role,
'default_agent_id': self.user.default_agent_id,
'feature_permissions': self.user.get_feature_permissions(),
'source': 'casdoor',
'access_token': self.access_token,
'refresh_token': self.refresh_token,
'id_token': self.id_token,
'token_type': self.token_type,
'expires_in': self.expires_in,
}
def refresh_payload(self) -> dict[str, Any]:
"""生成与现有 refresh 接口完全一致的 Token 响应。"""
return {
'access_token': self.access_token,
'refresh_token': self.refresh_token,
'id_token': self.id_token,
'token_type': self.token_type,
'expires_in': self.expires_in,
}
def _normalize_token_result(source: CasdoorTokenResult | dict[str, Any]) -> CasdoorTokenResult:
"""兼容重构期间旧字典替身和新的 CasdoorTokenResult。"""
if isinstance(source, CasdoorTokenResult):
return source
data = dict(source or {})
access_token = str(data.get('access_token') or '')
if not access_token:
raise AppError(code='CASDOOR_AUTH_FAILED', message='Authentication failed, please try again', http_status=401)
return CasdoorTokenResult(
access_token=access_token,
refresh_token=str(data['refresh_token']) if data.get('refresh_token') else None,
id_token=str(data['id_token']) if data.get('id_token') else None,
token_type=str(data.get('token_type') or 'Bearer'),
expires_in=int(data.get('expires_in') or 3600),
raw=data,
)
class HxopsLoginService:
"""把公共 Casdoor 能力与 HXOPS 用户、审计和 API JWT 组合起来。"""
def __init__(
self,
*,
password_login: TokenOperation,
authorization_code_login: TokenOperation,
refresh_token: TokenOperation,
userinfo: UserinfoOperation,
write_login_audit: AuditOperation | None = None,
decode_id_token: Callable[[str], dict[str, Any]] = _decode_jwt,
):
"""
注入 Casdoor 操作和可选审计函数,便于路由兼容与单元测试。
Args:
password_login: 执行 password grant 的函数。
authorization_code_login: 执行 code grant 的函数。
refresh_token: 执行 refresh grant 的函数。
userinfo: 读取 Casdoor userinfo 的函数。
write_login_audit: HXOPS 登录审计函数;公共模块不感知请求对象。
decode_id_token: 现有 Casdoor JWKS 验证函数。
"""
self._password_login = password_login
self._authorization_code_login = authorization_code_login
self._refresh_token = refresh_token
self._userinfo = userinfo
self._write_login_audit = write_login_audit
self._decode_id_token = decode_id_token
def _identity_from_token(self, token: CasdoorTokenResult, *, prefer_id_token: bool) -> AuthIdentity:
"""优先验证 ID token,失败或缺失时回退 HTTPS userinfo。"""
claims: dict[str, Any] | None = None
if prefer_id_token and token.id_token:
try:
claims = self._decode_id_token(token.id_token)
except Exception:
claims = None
if claims is None:
claims = self._userinfo(token.access_token)
try:
return identity_from_claims(
claims,
expected_issuer=str(current_app.config.get('AUTH_JWT_ISSUER') or ''),
)
except IdentityValidationError as exc:
current_app.logger.warning(
'[casdoor_login] invalid stable identity reason=%s claim_keys=%s',
str(exc),
sorted(str(key) for key in claims.keys()),
)
raise AppError(
code='AUTH.CASDOOR_IDENTITY_INVALID',
message='Casdoor identity is missing issuer or subject',
http_status=401,
) from exc
def _complete_login(
self,
token_source: CasdoorTokenResult | dict[str, Any],
*,
prefer_id_token: bool,
fallback_refresh_token: str | None = None,
audit_success: bool = False,
) -> LoginResult:
"""完成身份解析、本地用户映射和 HXOPS API Token 签发。"""
token = _normalize_token_result(token_source)
identity = self._identity_from_token(token, prefer_id_token=prefer_id_token)
try:
user = resolve_hxops_user(identity)
except HxopsIdentityMappingError as exc:
raise AppError(code=exc.code, message=str(exc), http_status=exc.status) from exc
if audit_success and self._write_login_audit:
self._write_login_audit('casdoor', 'success', user=user)
return LoginResult(
user=user,
identity=identity,
access_token=issue_hxops_access_token(user, identity),
refresh_token=token.refresh_token or fallback_refresh_token,
id_token=token.id_token,
token_type=token.token_type,
expires_in=token.expires_in,
)
def password(self, username: str, password: str) -> LoginResult:
"""通过 Casdoor password grant 登录 HXOPS。"""
return self._complete_login(
self._password_login(username, password),
prefer_id_token=True,
audit_success=True,
)
def authorization_code(self, code: str, redirect_uri: str) -> LoginResult:
"""通过 Casdoor authorization code 登录 HXOPS。"""
return self._complete_login(
self._authorization_code_login(code, redirect_uri),
prefer_id_token=True,
audit_success=True,
)
def refresh(self, refresh_token: str) -> LoginResult:
"""刷新 Casdoor token 后重新确认身份并签发 HXOPS API JWT。"""
return self._complete_login(
self._refresh_token(refresh_token),
prefer_id_token=False,
fallback_refresh_token=refresh_token,
)
@@ -0,0 +1,31 @@
"""
backend/app/services/auth/hxops/session_token.py
用途:为 HXOPS 本地 API 签发包含 Casdoor 稳定身份引用的会话 JWT。
依赖:User、AuthIdentity、app.core.auth.jwt 现有签发函数。
逻辑:保留现有 HS256 claims 和有效期;只调整调用边界,不改变 Token 契约。
"""
from __future__ import annotations
from app.core.auth.jwt import issue_local_access_token
from app.models import User
from app.services.auth.common import AuthIdentity
def issue_hxops_access_token(user: User, identity: AuthIdentity | None = None) -> str:
"""
签发 HXOPS API 会话 JWT,保持重构前 claims 完全兼容。
Args:
user: 已映射并检查 active 的 HXOPS 用户。
identity: 可选 Casdoor 稳定身份;存在时写入 casdoor_iss/casdoor_sub。
Returns:
由 HXOPS SECRET_KEY 签名的本站 Bearer Token。
"""
return issue_local_access_token(
user,
casdoor_issuer=identity.issuer if identity else None,
casdoor_subject=identity.subject if identity else None,
)
@@ -0,0 +1,84 @@
"""
backend/app/services/auth/hxops/user_resolver.py
用途:将统一 AuthIdentity 按工号映射为 HXOPS 本地 User。
依赖:Flask 日志、SQLAlchemy session、User、AuthIdentity。
逻辑:Casdoor 工号优先;用户名作为当前“用户名即工号”的过渡兼容,不使用邮箱或手机号。
"""
from __future__ import annotations
from flask import current_app
from app.extensions import db
from app.models import User
from app.services.auth.common import AuthIdentity
class HxopsIdentityMappingError(Exception):
"""HXOPS 本地用户无法映射或状态不允许登录。"""
def __init__(self, message: str, *, code: str, status: int):
super().__init__(message)
self.code = code
self.status = status
def resolve_hxops_user(identity: AuthIdentity) -> User:
"""
按工号优先规则将认证身份映射到 HXOPS 用户。
核心逻辑:优先使用 Casdoor employee_id;若其缺失,则将当前用户名作为工号
查找本地 employee_id,最后才按 username 兼容历史数据。邮箱和手机号不参与认证
匹配。若工号与用户名分别命中不同用户,拒绝登录以防错误账号关联。
Args:
identity: 已验证 Casdoor issuer/subject 的统一身份;employee_id 是首选匹配键。
Returns:
状态为 active 的 HXOPS User。
Raises:
HxopsIdentityMappingError: 用户未同步、身份字段冲突或账号已禁用。
"""
current_app.logger.info(
'[casdoor_login] identity employee_id=%s username=%s subject=%s',
identity.employee_id,
identity.username,
identity.subject,
)
# [STEP 1] 工号是当前产品用户的主映射键;Casdoor 未提供时用户名即工号。
employee_id = str(identity.employee_id or identity.username or '').strip()
employee_user = None
if employee_id:
employee_user = db.session.query(User).filter_by(employee_id=employee_id).first()
# [STEP 2] username 仅保留给尚未补齐 employee_id 的历史本地账号。
username_user = db.session.query(User).filter_by(username=identity.username).first()
if employee_user is not None and username_user is not None and employee_user.id != username_user.id:
current_app.logger.warning(
'[casdoor_login] identity_mapping_conflict employee_id=%s employee_user_id=%s '
'username=%s username_user_id=%s subject=%s',
employee_id,
employee_user.id,
identity.username,
username_user.id,
identity.subject,
)
raise HxopsIdentityMappingError(
'Casdoor employee ID and username map to different local accounts. Please contact admin.',
code='CASDOOR_IDENTITY_CONFLICT',
status=403,
)
user = employee_user or username_user
if user is None:
raise HxopsIdentityMappingError(
'No local user matched Casdoor identity. Please contact admin to provision account.',
code='CASDOOR_USER_NOT_FOUND',
status=403,
)
if user.status != 'active':
raise HxopsIdentityMappingError('Account is disabled', code='ACCOUNT_DISABLED', status=403)
return user
+18
View File
@@ -0,0 +1,18 @@
"""
backend/app/services/auth/sso/__init__.py
Purpose: Export the reusable HXOPS-to-peer-service SSO signing surface.
Dependencies: application registry and assertion signing modules.
Flow: API routes import this package; peer services consume the documented assertion/JWKS contract.
"""
from .application_registry import SsoApplication, get_application, list_applications
from .assertion_service import build_jwks, issue_assertion
__all__ = [
'SsoApplication',
'build_jwks',
'get_application',
'issue_assertion',
'list_applications',
]
@@ -0,0 +1,149 @@
"""
backend/app/services/auth/sso/application_registry.py
Purpose: Parse and validate peer services allowed to receive HXOPS SSO assertions.
Dependencies: Flask configuration, JSON, URL parsing, and AppError.
Flow: Assertion routes resolve app metadata here so browser-provided callback URLs are never trusted.
"""
from __future__ import annotations
import json
import re
from dataclasses import dataclass
from urllib.parse import urlparse
from flask import current_app
from app.core.errors import AppError, NotFoundError
_APP_KEY_RE = re.compile(r'^[a-z0-9][a-z0-9_-]{1,63}$')
@dataclass(frozen=True)
class SsoApplication:
"""Registered peer-service metadata safe for server-controlled SSO routing."""
key: str
display_name: str
login_url: str
callback_url: str
audience: str
enabled: bool = True
def public_payload(self) -> dict[str, str]:
"""Return fields safe for authenticated HXOPS navigation components."""
return {
'key': self.key,
'display_name': self.display_name,
'login_url': self.login_url,
}
def _validate_http_url(value: str, *, field: str) -> str:
"""
Validate an application URL from server configuration.
Args:
value: Absolute browser or callback URL.
field: Configuration field name used in diagnostics.
Returns:
Normalized URL without surrounding whitespace.
Raises:
AppError: URL is missing, malformed, or uses HTTP outside development/testing.
"""
normalized = str(value or '').strip()
parsed = urlparse(normalized)
if parsed.scheme not in {'http', 'https'} or not parsed.netloc:
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message=f'Invalid SSO application {field}',
http_status=503,
)
env_name = str(current_app.config.get('ENV_NAME') or current_app.config.get('FLASK_ENV') or '').lower()
if parsed.scheme != 'https' and env_name not in {'dev', 'development', 'test', 'testing'}:
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message=f'SSO application {field} must use HTTPS',
http_status=503,
)
return normalized
def list_applications() -> list[SsoApplication]:
"""
Parse the enabled SSO application registry from ``SSO_APPS_JSON``.
Returns:
Valid enabled application definitions.
Raises:
AppError: Configuration is invalid. Fail closed to avoid open redirects.
"""
if not bool(current_app.config.get('SSO_ENABLED', False)):
return []
raw = current_app.config.get('SSO_APPS_JSON') or '[]'
try:
items = json.loads(raw) if isinstance(raw, str) else raw
except (TypeError, ValueError) as exc:
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message='SSO application registry is invalid',
http_status=503,
) from exc
if not isinstance(items, list):
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message='SSO application registry must be a JSON array',
http_status=503,
)
applications: list[SsoApplication] = []
seen_keys: set[str] = set()
seen_audiences: set[str] = set()
for item in items:
if not isinstance(item, dict) or not bool(item.get('enabled', True)):
continue
key = str(item.get('key') or '').strip().lower()
audience = str(item.get('audience') or key).strip()
display_name = str(item.get('display_name') or key).strip()
if (
not _APP_KEY_RE.fullmatch(key)
or not _APP_KEY_RE.fullmatch(audience.lower())
or audience != audience.lower()
or not display_name
):
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message='SSO application identity configuration is incomplete',
http_status=503,
)
if key in seen_keys or audience in seen_audiences:
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message='SSO application keys and audiences must be unique',
http_status=503,
)
applications.append(SsoApplication(
key=key,
display_name=display_name,
login_url=_validate_http_url(item.get('login_url'), field='login_url'),
callback_url=_validate_http_url(item.get('callback_url'), field='callback_url'),
audience=audience,
enabled=True,
))
seen_keys.add(key)
seen_audiences.add(audience)
return applications
def get_application(app_key: str) -> SsoApplication:
"""Resolve one enabled application by its server-controlled key."""
normalized = str(app_key or '').strip().lower()
for application in list_applications():
if application.key == normalized:
return application
raise NotFoundError('SSO application not found', code='AUTH.SSO_APP_NOT_FOUND')
@@ -0,0 +1,265 @@
"""
backend/app/services/auth/sso/assertion_service.py
Purpose: Sign peer-service-specific short-lived login assertions and publish their verification key.
Dependencies: application registry, PyJWT, cryptography, Flask configuration, and User.
Flow: The SSO API authenticates an HXOPS user, this module signs an audience-bound JWT, and peers verify it through JWKS.
"""
from __future__ import annotations
import base64
import json
import secrets
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
import jwt
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from flask import current_app
from app.core.errors import AppError, ValidationError
from app.models import User
from app.services.auth.casdoor.identity import identity_from_claims
from app.services.auth.common import IdentityValidationError
from .application_registry import get_application
def _config_error(message: str) -> AppError:
"""Build a fail-closed SSO configuration error without leaking key material."""
return AppError(code='AUTH.SSO_CONFIG_ERROR', message=message, http_status=503)
def _read_signing_key() -> rsa.RSAPrivateKey:
"""
Load the configured RSA private key used only for product SSO assertions.
Returns:
Parsed RSA private key.
Raises:
AppError: The path is absent, unreadable, invalid, or not an RSA private key.
"""
raw_path = str(current_app.config.get('SSO_PRIVATE_KEY_PATH') or '').strip()
if not raw_path:
raise _config_error('SSO signing private key is not configured')
try:
key_bytes = Path(raw_path).read_bytes()
private_key = serialization.load_pem_private_key(key_bytes, password=None)
except (OSError, ValueError, TypeError) as exc:
raise _config_error('SSO signing private key cannot be loaded') from exc
if not isinstance(private_key, rsa.RSAPrivateKey):
raise _config_error('SSO signing key must be an RSA private key')
return private_key
def _issuer() -> str:
"""Return the configured absolute SSO issuer after environment-aware URL validation."""
issuer = str(current_app.config.get('SSO_ISSUER') or '').strip().rstrip('/')
parsed = urlparse(issuer)
if parsed.scheme not in {'http', 'https'} or not parsed.netloc:
raise _config_error('SSO issuer must be an absolute URL')
env_name = str(current_app.config.get('ENV_NAME') or current_app.config.get('FLASK_ENV') or '').lower()
if parsed.scheme != 'https' and env_name not in {'dev', 'development', 'test', 'testing'}:
raise _config_error('SSO issuer must use HTTPS')
return issuer
def _ttl_seconds() -> int:
"""Validate the short assertion lifetime; values outside 10-60 seconds fail closed."""
try:
ttl_seconds = int(current_app.config.get('SSO_ASSERTION_TTL_SECONDS') or 60)
except (TypeError, ValueError) as exc:
raise _config_error('SSO assertion TTL is invalid') from exc
if ttl_seconds < 10 or ttl_seconds > 60:
raise _config_error('SSO assertion TTL must be between 10 and 60 seconds')
return ttl_seconds
def _algorithm() -> str:
"""Enforce the single supported asymmetric signing algorithm and reject downgrade configuration."""
algorithm = str(current_app.config.get('SSO_SIGNING_ALGORITHM') or 'RS256').strip().upper()
if algorithm != 'RS256':
raise _config_error('SSO signing algorithm must be RS256')
return algorithm
def _key_id() -> str:
"""Return the stable public key identifier embedded in JWT and JWKS metadata."""
key_id = str(current_app.config.get('SSO_SIGNING_KEY_ID') or '').strip()
if not key_id or len(key_id) > 128:
raise _config_error('SSO signing key ID is not configured')
return key_id
def _identity_claims(user: User, claims: dict[str, Any]) -> dict[str, Any]:
"""
Build the portable Casdoor identity claims without HXOPS business permissions.
Args:
user: Active HXOPS user mapped from the authenticated Casdoor identity.
claims: Verified HXOPS API JWT claims containing ``casdoor_iss/casdoor_sub``.
Returns:
Stable identity plus mutable display attributes safe for peer-service user mapping.
"""
expected_issuer = str(current_app.config.get('AUTH_JWT_ISSUER') or '').strip()
try:
identity = identity_from_claims({
'iss': claims.get('casdoor_iss'),
'sub': claims.get('casdoor_sub'),
'preferred_username': user.username,
'name': user.real_name or user.username,
'email': user.email,
'phone_number': user.phone_number,
'employee_id': user.employee_id,
'department': user.department,
}, expected_issuer=expected_issuer)
except IdentityValidationError as exc:
raise AppError(
code='AUTH.SSO_IDENTITY_UNSUPPORTED',
message='Current login is not backed by a Casdoor identity',
http_status=403,
) from exc
return {
'sub': identity.subject,
'identity_issuer': identity.issuer,
'preferred_username': identity.username,
'name': identity.display_name,
'email': identity.email,
'phone_number': identity.phone_number,
'employee_id': identity.employee_id,
'department': identity.department,
}
def issue_assertion(*, app_key: str, user: User, claims: dict[str, Any], state: Any) -> dict[str, Any]:
"""
Sign a peer-service-specific login assertion for an active HXOPS user.
Args:
app_key: Server-registered target service key.
user: Current active HXOPS user.
claims: Verified HXOPS API JWT claims with Casdoor identity references.
state: Opaque signed state created by the peer service and returned unchanged.
Returns:
Registered callback URL, RS256 assertion, original state, and expiry seconds.
"""
if user.status != 'active':
raise AppError(code='AUTH.ACCOUNT_DISABLED', message='Account is disabled', http_status=403)
normalized_state = str(state or '').strip()
if not normalized_state or len(normalized_state) > 4096:
raise ValidationError('state is required and must not exceed 4096 characters')
application = get_application(app_key)
ttl_seconds = _ttl_seconds()
now = datetime.now(timezone.utc)
payload = {
'iss': _issuer(),
'aud': application.audience,
**_identity_claims(user, claims),
'iat': int(now.timestamp()),
'nbf': int((now - timedelta(seconds=5)).timestamp()),
'exp': int((now + timedelta(seconds=ttl_seconds)).timestamp()),
'jti': secrets.token_urlsafe(24),
}
try:
assertion = jwt.encode(
payload,
_read_signing_key(),
algorithm=_algorithm(),
headers={'kid': _key_id(), 'typ': 'JWT'},
)
except AppError:
raise
except Exception as exc:
current_app.logger.exception('[sso] failed to sign assertion app=%s', application.key)
raise AppError(
code='AUTH.SSO_ASSERTION_ISSUE_FAILED',
message='Failed to issue an SSO assertion',
http_status=503,
retryable=True,
) from exc
current_app.logger.info(
'[sso] assertion issued app=%s user_id=%s subject=%s ttl=%s',
application.key,
user.id,
payload['sub'],
ttl_seconds,
)
return {
'post_url': application.callback_url,
'assertion': assertion,
'state': normalized_state,
'expires_in': ttl_seconds,
}
def _base64url_uint(value: int) -> str:
"""Encode an RSA integer using the unpadded base64url form required by JWK."""
raw = value.to_bytes(max(1, (value.bit_length() + 7) // 8), 'big')
return base64.urlsafe_b64encode(raw).rstrip(b'=').decode('ascii')
def _public_jwk(public_key: rsa.RSAPublicKey, *, key_id: str) -> dict[str, str]:
"""Convert one trusted RSA public key to the minimal signing JWK contract."""
numbers = public_key.public_numbers()
return {
'kty': 'RSA',
'kid': key_id,
'use': 'sig',
'alg': _algorithm(),
'n': _base64url_uint(numbers.n),
'e': _base64url_uint(numbers.e),
}
def _additional_public_jwks(active_key_id: str) -> list[dict[str, str]]:
"""
Load verification-only public keys retained during a signing-key rotation window.
Returns:
Additional JWK entries configured as ``[{"kid", "public_key_path"}]``.
Raises:
AppError: JSON, key IDs, paths, or public key material are invalid.
"""
raw = current_app.config.get('SSO_ADDITIONAL_PUBLIC_KEYS_JSON') or '[]'
try:
items = json.loads(raw) if isinstance(raw, str) else raw
except (TypeError, ValueError) as exc:
raise _config_error('Additional SSO public keys configuration is invalid') from exc
if not isinstance(items, list):
raise _config_error('Additional SSO public keys must be a JSON array')
jwks: list[dict[str, str]] = []
seen_key_ids = {active_key_id}
for item in items:
if not isinstance(item, dict):
raise _config_error('Additional SSO public key entry is invalid')
key_id = str(item.get('kid') or '').strip()
path = str(item.get('public_key_path') or '').strip()
if not key_id or len(key_id) > 128 or not path or key_id in seen_key_ids:
raise _config_error('Additional SSO public key identity is invalid or duplicated')
try:
public_key = serialization.load_pem_public_key(Path(path).read_bytes())
except (OSError, ValueError, TypeError) as exc:
raise _config_error('Additional SSO public key cannot be loaded') from exc
if not isinstance(public_key, rsa.RSAPublicKey):
raise _config_error('Additional SSO public key must be RSA')
jwks.append(_public_jwk(public_key, key_id=key_id))
seen_key_ids.add(key_id)
return jwks
def build_jwks() -> dict[str, list[dict[str, str]]]:
"""Build JWKS with the active signing key plus verification-only rotation keys."""
active_key_id = _key_id()
active_jwk = _public_jwk(_read_signing_key().public_key(), key_id=active_key_id)
return {'keys': [active_jwk, *_additional_public_jwks(active_key_id)]}
@@ -560,12 +560,40 @@
"type": "string",
"nullable": true,
"description": "HXOPS 会话 ID;可与 sys.conversation_id 二选一,优先显式传入"
},
"mode": {
"type": "string",
"nullable": true,
"enum": ["incremental", "force_all", "single"],
"description": "【Dify 推荐】运行模式(立账凭证检核读取;文件检核忽略)。incremental=增量 / force_all=全量 / single=单发票;单发票时须同时填 invoice_no"
},
"invoice_no": {
"type": "string",
"nullable": true,
"description": "【Dify 推荐】mode=single 时必填的发票号;来自意图识别.invoice_no"
},
"run_options": {
"type": "object",
"nullable": true,
"description": "可选嵌套写法(部分 Dify 版本不展示对象字段;优先用顶层 mode/invoice_no)。mode=incremental|force_all|single;single 时须带 invoice_no",
"properties": {
"mode": {
"type": "string",
"enum": ["incremental", "force_all", "single"],
"default": "incremental"
},
"invoice_no": {
"type": "string",
"nullable": true,
"description": "mode=single 时必填的发票号"
}
}
}
},
"required": [
"task_id"
],
"description": "Chatflow Tool 节点绑定 task_id(Integer,来源 解析运行态上下文.task_id_int)、hxops_turn_id(经 agent_runtime_context 解析后传入);user_message 用于展示与兼容兜底"
"description": "Chatflow Tool 节点绑定 task_id(Integer,来源 解析运行态上下文.task_id_int)、hxops_turn_id(经 agent_runtime_context 解析后传入);立账凭证检核用顶层 mode/invoice_no(Dify 友好)或嵌套 run_options"
},
"RunCheckSuccessResponse": {
"type": "object",
+15 -6
View File
@@ -59,7 +59,7 @@ class HRLeaveSQLServerService:
_PERSON_NAME_PATTERNS = (
r"(?:查询|查下|查一下|帮我查|帮忙查|看看|核对|想知道|统计).{0,4}(?P<name>[\u4e00-\u9fa5]{2,4})(?:的)?(?:年假|育儿假|假期|休假)",
r"(?P<name>[\u4e00-\u9fa5]{2,4})(?:的)?(?:年假|育儿假|假期|休假).{0,8}(?:还剩|还有|剩余|可休|已休|未休|多少|情况|记录|明细|查询)",
r"(?P<name>[\u4e00-\u9fa5]{2,4}).{0,6}(?:还剩|还有|剩余|可休|已休|未休|多少).{0,6}(?:年假|育儿假|假期|休假)",
r"(?P<name>[\u4e00-\u9fa5]{2,4}?).{0,6}(?:还剩|还有|剩余|可休|已休|未休|多少).{0,6}(?:年假|育儿假|假期|休假)",
)
_PERSON_NAME_STOPWORDS = {
"我的",
@@ -92,6 +92,10 @@ class HRLeaveSQLServerService:
"部门",
}
_OTHER_PERSON_QUERY_MESSAGE = "暂时不支持查询其他人假期"
_SALARY_CONSULTATION_PATTERN = re.compile(
r"(?:请假|休假|年假|事假|病假).{0,12}(?:薪资|工资|薪酬|扣薪|扣钱|扣款|扣除|多少钱|福利|计算|公式)"
r"|(?:薪资|工资|薪酬|扣薪|扣钱|扣款|扣除|多少钱|福利|计算公式).{0,12}(?:请假|休假|年假|事假|病假)"
)
@classmethod
def supports(cls, query: str) -> bool:
@@ -104,6 +108,10 @@ class HRLeaveSQLServerService:
text = (query or "").strip()
if not text:
return False
# [STEP 1] 薪资/扣款是制度计算问答,必须交给 FAQ/Dify,不能进入个人假期余额 SQL。
# [PROMPT_UPDATE] 公式、适用条件和计薪口径由知识库原文负责,后端只做路由保护。
if cls._SALARY_CONSULTATION_PATTERN.search(text):
return False
if not any(keyword in text for keyword in cls._LEAVE_KEYWORDS):
return False
if any(keyword in text for keyword in cls._PROCESS_KEYWORDS):
@@ -129,10 +137,10 @@ class HRLeaveSQLServerService:
text = (query or "").strip()
if not text:
return False
if any(keyword in text for keyword in cls._SELF_KEYWORDS):
return False
if any(re.search(pattern, text) for pattern in cls._OTHER_PERSON_PRONOUN_PATTERNS):
return True
if any(keyword in text for keyword in cls._SELF_KEYWORDS):
return False
return bool(cls._extract_candidate_person_names(text))
@classmethod
@@ -170,10 +178,10 @@ class HRLeaveSQLServerService:
text = (query or "").strip()
if not text:
return False
if any(keyword in text for keyword in cls._SELF_KEYWORDS):
return False
if any(re.search(pattern, text) for pattern in cls._OTHER_PERSON_PRONOUN_PATTERNS):
return True
if any(keyword in text for keyword in cls._SELF_KEYWORDS):
return False
self_identifiers = {
str(getattr(user, "real_name", None) or "").strip(),
str(getattr(user, "username", None) or "").strip(),
@@ -181,7 +189,8 @@ class HRLeaveSQLServerService:
}
self_identifiers = {value for value in self_identifiers if value}
for candidate in cls._extract_candidate_person_names(text):
if candidate not in self_identifiers:
normalized_candidate = candidate.rstrip("的")
if normalized_candidate not in self_identifiers:
return True
return False
+48 -4
View File
@@ -1,5 +1,9 @@
"""
Integration API client for resolving original source-file download links.
backend/app/services/integration_api.py
用途:解析 Dify dataset/document 对应的源文件下载链接(本地 KB 映射 + Dify 签名 URL 兜底)。
依赖:Flask request/current_app、requests、Kb* 模型。
逻辑:chat.resolve_source_file / 预览代理调用本服务;本地无可读文件时回退 Dify download。
"""
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional, Tuple
@@ -223,8 +227,14 @@ class IntegrationApiService:
@staticmethod
def _lookup_local_db(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
"""
从本地 KbDifySyncRecord 反查可预览下载链接。
核心逻辑:优先返回磁盘上存在的源文件;缺失时回退清洗 Markdown;
两者皆无则返回 None,让上层继续走 Dify 签名下载兜底。
"""
if not has_app_context():
return None
from pathlib import Path
from app import db
from app.models import KbDifySyncRecord, KbDocumentVersion, KbDocument
@@ -251,6 +261,30 @@ class IntegrationApiService:
version = record.document_version
document = version.document
def _existing(path_value: str | None):
if not path_value:
return None
raw = Path(str(path_value))
root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve()
candidate = (raw if raw.is_absolute() else (root / raw)).resolve()
try:
candidate.relative_to(root)
except ValueError:
return None
if candidate.exists() and candidate.is_file():
return candidate
return None
source_path = _existing(version.source_file_path)
markdown_path = _existing(version.cleaned_file_path) or _existing(version.cleaned_preview_path)
if source_path is None and markdown_path is None:
current_app.logger.info(
'[integration-lookup] local mapping found but no readable file document_id=%s version_id=%s',
document.id,
version.id,
)
return None
base_url = IntegrationApiService._request_origin_url()
if not base_url:
explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/')
@@ -276,15 +310,25 @@ class IntegrationApiService:
}
token = jwt.encode(payload, secret, algorithm='HS256')
if source_path is not None:
kind = 'source'
source_filename = version.source_file_name
source_ext = version.source_file_ext
else:
kind = 'md'
stem = Path(str(version.source_file_name or document.title or f'document-{document.id}')).stem
source_filename = f'{stem}.md'
source_ext = 'md'
source_download_url = (
f'{base_url}/api/integration/files/{document.id}/download'
f'?kind=source&version_id={version.id}&token={token}'
f'?kind={kind}&version_id={version.id}&token={token}'
)
return {
"source_download_url": source_download_url,
"source_filename": version.source_file_name,
"source_ext": version.source_file_ext,
"source_filename": source_filename,
"source_ext": source_ext,
"download_url_expires_at": None,
"version_id": version.id,
"document_id": document.id,
@@ -0,0 +1,44 @@
"""
backend/app/services/integration_tool_auth.py
用途:Dify / 集成方 HTTP Tool API 共用鉴权(Bearer 或 X-Integration-Key)。
依赖:Flask current_app、core.errors。
逻辑:file-check / accounting-voucher-check 等 Tool Blueprint before_request 调用;
密钥优先 FILE_CHECK_TOOL_API_KEY,回退 INTEGRATION_API_KEY。
"""
from __future__ import annotations
from flask import current_app, request
from app.core.errors import ServiceUnavailableError, UnauthorizedError
def require_integration_tool_auth() -> None:
"""
校验 Tool API 访问权限。
核心逻辑:Authorization Bearer 与 X-Integration-Key 二选一,值须与配置密钥完全一致。
Raises:
ServiceUnavailableError: 服务端未配置密钥。
UnauthorizedError: 缺少或错误的凭证。
"""
configured = str(
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
or current_app.config.get("INTEGRATION_API_KEY")
or ""
).strip()
if not configured:
raise ServiceUnavailableError(
"FILE_CHECK_TOOL_API_KEY or INTEGRATION_API_KEY is not configured",
code="missing_auth",
)
bearer = str(request.headers.get("Authorization") or "").strip()
api_token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
if configured in {api_token, integration_key}:
return
if not api_token and not integration_key:
raise UnauthorizedError("missing_auth")
raise UnauthorizedError("invalid_auth")
@@ -7,6 +7,7 @@ from __future__ import annotations
from datetime import datetime
import hashlib
import re
import time
from pathlib import Path
import requests
@@ -19,6 +20,8 @@ from app.services.knowledge_cleaning.settings_service import get_kb_dify_setting
_EXCEL_SOURCE_EXTENSIONS = frozenset({'xlsx', 'xls', 'csv'})
_DIFY_INDEXING_SUCCEEDED = frozenset({'completed', 'completed_successfully', 'succeeded', 'success'})
_DIFY_INDEXING_FAILED = frozenset({'error', 'failed', 'failure'})
def _decode_separator(value: str) -> str:
@@ -65,6 +68,9 @@ class KbDifySyncService:
self.segment_chunk_overlap = int(str(settings.get('KB_DIFY_SEGMENT_CHUNK_OVERLAP') or '50'))
self.remove_urls_emails = _as_bool_setting(settings.get('KB_DIFY_REMOVE_URLS'))
self.timeout = 60
# Dify create/update 仅表示已接收文本,索引仍在后台异步执行。
self.indexing_wait_seconds = 60
self.indexing_poll_seconds = 2
def _build_process_rule(self, source_ext: str | None = None) -> dict:
ext = str(source_ext or '').strip().lower().lstrip('.')
@@ -137,9 +143,9 @@ class KbDifySyncService:
'retrieval_model': {
'search_method': self.search_method,
'reranking_enable': False,
'top_k': 3,
'score_threshold_enabled': False,
'score_threshold': None,
'top_k': 5,
'score_threshold_enabled': True,
'score_threshold': 0.25,
},
}
return self._request('POST', '/datasets', json=payload)
@@ -243,6 +249,54 @@ class KbDifySyncService:
def get_document(self, *, dataset_id: str, document_id: str) -> dict:
return self._request('GET', f'/datasets/{dataset_id}/documents/{document_id}')
def wait_for_document_indexing(
self,
*,
dataset_id: str,
document_id: str,
initial_payload: dict | None = None,
) -> dict:
"""
确认 Dify 异步索引的最终结果,禁止把“已受理”当作“已可检索”。
核心逻辑:读取创建/更新响应或文档详情中的 indexing_status,直到 completed 或 error。
超时也按失败处理,避免工作台把仍未可检索的文件标为同步成功。
Args:
dataset_id: Dify Dataset ID,不能为空。
document_id: Dify 文档 ID,不能为空。
initial_payload: create/update 接口的原始响应,可减少一次详情请求。
Returns:
含 indexing_status 和 Dify 文档详情的字典。
Raises:
KbDifySyncError: Dify 索引失败、状态缺失或在限定时间内未完成。
"""
if not dataset_id or not document_id:
raise KbDifySyncError('Dify 文档索引校验缺少 dataset_id 或 document_id')
payload = initial_payload or {}
deadline = time.monotonic() + self.indexing_wait_seconds
last_status = ''
while True:
document = payload.get('document') if isinstance(payload, dict) else None
document = document if isinstance(document, dict) else payload
document = document if isinstance(document, dict) else {}
status = str(document.get('indexing_status') or '').strip().lower()
error = str(document.get('error') or document.get('error_message') or '').strip()
last_status = status or last_status
if status in _DIFY_INDEXING_SUCCEEDED:
return {'indexing_status': status, 'document': document}
if status in _DIFY_INDEXING_FAILED:
raise KbDifySyncError(error or f'Dify 文档索引失败(状态:{status})')
if time.monotonic() >= deadline:
raise KbDifySyncError(
f'Dify 文档索引未在 {self.indexing_wait_seconds} 秒内完成(当前状态:{last_status or "unknown"}),请在 Dify 查看文档错误后重试'
)
time.sleep(self.indexing_poll_seconds)
payload = self.get_document(dataset_id=dataset_id, document_id=document_id)
def delete_document(self, *, dataset_id: str, document_id: str) -> None:
self._request(
'DELETE',
@@ -274,9 +328,30 @@ def _load_sync_text(version: KbDocumentVersion) -> tuple[str, str]:
def _is_remote_document_missing(error_text: str) -> bool:
"""
判断同步记录指向的 Dify 远端文档是否已失效。
Dify 在不同版本中会对已删除或不可访问的文档返回 404/not_found,
也可能返回 400 invalid_param 和 ``Document is not available``。两种结果都表示
不能继续 update-by-text,调用方必须新建远端文档并刷新本地映射。
Args:
error_text: Dify HTTP 异常转换后的完整错误文本。
Returns:
远端文档已失效时返回 True;其他 API 错误返回 False,避免掩盖配置或网络问题。
"""
normalized_error = str(error_text or '').lower()
return (
'404' in error_text
and ('Document not found' in error_text or '"code":"not_found"' in error_text)
('404' in normalized_error and (
'document not found' in normalized_error
or '"code":"not_found"' in normalized_error
))
or (
'400' in normalized_error
and '"code":"invalid_param"' in normalized_error
and 'document is not available' in normalized_error
)
)
@@ -290,7 +365,90 @@ def _resolve_upload_name(version: KbDocumentVersion) -> str:
return f'文档-{version.document_id}'
def _save_sync_record(
*,
version: KbDocumentVersion,
dataset_id: str,
dataset_name: str,
remote_document_id: str,
remote_document_name: str | None,
sync_hash: str,
synced_by_id: int | None,
status: str,
error_message: str | None,
) -> KbDifySyncRecord:
"""
持久化本地到 Dify 的映射及最终索引结果。
核心逻辑:同一版本和远端文档复用记录;成功与失败均保存,
让工作台能展示 Dify 的真实索引状态和原因。
Args:
version: 已上传且归属有效分组的文档版本。
dataset_id: Dify Dataset ID。
remote_document_id: Dify 文档 ID。
status: 本地同步状态,仅传 synced 或 failed。
error_message: Dify 索引失败详情;成功时传 None。
Returns:
已 flush 的 KbDifySyncRecord。
"""
document = version.document
group = document.group
record = (
db.session.query(KbDifySyncRecord)
.filter(
KbDifySyncRecord.document_version_id == version.id,
KbDifySyncRecord.remote_document_id == remote_document_id,
)
.first()
)
if not record:
record = KbDifySyncRecord(
group_id=group.id,
document_id=document.id,
document_version_id=version.id,
dataset_id=dataset_id,
dataset_name=dataset_name,
remote_document_id=remote_document_id,
remote_document_name=remote_document_name,
status=status,
sync_hash=sync_hash,
error_message=error_message,
synced_by_id=synced_by_id,
synced_at=datetime.utcnow(),
)
add_and_flush_with_sequence_retry(record, 'kb_dify_sync_records')
return record
record.dataset_id = dataset_id
record.dataset_name = dataset_name
record.remote_document_name = remote_document_name
record.status = status
record.sync_hash = sync_hash
record.error_message = error_message
record.synced_by_id = synced_by_id
record.synced_at = datetime.utcnow()
return record
def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | None = None) -> dict:
"""
同步清洗后的知识库版本,并以 Dify 最终索引结果作为成功标准。
核心逻辑:上传/更新文本后轮询 Dify 的 indexing_status;仅 completed 写入 synced,
error 时持久化失败原因并抛错,由调用任务将工作台同步步骤标红。
Args:
document_version_id: 当前待同步的 KbDocumentVersion 主键。
synced_by_id: 发起同步的用户 ID,可为空(自动任务)。
Returns:
含 Dify 映射与 indexing_status 的同步结果。
Raises:
KbDifySyncError: 本地文本、Dify API 或 Dify 索引失败。
"""
version = db.session.get(KbDocumentVersion, document_version_id)
if not version or not version.document or not version.document.group:
raise KbDifySyncError('文档版本或关联分组不存在')
@@ -318,7 +476,13 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
remote_document_id = None
remote_document_name = None
upload_name = _resolve_upload_name(version)
if existing_record and existing_record.dataset_id == dataset_id and existing_record.sync_hash == sync_hash:
indexing_payload: dict | None = None
if (
existing_record
and existing_record.dataset_id == dataset_id
and existing_record.sync_hash == sync_hash
and existing_record.status == 'synced'
):
try:
payload = service.get_document(
dataset_id=dataset_id,
@@ -326,6 +490,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
)
remote_document_id = payload.get('id') or existing_record.remote_document_id
remote_document_name = payload.get('name') or existing_record.remote_document_name or upload_name
indexing_payload = payload
except KbDifySyncError as exc:
if not _is_remote_document_missing(str(exc)):
raise
@@ -337,6 +502,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
)
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
remote_document_name = payload.get('document', {}).get('name') or upload_name
indexing_payload = payload
elif existing_record and existing_record.dataset_id == dataset_id:
try:
payload = service.update_document_by_text(
@@ -357,6 +523,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
)
remote_document_id = payload.get('document', {}).get('id') or payload.get('id') or existing_record.remote_document_id
remote_document_name = payload.get('document', {}).get('name') or upload_name
indexing_payload = payload
else:
payload = service.create_document_by_text(
dataset_id=dataset_id,
@@ -366,42 +533,43 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
)
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
remote_document_name = payload.get('document', {}).get('name') or upload_name
indexing_payload = payload
if not remote_document_id:
raise KbDifySyncError('Dify 未返回远端文档 ID')
record = (
db.session.query(KbDifySyncRecord)
.filter(
KbDifySyncRecord.document_version_id == version.id,
KbDifySyncRecord.remote_document_id == remote_document_id,
try:
indexing_result = service.wait_for_document_indexing(
dataset_id=dataset_id,
document_id=remote_document_id,
initial_payload=indexing_payload,
)
.first()
)
if not record:
record = KbDifySyncRecord(
group_id=group.id,
document_id=document.id,
document_version_id=version.id,
except KbDifySyncError as exc:
_save_sync_record(
version=version,
dataset_id=dataset_id,
dataset_name=dataset_name,
remote_document_id=remote_document_id,
remote_document_name=remote_document_name,
status='synced',
sync_hash=sync_hash,
synced_by_id=synced_by_id,
status='failed',
error_message=str(exc),
)
add_and_flush_with_sequence_retry(record, "kb_dify_sync_records")
else:
record.dataset_id = dataset_id
record.dataset_name = dataset_name
record.remote_document_name = remote_document_name
record.status = 'synced'
record.sync_hash = sync_hash
record.error_message = None
record.synced_by_id = synced_by_id
db.session.commit()
raise
record.synced_at = datetime.utcnow()
_save_sync_record(
version=version,
dataset_id=dataset_id,
dataset_name=dataset_name,
remote_document_id=remote_document_id,
remote_document_name=remote_document_name,
sync_hash=sync_hash,
synced_by_id=synced_by_id,
status='synced',
error_message=None,
)
db.session.commit()
content_changed = previous_sync_hash != sync_hash
@@ -438,6 +606,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
'remote_document_id': remote_document_id,
'remote_document_name': remote_document_name,
'sync_hash': sync_hash,
'indexing_status': indexing_result['indexing_status'],
'source_path': source_path,
}
@@ -1,6 +1,9 @@
"""
backend/app/services/knowledge_cleaning/edkb_adapter.py
文件用途:edkb_system 轻量适配层
用途:把 edkb_system 的清洗产物适配为业务服务可直接使用的文件路径和统计信息。
依赖:edkb_system.controller、文件系统临时目录和导出产物约定。
逻辑:复制源文件到隔离目录执行清洗,再把 Markdown、分块和原始布局等必要产物持久化到目标目录。
"""
from __future__ import annotations
@@ -60,6 +63,15 @@ def _find_generated_chunks_jsonl(output_root: Path) -> Path | None:
return candidates[0]
def _find_generated_raw_layout(output_root: Path) -> Path | None:
"""定位包含 OCR Block 元数据的原始布局产物,供下游复用检测框。"""
candidates = [path for path in output_root.rglob('01_raw_layout.json') if path.is_file()]
if not candidates:
return None
candidates.sort(key=lambda item: len(item.parts))
return candidates[0]
def _count_jsonl_lines(path: Path) -> int:
count = 0
with path.open(encoding='utf-8', errors='ignore') as handle:
@@ -178,6 +190,12 @@ def build_clean_result(source_path: Path, target_dir: Path) -> dict:
_rewrite_preview_markdown_if_needed(preview_path, target_dir)
content = cleaned_path.read_text(encoding='utf-8', errors='ignore')
chunks_file_path, chunks_count = _persist_debug_chunks(output_dir, target_dir)
raw_layout_source = _find_generated_raw_layout(output_dir)
raw_layout_path = None
if raw_layout_source:
raw_layout_target = target_dir / '01_raw_layout.json'
shutil.copy2(raw_layout_source, raw_layout_target)
raw_layout_path = str(raw_layout_target)
return {
'mode': 'edkb_system',
@@ -186,4 +204,5 @@ def build_clean_result(source_path: Path, target_dir: Path) -> dict:
'word_count': len(content.split()),
'chunks_file_path': chunks_file_path,
'chunks_count': chunks_count,
'raw_layout_path': raw_layout_path,
}
@@ -18,14 +18,16 @@ SETTING_DEFAULTS = {
'DIFY_API_KEY': '',
'KB_DIFY_PERMISSION': 'only_me',
'KB_DIFY_INDEXING_TECHNIQUE': 'high_quality',
'KB_DIFY_SEARCH_METHOD': 'semantic_search',
# 混合检索同时利用关键词与向量相似度,适合“水型灭火器/A 类火灾”等实体明确问法。
'KB_DIFY_SEARCH_METHOD': 'hybrid_search',
'KB_DIFY_DOC_FORM': 'text_model',
'KB_DIFY_PROCESS_MODE': 'automatic',
# 普通制度文档也按空行保留完整知识单元,避免标题、适用范围和禁用条件被拆散。
'KB_DIFY_PROCESS_MODE': 'custom',
'KB_DIFY_PROCESS_MODE_EXCEL': 'custom',
'KB_DIFY_SEGMENT_SEPARATOR': '\\n\\n',
'KB_DIFY_SEGMENT_SEPARATOR_EXCEL': '\\n\\n',
'KB_DIFY_SEGMENT_MAX_TOKENS': '800',
'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '50',
'KB_DIFY_SEGMENT_MAX_TOKENS': '600',
'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '100',
'KB_DIFY_REMOVE_URLS': 'false',
}
@@ -622,6 +622,7 @@ def run_sync_job(job_id: int) -> tuple[bool, str]:
result = sync_document_version_to_dify(version.id, synced_by_id=job.created_by_id)
except KbDifySyncError as exc:
version.status = 'ready'
version.error_message = str(exc)
job.status = 'failed'
job.progress = 100
job.error_message = str(exc)
@@ -632,6 +633,7 @@ def run_sync_job(job_id: int) -> tuple[bool, str]:
return False, str(exc)
except Exception as exc:
version.status = 'ready'
version.error_message = f'同步到 Dify 时发生未预期错误:{exc}'
job.status = 'failed'
job.progress = 100
job.error_message = f'同步到 Dify 时发生未预期错误:{exc}'
@@ -642,6 +644,7 @@ def run_sync_job(job_id: int) -> tuple[bool, str]:
return False, str(exc)
version.status = 'synced'
version.error_message = None
job.status = 'success'
job.progress = 100
job.message = '已同步到 Dify'
@@ -0,0 +1,7 @@
"""
backend/app/services/procurement_contract/__init__.py
用途:采购合同审查域服务包入口。
依赖:template_service、review_service。
逻辑:API / Tool 层从此包导入业务函数。
"""
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,223 @@
"""
backend/app/services/procurement_contract/artifact_archive.py
用途:将采购合同审核的本地运行产物归档至私有 MinIO,并在本地缓存缺失时按需恢复。
依赖:Flask current_app、minio、procurement_contract.preprocessing 的审查目录约定。
逻辑:审核完成后先上传所有文件,再上传 manifest;manifest 成功后本地目录可安全清理,
后续标注合同或 OCR 页码定位通过 manifest 从 MinIO 恢复所需文件。
"""
from __future__ import annotations
import hashlib
import io
import json
import logging
import mimetypes
import shutil
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from flask import current_app
from minio import Minio
from minio.error import S3Error
_LOGGER = logging.getLogger(__name__)
_MANIFEST_NAME = "_manifest.json"
def _archive_enabled() -> bool:
"""读取归档开关,关闭时调用方保持本地缓存行为。"""
return bool(current_app.config.get("PROCUREMENT_CONTRACT_ARCHIVE_ENABLED", True))
def _archive_bucket() -> str:
"""获取合同专用私有桶名,拒绝空配置避免误写默认桶。"""
bucket = str(current_app.config.get("PROCUREMENT_CONTRACT_ARCHIVE_BUCKET") or "").strip()
if not bucket:
raise RuntimeError("PROCUREMENT_CONTRACT_ARCHIVE_BUCKET is required")
return bucket
def _archive_client() -> Minio:
"""构造 MinIO 客户端;合同归档不设置 public-read policy。"""
endpoint = str(current_app.config.get("MINIO_ENDPOINT") or "").strip()
if not endpoint:
raise RuntimeError("MINIO_ENDPOINT is required")
return Minio(
endpoint,
access_key=str(current_app.config.get("MINIO_ACCESS_KEY") or ""),
secret_key=str(current_app.config.get("MINIO_SECRET_KEY") or ""),
secure=bool(current_app.config.get("MINIO_SECURE", False)),
)
def _review_root(review_no: str) -> Path:
"""将审查编号限制在存储根目录内,和预处理阶段保持同一目录规则。"""
root = Path(str(current_app.config["PROCUREMENT_CONTRACT_STORAGE_ROOT"])).resolve()
candidate = (root / str(review_no or "").strip()).resolve()
if candidate.parent != root:
raise RuntimeError("invalid review_no")
return candidate
def _object_key(review_no: str, relative_path: Path) -> str:
"""生成稳定对象键,保留审查目录内的相对层级。"""
return f"reviews/{review_no}/{relative_path.as_posix()}"
def _ensure_bucket(client: Minio, bucket: str) -> None:
"""确保私有合同桶存在;禁止继承公开资料桶策略。"""
if not client.bucket_exists(bucket):
client.make_bucket(bucket)
def _file_entry(path: Path, *, root: Path) -> dict[str, Any]:
"""生成可校验的归档清单条目,供恢复时限定允许路径。"""
data = path.read_bytes()
relative = path.relative_to(root)
return {
"path": relative.as_posix(),
"size": len(data),
"sha256": hashlib.sha256(data).hexdigest(),
"content_type": mimetypes.guess_type(path.name)[0] or "application/octet-stream",
}
def archive_review_artifacts(review_no: str) -> dict[str, Any]:
"""
上传一份审核的所有本地产物,并最后写入 manifest 作为完整归档提交标记。
Args:
review_no: 已完成审核编号。
Returns:
归档状态、bucket、对象前缀和文件数量;开关关闭时返回 disabled。
Raises:
RuntimeError: 本地目录不存在或 MinIO 上传失败;调用方必须保留本地目录。
"""
if not _archive_enabled():
return {"status": "disabled"}
root = _review_root(review_no)
if not root.is_dir():
raise RuntimeError(f"review artifact directory not found: {review_no}")
files = sorted(
(path for path in root.rglob("*") if path.is_file() and path.name != _MANIFEST_NAME),
key=lambda path: path.relative_to(root).as_posix(),
)
if not files:
raise RuntimeError(f"review artifact directory is empty: {review_no}")
client = _archive_client()
bucket = _archive_bucket()
_ensure_bucket(client, bucket)
entries: list[dict[str, Any]] = []
for path in files:
entry = _file_entry(path, root=root)
data = path.read_bytes()
client.put_object(
bucket,
_object_key(review_no, Path(entry["path"])),
io.BytesIO(data),
len(data),
content_type=entry["content_type"],
)
entries.append(entry)
manifest = {
"review_no": review_no,
"archived_at": datetime.now(timezone.utc).isoformat(),
"files": entries,
}
manifest_data = json.dumps(manifest, ensure_ascii=False, indent=2).encode("utf-8")
client.put_object(
bucket,
_object_key(review_no, Path(_MANIFEST_NAME)),
io.BytesIO(manifest_data),
len(manifest_data),
content_type="application/json",
)
return {
"status": "archived",
"bucket": bucket,
"prefix": f"reviews/{review_no}/",
"manifest_key": _object_key(review_no, Path(_MANIFEST_NAME)),
"file_count": len(entries),
}
def restore_review_artifact(review_no: str, relative_path: str) -> Path | None:
"""
本地缓存缺失时,从已提交 manifest 的私有归档恢复单个文件。
Args:
review_no: 审查编号。
relative_path: 审查目录下的相对文件路径,不允许绝对路径或父级跳转。
Returns:
已存在或恢复后的本地路径;归档关闭或 manifest 未包含该文件时返回 None。
"""
root = _review_root(review_no)
relative = Path(relative_path)
target = (root / relative).resolve()
if target.parent != root and root not in target.parents:
raise RuntimeError("invalid artifact relative path")
if target.is_file():
return target
if not _archive_enabled():
return None
client = _archive_client()
bucket = _archive_bucket()
try:
response = client.get_object(bucket, _object_key(review_no, Path(_MANIFEST_NAME)))
try:
manifest = json.loads(response.read().decode("utf-8"))
finally:
response.close()
response.release_conn()
allowed = {str(item.get("path")): item for item in manifest.get("files") or [] if isinstance(item, dict)}
entry = allowed.get(relative.as_posix())
if not entry:
return None
response = client.get_object(bucket, _object_key(review_no, relative))
try:
data = response.read()
finally:
response.close()
response.release_conn()
except S3Error as exc:
if exc.code == "NoSuchKey":
# [STEP 1] 审核执行中可选 OCR 坐标不存在时,归档尚未提交属于预期状态,不刷告警。
_LOGGER.debug(
"[contract-review] artifact manifest not ready review_no=%s path=%s",
review_no,
relative,
)
return None
_LOGGER.warning("[contract-review] artifact restore failed review_no=%s path=%s err=%s", review_no, relative, exc)
return None
except Exception as exc:
_LOGGER.warning("[contract-review] artifact restore failed review_no=%s path=%s err=%s", review_no, relative, exc)
return None
if hashlib.sha256(data).hexdigest() != str(entry.get("sha256") or ""):
_LOGGER.warning("[contract-review] artifact checksum mismatch review_no=%s path=%s", review_no, relative)
return None
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
return target
def cleanup_local_review_artifacts(review_no: str) -> bool:
"""仅在归档成功后删除本地运行缓存;由环境开关控制,删除失败不影响归档结果。"""
if not bool(current_app.config.get("PROCUREMENT_CONTRACT_ARCHIVE_CLEANUP_LOCAL", True)):
return False
root = _review_root(review_no)
if not root.is_dir():
return False
shutil.rmtree(root)
return True
@@ -0,0 +1,388 @@
"""
backend/app/services/procurement_contract/comparison_regions.py
Purpose: Validate template comparison-region rules and split uploaded contracts into metadata,
body, signature, and attachment scopes.
Dependencies: Standard-library regex/dataclasses only; review_service invokes this before analyze_compare.
Flow: Admin saves validated JSON; compare reviews partition both user-uploaded files and pass only body text
to the existing diff engine while returning metadata and attachment summaries separately.
"""
from __future__ import annotations
import copy
import re
from dataclasses import dataclass
from typing import Any
from app.core.errors import ValidationError
ALLOWED_METADATA_FIELDS = {"title", "version", "contract_no", "buyer", "seller"}
ALLOWED_ATTACHMENT_POLICIES = {"page_count_only"}
CONFIG_ARRAY_FIELDS = (
"metadata_fields",
"body_start_anchors",
"body_end_anchors",
"signature_terms",
"attachment_start_anchors",
)
DEFAULT_COMPARISON_REGION_CONFIG: dict[str, Any] = {
"metadata_fields": ["contract_no", "buyer", "seller", "version"],
"body_start_anchors": ["兹因甲方向乙方购买设备"],
"body_end_anchors": ["本合同一式两份", "以下无正文", "本页以下无正文"],
"signature_terms": ["甲方", "乙方", "盖章", "签署日期", "合同专用章"],
"attachment_start_anchors": ["附件", "性能需求表", "技术协议", "设备配置清单"],
"attachment_policy": "page_count_only",
}
_FIELD_PATTERNS = {
"version": re.compile(r"(?:版本|版次)\s*[::]\s*([^\n;;]{1,40})", re.I),
"contract_no": re.compile(r"(?:合同(?:编号|号)|编号)\s*[::]\s*([^\n;;]{2,128})", re.I),
"buyer": re.compile(r"(?:买方|甲方)\s*[::]\s*([^\n;;((]{2,128})", re.I),
"seller": re.compile(r"(?:卖方|乙方|供应商)\s*[::]\s*([^\n;;((]{2,128})", re.I),
}
@dataclass(frozen=True)
class RegionPartition:
"""Recognized comparison scopes for one uploaded contract."""
metadata: dict[str, str | None]
body: str
signature: str
attachment_pages: int
body_start_anchor: str
body_end_anchor: str
attachment_anchor: str | None
signature_terms_found: list[str]
def default_comparison_region_config() -> dict[str, Any]:
"""Return an isolated V4 default config so callers cannot mutate the shared constant."""
return copy.deepcopy(DEFAULT_COMPARISON_REGION_CONFIG)
def validate_comparison_region_config(value: Any) -> dict[str, Any]:
"""
Validate and normalize a comparison-region JSON object received from Admin.
Args:
value: Dict containing known array fields and attachment_policy.
Returns:
Normalized JSON-safe config with trimmed, deduplicated string arrays.
Raises:
ValidationError: The shape, anchors, metadata field, or policy is unsupported.
"""
if not isinstance(value, dict):
raise ValidationError(
"comparison_region_config must be an object",
code="PROCUREMENT_CONTRACT.INVALID_COMPARISON_REGION_CONFIG",
)
normalized: dict[str, Any] = {}
for field in CONFIG_ARRAY_FIELDS:
raw_items = value.get(field)
if not isinstance(raw_items, list) or not raw_items:
raise ValidationError(
f"{field} must be a non-empty array",
code="PROCUREMENT_CONTRACT.INVALID_COMPARISON_REGION_CONFIG",
details={"field": field},
)
if len(raw_items) > 20:
raise ValidationError(
f"{field} supports at most 20 items",
code="PROCUREMENT_CONTRACT.INVALID_COMPARISON_REGION_CONFIG",
details={"field": field},
)
items: list[str] = []
for raw_item in raw_items:
item = str(raw_item).strip() if isinstance(raw_item, str) else ""
if not item or len(item) > 120:
raise ValidationError(
f"{field} contains an invalid item",
code="PROCUREMENT_CONTRACT.INVALID_COMPARISON_REGION_CONFIG",
details={"field": field},
)
if item not in items:
items.append(item)
normalized[field] = items
unknown_fields = set(normalized["metadata_fields"]) - ALLOWED_METADATA_FIELDS
if unknown_fields:
raise ValidationError(
"metadata_fields contains unsupported fields",
code="PROCUREMENT_CONTRACT.INVALID_COMPARISON_REGION_CONFIG",
details={"field": "metadata_fields", "unknown": sorted(unknown_fields)},
)
policy = str(value.get("attachment_policy") or "").strip()
if policy not in ALLOWED_ATTACHMENT_POLICIES:
raise ValidationError(
"unsupported attachment_policy",
code="PROCUREMENT_CONTRACT.INVALID_COMPARISON_REGION_CONFIG",
details={"field": "attachment_policy", "value": policy},
)
normalized["attachment_policy"] = policy
return normalized
def _compact_with_positions(text: str) -> tuple[str, list[int]]:
"""Build punctuation-insensitive text plus source indexes for robust OCR anchor matching."""
compact: list[str] = []
positions: list[int] = []
for index, char in enumerate(text or ""):
if not char.isalnum():
continue
compact.append(char.lower())
positions.append(index)
return "".join(compact), positions
def _find_anchor(text: str, anchors: list[str], *, start: int = 0) -> tuple[int, int, str] | None:
"""Locate the earliest configured anchor while tolerating OCR whitespace and punctuation noise."""
compact_text, positions = _compact_with_positions(text)
if not compact_text or not positions:
return None
compact_start = next((i for i, source_index in enumerate(positions) if source_index >= start), len(positions))
matches: list[tuple[int, int, str]] = []
for anchor in anchors:
compact_anchor, _ = _compact_with_positions(anchor)
if not compact_anchor:
continue
compact_index = compact_text.find(compact_anchor, compact_start)
if compact_index < 0:
continue
source_start = positions[compact_index]
source_end = positions[min(compact_index + len(compact_anchor) - 1, len(positions) - 1)] + 1
matches.append((source_start, source_end, anchor))
return min(matches, key=lambda item: item[0]) if matches else None
def _body_end_index(text: str, match: tuple[int, int, str]) -> int:
"""Keep the last substantive clause but exclude explicit no-body markers and following signatures."""
start, end, anchor = match
if "无正文" in anchor:
return start
tail = text[end : end + 300]
sentence_end = re.search(r"[。;;\n]", tail)
return end + sentence_end.end() if sentence_end else end
def _extract_metadata(header_text: str, fields: list[str]) -> dict[str, str | None]:
"""Extract configured header fields from text preceding the body start anchor."""
metadata: dict[str, str | None] = {}
for field in fields:
if field == "title":
title = next(
(line.strip() for line in header_text.splitlines() if "合同" in line and len(line.strip()) <= 80),
None,
)
metadata[field] = title
continue
pattern = _FIELD_PATTERNS.get(field)
match = pattern.search(header_text) if pattern else None
metadata[field] = re.sub(r"\s+", "", match.group(1)).strip("::;;。 ")[:128] if match else None
return metadata
def _page_index_for_anchor(page_texts: list[str], anchors: list[str]) -> int | None:
"""Return the page containing a configured body anchor."""
for page_index, page_text in enumerate(page_texts):
if _find_anchor(page_text, anchors):
return page_index
return None
def _attachment_boundary(
page_texts: list[str],
anchors: list[str],
*,
minimum_page_index: int,
) -> tuple[int, str] | None:
"""Find an attachment heading near the start of a page after the body/signature boundary."""
for page_index in range(max(0, minimum_page_index), len(page_texts)):
page_text = page_texts[page_index]
compact_page, _ = _compact_with_positions(page_text)
for anchor in anchors:
match = _find_anchor(page_text, [anchor])
if not match:
continue
compact_prefix, _ = _compact_with_positions(page_text[: match[0]])
# Generic "attachment" wording frequently appears inside body clauses; only accept page headings.
prefix_limit = 45 if anchor in {"附件", "附录"} else 140
if len(compact_prefix) <= prefix_limit and len(compact_page) > len(anchor):
return page_index, anchor
return None
def diagnose_partition(
text: str,
page_texts: list[str],
config: dict[str, Any],
) -> dict[str, Any]:
"""
Report why one uploaded contract can or cannot use comparison-region partitioning.
Args:
text: Cleaned full-document text used by the deterministic comparison.
page_texts: Extracted text for each physical page, including blank pages.
config: Already validated comparison-region config.
Returns:
JSON-safe recognition facts for audit records and Worker warning logs. It does not expose
contract text, only anchor/section availability and the resulting fallback reason.
"""
start_match = _find_anchor(text, config["body_start_anchors"])
end_match = _find_anchor(text, config["body_end_anchors"], start=start_match[1] if start_match else 0)
body_end = _body_end_index(text, end_match) if end_match else None
signature_text = text[body_end:] if body_end is not None else ""
signature_terms_found = [
term for term in config["signature_terms"] if _find_anchor(signature_text, [term])
]
page_text_available = bool(page_texts and any(page.strip() for page in page_texts))
body_start_page = _page_index_for_anchor(page_texts, config["body_start_anchors"]) if page_text_available else None
body_end_page = _page_index_for_anchor(page_texts, config["body_end_anchors"]) if page_text_available else None
attachment = (
_attachment_boundary(
page_texts,
config["attachment_start_anchors"],
minimum_page_index=body_end_page,
)
if body_end_page is not None
else None
)
if not text.strip():
fallback_reason = "clean_text_unavailable"
elif not page_text_available:
fallback_reason = "page_text_unavailable"
elif not start_match:
fallback_reason = "body_start_anchor_missing"
elif not end_match or body_end is None or body_end <= start_match[0]:
fallback_reason = "body_end_anchor_missing"
elif body_start_page is None or body_end_page is None or body_end_page < body_start_page:
fallback_reason = "anchor_page_unavailable"
elif not signature_terms_found:
fallback_reason = "signature_term_missing"
else:
fallback_reason = None
return {
"page_text_available": page_text_available,
"page_count": len(page_texts),
"body_start_anchor": start_match[2] if start_match else None,
"body_end_anchor": end_match[2] if end_match else None,
"body_start_page": body_start_page + 1 if body_start_page is not None else None,
"body_end_page": body_end_page + 1 if body_end_page is not None else None,
"signature_terms_found": signature_terms_found,
"attachment_anchor": attachment[1] if attachment else None,
"attachment_page": attachment[0] + 1 if attachment else None,
"fallback_reason": fallback_reason,
}
def partition_document(
text: str,
page_texts: list[str],
config: dict[str, Any],
) -> RegionPartition | None:
"""
Partition one contract; return None unless required body anchors and reliable pages are available.
Args:
text: Existing cleaned contract text used by analyze_compare.
page_texts: Text extracted page-by-page from the original PDF or converted Word PDF.
config: Already validated comparison-region config.
Returns:
RegionPartition when safe to apply, otherwise None to force legacy full-document comparison.
"""
if not text.strip() or not page_texts or not any(page.strip() for page in page_texts):
return None
start_match = _find_anchor(text, config["body_start_anchors"])
if not start_match:
return None
end_match = _find_anchor(text, config["body_end_anchors"], start=start_match[1])
if not end_match:
return None
body_end = _body_end_index(text, end_match)
if body_end <= start_match[0]:
return None
body_start_page = _page_index_for_anchor(page_texts, config["body_start_anchors"])
body_end_page = _page_index_for_anchor(page_texts, config["body_end_anchors"])
if body_start_page is None or body_end_page is None or body_end_page < body_start_page:
return None
attachment = _attachment_boundary(
page_texts,
config["attachment_start_anchors"],
minimum_page_index=body_end_page,
)
attachment_page = attachment[0] if attachment else len(page_texts)
attachment_pages = max(0, len(page_texts) - attachment_page)
signature_text = text[body_end:]
signature_terms_found = [
term for term in config["signature_terms"] if _find_anchor(signature_text, [term])
]
if not signature_terms_found:
return None
return RegionPartition(
metadata=_extract_metadata(text[: start_match[0]], config["metadata_fields"]),
body=text[start_match[0] : body_end].strip(),
signature=signature_text.strip(),
attachment_pages=attachment_pages,
body_start_anchor=start_match[2],
body_end_anchor=end_match[2],
attachment_anchor=attachment[1] if attachment else None,
signature_terms_found=signature_terms_found,
)
def build_metadata_comparison(
original: dict[str, str | None],
returned: dict[str, str | None],
) -> dict[str, dict[str, str | None]]:
"""Build stable field-by-field statuses without adding metadata changes to clause counts."""
result: dict[str, dict[str, str | None]] = {}
for field in original.keys() | returned.keys():
before = original.get(field)
after = returned.get(field)
if before == after:
status = "unchanged"
elif not before and after:
status = "filled"
elif before and not after:
status = "removed"
else:
status = "changed"
result[field] = {"original": before, "returned": after, "status": status}
return result
def build_attachment_comparison(original_pages: int, returned_pages: int) -> dict[str, Any]:
"""Summarize attachment page deltas without exposing attachment content."""
added = max(0, returned_pages - original_pages)
removed = max(0, original_pages - returned_pages)
status = "added" if added else "removed" if removed else "unchanged"
return {
"status": status,
"original_pages": original_pages,
"returned_pages": returned_pages,
"added_pages": added,
"removed_pages": removed,
}
def preview_anchor_recognition(text: str, config: dict[str, Any]) -> dict[str, Any]:
"""Preview which configured anchors can be recognized in an Admin template file."""
start = _find_anchor(text, config["body_start_anchors"])
end = _find_anchor(text, config["body_end_anchors"], start=start[1] if start else 0)
attachment = _find_anchor(text, config["attachment_start_anchors"], start=end[1] if end else 0)
signature_terms = [term for term in config["signature_terms"] if _find_anchor(text, [term])]
return {
"status": "recognized" if start and end else "incomplete",
"body_start_anchor": start[2] if start else None,
"body_end_anchor": end[2] if end else None,
"signature_terms_found": signature_terms,
"attachment_anchor": attachment[2] if attachment else None,
"warning": None if start and end else "Body start or end anchor was not recognized",
}
@@ -0,0 +1,512 @@
"""
backend/app/services/procurement_contract/llm_enhancer.py
Purpose: Dify Chatflow/Workflow-based comprehensive legal review for cleaned procurement contracts.
Dependencies: Config, DifyService, Agent model.
Flow: review_service passes cleaned text, structured clauses and deterministic findings; Dify Chatflow or Workflow enhances existing findings
and independently returns new legal risks, then this module validates and merges them without lowering deterministic risk.
"""
from __future__ import annotations
import json
import re
from typing import Any
from flask import current_app
from app import db
from app.core.config.settings import Config
from app.models import Agent
from app.services.dify import DifyService
MAX_FINDINGS = 20
MAX_TEXT_CHARS = 900
VALID_RISK_LEVELS = {"high", "medium", "low", "ok"}
RISK_RANK = {"ok": 0, "low": 1, "medium": 2, "high": 3}
def is_enabled() -> bool:
"""Return whether procurement-contract LLM enhancement is enabled by configuration."""
return bool(getattr(Config, "PROCUREMENT_CONTRACT_LLM_ENABLED", False))
def enhance_review_result(
result: dict[str, Any],
*,
review_no: str,
review_mode: str,
contract_type: str | None,
template_name: str | None = None,
clean_text: str = "",
structured_clauses: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""
Ask Dify to enhance deterministic findings and independently scan the cleaned contract.
AI trigger timing: call after HXOPS has cleaned and structured the contract and completed Diff/rule checks.
The LLM must return JSON only; it may add risks and may challenge deterministic findings only with verified evidence.
Args:
result: HXOPS deterministic review result.
review_no/review_mode/contract_type/template_name: Review context passed to Dify.
clean_text: Cleaned contract Markdown text; never pass a server-local path.
structured_clauses: Full ordered clause list generated by HXOPS.
Returns:
Result with enhanced existing findings, validated new_items and Dify audit metadata.
"""
if not is_enabled():
return result
clauses = result.get("clauses_json") if isinstance(result.get("clauses_json"), list) else []
clean_text = str(clean_text or "").strip()
structured_clauses = structured_clauses or []
if not clean_text or not structured_clauses:
return _with_llm_meta(result, enabled=True, status="skipped", message="cleaned contract is unavailable")
agent = _resolve_agent()
if not agent:
return _with_llm_meta(result, enabled=True, status="skipped", message="LLM agent is not configured")
findings = _build_findings_payload(clauses)
max_text_chars = max(int(getattr(Config, "PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS", 120000) or 120000), 10000)
max_clauses = max(int(getattr(Config, "PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES", 160) or 160), 20)
sent_text = clean_text[:max_text_chars]
sent_clauses = structured_clauses[:max_clauses]
input_truncated = len(clean_text) > len(sent_text) or len(structured_clauses) > len(sent_clauses)
inputs = {
"review_no": review_no,
"review_mode": review_mode,
"contract_type": contract_type or "general_procurement",
"template_name": template_name or "",
"findings_json": json.dumps(findings, ensure_ascii=False),
"clauses_json": json.dumps(sent_clauses, ensure_ascii=False),
"clean_text": sent_text,
"scan_enabled": "true",
"scan_scope": "bounded_contract" if input_truncated else "full_contract",
"instruction": _review_instruction(),
}
try:
timeout = (
int(getattr(Config, "PROCUREMENT_CONTRACT_LLM_CONNECT_TIMEOUT_SECONDS", 5) or 5),
int(getattr(Config, "PROCUREMENT_CONTRACT_LLM_READ_TIMEOUT_SECONDS", 120) or 120),
)
provider = _review_provider(agent)
if provider == "chatflow":
response = DifyService.run_chatflow_once(
agent=agent,
query=_chatflow_review_query(),
inputs=inputs,
user=f"contract-review:{review_no}",
timeout=timeout,
)
enhancements, new_items = _extract_review_output({"answer": response.get("answer")})
workflow_run_id = str(response.get("message_id") or "") or None
else:
response = DifyService.run_workflow_streaming(
agent=agent,
inputs=inputs,
user=f"contract-review:{review_no}",
timeout=timeout,
)
enhancements, new_items = _extract_review_output(response)
workflow_run_id = _workflow_run_id(response)
except Exception as exc: # noqa: BLE001 - enhancement must not fail deterministic review
if current_app:
current_app.logger.warning("[contract-llm] enhance failed review_no=%s err=%s", review_no, exc)
return _with_llm_meta(result, enabled=True, status="failed", message=str(exc)[:500])
if not enhancements and not new_items:
return _with_llm_meta(result, enabled=True, status="empty", message="LLM returned no usable review items")
merged = _merge_review_output(
result,
enhancements,
new_items,
clean_text=clean_text,
structured_clauses=structured_clauses,
)
summary = merged.get("summary_json") if isinstance(merged.get("summary_json"), dict) else {}
summary["llm_input"] = {
"text_characters": len(clean_text),
"sent_text_characters": len(sent_text),
"clause_count": len(structured_clauses),
"sent_clause_count": len(sent_clauses),
"truncated": input_truncated,
}
merged["summary_json"] = summary
return _with_llm_meta(
merged,
enabled=True,
status="success",
message="Dify comprehensive review applied",
provider=provider,
workflow_run_id=workflow_run_id,
)
def _resolve_agent() -> Agent | None:
"""Resolve the configured Dify Chatflow or Workflow agent used for contract review."""
agent_id = int(getattr(Config, "PROCUREMENT_CONTRACT_LLM_AGENT_ID", 0) or 0)
if agent_id:
row = db.session.get(Agent, agent_id)
if row and row.is_active and row.dify_api_key:
return row
app_id = str(getattr(Config, "PROCUREMENT_CONTRACT_LLM_DIFY_APP_ID", "") or "").strip()
if app_id:
row = db.session.query(Agent).filter(Agent.dify_app_id == app_id, Agent.is_active.is_(True)).first()
if row and row.dify_api_key:
return row
api_key = str(getattr(Config, "PROCUREMENT_CONTRACT_LLM_DIFY_API_KEY", "") or "").strip()
if api_key:
return Agent(
id=0,
name="Procurement Contract LLM Enhancer",
dify_api_key=api_key,
api_base_url=str(getattr(Config, "PROCUREMENT_CONTRACT_LLM_DIFY_BASE", "") or "").strip() or Config.DIFY_API_BASE,
dify_app_type="workflow",
)
return None
def _review_provider(agent: Agent) -> str:
"""Return the configured Dify provider; env override supports reusing a Chatflow during rollout."""
configured = str(getattr(Config, "PROCUREMENT_CONTRACT_LLM_PROVIDER", "agent") or "agent").strip().lower()
if configured in {"chatflow", "workflow"}:
return configured
app_type = str(getattr(agent, "dify_app_type", "") or "").strip().lower()
return "chatflow" if app_type == "chatflow" else "workflow"
def _chatflow_review_query() -> str:
"""
提供给 Chatflow 的一次性任务提示;正式合同内容均通过 Start inputs 传入。
Chatflow 可以沿用普通会话应用,但必须在画布中识别该指令并只输出 JSON,
否则后端会把非 JSON 回答标为无可用审核项。
"""
return "执行合同全面审核任务。请严格根据 Start 输入变量返回 instruction 要求的 JSON,不要输出解释性文字。"
def _build_findings_payload(clauses: list[Any]) -> list[dict[str, Any]]:
"""Build compact findings for LLM consumption without sending the whole contract."""
findings: list[dict[str, Any]] = []
for idx, raw in enumerate(clauses[:MAX_FINDINGS], start=1):
if not isinstance(raw, dict):
continue
findings.append(
{
"id": str(raw.get("clause_no") or idx),
"title": str(raw.get("title") or raw.get("clause_category") or f"finding-{idx}")[:120],
"change_type": str(raw.get("change_type") or ""),
"rule_risk_level": str(raw.get("risk_level") or ""),
"category": str(raw.get("clause_category") or ""),
"rule_detail": _clip(raw.get("detail")),
"rule_risk_hint": _clip(raw.get("risk_hint")),
"rule_suggestion": _clip(raw.get("suggestion")),
"template_excerpt": _clip(raw.get("old_text"), 450),
"contract_excerpt": _clip(raw.get("new_text"), 450),
}
)
return findings
def _review_instruction() -> str:
"""Build the versioned instruction consumed by the Chatflow review branch's LLM node."""
# [PROMPT_UPDATE] 2026-07-21: 增加带原文证据和置信度门槛的 confirm/reject/uncertain 纠错协议。
return (
"你是企业采购方合同审核助手。输入包含 clean_text、clauses_json、findings_json。"
"必须逐条覆盖 clauses_json,并结合全文检查付款、交付、验收、质保、违约赔偿、免责、"
"责任上限、知识产权、保密数据、解除续期、不可抗力、争议解决以及跨条款冲突。"
"items 用于增强 findings_json 已有项;new_items 用于返回后端未发现的新风险。"
"每个 new_item 必须引用真实 clause_id/clause_no,并给出合同原文 evidence;禁止编造法条编号。"
"返回严格 JSON:{\"items\":[{\"id\":\"1\",\"decision\":\"confirm|reject|uncertain\",\"evidence\":\"合同原文\",\"professional_reason\":\"...\","
"\"professional_suggestion\":\"...\",\"negotiation_text\":\"...\","
"\"model_risk_level\":\"high|medium|low|ok\",\"confidence\":0.0}],"
"\"new_items\":[{\"id\":\"llm-1\",\"clause_id\":\"clause-0001\","
"\"clause_no\":\"第八条\",\"title\":\"...\",\"clause_category\":\"liability\","
"\"risk_level\":\"high|medium|low\",\"professional_reason\":\"...\","
"\"business_impact\":\"...\",\"professional_suggestion\":\"...\","
"\"negotiation_text\":\"...\",\"evidence\":\"合同原文\",\"confidence\":0.0}]}."
"已有项若规则结论正确返回 confirm;若原文明确证明规则误报可返回 reject;OCR 无法确认返回 uncertain。"
"reject 必须引用能直接反驳规则结论的真实合同原文,且 confidence 不低于0.8;confidence 必须为 0 到 1。"
)
def _clip(value: Any, limit: int = MAX_TEXT_CHARS) -> str:
"""Normalize and clip text sent to or returned from the LLM."""
text = re.sub(r"\s+", " ", str(value or "")).strip()
if len(text) <= limit:
return text
return text[:limit] + "..."
def _extract_review_output(
workflow_result: dict[str, Any] | None,
) -> tuple[dict[str, dict[str, Any]], list[dict[str, Any]]]:
"""Parse Dify outputs into existing-finding enhancements and independent new risks."""
data = workflow_result if isinstance(workflow_result, dict) else {}
outputs = data.get("outputs") if isinstance(data.get("outputs"), dict) else {}
direct_output = None
if outputs.get("items") is not None or outputs.get("new_items") is not None:
direct_output = {
"items": _parse_json_candidate(outputs.get("items")) or outputs.get("items") or [],
"new_items": _parse_json_candidate(outputs.get("new_items")) or outputs.get("new_items") or [],
}
candidates = [
direct_output,
outputs.get("items"),
outputs.get("enhancements"),
outputs.get("result"),
outputs.get("text"),
outputs.get("output"),
data.get("answer"),
]
parsed: Any = None
for candidate in candidates:
parsed = _parse_json_candidate(candidate)
if parsed:
break
raw_new_items: list[Any] = []
if isinstance(parsed, dict):
raw_items = parsed.get("items") or parsed.get("enhancements") or []
raw_new_items = parsed.get("new_items") or parsed.get("newItems") or []
elif isinstance(parsed, list):
raw_items = parsed
else:
raw_items = []
out: dict[str, dict[str, Any]] = {}
for item in raw_items:
if not isinstance(item, dict):
continue
item_id = str(item.get("id") or item.get("clause_no") or "").strip()
if not item_id:
continue
confidence = _normalize_confidence(item.get("confidence"))
level = str(item.get("model_risk_level") or item.get("risk_level") or "").strip().lower()
if level not in VALID_RISK_LEVELS:
level = ""
decision = str(item.get("decision") or "confirm").strip().lower()
if decision not in {"confirm", "reject", "uncertain"}:
decision = "confirm"
out[item_id] = {
"llm_reason": _clip(item.get("professional_reason") or item.get("reason") or item.get("detail")),
"llm_suggestion": _clip(item.get("professional_suggestion") or item.get("suggestion")),
"llm_negotiation_text": _clip(item.get("negotiation_text")),
"llm_model_risk_level": level,
"llm_confidence": confidence,
"llm_decision": decision,
"llm_evidence": _clip(item.get("evidence"), 1200),
}
new_items = [item for item in raw_new_items if isinstance(item, dict)]
return out, new_items
def _parse_json_candidate(value: Any) -> Any:
"""Parse a Dify output value that may already be JSON or may be JSON text."""
if isinstance(value, (dict, list)):
return value
if not isinstance(value, str) or not value.strip():
return None
text = value.strip()
try:
return json.loads(text)
except json.JSONDecodeError:
pass
match = re.search(r"```(?:json)?\s*(.*?)```", text, flags=re.S)
if match:
try:
return json.loads(match.group(1).strip())
except json.JSONDecodeError:
return None
start = min([i for i in [text.find("{"), text.find("[")] if i >= 0], default=-1)
end = max(text.rfind("}"), text.rfind("]"))
if start >= 0 and end > start:
try:
return json.loads(text[start : end + 1])
except json.JSONDecodeError:
return None
return None
def _normalize_confidence(value: Any) -> float | None:
"""Normalize confidence to 0..1."""
try:
num = float(value)
except (TypeError, ValueError):
return None
if num > 1:
num = num / 100
return max(0.0, min(1.0, round(num, 2)))
def _normalize_evidence(value: Any) -> str:
"""归一化证据文本,供原文包含校验和结果展示。"""
return re.sub(r"\s+", "", str(value or "")).strip()
def _merge_review_output(
result: dict[str, Any],
enhancements: dict[str, dict[str, Any]],
new_items: list[dict[str, Any]],
*,
clean_text: str,
structured_clauses: list[dict[str, Any]],
) -> dict[str, Any]:
"""
合并 Dify 对已有发现的增强及其独立发现,并执行证据、去重和风险等级治理。
Args:
result: HXOPS 确定性结果。
enhancements: finding id 对应的解释增强。
new_items: Dify 独立发现的候选风险。
clean_text/structured_clauses: 用于验证 clause_id 与 evidence 是否真实存在。
Returns:
合并后的结果;证据不足项保留但标记 needs_review,便于采购人员识别不确定结论。
"""
clauses = result.get("clauses_json") if isinstance(result.get("clauses_json"), list) else []
for idx, clause in enumerate(clauses, start=1):
if not isinstance(clause, dict):
continue
item_id = str(clause.get("clause_no") or idx)
extra = enhancements.get(item_id)
if not extra:
continue
clause["llm_enabled"] = True
clause.update({k: v for k, v in extra.items() if v not in ("", None)})
if extra.get("llm_reason"):
clause["detail"] = extra["llm_reason"]
if extra.get("llm_suggestion"):
clause["suggestion"] = extra["llm_suggestion"]
if extra.get("llm_negotiation_text"):
clause["negotiation_text"] = extra["llm_negotiation_text"]
deterministic_level = str(clause.get("risk_level") or "ok").lower()
model_level = str(extra.get("llm_model_risk_level") or "").lower()
decision = str(extra.get("llm_decision") or "confirm")
evidence = str(extra.get("llm_evidence") or "").strip()
evidence_valid = bool(_normalize_evidence(evidence) and _normalize_evidence(evidence) in _normalize_evidence(clean_text))
confidence = extra.get("llm_confidence")
if decision == "reject" and evidence_valid and isinstance(confidence, float) and confidence >= 0.8:
clause["risk_level"] = "ok"
clause["change_type"] = "pass"
clause["validation_status"] = "confirmed"
clause["evidence"] = evidence
clause["detail"] = extra.get("llm_reason") or "原文证据表明该确定性风险未命中。"
elif decision == "uncertain":
clause["validation_status"] = "needs_review"
if evidence_valid:
clause["evidence"] = evidence
elif RISK_RANK.get(model_level, -1) > RISK_RANK.get(deterministic_level, 0):
clause["risk_level"] = model_level
clause_map = {
str(item.get("clause_id") or ""): item
for item in structured_clauses
if isinstance(item, dict) and item.get("clause_id")
}
clause_no_map = {
str(item.get("clause_no") or "").strip(): item
for item in structured_clauses
if isinstance(item, dict) and str(item.get("clause_no") or "").strip()
}
normalized_contract = _normalize_evidence(clean_text)
fingerprints = {
_normalize_evidence(
f"{item.get('clause_no') or ''}|{item.get('title') or ''}|{item.get('detail') or ''}"
)[:240]
for item in clauses
if isinstance(item, dict)
}
accepted = 0
needs_review = 0
for idx, raw in enumerate(new_items, start=1):
clause_id = str(raw.get("clause_id") or "").strip()
requested_clause_no = str(raw.get("clause_no") or "").strip()
linked_clause = clause_map.get(clause_id) or clause_no_map.get(requested_clause_no)
evidence = _clip(raw.get("evidence"), 1200)
evidence_key = _normalize_evidence(evidence)
evidence_valid = bool(evidence_key and evidence_key in normalized_contract)
clause_valid = bool(linked_clause)
title = _clip(raw.get("title") or "AI 新发现风险", 120)
reason = _clip(raw.get("professional_reason") or raw.get("legal_reason") or raw.get("reason"))
fingerprint = _normalize_evidence(
f"{raw.get('clause_no') or (linked_clause or {}).get('clause_no') or ''}|{title}|{reason}"
)[:240]
if not fingerprint or fingerprint in fingerprints:
continue
level = str(raw.get("risk_level") or raw.get("model_risk_level") or "medium").lower()
if level not in {"high", "medium", "low"}:
level = "medium"
confidence = _normalize_confidence(raw.get("confidence"))
validation_status = "confirmed" if clause_valid and evidence_valid else "needs_review"
item = {
"clause_no": str(
requested_clause_no or (linked_clause or {}).get("clause_no") or f"AI-{idx}"
),
"clause_id": clause_id or None,
"title": title,
"clause_category": str(
raw.get("clause_category") or raw.get("category") or (linked_clause or {}).get("category") or "other"
),
"change_type": "llm_scan",
"risk_level": level,
"detail": reason or "大模型识别到潜在合同风险。",
"risk_hint": reason,
"business_impact": _clip(raw.get("business_impact")),
"suggestion": _clip(raw.get("professional_suggestion") or raw.get("suggestion")),
"negotiation_text": _clip(raw.get("negotiation_text")),
"evidence": evidence,
"source": "llm",
"llm_enabled": True,
"llm_confidence": confidence,
"llm_reason": reason,
"llm_model_risk_level": level,
"validation_status": validation_status,
}
clauses.append(item)
fingerprints.add(fingerprint)
accepted += 1
if validation_status == "needs_review":
needs_review += 1
result["clauses_json"] = clauses
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
summary["llm_new_findings"] = {"accepted": accepted, "needs_review": needs_review}
result["summary_json"] = summary
return result
def _with_llm_meta(
result: dict[str, Any],
*,
enabled: bool,
status: str,
message: str,
provider: str | None = None,
workflow_run_id: str | None = None,
) -> dict[str, Any]:
"""Attach LLM enhancement metadata to summary_json."""
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
summary["llm_enhancement"] = {
"enabled": enabled,
"status": status,
"message": message,
"provider": provider,
"workflow_run_id": workflow_run_id,
}
result["summary_json"] = summary
return result
def _workflow_run_id(workflow_result: dict[str, Any] | None) -> str | None:
"""Read Dify workflow run id from gateway metadata."""
if not isinstance(workflow_result, dict):
return None
value = workflow_result.get("workflow_run_id") or workflow_result.get("id")
return str(value) if value else None
@@ -0,0 +1,513 @@
"""
backend/app/services/procurement_contract/pdf_annotation.py
用途:把合同审核发现锚定到原 PDF 页码/坐标,并生成带标准高亮批注的合同副本。
依赖:pypdfium2 提取逐字坐标;pypdf 写入 Highlight annotation。
逻辑:审核结果合并后调用 enrich_result_with_pdf_anchors → 条款写入 evidence_anchor;
下载时文本型 PDF 复用字符坐标,纯图片 PDF 复用持久化 OCR 行框绘制高亮,最后才降级页级批注。
"""
from __future__ import annotations
import difflib
import io
import re
import unicodedata
from typing import Any
MAX_ANCHOR_CANDIDATES = 6
MAX_ANCHOR_CHARS = 180
MIN_FUZZY_ANCHOR_CHARS = 10
MIN_FUZZY_SCORE = 0.82
PAGE_IMAGE_MARKER_RE = re.compile(r"!\[page-image-(\d+)\]", re.IGNORECASE)
def _compact_text(value: Any) -> str:
"""归一化空白和全半角,保留字符顺序供 PDF 搜索。"""
text = unicodedata.normalize("NFKC", str(value or ""))
return re.sub(r"\s+", "", text).strip()
def _candidate_texts(item: dict[str, Any]) -> list[str]:
"""
按证据可靠性生成 PDF 锚定候选文本。
比对模式优先合同侧 new_text;单份审核优先 evidence。建议、原因和谈判话术不是合同原文,
禁止作为锚点候选,避免把模型生成内容标进 PDF。
"""
raw_values = [item.get("new_text"), item.get("evidence")]
candidates: list[str] = []
seen: set[str] = set()
for raw in raw_values:
text = re.sub(r"\s+", " ", str(raw or "")).strip()
if not text:
continue
fragments = [
part.strip(" ,,。;;::()()[]【】")
for part in re.split(r"\n+|(?<=[。!?;;])", text)
if part.strip()
]
for fragment in sorted(fragments or [text], key=len, reverse=True):
compact = _compact_text(fragment)
if len(compact) < 4 or compact in seen:
continue
seen.add(compact)
candidates.append(fragment[:MAX_ANCHOR_CHARS])
if len(candidates) >= MAX_ANCHOR_CANDIDATES:
return candidates
# OCR 可能只错一个值,完整句无法命中时仍可用稳定字段名定位同一行。
stable_values = [item.get("new_text")]
if str(item.get("change_type") or "") == "modify":
stable_values.append(item.get("old_text"))
for raw in stable_values:
text = re.sub(r"^\s*\d+(?:[.、.])?\s*", "", str(raw or "")).strip()
label = re.split(r"[::]", text, maxsplit=1)[0].strip(" ,。;;::")
compact = _compact_text(label)
if 4 <= len(compact) <= 30 and compact not in seen:
seen.add(compact)
candidates.append(label)
if len(candidates) >= MAX_ANCHOR_CANDIDATES:
break
return candidates
def _ocr_pages(clean_text: str) -> list[tuple[int, str]]:
"""按清洗 Markdown 的 page-image 标记拆分 OCR 扫描件页文本。"""
matches = list(PAGE_IMAGE_MARKER_RE.finditer(str(clean_text or "")))
pages: list[tuple[int, str]] = []
for index, match in enumerate(matches):
start = match.end()
end = matches[index + 1].start() if index + 1 < len(matches) else len(clean_text)
pages.append((int(match.group(1)), clean_text[start:end]))
return pages
def locate_ocr_evidence_page(clean_text: str, item: dict[str, Any]) -> dict[str, Any] | None:
"""
扫描 PDF 无文本坐标时,用 OCR 分页正文可靠定位证据所在页。
Returns:
命中时返回 page_no/source_text/confidence/method,不生成伪造矩形坐标。
"""
pages = _ocr_pages(clean_text)
candidates = _candidate_texts(item)
if not pages or not candidates:
return None
best: dict[str, Any] | None = None
for page_no, page_text in pages:
page_key = _compact_text(page_text)
if not page_key:
continue
for candidate in candidates:
candidate_key = _compact_text(candidate)
if len(candidate_key) < 4:
continue
if candidate_key in page_key:
return {
"page_no": page_no,
"rects": [],
"matched_text": candidate,
"source_text": candidate,
"confidence": 1.0,
"method": "ocr_page",
}
window_size = min(len(candidate_key), 80)
if window_size < MIN_FUZZY_ANCHOR_CHARS or len(page_key) < window_size:
continue
candidate_window = candidate_key[:window_size]
step = max(1, window_size // 12)
score = max(
difflib.SequenceMatcher(
a=candidate_window,
b=page_key[start : start + window_size],
autojunk=False,
).ratio()
for start in range(0, len(page_key) - window_size + 1, step)
)
if score >= MIN_FUZZY_SCORE and (best is None or score > best["confidence"]):
best = {
"page_no": page_no,
"rects": [],
"matched_text": candidate,
"source_text": candidate,
"confidence": round(score, 3),
"method": "ocr_page",
}
return best
def _ocr_layout_pages(ocr_layout: dict[str, Any] | None) -> list[dict[str, Any]]:
"""校验并返回 OCR 坐标产物中的页面列表。"""
if not isinstance(ocr_layout, dict):
return []
pages = ocr_layout.get("pages")
return [page for page in pages if isinstance(page, dict)] if isinstance(pages, list) else []
def _layout_match(
page: dict[str, Any],
candidate: str,
) -> tuple[list[dict[str, Any]], float] | None:
"""在单页 OCR 行序列中匹配候选文本,并返回覆盖该文本的行框。"""
lines = [line for line in page.get("lines") or [] if isinstance(line, dict)]
compact_chars: list[str] = []
char_line_indexes: list[int] = []
for line_index, line in enumerate(lines):
for char in _compact_text(line.get("text")):
compact_chars.append(char)
char_line_indexes.append(line_index)
page_key = "".join(compact_chars)
candidate_key = _compact_text(candidate)
if len(candidate_key) < 4 or len(page_key) < len(candidate_key):
return None
window_size = min(len(candidate_key), 80)
candidate_window = candidate_key[:window_size]
best_start = page_key.find(candidate_window)
best_score = 1.0 if best_start >= 0 else 0.0
if best_start < 0 and window_size >= MIN_FUZZY_ANCHOR_CHARS:
step = max(1, window_size // 12)
for start in range(0, len(page_key) - window_size + 1, step):
score = difflib.SequenceMatcher(
a=candidate_window,
b=page_key[start : start + window_size],
autojunk=False,
).ratio()
if score > best_score:
best_start = start
best_score = score
if best_start < 0 or best_score < MIN_FUZZY_SCORE:
return None
end = min(best_start + window_size, len(char_line_indexes))
matched_indexes = sorted(set(char_line_indexes[best_start:end]))
matched_lines = [lines[index] for index in matched_indexes if lines[index].get("polygon")]
if not matched_lines:
return None
return matched_lines, best_score
def locate_ocr_layout_evidence(
ocr_layout: dict[str, Any] | None,
item: dict[str, Any],
) -> dict[str, Any] | None:
"""
在纯图片 PDF 的持久化 OCR 行框中定位证据。
Returns:
命中时返回页码、归一化多边形和置信度;坐标转换延迟到写 PDF 批注阶段完成。
"""
candidates = _candidate_texts(item)
if not candidates:
return None
best: dict[str, Any] | None = None
for page in _ocr_layout_pages(ocr_layout):
page_no = int(page.get("page_no") or 0)
if page_no <= 0:
continue
for candidate in candidates:
matched = _layout_match(page, candidate)
if not matched:
continue
lines, score = matched
anchor = {
"page_no": page_no,
"rects": [],
"ocr_polygons": [line["polygon"] for line in lines],
"matched_text": "\n".join(str(line.get("text") or "") for line in lines),
"source_text": candidate,
"confidence": round(score, 3),
"method": "ocr_bbox_exact" if score == 1.0 else "ocr_bbox_fuzzy",
}
if score == 1.0:
return anchor
if best is None or score > float(best.get("confidence") or 0):
best = anchor
return best
def _merge_char_rects(rects: list[tuple[float, float, float, float]]) -> list[list[float]]:
"""把同一文本行的逐字坐标合并成适合高亮显示的矩形。"""
if not rects:
return []
ordered = sorted(rects, key=lambda rect: (-rect[3], rect[0]))
lines: list[list[float]] = []
for left, bottom, right, top in ordered:
if not lines:
lines.append([left, bottom, right, top])
continue
current = lines[-1]
vertical_overlap = min(current[3], top) - max(current[1], bottom)
min_height = max(1.0, min(current[3] - current[1], top - bottom))
if vertical_overlap / min_height >= 0.45:
current[0] = min(current[0], left)
current[1] = min(current[1], bottom)
current[2] = max(current[2], right)
current[3] = max(current[3], top)
else:
lines.append([left, bottom, right, top])
return [[round(value, 2) for value in rect] for rect in lines]
def _exact_anchor(textpage: Any, candidate: str) -> dict[str, Any] | None:
"""使用 PDFium 原生搜索返回首个精确文本命中的坐标。"""
query = re.sub(r"\s+", "", candidate)
if len(query) < 4:
return None
searcher = textpage.search(query, match_case=False)
occurrence = searcher.get_next()
if not occurrence:
return None
index, count = occurrence
rects = [textpage.get_charbox(char_index) for char_index in range(index, index + count)]
return {
"char_index": int(index),
"char_count": int(count),
"rects": _merge_char_rects(rects),
"matched_text": textpage.get_text_range(index, count),
"confidence": 1.0,
"method": "exact",
}
def _fuzzy_anchor(page_text: str, textpage: Any, candidate: str) -> dict[str, Any] | None:
"""精确搜索失败时,在去空白页文本上做受限滑窗匹配并映射回原字符坐标。"""
compact_page_chars: list[str] = []
compact_to_raw: list[int] = []
for raw_index, char in enumerate(page_text):
normalized = _compact_text(char)
if not normalized:
continue
compact_page_chars.append(normalized)
compact_to_raw.append(raw_index)
page_key = "".join(compact_page_chars)
candidate_key = _compact_text(candidate)
if len(candidate_key) < MIN_FUZZY_ANCHOR_CHARS or len(page_key) < len(candidate_key):
return None
window_size = min(len(candidate_key), 80)
candidate_window = candidate_key[:window_size]
best_score = 0.0
best_start = -1
exact_start = page_key.find(candidate_window)
if exact_start >= 0:
best_score = 1.0
best_start = exact_start
step = max(1, window_size // 12)
for start in range(0, len(page_key) - window_size + 1, step):
if best_score == 1.0:
break
window = page_key[start : start + window_size]
score = difflib.SequenceMatcher(a=candidate_window, b=window, autojunk=False).ratio()
if score > best_score:
best_score = score
best_start = start
if best_start < 0 or best_score < MIN_FUZZY_SCORE:
return None
raw_start = compact_to_raw[best_start]
raw_end_index = min(best_start + window_size - 1, len(compact_to_raw) - 1)
raw_end = compact_to_raw[raw_end_index]
count = max(1, raw_end - raw_start + 1)
rects = [textpage.get_charbox(char_index) for char_index in range(raw_start, raw_start + count)]
return {
"char_index": int(raw_start),
"char_count": int(count),
"rects": _merge_char_rects(rects),
"matched_text": textpage.get_text_range(raw_start, count),
"confidence": round(best_score, 3),
"method": "fuzzy",
}
def locate_pdf_evidence(pdf_bytes: bytes, item: dict[str, Any]) -> dict[str, Any] | None:
"""
在 PDF 中定位一个审核发现的合同原文证据。
Args:
pdf_bytes: 原合同 PDF 字节。
item: 审核发现项,仅使用 new_text/evidence 字段。
Returns:
成功时返回 page_no、rects、matched_text、confidence;无法可靠定位时返回 None。
"""
import pypdfium2 as pdfium
candidates = _candidate_texts(item)
if not candidates:
return None
document = pdfium.PdfDocument(pdf_bytes)
try:
best: dict[str, Any] | None = None
for page_index in range(len(document)):
page = document[page_index]
textpage = page.get_textpage()
page_text = textpage.get_text_range()
for candidate in candidates:
located = _exact_anchor(textpage, candidate)
if located is None:
located = _fuzzy_anchor(page_text, textpage, candidate)
if located is None:
continue
located["page_no"] = page_index + 1
located["source_text"] = candidate
if located["method"] == "exact":
return located
if best is None or located["confidence"] > best["confidence"]:
best = located
return best
finally:
document.close()
def enrich_result_with_pdf_anchors(
result: dict[str, Any],
*,
filename: str,
pdf_bytes: bytes,
ocr_layout: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
给审核结果逐项写入 PDF 证据锚点和定位统计;失败不会中断审核主流程。
Args:
result: 已完成规则和 LLM 合并的审核结果。
filename: 原合同文件名;非 PDF 时直接标记 unsupported。
pdf_bytes: 原合同字节。
Returns:
原 result 的更新版本。
"""
clauses = result.get("clauses_json") if isinstance(result.get("clauses_json"), list) else []
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
if not str(filename or "").lower().endswith(".pdf"):
summary["evidence_anchoring"] = {"status": "unsupported", "anchored": 0, "unanchored": len(clauses)}
result["summary_json"] = summary
return result
anchored = 0
attempted = 0
for item in clauses:
if not isinstance(item, dict):
continue
is_compare_change = str(item.get("change_type") or "") in {"insert", "delete", "modify"}
if item.get("risk_level") == "ok" and not is_compare_change:
continue
attempted += 1
anchor = locate_pdf_evidence(pdf_bytes, item)
if anchor is None:
anchor = locate_ocr_layout_evidence(ocr_layout, item)
if anchor:
item["evidence_anchor"] = anchor
item["anchor_status"] = "anchored"
anchored += 1
else:
item["anchor_status"] = "unanchored"
summary["evidence_anchoring"] = {
"status": "complete",
"anchored": anchored,
"unanchored": max(0, attempted - anchored),
}
result["summary_json"] = summary
return result
def _annotation_color(risk_level: str) -> str:
"""映射风险等级到 PDF 高亮颜色。"""
if risk_level == "high":
return "ff6b6b"
if risk_level == "medium":
return "ffb84d"
return "ffe066"
def build_annotated_pdf_bytes(
pdf_bytes: bytes,
clauses: list[dict[str, Any]],
*,
clean_text: str = "",
ocr_layout: dict[str, Any] | None = None,
) -> bytes:
"""
按 evidence_anchor 在原 PDF 副本上写入可打印的标准高亮批注。
Args:
pdf_bytes: 原合同 PDF 字节。
clauses: 审核发现列表;优先使用 evidence_anchor,扫描件可回退 OCR 页码定位。
clean_text: 包含 page-image 标记的清洗正文,仅用于扫描 PDF 页级批注。
Returns:
带高亮批注的 PDF 字节;没有可定位发现时返回原合同副本。
"""
from pypdf import PdfReader, PdfWriter
from pypdf.annotations import Highlight, Text
from pypdf.generic import ArrayObject, FloatObject, NameObject, TextStringObject
reader = PdfReader(io.BytesIO(pdf_bytes))
writer = PdfWriter()
writer.clone_document_from_reader(reader)
annotation_count = 0
for item in clauses:
anchor = item.get("evidence_anchor") if isinstance(item, dict) else None
if not isinstance(anchor, dict) and isinstance(item, dict):
anchor = locate_ocr_layout_evidence(ocr_layout, item)
if not isinstance(anchor, dict) and isinstance(item, dict):
anchor = locate_ocr_evidence_page(clean_text, item)
if not isinstance(anchor, dict):
continue
page_index = int(anchor.get("page_no") or 0) - 1
if page_index < 0 or page_index >= len(writer.pages):
continue
rects = anchor.get("rects") or []
if not rects and anchor.get("ocr_polygons"):
page = writer.pages[page_index]
width = float(page.mediabox.width)
height = float(page.mediabox.height)
page_left = float(page.mediabox.left)
page_bottom = float(page.mediabox.bottom)
for polygon in anchor.get("ocr_polygons") or []:
if not isinstance(polygon, list) or len(polygon) < 4:
continue
try:
xs = [float(point[0]) for point in polygon]
ys = [float(point[1]) for point in polygon]
except (TypeError, ValueError, IndexError):
continue
rects.append([
page_left + min(xs) * width,
page_bottom + (1.0 - max(ys)) * height,
page_left + max(xs) * width,
page_bottom + (1.0 - min(ys)) * height,
])
for raw_rect in rects:
if not isinstance(raw_rect, list) or len(raw_rect) != 4:
continue
left, bottom, right, top = [float(value) for value in raw_rect]
quad_points = ArrayObject(
[
FloatObject(left), FloatObject(top), FloatObject(right), FloatObject(top),
FloatObject(left), FloatObject(bottom), FloatObject(right), FloatObject(bottom),
]
)
annotation = Highlight(
rect=(left, bottom, right, top),
quad_points=quad_points,
highlight_color=_annotation_color(str(item.get("risk_level") or "low")),
printing=True,
)
annotation[NameObject("/Contents")] = TextStringObject(
f"{item.get('title') or '合同审核提示'}: {item.get('detail') or ''}"
)
writer.add_annotation(page_number=page_index, annotation=annotation)
annotation_count += 1
if not rects:
page = writer.pages[page_index]
top = float(page.mediabox.top)
note = Text(
rect=(18, max(18, top - 42), 38, max(38, top - 22)),
text=f"{item.get('title') or '合同审核提示'}: {item.get('detail') or ''}",
open=False,
)
writer.add_annotation(page_number=page_index, annotation=note)
annotation_count += 1
output = io.BytesIO()
writer.write(output)
return output.getvalue()
@@ -0,0 +1,468 @@
"""
backend/app/services/procurement_contract/preprocessing.py
用途:复用知识库 edkb_system 清洗能力,为单次合同审核生成 Markdown 和结构化条款产物。
依赖:knowledge_cleaning.edkb_adapter、file_assets、procurement_contract.analyze。
逻辑:合同 Worker 读取 FileAsset 字节 → 写入审查专属目录 → 清洗为 Markdown → 合同去噪与条款切分;
不创建 KbDocument,也不把一次性合同同步到企业正式 Dataset。
"""
from __future__ import annotations
import json
import mimetypes
import re
import shutil
from pathlib import Path
from typing import Any
import requests
from flask import current_app
from app.core.errors import ValidationError
from app.models import FileAsset
from app.services.file_assets.service import read_asset_bytes
from app.services.knowledge_cleaning.edkb_adapter import build_clean_result
from app.services.procurement_contract import analyze, artifact_archive
from edkb_system.skills.soffice_util import convert_with_soffice, find_soffice
OCR_LAYOUT_ARTIFACT = "ocr_layout.json"
_OCR_RENDER_SCALE = 1.25
def _extract_pdf_page_texts(pdf_path: Path) -> list[str]:
"""
Extract searchable text per PDF page while preserving the source pagination.
Args:
pdf_path: Existing PDF path produced by upload or LibreOffice conversion.
Returns:
One string per physical page; blank strings are retained so page counts remain exact.
"""
import pypdfium2 as pdfium
document = pdfium.PdfDocument(str(pdf_path))
try:
pages: list[str] = []
for page_index in range(len(document)):
page = document[page_index]
text_page = page.get_textpage()
try:
pages.append(text_page.get_text_range() or "")
finally:
text_page.close()
page.close()
return pages
finally:
document.close()
def _ocr_marker_page_texts(raw_text: str) -> list[str]:
"""Recover page-aligned OCR text from existing `page-image-N` markers for scanned PDFs."""
matches = list(re.finditer(r"!\[page-image-(\d+)\]", raw_text or "", flags=re.I))
if not matches:
return []
pages: list[str] = []
for index, match in enumerate(matches):
end = matches[index + 1].start() if index + 1 < len(matches) else len(raw_text)
pages.append(raw_text[match.end() : end].strip())
return pages
def _ocr_layout_from_edkb(raw_layout_path: Path | None) -> list[dict[str, Any]]:
"""从 edkb 原始布局中提取 PDF 整页 OCR 行框,避免重复执行 OCR。"""
if not raw_layout_path or not raw_layout_path.is_file():
return []
try:
blocks = json.loads(raw_layout_path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return []
pages: dict[int, list[dict[str, Any]]] = {}
for block in blocks if isinstance(blocks, list) else []:
if not isinstance(block, dict) or block.get("type") != "ocr_text":
continue
meta = block.get("meta") if isinstance(block.get("meta"), dict) else {}
if not meta.get("page_image") or not isinstance(meta.get("ocr_lines"), list):
continue
page_no = int(block.get("page") or 0)
if page_no <= 0:
continue
lines = [item for item in meta["ocr_lines"] if isinstance(item, dict) and item.get("polygon")]
if lines:
pages.setdefault(page_no, []).extend(lines)
return [{"page_no": page_no, "lines": pages[page_no]} for page_no in sorted(pages)]
def _ocr_layout_from_pdf(pdf_path: Path) -> list[dict[str, Any]]:
"""
为无文本层 PDF 生成行级 OCR 坐标;RapidOCR 不可用或单页失败时安全返回其余页面。
坐标保存为左上角原点的归一化多边形,下载标注时再按实际 PDF 页面尺寸换算。
"""
try:
import numpy as np
import pypdfium2 as pdfium
from edkb_system.skills.ocr import recognize_image_lines
except Exception:
return []
try:
document = pdfium.PdfDocument(str(pdf_path))
except Exception:
return []
pages: list[dict[str, Any]] = []
try:
for page_index in range(len(document)):
page = document[page_index]
try:
text_page = page.get_textpage()
try:
if (text_page.get_text_range() or "").strip():
continue
finally:
text_page.close()
bitmap = page.render(scale=_OCR_RENDER_SCALE)
image = np.asarray(bitmap.to_pil().convert("RGB"))
lines = recognize_image_lines(image, pdf_page_image=True)
if lines:
pages.append({"page_no": page_index + 1, "lines": lines})
except Exception:
continue
finally:
page.close()
finally:
document.close()
return pages
def _persist_pdf_ocr_layout(
source_path: Path,
target_dir: Path,
*,
raw_layout_path: Path | None = None,
) -> dict[str, Any] | None:
"""复用或生成纯图片 PDF 行坐标,并保存为合同审查可归档产物。"""
if source_path.suffix.lower() != ".pdf":
return None
pages = _ocr_layout_from_edkb(raw_layout_path)
source = "edkb"
if not pages:
pages = _ocr_layout_from_pdf(source_path)
source = "rapidocr_fallback"
if not pages:
return None
payload = {"version": 1, "coordinate_space": "normalized_top_left", "pages": pages}
artifact_path = target_dir / OCR_LAYOUT_ARTIFACT
artifact_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
return {
"source": source,
"page_count": len(pages),
"line_count": sum(len(page.get("lines") or []) for page in pages),
}
def _extract_page_texts(source_path: Path, target_dir: Path, raw_text: str) -> tuple[list[str], str | None]:
"""
Produce physical-page text for PDF and Word files without inventing page boundaries.
Word files are converted to PDF through the existing LibreOffice utility. If conversion or PDF
parsing fails, callers receive no pages and comparison-region logic safely falls back to full diff.
When MinerU supplies readable full-document OCR but a PDF has no native text layer, use one logical
page for body-boundary recognition. Logical pagination deliberately does not claim physical page counts.
"""
suffix = source_path.suffix.lower()
pdf_path = source_path
warning: str | None = None
if suffix in {".doc", ".docx"}:
soffice = find_soffice()
if not soffice:
return [], "LibreOffice is unavailable; comparison regions were not applied"
page_dir = target_dir / "page_source"
page_dir.mkdir(parents=True, exist_ok=True)
completed = convert_with_soffice(
soffice,
convert_to="pdf",
source_path=source_path,
out_dir=page_dir,
)
pdf_path = page_dir / f"{source_path.stem}.pdf"
if completed.returncode != 0 or not pdf_path.is_file():
shutil.rmtree(page_dir, ignore_errors=True)
return [], "LibreOffice conversion failed; comparison regions were not applied"
elif suffix != ".pdf":
return [], "File format has no reliable pagination; comparison regions were not applied"
try:
pages = _extract_pdf_page_texts(pdf_path)
marker_pages = _ocr_marker_page_texts(raw_text)
if marker_pages and len(marker_pages) >= len(pages):
pages = marker_pages
elif not any(page.strip() for page in pages) and raw_text.strip():
# MinerU's current response exposes only md_content. Keep its readable OCR available for
# body anchors instead of rejecting the region config solely because the source PDF lacks text.
pages = [raw_text]
warning = "PDF native page text unavailable; used MinerU logical page for body boundaries"
return [analyze.clean_contract_text(page) for page in pages], warning
except Exception as exc: # noqa: BLE001 - page extraction is optional and has an explicit fallback
marker_pages = _ocr_marker_page_texts(raw_text)
if marker_pages:
return [analyze.clean_contract_text(page) for page in marker_pages], str(exc)[:500]
return [], str(exc)[:500]
def _mineru_parse_pdf(source_path: Path, target_dir: Path) -> tuple[str, dict[str, Any]]:
"""
调用部署在内网的 MinerU API 解析 PDF,并保存完整返回供合同审核审计追溯。
核心逻辑:以同步 `/file_parse` 接口上传单份 PDF,读取对应文件的 `md_content`;MinerU
服务地址为空、接口失败或未返回 Markdown 时抛出异常,调用方再回退现有清洗器。
Args:
source_path: 审查目录内的 PDF 文件。
target_dir: 当前合同角色的清洗产物目录。
Returns:
MinerU Markdown 正文和不含绝对路径的解析元数据。
Raises:
RuntimeError: MinerU 未配置、请求失败或响应缺少当前文件的 Markdown。
"""
api_url = str(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_API_URL") or "").strip().rstrip("/")
if not api_url:
raise RuntimeError("MinerU API is not configured")
connect_timeout = max(int(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_CONNECT_TIMEOUT_SECONDS") or 5), 1)
read_timeout = max(int(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_READ_TIMEOUT_SECONDS") or 300), 30)
backend = str(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_BACKEND") or "pipeline").strip() or "pipeline"
parse_method = str(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_PARSE_METHOD") or "auto").strip() or "auto"
content_type = mimetypes.guess_type(source_path.name)[0] or "application/pdf"
payload = {
"lang_list": "ch",
"backend": backend,
"parse_method": parse_method,
"formula_enable": "false",
}
try:
with source_path.open("rb") as handle:
response = requests.post(
f"{api_url}/file_parse",
data=payload,
files=[("files", (source_path.name, handle, content_type))],
timeout=(connect_timeout, read_timeout),
)
response.raise_for_status()
result = response.json()
except (OSError, ValueError, requests.RequestException) as exc:
raise RuntimeError(f"MinerU parse failed: {exc}") from exc
if str(result.get("status") or "").lower() != "completed":
detail = str(result.get("error") or result.get("status") or "unknown status")
raise RuntimeError(f"MinerU parse did not complete: {detail}")
results = result.get("results")
if not isinstance(results, dict) or not results:
raise RuntimeError("MinerU response has no file results")
# API 以去扩展名文件名为 key;单文件请求直接取唯一结果,避免依赖服务端命名规则。
parsed = next((value for value in results.values() if isinstance(value, dict)), None)
markdown = str((parsed or {}).get("md_content") or "").strip()
if not markdown:
raise RuntimeError("MinerU response has no md_content")
(target_dir / "mineru_result.json").write_text(
json.dumps(result, ensure_ascii=False, indent=2),
encoding="utf-8",
)
(target_dir / "mineru_document.md").write_text(markdown, encoding="utf-8")
return markdown, {
"provider": "mineru",
"backend": str(result.get("backend") or backend),
"version": str(result.get("version") or ""),
"parse_method": parse_method,
"result_artifact": "mineru_result.json",
}
def _review_root(review_no: str) -> Path:
"""解析并创建审查专属存储目录,拒绝把审查编号解释为路径。"""
safe_no = re.sub(r"[^A-Za-z0-9_-]+", "_", str(review_no or "").strip())[:80]
if not safe_no:
raise ValidationError("review_no is required")
root = Path(str(current_app.config["PROCUREMENT_CONTRACT_STORAGE_ROOT"])).resolve() / safe_no
root.mkdir(parents=True, exist_ok=True)
return root
def _safe_source_name(filename: str, role: str) -> str:
"""生成保留扩展名的本地文件名,避免原文件名穿越审查目录。"""
suffix = Path(str(filename or "")).suffix.lower()[:16]
return f"{role}{suffix or '.bin'}"
def clean_review_asset(
*,
review_no: str,
role: str,
asset: FileAsset,
) -> dict[str, Any]:
"""
清洗一份合同或模板并产出合同审核结构。
核心逻辑:优先使用知识库 edkb_system 生成 Markdown;失败时回退到合同域本地抽取器,
随后执行合同专用去噪和条款切分,并保存 `document.md` / `clauses.json`。
Args:
review_no: 合同审查编号,只用于隔离产物目录。
role: 仅允许 contract 或 template。
asset: 已校验可读的 FileAsset ORM 对象。
Returns:
包含 clean_text、clauses 和不暴露绝对路径的 extraction_meta。
Raises:
ValidationError: 文件无法产生可审核正文。
"""
normalized_role = str(role or "").strip().lower()
if normalized_role not in {"contract", "template"}:
raise ValidationError("role must be contract or template")
review_root = _review_root(review_no)
source_dir = review_root / "source"
target_dir = review_root / "cleaned" / normalized_role
source_dir.mkdir(parents=True, exist_ok=True)
target_dir.mkdir(parents=True, exist_ok=True)
data = read_asset_bytes(asset)
source_path = source_dir / _safe_source_name(asset.original_filename, normalized_role)
source_path.write_bytes(data)
mode = "edkb_system"
warning: str | None = None
mineru_meta: dict[str, Any] = {}
raw_layout_path: Path | None = None
# [STEP 1] PDF 优先交给 MinerU 恢复版面、表格与阅读顺序;未配置或服务异常时保持旧链路可用。
if source_path.suffix.lower() == ".pdf" and current_app.config.get("PROCUREMENT_CONTRACT_MINERU_API_URL"):
try:
raw_text, mineru_meta = _mineru_parse_pdf(source_path, target_dir)
mode = "mineru"
except Exception as exc: # noqa: BLE001 - MinerU is an optional parser with explicit fallback
warning = str(exc)[:500]
if mode != "mineru":
try:
clean_result = build_clean_result(source_path, target_dir)
cleaned_path = Path(str(clean_result.get("cleaned_file_path") or ""))
raw_text = cleaned_path.read_text(encoding="utf-8", errors="ignore") if cleaned_path.is_file() else ""
mode = str(clean_result.get("mode") or mode)
raw_layout_value = str(clean_result.get("raw_layout_path") or "").strip()
raw_layout_path = Path(raw_layout_value) if raw_layout_value else None
except Exception as exc: # noqa: BLE001 - local extractor is the intended degradation path
warning = f"{warning}; {exc}".strip("; ")[:500]
mode = "local_fallback"
raw_text = analyze.extract_text_from_bytes(asset.original_filename, data)
# 保留清洗器原始分页/OCR文本供扫描 PDF 批注定位;审核正文会继续移除页码和图片标记。
(target_dir / "ocr_document.md").write_text(raw_text, encoding="utf-8")
clean_text = analyze.clean_contract_text(raw_text)
if not clean_text or clean_text.startswith("[binary:"):
raise ValidationError("合同正文无法解析,请上传 Word 或可检索文本的 PDF")
clauses = analyze.structure_contract_clauses(clean_text)
if not clauses:
raise ValidationError("合同正文未识别到可审核条款")
document_path = target_dir / "document.md"
clauses_path = target_dir / "clauses.json"
document_path.write_text(clean_text, encoding="utf-8")
clauses_path.write_text(json.dumps(clauses, ensure_ascii=False, indent=2), encoding="utf-8")
quality = analyze.extraction_quality(clean_text)
page_texts, page_warning = _extract_page_texts(source_path, target_dir, raw_text)
ocr_layout = _persist_pdf_ocr_layout(source_path, target_dir, raw_layout_path=raw_layout_path)
if ocr_layout:
ocr_layout["artifact"] = f"cleaned/{normalized_role}/{OCR_LAYOUT_ARTIFACT}"
return {
"clean_text": clean_text,
"clauses": clauses,
"page_texts": page_texts,
"page_count": len(page_texts),
"extraction_meta": {
"role": normalized_role,
"mode": mode,
"character_count": len(clean_text),
"clause_count": len(clauses),
"quality": quality,
"warning": warning or page_warning or quality.get("warning"),
"document_artifact": f"cleaned/{normalized_role}/document.md",
"clauses_artifact": f"cleaned/{normalized_role}/clauses.json",
"mineru": mineru_meta or None,
"ocr_layout": ocr_layout,
},
}
def persist_review_result_artifact(review_no: str, result: dict[str, Any]) -> None:
"""
保存最终结构化结果副本,供问题排查和审计回溯。
Args:
review_no: 合同审查编号。
result: 已完成后端校验和合并的结果字典。
"""
result_dir = _review_root(review_no) / "result"
result_dir.mkdir(parents=True, exist_ok=True)
(result_dir / "merged_result.json").write_text(
json.dumps(result, ensure_ascii=False, indent=2, default=str),
encoding="utf-8",
)
def read_review_clean_text(review_no: str, *, role: str = "contract") -> str:
"""
读取审查任务已保存的清洗正文,供扫描 PDF 下载时按 OCR 分页补充批注定位。
Args:
review_no: 合同审查编号。
role: 仅允许 contract 或 template;下载标注合同默认读取 contract。
Returns:
清洗后的 Markdown 正文;产物不存在时返回空字符串。
"""
normalized_role = str(role or "").strip().lower()
if normalized_role not in {"contract", "template"}:
raise ValidationError("role must be contract or template")
role_root = _review_root(review_no) / "cleaned" / normalized_role
ocr_document_path = role_root / "ocr_document.md"
if not ocr_document_path.is_file():
artifact_archive.restore_review_artifact(
review_no,
f"cleaned/{normalized_role}/ocr_document.md",
)
if ocr_document_path.is_file():
return ocr_document_path.read_text(encoding="utf-8", errors="ignore")
document_path = role_root / "document.md"
if not document_path.is_file():
artifact_archive.restore_review_artifact(
review_no,
f"cleaned/{normalized_role}/document.md",
)
if not document_path.is_file():
return ""
return document_path.read_text(encoding="utf-8", errors="ignore")
def read_review_ocr_layout(review_no: str, *, role: str = "contract") -> dict[str, Any]:
"""读取或从 MinIO 恢复纯图片 PDF 的行级 OCR 坐标产物。"""
normalized_role = str(role or "").strip().lower()
if normalized_role not in {"contract", "template"}:
raise ValidationError("role must be contract or template")
relative_path = f"cleaned/{normalized_role}/{OCR_LAYOUT_ARTIFACT}"
layout_path = _review_root(review_no) / relative_path
if not layout_path.is_file():
artifact_archive.restore_review_artifact(review_no, relative_path)
if not layout_path.is_file():
return {}
try:
payload = json.loads(layout_path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
return payload if isinstance(payload, dict) else {}
@@ -0,0 +1,838 @@
"""
backend/app/services/procurement_contract/review_service.py
用途:创建、异步执行、查询与导出采购合同审查记录。
依赖:ContractReview/FileAsset/Job、知识库清洗适配器、rule/analyze/llm_enhancer/pdf_annotation/visual_ocr_validation。
逻辑:Chat/Admin API 创建 queued 审查 → Worker 清洗 → 改稿 Diff/五灯或单份五问 →
(仅 solo 可选)LLM 增强 → 页锚落库。比对模式默认不做 Dify 全面扫描。
"""
from __future__ import annotations
import secrets
from datetime import datetime, timedelta
from typing import Any
from flask import current_app
from sqlalchemy import or_
from app import db
from app.core.config.settings import Config
from app.core.errors import ForbiddenError, NotFoundError, ValidationError
from app.core.response import utc_iso
from app.models import ContractReview, FileAsset, Job, User
from app.services.file_assets.service import mark_asset_referenced, read_asset_bytes
from app.services.procurement_contract import (
analyze,
artifact_archive,
comparison_regions,
llm_enhancer,
pdf_annotation,
preprocessing,
rule_service,
template_service,
visual_ocr_validation,
)
DEFAULT_CONTRACT_TYPE = "general_procurement"
def _gen_review_no() -> str:
"""Generate review number like CR-YYYYMMDD-AB12."""
day = datetime.utcnow().strftime("%Y%m%d")
return f"CR-{day}-{secrets.token_hex(2).upper()}"
def serialize_review(row: ContractReview, *, include_detail: bool = False) -> dict[str, Any]:
"""Convert a review ORM row into API response data."""
user = db.session.get(User, row.user_id) if row.user_id else None
data: dict[str, Any] = {
"id": row.id,
"review_no": row.review_no,
"review_mode": row.review_mode,
"status": row.status,
"contract_file_name": row.contract_file_name,
"supplier_name": row.supplier_name,
"contract_no": row.contract_no,
"contract_type": row.contract_type,
"template_id": row.template_id,
"template_source": row.template_source,
"template_name": row.template_name,
"total_change_count": row.total_change_count,
"high_risk_count": row.high_risk_count,
"medium_risk_count": row.medium_risk_count,
"low_risk_count": row.low_risk_count,
"user_id": row.user_id,
"user_name": (user.real_name or user.username) if user else None,
"error_message": row.error_message,
"started_at": utc_iso(row.started_at),
"finished_at": utc_iso(row.finished_at),
"created_at": utc_iso(row.created_at),
}
processing = row.summary_json.get("processing") if isinstance(row.summary_json, dict) else None
if isinstance(processing, dict):
data["progress"] = int(processing.get("progress") or 0)
data["processing_stage"] = processing.get("stage")
data["processing_message"] = processing.get("message")
else:
data["progress"] = 100 if row.status in {"success", "failed"} else 0
data["processing_stage"] = row.status
data["processing_message"] = None
if include_detail:
data["summary_json"] = row.summary_json
data["clauses_json"] = row.clauses_json
data["report_text"] = row.report_text
data["contract_asset_id"] = row.contract_asset_id
data["template_asset_id"] = row.template_asset_id
data["agent_id"] = row.agent_id
data["chat_log_id"] = row.chat_log_id
return data
def _parse_date(value: str | None, *, end_of_day: bool = False) -> datetime | None:
"""Parse YYYY-MM-DD or ISO datetime filter values."""
raw = str(value or "").strip()
if not raw:
return None
try:
if len(raw) == 10:
dt = datetime.strptime(raw, "%Y-%m-%d")
return dt + timedelta(days=1) if end_of_day else dt
return datetime.fromisoformat(raw.replace("Z", "+00:00")).replace(tzinfo=None)
except ValueError as exc:
raise ValidationError("invalid date filter") from exc
def list_reviews(
*,
review_mode: str | None = None,
template_source: str | None = None,
status: str | None = None,
keyword: str | None = None,
user_id: int | None = None,
contract_type: str | None = None,
supplier_name: str | None = None,
risk_level: str | None = None,
date_from: str | None = None,
date_to: str | None = None,
limit: int = 100,
offset: int = 0,
) -> dict[str, Any]:
"""List review history with filters used by admin and chat pages."""
q = db.session.query(ContractReview)
if review_mode:
q = q.filter(ContractReview.review_mode == review_mode)
if template_source:
q = q.filter(ContractReview.template_source == template_source)
if status:
q = q.filter(ContractReview.status == status)
if user_id is not None:
q = q.filter(ContractReview.user_id == user_id)
if contract_type:
q = q.filter(ContractReview.contract_type == contract_type)
if supplier_name:
q = q.filter(ContractReview.supplier_name.ilike(f"%{supplier_name.strip()}%"))
if risk_level == "high":
q = q.filter(ContractReview.high_risk_count > 0)
elif risk_level == "medium":
q = q.filter(ContractReview.high_risk_count == 0, ContractReview.medium_risk_count > 0)
elif risk_level == "low":
q = q.filter(
ContractReview.high_risk_count == 0,
ContractReview.medium_risk_count == 0,
ContractReview.low_risk_count > 0,
)
start = _parse_date(date_from)
end = _parse_date(date_to, end_of_day=True)
if start:
q = q.filter(ContractReview.created_at >= start)
if end:
q = q.filter(ContractReview.created_at < end)
if keyword:
like = f"%{keyword.strip()}%"
q = q.filter(
or_(
ContractReview.review_no.ilike(like),
ContractReview.contract_file_name.ilike(like),
ContractReview.template_name.ilike(like),
ContractReview.supplier_name.ilike(like),
ContractReview.contract_no.ilike(like),
)
)
total = q.count()
rows = (
q.order_by(ContractReview.created_at.desc())
.offset(max(0, int(offset or 0)))
.limit(min(max(int(limit or 100), 1), 200))
.all()
)
return {"total": total, "items": [serialize_review(r) for r in rows]}
def _load_review_row(*, review_id: int | None = None, review_no: str | None = None) -> ContractReview:
"""Load a review row by id or review_no."""
row = None
if review_id is not None:
row = db.session.get(ContractReview, review_id)
elif review_no:
row = db.session.query(ContractReview).filter(ContractReview.review_no == review_no).first()
if not row:
raise NotFoundError("review not found")
return row
def get_review(review_id: int | None = None, review_no: str | None = None) -> dict[str, Any]:
"""Get review details by id or review_no."""
return serialize_review(_load_review_row(review_id=review_id, review_no=review_no), include_detail=True)
def get_review_for_owner(*, review_no: str, user_id: int) -> dict[str, Any]:
"""
Get a user's review, recovering a stale background job before serializing it.
A browser reload must not leave a card permanently at its last persisted progress when the
contract worker has exited mid-task. Only an already-stale running job is recovered here;
normal task claiming remains the worker's responsibility.
"""
row = _load_review_row(review_no=review_no)
if row.user_id != user_id:
raise ForbiddenError("not your review")
_recover_stale_review_if_needed(row)
db.session.refresh(row)
return serialize_review(row, include_detail=True)
def _recover_stale_review_if_needed(row: ContractReview) -> None:
"""Recover timed-out contract jobs when a user polls a still-running review card."""
if row.status != "running" or not row.started_at:
return
timeout_seconds = max(int(getattr(Config, "PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS", 600) or 600), 60)
if row.started_at >= datetime.utcnow() - timedelta(seconds=timeout_seconds):
return
from app.jobs.queue import recover_stale_jobs
from app.jobs.types import JobType
recover_stale_jobs(
domain="procurement_contract",
timeout_seconds=timeout_seconds,
job_type=JobType.PROCUREMENT_CONTRACT_REVIEW,
on_recovered=sync_review_after_job_recovery,
)
def read_review_report_bytes(*, review_id: int | None = None, review_no: str | None = None) -> tuple[str, bytes]:
"""
读取纯文本审查报告字节。
核心逻辑:正文前拼接审查编号、业务合同编号与供应商(乙方/卖方)。
"""
row = _load_review_row(review_id=review_id, review_no=review_no)
body = row.report_text or ""
if not body and isinstance(row.summary_json, dict):
body = str(row.summary_json.get("headline") or "")
header = "\n".join(
[
f"审查编号:{row.review_no}",
f"待审合同:{row.contract_file_name}",
f"合同编号:{row.contract_no or '-'}",
f"供应商(乙方/卖方):{row.supplier_name or '-'}",
"",
body,
]
)
return f"{row.review_no}_report.txt", header.encode("utf-8")
def read_review_report_docx_bytes(*, review_id: int | None = None, review_no: str | None = None) -> tuple[str, bytes, str]:
"""
Create a docx report when python-docx is available.
Returns filename, bytes and mimetype; falls back to plain text without failing export.
"""
row = _load_review_row(review_id=review_id, review_no=review_no)
try:
import io
from docx import Document
doc = Document()
doc.add_heading("合同差异对比报告" if row.review_mode == "compare" else "采购合同风险审核报告", level=1)
doc.add_paragraph(f"审查编号:{row.review_no}")
doc.add_paragraph(f"待审合同:{row.contract_file_name}")
doc.add_paragraph(f"合同编号:{row.contract_no or '-'}")
doc.add_paragraph(f"供应商(乙方/卖方):{row.supplier_name or '-'}")
doc.add_paragraph(f"审查模式:{row.review_mode}")
if row.review_mode == "compare":
doc.add_paragraph(
f"差异统计:共 {row.total_change_count} 项;风险参考:高 {row.high_risk_count} / "
f"中 {row.medium_risk_count} / 低 {row.low_risk_count}"
)
else:
doc.add_paragraph(f"风险统计:高 {row.high_risk_count} / 中 {row.medium_risk_count} / 低 {row.low_risk_count}")
doc.add_paragraph("说明:本报告为采购风险提示,不作为法律意见。")
doc.add_paragraph(row.report_text or "")
buffer = io.BytesIO()
doc.save(buffer)
return (
f"{row.review_no}_report.docx",
buffer.getvalue(),
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
)
except Exception:
name, data = read_review_report_bytes(review_id=review_id, review_no=review_no)
return name, data, "text/plain; charset=utf-8"
def read_review_contract_bytes(*, review_id: int | None = None, review_no: str | None = None) -> tuple[str, bytes]:
"""Read original contract bytes for a review."""
row = _load_review_row(review_id=review_id, review_no=review_no)
asset = db.session.get(FileAsset, row.contract_asset_id) if row.contract_asset_id else None
if not asset or asset.deleted_at is not None:
raise NotFoundError("contract file not found")
return asset.original_filename or row.contract_file_name or "contract.bin", read_asset_bytes(asset)
def read_review_template_bytes(*, review_id: int | None = None, review_no: str | None = None) -> tuple[str, bytes]:
"""Read the comparison baseline file used for a review (legacy field name: template)."""
row = _load_review_row(review_id=review_id, review_no=review_no)
asset = db.session.get(FileAsset, row.template_asset_id) if row.template_asset_id else None
if not asset or asset.deleted_at is not None:
raise NotFoundError("comparison baseline file not found")
return asset.original_filename or "original-contract.bin", read_asset_bytes(asset)
def read_review_annotated_contract_bytes(
*,
review_id: int | None = None,
review_no: str | None = None,
) -> tuple[str, bytes, str]:
"""
生成并读取带审核高亮批注的合同 PDF。
核心逻辑:文本型 PDF 使用 evidence_anchor 写入 Highlight;纯图片 PDF 优先使用已保存 OCR 行框,
无行框时再按 OCR 分页正文定位页面并写入批注意见。
原始 FileAsset 永不修改。没有任何可定位证据时仍返回原合同副本,避免下载入口报错。
"""
row = _load_review_row(review_id=review_id, review_no=review_no)
asset = db.session.get(FileAsset, row.contract_asset_id) if row.contract_asset_id else None
if not asset or asset.deleted_at is not None:
raise NotFoundError("contract file not found")
filename = asset.original_filename or row.contract_file_name or "contract.pdf"
if not filename.lower().endswith(".pdf"):
raise ValidationError("annotated contract is only available for PDF files")
clauses = row.clauses_json if isinstance(row.clauses_json, list) else []
data = pdf_annotation.build_annotated_pdf_bytes(
read_asset_bytes(asset),
clauses,
clean_text=preprocessing.read_review_clean_text(row.review_no),
ocr_layout=preprocessing.read_review_ocr_layout(row.review_no),
)
stem = filename.rsplit(".", 1)[0]
return f"{stem}_{row.review_no}_annotated.pdf", data, "application/pdf"
def start_review(
*,
user_id: int,
review_mode: str,
contract_asset_id: int | None = None,
contract_asset_no: str | None = None,
original_contract_asset_id: int | None = None,
original_contract_asset_no: str | None = None,
contract_type: str | None = None,
supplier_name: str | None = None,
agent_id: int | None = None,
chat_log_id: int | None = None,
) -> dict[str, Any]:
"""
创建采购合同审核记录并投递异步任务。
核心逻辑:比对模式校验我方原合同和卖方回传合同,单份模式仅校验待审合同;随后同事务写入 queued 审查与通用 Job。
文件清洗、Dify 调用和报告生成均由 Worker 执行,避免 Web 请求超时。
"""
mode = (review_mode or "").strip()
if mode not in ("compare", "solo"):
raise ValidationError("review_mode must be compare or solo")
if mode == "compare" and not (original_contract_asset_id or original_contract_asset_no):
raise ValidationError("original_contract_asset_no is required for compare mode")
contract_asset = _resolve_asset_for_user(
user_id=user_id,
asset_id=contract_asset_id,
asset_no=contract_asset_no,
label="contract",
)
normalized_contract_type = (contract_type or DEFAULT_CONTRACT_TYPE).strip() or DEFAULT_CONTRACT_TYPE
template_source = "none"
template_name = None
template_asset_id = None
template_id = None
if mode == "compare":
original_asset = _resolve_asset_for_user(
user_id=user_id,
asset_id=original_contract_asset_id,
asset_no=original_contract_asset_no,
label="original contract",
)
template_source = "user_upload"
template_asset_id = original_asset.id
template_name = original_asset.original_filename
row = ContractReview(
review_no=_gen_review_no(),
agent_id=agent_id,
user_id=user_id,
chat_log_id=chat_log_id,
review_mode=mode,
status="queued",
contract_asset_id=contract_asset.id,
contract_file_name=contract_asset.original_filename,
supplier_name=(supplier_name or "").strip() or None,
contract_type=normalized_contract_type,
template_id=template_id,
template_source=template_source,
template_asset_id=template_asset_id,
template_name=template_name,
total_change_count=0,
high_risk_count=0,
medium_risk_count=0,
low_risk_count=0,
summary_json={
"mode": mode,
"processing": {"stage": "queued", "progress": 0, "message": "等待后台审核"},
"review_note": "本结果为采购风险提示,不作为法律意见。",
},
)
db.session.add(row)
db.session.flush()
mark_asset_referenced(contract_asset)
if template_source == "user_upload" and template_asset_id:
original_asset = db.session.get(FileAsset, template_asset_id)
if original_asset:
mark_asset_referenced(original_asset)
from app.jobs import enqueue
from app.jobs.types import JobType
enqueue(
JobType.PROCUREMENT_CONTRACT_REVIEW,
{"review_no": row.review_no},
domain="procurement_contract",
business_ref=row.review_no,
created_by_id=user_id,
max_attempts=2,
message="等待合同清洗与审核",
commit=False,
)
db.session.commit()
return serialize_review(row, include_detail=True)
def _resolve_asset_for_user(*, user_id: int, asset_id: int | None, asset_no: str | None, label: str) -> FileAsset:
"""Resolve an uploaded file asset and enforce ownership for asset_no path."""
asset: FileAsset | None = None
if asset_id:
asset = db.session.get(FileAsset, asset_id)
elif asset_no:
from app.services.file_assets.service import get_asset_for_user
asset = get_asset_for_user(asset_no, user_id)
if not asset or asset.deleted_at is not None:
raise ValidationError(f"{label} file asset not found")
if asset.upload_status != "ready":
raise ValidationError(f"{label} file asset is not ready")
return asset
def _set_processing(
row: ContractReview,
*,
stage: str,
progress: int,
message: str,
job_id: int | None = None,
) -> None:
"""
同步更新业务审核记录和通用 Job 的阶段进度。
Args:
row: 当前 ContractReview。
stage/progress/message: 前端轮询展示的稳定阶段协议。
job_id: 可选通用 Job 主键;Worker 调用时同时更新队列监控信息。
"""
summary = dict(row.summary_json or {})
summary["processing"] = {
"stage": stage,
"progress": max(0, min(100, int(progress))),
"message": message,
}
row.summary_json = summary
row.status = "running" if stage not in {"success", "failed"} else stage
if job_id:
job = db.session.get(Job, int(job_id))
if job:
job.progress = max(0, min(100, int(progress)))
job.message = message[:500]
db.session.commit()
def execute_review_job(*, review_no: str, job_id: int | None = None) -> dict[str, Any]:
"""
在后台 Worker 中执行一份采购合同的完整审核。
核心逻辑:[STEP 1] 复用知识库清洗器;[STEP 2] 合同结构化;[STEP 3] Diff 与双边视觉 OCR 复核;
[STEP 4] 单份审核可选 Dify 法律扫描;[STEP 5] 后端重算、持久化和报告生成。
Args:
review_no: 已创建的审查编号。
job_id: 通用 Job 主键,用于同步进度。
Returns:
已落库的完整审核详情。
"""
row = _load_review_row(review_no=review_no)
row.started_at = row.started_at or datetime.utcnow()
row.finished_at = None
row.error_message = None
_set_processing(row, stage="extracting", progress=10, message="正在提取并清洗合同", job_id=job_id)
contract_asset = db.session.get(FileAsset, row.contract_asset_id)
if not contract_asset:
raise ValidationError("contract asset missing")
contract_doc = preprocessing.clean_review_asset(
review_no=row.review_no,
role="contract",
asset=contract_asset,
)
contract_text = str(contract_doc["clean_text"])
contract_clauses = list(contract_doc["clauses"])
party = analyze.extract_party_fields(contract_text)
if not row.supplier_name and party.get("supplier_name"):
row.supplier_name = str(party["supplier_name"])
if party.get("contract_no"):
row.contract_no = str(party["contract_no"])
_set_processing(row, stage="structuring", progress=30, message="正在识别合同条款结构", job_id=job_id)
rules = rule_service.get_enabled_rules(row.contract_type)
template_meta: dict[str, Any] | None = None
_set_processing(
row,
stage="deterministic_review",
progress=45,
message="正在执行模板比对与公司红线检查",
job_id=job_id,
)
if row.review_mode == "solo":
result = analyze.analyze_solo(contract_text, rules=rules)
else:
if not row.template_asset_id:
raise ValidationError("original contract asset missing for compare mode")
template_asset = db.session.get(FileAsset, row.template_asset_id)
if not template_asset:
raise ValidationError("original contract asset missing")
template_doc = preprocessing.clean_review_asset(
review_no=row.review_no,
role="template",
asset=template_asset,
)
template_meta = dict(template_doc["extraction_meta"])
# [STEP 1] 比对模式只做改稿红线 + 五灯,不再叠加整份 solo 扫描(避免噪声淹没采购)。
original_text = str(template_doc["clean_text"])
returned_text = contract_text
comparison_scope: dict[str, Any] = {
"status": "fallback",
"template_id": None,
"template_name": None,
"warning": "No enabled default template comparison-region config was available",
}
metadata_comparison: dict[str, Any] = {}
attachment_comparison: dict[str, Any] = {"status": "unavailable"}
default_template = template_service.get_default_enabled_template()
if default_template and isinstance(default_template.comparison_region_config, dict):
comparison_scope.update({
"template_id": default_template.id,
"template_name": default_template.name,
"warning": "Comparison-region anchors could not be recognized in both uploaded files",
})
try:
region_config = comparison_regions.validate_comparison_region_config(
default_template.comparison_region_config
)
original_diagnostic = comparison_regions.diagnose_partition(
original_text,
list(template_doc.get("page_texts") or []),
region_config,
)
returned_diagnostic = comparison_regions.diagnose_partition(
returned_text,
list(contract_doc.get("page_texts") or []),
region_config,
)
comparison_scope["diagnostics"] = {
"original_contract": original_diagnostic,
"returned_contract": returned_diagnostic,
}
original_partition = comparison_regions.partition_document(
original_text,
list(template_doc.get("page_texts") or []),
region_config,
)
returned_partition = comparison_regions.partition_document(
returned_text,
list(contract_doc.get("page_texts") or []),
region_config,
)
if original_partition and returned_partition:
original_text = original_partition.body
returned_text = returned_partition.body
metadata_comparison = comparison_regions.build_metadata_comparison(
original_partition.metadata,
returned_partition.metadata,
)
attachment_comparison = comparison_regions.build_attachment_comparison(
original_partition.attachment_pages,
returned_partition.attachment_pages,
)
comparison_scope = {
"status": "applied",
"template_id": default_template.id,
"template_name": default_template.name,
"body_start_found": True,
"body_end_found": True,
"signature_excluded": True,
"attachment_policy": region_config["attachment_policy"],
"diagnostics": {
"original_contract": original_diagnostic,
"returned_contract": returned_diagnostic,
},
"warning": None,
}
except ValidationError as exc:
comparison_scope["warning"] = exc.message
elif default_template:
comparison_scope.update({
"template_id": default_template.id,
"template_name": default_template.name,
"warning": "The enabled default template has no comparison-region config",
})
if comparison_scope["status"] == "fallback":
current_app.logger.warning(
"[contract-review] comparison region fallback review_no=%s template_id=%s "
"warning=%s diagnostics=%s",
row.review_no,
comparison_scope.get("template_id"),
comparison_scope.get("warning"),
comparison_scope.get("diagnostics"),
)
# [STEP 1] Uploaded original remains the baseline; Admin contributes only reusable region rules.
result = analyze.analyze_compare(original_text, returned_text, rules=rules)
# [STEP 2] 混合提取产生的地点类差异再做双边同源 OCR;只有视觉结果一致才移除。
try:
result = visual_ocr_validation.suppress_mixed_extraction_ocr_noise(
result,
review_no=row.review_no,
original_filename=template_asset.original_filename or row.template_name or "template.pdf",
original_pdf_bytes=read_asset_bytes(template_asset),
original_extraction_meta=template_meta,
original_ocr_layout=preprocessing.read_review_ocr_layout(row.review_no, role="template"),
returned_filename=contract_asset.original_filename or row.contract_file_name,
returned_pdf_bytes=read_asset_bytes(contract_asset),
returned_extraction_meta=dict(contract_doc["extraction_meta"]),
returned_ocr_layout=preprocessing.read_review_ocr_layout(row.review_no, role="contract"),
)
except Exception as exc: # noqa: BLE001 - OCR复核失败时必须保留原始差异并继续审核
current_app.logger.warning(
"[contract-review] visual OCR validation failed review_no=%s err=%s",
row.review_no,
exc,
)
validation_summary = (
result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
)
comparison_quality = (
validation_summary.get("comparison_quality")
if isinstance(validation_summary.get("comparison_quality"), dict)
else {}
)
comparison_quality["visual_ocr_rechecks"] = {
"status": "failed",
"mixed_extraction": None,
"checked": 0,
"ignored": 0,
"kept": 0,
"reason": str(exc)[:500],
"items": [],
}
validation_summary["comparison_quality"] = comparison_quality
result["summary_json"] = validation_summary
region_summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
region_summary["comparison_scope"] = comparison_scope
region_summary["metadata_comparison"] = metadata_comparison
region_summary["attachment_comparison"] = attachment_comparison
result["summary_json"] = region_summary
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
summary["extraction"] = {
"contract": contract_doc["extraction_meta"],
"template": template_meta,
}
summary["structured_clause_count"] = len(contract_clauses)
result["summary_json"] = summary
# [STEP 2] 比对模式关闭 Dify 全面审核;仅单份卖方合同可选 LLM 解释增强。
if row.review_mode == "solo":
_set_processing(row, stage="llm_reviewing", progress=60, message="正在补充 AI 风险说明", job_id=job_id)
result = llm_enhancer.enhance_review_result(
result,
review_no=row.review_no,
review_mode=row.review_mode,
contract_type=row.contract_type,
template_name=row.template_name,
clean_text=contract_text,
structured_clauses=contract_clauses,
)
else:
_set_processing(row, stage="validating", progress=70, message="正在整理比对结果", job_id=job_id)
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
summary["llm_enhancement"] = {
"enabled": False,
"status": "skipped",
"message": "compare mode uses redline + focus lights only",
}
result["summary_json"] = summary
_set_processing(row, stage="validating", progress=88, message="正在校验并合并审核结果", job_id=job_id)
try:
result = pdf_annotation.enrich_result_with_pdf_anchors(
result,
filename=contract_asset.original_filename or row.contract_file_name,
pdf_bytes=read_asset_bytes(contract_asset),
ocr_layout=preprocessing.read_review_ocr_layout(row.review_no),
)
except Exception as exc: # noqa: BLE001 - evidence anchoring is a non-blocking report enhancement
current_app.logger.warning(
"[contract-review] evidence anchoring failed review_no=%s err=%s",
row.review_no,
exc,
)
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
summary["evidence_anchoring"] = {"status": "failed", "anchored": 0, "unanchored": 0}
result["summary_json"] = summary
result = analyze.rebuild_result(result)
summary = result["summary_json"]
summary["processing"] = {"stage": "success", "progress": 100, "message": "审核完成"}
result["summary_json"] = summary
row.status = "success"
row.total_change_count = int(result.get("total_change_count") or 0)
row.high_risk_count = int(result.get("high_risk_count") or 0)
row.medium_risk_count = int(result.get("medium_risk_count") or 0)
row.low_risk_count = int(result.get("low_risk_count") or 0)
row.summary_json = result["summary_json"]
row.clauses_json = result["clauses_json"]
row.report_text = result["report_text"]
row.error_message = None
row.finished_at = datetime.utcnow()
db.session.commit()
try:
preprocessing.persist_review_result_artifact(row.review_no, result)
except Exception as exc: # noqa: BLE001 - audit copy failure must not invalidate persisted review
current_app.logger.warning("[contract-review] result artifact failed review_no=%s err=%s", row.review_no, exc)
try:
archive_meta = artifact_archive.archive_review_artifacts(row.review_no)
summary = dict(row.summary_json or {})
summary["artifact_archive"] = archive_meta
row.summary_json = summary
db.session.commit()
if archive_meta.get("status") == "archived":
artifact_archive.cleanup_local_review_artifacts(row.review_no)
except Exception as exc: # noqa: BLE001 - MinIO archiving must not turn a completed review into failure
current_app.logger.warning("[contract-review] artifact archive failed review_no=%s err=%s", row.review_no, exc)
summary = dict(row.summary_json or {})
summary["artifact_archive"] = {"status": "failed", "message": str(exc)[:500]}
row.summary_json = summary
db.session.commit()
return serialize_review(row, include_detail=True)
def mark_review_failed(*, review_no: str, error: str) -> None:
"""在后台任务最终失败时将审核记录收口为 failed,避免前端永久轮询。"""
row = _load_review_row(review_no=review_no)
summary = dict(row.summary_json or {})
summary["processing"] = {"stage": "failed", "progress": 100, "message": "审核失败"}
row.summary_json = summary
row.status = "failed"
row.error_message = str(error or "contract review failed")[:2000]
row.finished_at = datetime.utcnow()
db.session.commit()
def mark_review_retrying(*, review_no: str, error: str) -> None:
"""普通执行异常仍可重试时将业务审核状态恢复为 queued。"""
row = _load_review_row(review_no=review_no)
summary = dict(row.summary_json or {})
summary["processing"] = {"stage": "queued", "progress": 0, "message": "审核失败,等待后台重试"}
row.summary_json = summary
row.status = "queued"
row.error_message = str(error or "contract review retrying")[:2000]
row.finished_at = None
db.session.commit()
def sync_review_after_job_recovery(job: Job) -> None:
"""
通用队列回收超时合同任务时同步业务审核状态。
核心逻辑:任务仍可重试时把进度重置为 queued;重试耗尽时收口 failed。
本函数由 recover_stale_jobs 在同一事务内调用,不自行 commit。
Args:
job: 已被队列更新为 queued 或 failed 的通用 Job。
"""
review_no = str(job.business_ref or (job.payload_json or {}).get("review_no") or "").strip()
if not review_no:
return
row = db.session.query(ContractReview).filter(ContractReview.review_no == review_no).first()
if not row:
return
summary = dict(row.summary_json or {})
if job.status == "queued":
summary["processing"] = {"stage": "queued", "progress": 0, "message": "任务超时,等待后台重试"}
row.status = "queued"
row.finished_at = None
elif job.status == "failed":
summary["processing"] = {"stage": "failed", "progress": 100, "message": "审核任务执行超时"}
row.status = "failed"
row.error_message = str(job.error_message or "合同审核任务执行超时")[:2000]
row.finished_at = datetime.utcnow()
row.summary_json = summary
def _run_analysis(row: ContractReview) -> dict[str, Any]:
"""
兼容旧测试和内部调用的同步确定性分析入口。
核心逻辑:提取文本 → 解析供应商/合同编号 → Diff 或红线规则 → 把当事人字段写入报告头。
"""
contract_asset = db.session.get(FileAsset, row.contract_asset_id)
if not contract_asset:
raise ValidationError("contract asset missing")
contract_bytes = read_asset_bytes(contract_asset)
contract_text = analyze.extract_text_from_bytes(contract_asset.original_filename, contract_bytes)
party = analyze.extract_party_fields(contract_text)
rules = rule_service.get_enabled_rules(row.contract_type)
if row.review_mode == "solo":
result = analyze.analyze_solo(contract_text, rules=rules)
else:
if not row.template_asset_id:
raise ValidationError("original contract asset missing for compare mode")
tpl_asset = db.session.get(FileAsset, row.template_asset_id)
if not tpl_asset:
raise ValidationError("original contract asset missing")
tpl_bytes = read_asset_bytes(tpl_asset)
tpl_text = analyze.extract_text_from_bytes(tpl_asset.original_filename, tpl_bytes)
result = analyze.analyze_compare(tpl_text, contract_text, rules=rules)
result["extracted_supplier_name"] = party.get("supplier_name")
result["extracted_contract_no"] = party.get("contract_no")
return result
@@ -0,0 +1,289 @@
"""
backend/app/services/procurement_contract/rule_service.py
Purpose: Manage procurement contract risk rules used by compare and solo review.
Dependencies: ContractRiskRule model, SQLAlchemy session, unified AppError classes.
Flow: Admin CRUD persists configurable red-line rules; review_service loads enabled rules for analysis.
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from uuid import uuid4
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.core.response import utc_iso
from app.models import ContractRiskRule
DEFAULT_CONTRACT_TYPE = "general_procurement"
VALID_RISK_LEVELS = {"high", "medium", "low"}
VALID_STATUS = {"enabled", "disabled"}
VALID_TRIGGER_TYPES = {"keyword_missing", "keyword_present"}
# Keep categories stable because they drive result grouping, de-duplication and policy replacement.
VALID_CLAUSE_CATEGORIES = {
"payment",
"delivery",
"acceptance",
"warranty",
"liability",
"jurisdiction",
"dispute",
"ip",
"other",
}
BUILTIN_RULE_CODES = {
"payment_acceptance_required",
"acceptance_process_required",
"liability_required",
"jurisdiction_required",
"warranty_required",
}
def serialize_rule(row: ContractRiskRule) -> dict[str, Any]:
"""Convert a risk rule ORM row into API response data."""
return {
"id": row.id,
"code": row.code,
"rule_kind": "builtin" if row.code in BUILTIN_RULE_CODES else "custom",
"contract_type": row.contract_type,
"clause_category": row.clause_category,
"title": row.title,
"keywords": row.keywords or [],
"trigger_type": row.trigger_type,
"risk_level": row.risk_level,
"risk_hint": row.risk_hint,
"suggestion": row.suggestion,
"negotiation_text": row.negotiation_text,
"status": row.status,
"sort_order": row.sort_order,
"created_at": utc_iso(row.created_at),
"updated_at": utc_iso(row.updated_at),
}
def _normalize_keywords(raw: Any) -> list[str]:
"""Normalize JSON/list/string keywords into a unique non-empty string list."""
if isinstance(raw, str):
items = [p.strip() for p in raw.replace(",", ",").split(",")]
elif isinstance(raw, list):
items = [str(p).strip() for p in raw]
else:
items = []
seen: set[str] = set()
result: list[str] = []
for item in items:
if item and item not in seen:
seen.add(item)
result.append(item)
return result
def _validate_clause_category(category: str) -> str:
"""
Validate and normalize a rule category used by the contract analyzer.
Args:
category: Stable category code selected in the admin form; free-form labels are not supported.
Returns:
A validated category code.
Raises:
ValidationError: If the category cannot participate in result grouping safely.
"""
normalized = category.strip().lower()
if normalized not in VALID_CLAUSE_CATEGORIES:
raise ValidationError("invalid clause_category")
return normalized
def _generate_custom_rule_code(category: str) -> str:
"""
Generate an opaque code for a custom keyword rule.
The code is an internal identifier only. Generating it server-side prevents administrators from
accidentally using a built-in code that carries compound business logic.
Args:
category: Validated clause category used to make the generated code traceable.
Returns:
Globally unique custom rule code.
"""
return f"custom_{category}_{uuid4().hex[:12]}"
def list_rules(
*,
contract_type: str | None = None,
status: str | None = None,
clause_category: str | None = None,
) -> list[dict[str, Any]]:
"""List risk rules with optional filters."""
q = db.session.query(ContractRiskRule)
if contract_type:
q = q.filter(ContractRiskRule.contract_type == contract_type)
if status:
q = q.filter(ContractRiskRule.status == status)
if clause_category:
q = q.filter(ContractRiskRule.clause_category == clause_category)
rows = q.order_by(ContractRiskRule.sort_order.asc(), ContractRiskRule.id.asc()).all()
return [serialize_rule(r) for r in rows]
def get_enabled_rules(contract_type: str | None = None) -> list[dict[str, Any]]:
"""
Load enabled rules for analysis.
Rules for the requested contract type are used first; general procurement rules are included as fallback.
"""
normalized = (contract_type or DEFAULT_CONTRACT_TYPE).strip() or DEFAULT_CONTRACT_TYPE
q = db.session.query(ContractRiskRule).filter(ContractRiskRule.status == "enabled")
if normalized != DEFAULT_CONTRACT_TYPE:
q = q.filter(ContractRiskRule.contract_type.in_([normalized, DEFAULT_CONTRACT_TYPE]))
else:
q = q.filter(ContractRiskRule.contract_type == DEFAULT_CONTRACT_TYPE)
rows = q.order_by(ContractRiskRule.sort_order.asc(), ContractRiskRule.id.asc()).all()
return [serialize_rule(r) for r in rows]
def create_rule(*, user_id: int, data: dict[str, Any]) -> dict[str, Any]:
"""
Create a custom keyword-based contract risk rule.
Built-in codes are reserved for compound procurement checks. Custom rules receive an internal
generated code so their keywords cannot accidentally change a built-in rule's semantics.
Args:
user_id: Administrator creating the rule.
data: Rule display fields, category, keywords and trigger configuration; code is optional.
Returns:
Serialized newly created rule.
Raises:
ValidationError: If category, keywords or enum fields are invalid, or a built-in code is supplied.
"""
code = str(data.get("code") or "").strip()
title = str(data.get("title") or "").strip()
category = _validate_clause_category(str(data.get("clause_category") or ""))
risk_level = str(data.get("risk_level") or "").strip()
risk_hint = str(data.get("risk_hint") or "").strip()
suggestion = str(data.get("suggestion") or "").strip()
keywords = _normalize_keywords(data.get("keywords"))
trigger_type = str(data.get("trigger_type") or "keyword_missing").strip()
status = str(data.get("status") or "enabled").strip()
if not title:
raise ValidationError("title is required")
if not keywords:
raise ValidationError("keywords are required")
if risk_level not in VALID_RISK_LEVELS:
raise ValidationError("invalid risk_level")
if trigger_type not in VALID_TRIGGER_TYPES:
raise ValidationError("invalid trigger_type")
if status not in VALID_STATUS:
raise ValidationError("invalid status")
if code:
if code in BUILTIN_RULE_CODES:
raise ValidationError("built-in rule code is reserved")
raise ValidationError("custom rule code is generated by server")
code = _generate_custom_rule_code(category)
exists = db.session.query(ContractRiskRule).filter(ContractRiskRule.code == code).first()
if exists:
raise ValidationError("rule code already exists")
row = ContractRiskRule(
code=code,
contract_type=str(data.get("contract_type") or DEFAULT_CONTRACT_TYPE).strip() or DEFAULT_CONTRACT_TYPE,
clause_category=category,
title=title,
keywords=keywords,
trigger_type=trigger_type,
risk_level=risk_level,
risk_hint=risk_hint,
suggestion=suggestion,
negotiation_text=(str(data.get("negotiation_text") or "").strip() or None),
status=status,
sort_order=int(data.get("sort_order") or 100),
created_by=user_id,
updated_by=user_id,
)
db.session.add(row)
db.session.commit()
return serialize_rule(row)
def update_rule(rule_id: int, *, user_id: int, data: dict[str, Any]) -> dict[str, Any]:
"""
Update an existing risk rule without changing its detection semantics.
Built-in rules may keep editable display and risk guidance fields, but their category, keywords and
trigger remain fixed because those fields are coupled to compound analyzer logic.
Args:
rule_id: Existing rule primary key.
user_id: Administrator making the change.
data: Partial editable rule payload.
Returns:
Serialized updated rule.
Raises:
NotFoundError: If the rule does not exist.
ValidationError: If enum values are invalid or a built-in detection definition is changed.
"""
row = db.session.get(ContractRiskRule, rule_id)
if not row:
raise NotFoundError("risk rule not found")
if row.code in BUILTIN_RULE_CODES:
if "clause_category" in data and _validate_clause_category(str(data.get("clause_category") or "")) != row.clause_category:
raise ValidationError("built-in rule definition is read-only")
if "keywords" in data and _normalize_keywords(data.get("keywords")) != list(row.keywords or []):
raise ValidationError("built-in rule definition is read-only")
if "trigger_type" in data and str(data.get("trigger_type") or "").strip() != row.trigger_type:
raise ValidationError("built-in rule definition is read-only")
for key in ("contract_type", "clause_category", "title", "risk_hint", "suggestion", "negotiation_text"):
if key in data:
value = str(data.get(key) or "").strip()
if key != "negotiation_text" and not value:
raise ValidationError(f"{key} is required")
if key == "clause_category":
value = _validate_clause_category(value)
setattr(row, key, value or None)
if "keywords" in data:
keywords = _normalize_keywords(data.get("keywords"))
if not keywords:
raise ValidationError("keywords are required")
row.keywords = keywords
if "trigger_type" in data:
trigger_type = str(data.get("trigger_type") or "").strip()
if trigger_type not in VALID_TRIGGER_TYPES:
raise ValidationError("invalid trigger_type")
row.trigger_type = trigger_type
if "risk_level" in data:
risk_level = str(data.get("risk_level") or "").strip()
if risk_level not in VALID_RISK_LEVELS:
raise ValidationError("invalid risk_level")
row.risk_level = risk_level
if "status" in data:
status = str(data.get("status") or "").strip()
if status not in VALID_STATUS:
raise ValidationError("invalid status")
row.status = status
if "sort_order" in data:
row.sort_order = int(data.get("sort_order") or 100)
row.updated_by = user_id
row.updated_at = datetime.utcnow()
db.session.commit()
return serialize_rule(row)
def delete_rule(rule_id: int) -> dict[str, Any]:
"""Delete a risk rule."""
row = db.session.get(ContractRiskRule, rule_id)
if not row:
raise NotFoundError("risk rule not found")
db.session.delete(row)
db.session.commit()
return {"deleted": True, "id": rule_id}
@@ -0,0 +1,293 @@
"""
backend/app/services/procurement_contract/template_service.py
用途:采购合同标准模板库 CRUD、设默认、列表。
依赖:models.ContractTemplate、file_assets、db、errors。
逻辑:Admin API 调用;Chat 下拉读 enabled 列表。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.core.response import utc_iso
from app.models import ContractReview, ContractTemplate, FileAsset, User
from app.services.file_assets.service import (
get_asset_for_user,
mark_asset_referenced,
read_asset_bytes,
release_asset_reference,
)
from app.services.procurement_contract import analyze
from app.services.procurement_contract.comparison_regions import (
preview_anchor_recognition,
validate_comparison_region_config,
)
def serialize_template(row: ContractTemplate) -> dict[str, Any]:
"""ORM → API dict。"""
return {
"id": row.id,
"name": row.name,
"version": row.version,
"file_name": row.file_name,
"file_asset_id": row.file_asset_id,
"contract_type": row.contract_type,
"applicable_scope": row.applicable_scope,
"change_note": row.change_note,
"comparison_region_config": row.comparison_region_config,
"status": row.status,
"is_default": bool(row.is_default),
"remark": row.remark,
"created_by": row.created_by,
"updated_by": row.updated_by,
"updated_by_name": _user_name(row.updated_by),
"created_at": utc_iso(row.created_at),
"updated_at": utc_iso(row.updated_at),
}
def list_templates(*, status: str | None = None) -> list[dict[str, Any]]:
"""列出模板;可按 status 过滤。"""
q = db.session.query(ContractTemplate)
if status:
q = q.filter(ContractTemplate.status == status)
rows = q.order_by(ContractTemplate.is_default.desc(), ContractTemplate.updated_at.desc()).all()
return [serialize_template(r) for r in rows]
def _user_name(user_id: int | None) -> str | None:
"""Resolve a user's display name for template metadata."""
if not user_id:
return None
user = db.session.get(User, user_id)
if not user:
return None
return user.real_name or user.username
def list_enabled_for_chat() -> list[dict[str, Any]]:
"""会话下拉:仅启用中的模板。"""
return list_templates(status="enabled")
def get_default_enabled_template() -> ContractTemplate | None:
"""Return the single enabled default template whose config controls compare-region partitioning."""
return (
db.session.query(ContractTemplate)
.filter(
ContractTemplate.status == "enabled",
ContractTemplate.is_default.is_(True),
)
.order_by(ContractTemplate.updated_at.desc())
.first()
)
def create_template(
*,
user_id: int,
name: str,
version: str,
file_asset_id: int | None = None,
file_asset_no: str | None = None,
remark: str | None = None,
is_default: bool = False,
status: str = "enabled",
contract_type: str = "general_procurement",
applicable_scope: str | None = None,
change_note: str | None = None,
comparison_region_config: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
创建模板并可选设为默认。
Raises:
ValidationError: 参数非法或资产不可用。
"""
name = (name or "").strip()
version = (version or "").strip()
if not name or not version:
raise ValidationError("name and version are required")
if status not in ("enabled", "disabled"):
raise ValidationError("invalid status")
asset: FileAsset | None = None
if file_asset_id:
asset = db.session.get(FileAsset, file_asset_id)
elif file_asset_no:
asset = get_asset_for_user(file_asset_no, user_id)
if not asset or asset.deleted_at is not None:
raise ValidationError("file asset not found")
exists = (
db.session.query(ContractTemplate)
.filter(ContractTemplate.name == name, ContractTemplate.version == version)
.first()
)
if exists:
raise ValidationError("template name+version already exists")
if is_default and status == "enabled":
_clear_defaults()
row = ContractTemplate(
name=name,
version=version,
file_asset_id=asset.id,
file_name=asset.original_filename,
contract_type=(contract_type or "general_procurement").strip() or "general_procurement",
applicable_scope=(applicable_scope or "").strip() or None,
change_note=(change_note or "").strip() or None,
comparison_region_config=(
validate_comparison_region_config(comparison_region_config)
if comparison_region_config is not None
else None
),
status=status,
is_default=bool(is_default and status == "enabled"),
remark=(remark or "").strip() or None,
created_by=user_id,
updated_by=user_id,
)
db.session.add(row)
mark_asset_referenced(asset)
db.session.commit()
return serialize_template(row)
def update_template(template_id: int, *, user_id: int, data: dict[str, Any]) -> dict[str, Any]:
"""更新模板元数据 / 启停 / 设默认。"""
row = db.session.get(ContractTemplate, template_id)
if not row:
raise NotFoundError("template not found")
if "name" in data and data["name"] is not None:
row.name = str(data["name"]).strip() or row.name
if "version" in data and data["version"] is not None:
row.version = str(data["version"]).strip() or row.version
if "remark" in data:
row.remark = (str(data["remark"]).strip() or None) if data["remark"] is not None else None
if "contract_type" in data and data["contract_type"] is not None:
row.contract_type = str(data["contract_type"]).strip() or row.contract_type
if "applicable_scope" in data:
row.applicable_scope = (str(data["applicable_scope"]).strip() or None) if data["applicable_scope"] is not None else None
if "change_note" in data:
row.change_note = (str(data["change_note"]).strip() or None) if data["change_note"] is not None else None
if "comparison_region_config" in data:
row.comparison_region_config = (
validate_comparison_region_config(data["comparison_region_config"])
if data["comparison_region_config"] is not None
else None
)
if "status" in data and data["status"] is not None:
status = str(data["status"])
if status not in ("enabled", "disabled"):
raise ValidationError("invalid status")
if status == "disabled" and row.is_default:
raise ValidationError("cannot disable default template; set another default first")
row.status = status
if data.get("is_default") is True:
if row.status != "enabled":
raise ValidationError("only enabled template can be default")
_clear_defaults()
row.is_default = True
elif data.get("is_default") is False:
row.is_default = False
row.updated_by = user_id
row.updated_at = datetime.utcnow()
db.session.commit()
return serialize_template(row)
def delete_template(template_id: int) -> dict[str, Any]:
"""
Delete a non-default template that is not referenced by review history.
Historical reviews retain their template relationship for audit and file download,
so referenced templates must be disabled rather than deleted.
Raises:
NotFoundError: The template does not exist.
ValidationError: The template is currently the default template.
ConflictError: One or more review history records reference the template.
"""
row = db.session.get(ContractTemplate, template_id)
if not row:
raise NotFoundError("template not found")
if row.is_default:
raise ValidationError("cannot delete default template")
review_count = (
db.session.query(ContractReview.id)
.filter(ContractReview.template_id == template_id)
.count()
)
if review_count:
raise ConflictError(
code="PROCUREMENT_CONTRACT.TEMPLATE_REFERENCED",
message="模板已被审查历史引用,无法删除;请停用该模板",
details={"template_id": template_id, "review_count": review_count},
)
asset = db.session.get(FileAsset, row.file_asset_id) if row.file_asset_id else None
db.session.delete(row)
if asset:
release_asset_reference(asset)
db.session.commit()
return {"deleted": True, "id": template_id}
def get_template_or_404(template_id: int) -> ContractTemplate:
"""取模板实体。"""
row = db.session.get(ContractTemplate, template_id)
if not row:
raise NotFoundError("template not found")
return row
def read_template_bytes(template: ContractTemplate) -> tuple[str, bytes]:
"""读取模板文件字节。"""
if not template.file_asset_id:
raise ValidationError("template has no file")
asset = db.session.get(FileAsset, template.file_asset_id)
if not asset:
raise NotFoundError("template file not found")
return asset.original_filename, read_asset_bytes(asset)
def preview_comparison_regions(template_id: int, config: Any) -> dict[str, Any]:
"""
Preview configured anchors against the stored Admin template without changing review baselines.
Args:
template_id: Admin template primary key.
config: Unsaved comparison-region config from the edit dialog.
Returns:
Recognition status for body, signature, and attachment anchors.
"""
template = get_template_or_404(template_id)
normalized = validate_comparison_region_config(config)
filename, data = read_template_bytes(template)
raw_text = analyze.extract_text_from_bytes(filename, data)
clean_text = analyze.clean_contract_text(raw_text)
if not clean_text or clean_text.startswith("[binary:"):
raise ValidationError(
"template text cannot be extracted for comparison-region preview",
code="PROCUREMENT_CONTRACT.COMPARISON_REGION_PREVIEW_FAILED",
)
result = preview_anchor_recognition(clean_text, normalized)
result["template_id"] = template.id
result["template_name"] = template.name
return result
def _clear_defaults() -> None:
"""清除所有默认标记。"""
db.session.query(ContractTemplate).filter(ContractTemplate.is_default.is_(True)).update(
{"is_default": False},
synchronize_session=False,
)
Loaded 100 of 397 files, more files were not shown because too many files have changed in this diff. Show more